Merge "Create ArtifactSaverRule to be reused in different tests" into main
diff --git a/ADPF_OWNERS b/ADPF_OWNERS
new file mode 100644
index 0000000..e6ca8f4
--- /dev/null
+++ b/ADPF_OWNERS
@@ -0,0 +1,3 @@
+lpy@google.com
+mattbuckley@google.com
+xwxw@google.com
diff --git a/OWNERS b/OWNERS
index 4860acc..8ee488dc 100644
--- a/OWNERS
+++ b/OWNERS
@@ -31,9 +31,6 @@
 per-file */res*/values*/*.xml = byi@google.com, delphij@google.com
 
 per-file **.bp,**.mk = hansson@google.com
-per-file *.bp = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION}
-per-file Android.mk = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION}
-per-file framework-jarjar-rules.txt = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION}
 per-file TestProtoLibraries.bp = file:platform/platform_testing:/libraries/health/OWNERS
 per-file TestProtoLibraries.bp = file:platform/tools/tradefederation:/OWNERS
 
diff --git a/apct-tests/perftests/core/src/android/graphics/perftests/RenderNodePerfTest.java b/apct-tests/perftests/core/src/android/graphics/perftests/RenderNodePerfTest.java
index e805ab9..abb0fa7 100644
--- a/apct-tests/perftests/core/src/android/graphics/perftests/RenderNodePerfTest.java
+++ b/apct-tests/perftests/core/src/android/graphics/perftests/RenderNodePerfTest.java
@@ -42,22 +42,6 @@
     }
 
     @Test
-    public void testCreateRenderNodeNoName() {
-        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
-        while (state.keepRunning()) {
-            RenderNode.create(null, null);
-        }
-    }
-
-    @Test
-    public void testCreateRenderNode() {
-        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
-        while (state.keepRunning()) {
-            RenderNode.create("LinearLayout", null);
-        }
-    }
-
-    @Test
     public void testIsValid() {
         final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
         RenderNode node = RenderNode.create("LinearLayout", null);
diff --git a/apct-tests/perftests/core/src/android/graphics/perftests/TypefaceSerializationPerfTest.java b/apct-tests/perftests/core/src/android/graphics/perftests/TypefaceSerializationPerfTest.java
index bc8fc53..2de6f36 100644
--- a/apct-tests/perftests/core/src/android/graphics/perftests/TypefaceSerializationPerfTest.java
+++ b/apct-tests/perftests/core/src/android/graphics/perftests/TypefaceSerializationPerfTest.java
@@ -147,28 +147,4 @@
             out.clear();
         }
     }
-
-    @ManualBenchmarkState.ManualBenchmarkTest(
-            warmupDurationNs = WARMUP_DURATION_NS,
-            targetTestDurationNs = TARGET_TEST_DURATION_NS)
-    @Test
-    public void testSetSystemFontMap() throws Exception {
-        SharedMemory memory = null;
-        ManualBenchmarkState state = mPerfManualStatusReporter.getBenchmarkState();
-
-        long elapsedTime = 0;
-        while (state.keepRunning(elapsedTime)) {
-            // Explicitly destroy lazy-loaded typefaces, so that we don't hit the mmap limit
-            // (max_map_count).
-            Typeface.destroySystemFontMap();
-            Typeface.loadPreinstalledSystemFontMap();
-            if (memory != null) {
-                memory.close();
-            }
-            memory = Typeface.serializeFontMap(Typeface.getSystemFontMap());
-            long startTime = System.nanoTime();
-            Typeface.setSystemFontMap(memory);
-            elapsedTime = System.nanoTime() - startTime;
-        }
-    }
 }
diff --git a/apex/jobscheduler/framework/java/android/app/job/JobService.java b/apex/jobscheduler/framework/java/android/app/job/JobService.java
index 3b5f11b..29afb27 100644
--- a/apex/jobscheduler/framework/java/android/app/job/JobService.java
+++ b/apex/jobscheduler/framework/java/android/app/job/JobService.java
@@ -40,10 +40,26 @@
  * <p>This service executes each incoming job on a {@link android.os.Handler} running on your
  * application's main thread. This means that you <b>must</b> offload your execution logic to
  * another thread/handler/{@link android.os.AsyncTask} of your choosing. Not doing so will result
- * in blocking any future callbacks from the JobManager - specifically
+ * in blocking any future callbacks from the JobScheduler - specifically
  * {@link #onStopJob(android.app.job.JobParameters)}, which is meant to inform you that the
  * scheduling requirements are no longer being met.</p>
  *
+ * <p class="note">
+ * Since the introduction of JobScheduler, if an app did not return from
+ * {@link #onStartJob(JobParameters)} within several seconds, JobScheduler would consider the app
+ * unresponsive and clean up job execution. In such cases, the app was no longer considered
+ * to be running a job and therefore did not have any of the job lifecycle guarantees outlined
+ * in {@link JobScheduler}. However, prior to Android version
+ * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the failure and cleanup were silent
+ * and apps had no indication that they no longer had job lifecycle guarantees.
+ * Starting with Android version {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
+ * JobScheduler will explicitly trigger an ANR in such cases so that apps and developers
+ * can be aware of the issue.
+ * Similar behavior applies to the return time from {@link #onStopJob(JobParameters)} as well.
+ * <br /> <br />
+ * If you see ANRs, then the app may be doing too much work on the UI thread. Ensure that
+ * potentially long operations are moved to a worker thread.
+ *
  * <p>As a subclass of {@link Service}, there will only be one active instance of any JobService
  * subclasses, regardless of job ID. This means that if you schedule multiple jobs with different
  * job IDs but using the same JobService class, that JobService may receive multiple calls to
@@ -240,7 +256,7 @@
      * @param params The parameters identifying this job, similar to what was supplied to the job in
      *               the {@link #onStartJob(JobParameters)} callback, but with the stop reason
      *               included.
-     * @return {@code true} to indicate to the JobManager whether you'd like to reschedule
+     * @return {@code true} to indicate to the JobScheduler whether you'd like to reschedule
      * this job based on the retry criteria provided at job creation-time; or {@code false}
      * to end the job entirely (or, for a periodic job, to reschedule it according to its
      * requested periodic criteria). Regardless of the value returned, your job must stop executing.
diff --git a/apex/jobscheduler/service/java/com/android/server/DeviceIdleController.java b/apex/jobscheduler/service/java/com/android/server/DeviceIdleController.java
index 76d1935..1be07fd 100644
--- a/apex/jobscheduler/service/java/com/android/server/DeviceIdleController.java
+++ b/apex/jobscheduler/service/java/com/android/server/DeviceIdleController.java
@@ -79,6 +79,7 @@
 import android.os.SystemClock;
 import android.os.Trace;
 import android.os.UserHandle;
+import android.os.WearModeManagerInternal;
 import android.provider.DeviceConfig;
 import android.telephony.TelephonyCallback;
 import android.telephony.TelephonyManager;
@@ -126,6 +127,7 @@
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
+import java.util.function.Consumer;
 import java.util.stream.Collectors;
 
 /**
@@ -373,10 +375,9 @@
     @GuardedBy("this")
     private boolean mBatterySaverEnabled;
     @GuardedBy("this")
-    private boolean mIsOffBody;
+    private boolean mModeManagerRequestedQuickDoze;
     @GuardedBy("this")
-    private boolean mForceBodyState;
-    private Sensor mOffBodySensor;
+    private boolean mForceModeManagerQuickDozeRequest;
 
     /** Time in the elapsed realtime timebase when this listener last received a motion event. */
     @GuardedBy("this")
@@ -435,7 +436,7 @@
     private static final int ACTIVE_REASON_FORCED = 6;
     private static final int ACTIVE_REASON_ALARM = 7;
     private static final int ACTIVE_REASON_EMERGENCY_CALL = 8;
-    private static final int ACTIVE_REASON_ONBODY = 9;
+    private static final int ACTIVE_REASON_MODE_MANAGER = 9;
 
     @VisibleForTesting
     static String stateToString(int state) {
@@ -832,64 +833,35 @@
         }
     }
 
-    /**
-     * LowLatencyOffBodyListener monitors if a device is on body or off body.
-     */
     @VisibleForTesting
-    final class LowLatencyOffBodyListener implements SensorEventListener {
+    class ModeManagerQuickDozeRequestConsumer implements Consumer<Boolean> {
         @Override
-        public void onSensorChanged(SensorEvent event) {
-            if (DEBUG) {
-                Slog.d(TAG, "LowLatencyOffBodyListener detects onSensorChanged event, values are: "
-                        + Arrays.toString(event.values));
-            }
-            if (event.values == null || event.values.length == 0) {
-                // The event returned should contain a single value to indicate off-body state.
-                // No value indicates something went wrong. Take no action and log an error.
-                Slog.e(TAG,
-                        "LowLatencyOffBodyListener detects onSensorChanged event but no event "
-                                + "value returns.");
-                return;
-            }
+        public void accept(Boolean enabled) {
+            Slog.d(TAG, "Mode manager quick doze request: " + enabled);
             synchronized (DeviceIdleController.this) {
-                final boolean isOffBody = (event.values[0] == 0);
-                if (!mForceBodyState && mIsOffBody != isOffBody) {
-                    // Only consider the sensor value change when mForceBodyState is false, which
-                    // is used to enforce the mIsOffBody to be set by the adb shell command.
-                    mIsOffBody = isOffBody;
-                    onOffBodyChangedLocked();
+                if (!mForceModeManagerQuickDozeRequest
+                        && mModeManagerRequestedQuickDoze != enabled) {
+                    mModeManagerRequestedQuickDoze = enabled;
+                    onModeManagerRequestChangedLocked();
                 }
             }
         }
 
         @GuardedBy("DeviceIdleController.this")
-        public void onOffBodyChangedLocked() {
-            // Get into quick doze faster when the device is off body instead of taking
+        public void onModeManagerRequestChangedLocked() {
+            // Get into quick doze faster when mode manager requests instead of taking
             // traditional multi-stage approach.
             updateQuickDozeFlagLocked();
-            if (!mIsOffBody && !mBatterySaverEnabled) {
-                mActiveReason = ACTIVE_REASON_ONBODY;
-                becomeActiveLocked("onbody", Process.myUid());
+            if (!mModeManagerRequestedQuickDoze && !mBatterySaverEnabled) {
+                mActiveReason = ACTIVE_REASON_MODE_MANAGER;
+                becomeActiveLocked("mode_manager", Process.myUid());
             }
         }
-
-        @Override
-        public void onAccuracyChanged(Sensor sensor, int accuracy) {}
-
-        public void registerLocked() {
-            mOffBodySensor =
-                    mSensorManager.getDefaultSensor(Sensor.TYPE_LOW_LATENCY_OFFBODY_DETECT, true);
-            if (mOffBodySensor == null) {
-                Slog.w(TAG, "Body sensor is NULL, unable to register mOffBodySensor.");
-                return;
-            }
-            mSensorManager.registerListener(this, mOffBodySensor,
-                    SensorManager.SENSOR_DELAY_NORMAL);
-        }
     }
 
     @VisibleForTesting
-    final LowLatencyOffBodyListener mLowLatencyOffBodyListener = new LowLatencyOffBodyListener();
+    final ModeManagerQuickDozeRequestConsumer mModeManagerQuickDozeRequestConsumer =
+            new ModeManagerQuickDozeRequestConsumer();
 
     @VisibleForTesting
     final class MotionListener extends TriggerEventListener
@@ -1052,7 +1024,7 @@
          */
         private static final String KEY_WAIT_FOR_UNLOCK = "wait_for_unlock";
         private static final String KEY_USE_WINDOW_ALARMS = "use_window_alarms";
-        private static final String KEY_USE_BODY_SENSOR = "use_body_sensor";
+        private static final String KEY_USE_MODE_MANAGER = "use_mode_manager";
 
         private long mDefaultFlexTimeShort =
                 !COMPRESS_TIME ? 60 * 1000L : 5 * 1000L;
@@ -1112,7 +1084,7 @@
         private long mDefaultNotificationAllowlistDurationMs = 30 * 1000L;
         private boolean mDefaultWaitForUnlock = true;
         private boolean mDefaultUseWindowAlarms = true;
-        private boolean mDefaultUseBodySensor = false;
+        private boolean mDefaultUseModeManager = false;
 
         /**
          * A somewhat short alarm window size that we will tolerate for various alarm timings.
@@ -1356,7 +1328,7 @@
         /**
          * Whether to use an on/off body signal to affect state transition policy.
          */
-        public boolean USE_BODY_SENSOR = mDefaultUseBodySensor;
+        public boolean USE_MODE_MANAGER = mDefaultUseModeManager;
 
         private final boolean mSmallBatteryDevice;
 
@@ -1464,8 +1436,8 @@
                     com.android.internal.R.bool.device_idle_wait_for_unlock);
             mDefaultUseWindowAlarms = res.getBoolean(
                     com.android.internal.R.bool.device_idle_use_window_alarms);
-            mDefaultUseBodySensor = res.getBoolean(
-                    com.android.internal.R.bool.device_idle_use_body_sensor);
+            mDefaultUseModeManager = res.getBoolean(
+                    com.android.internal.R.bool.device_idle_use_mode_manager);
 
             FLEX_TIME_SHORT = mDefaultFlexTimeShort;
             LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mDefaultLightIdleAfterInactiveTimeout;
@@ -1499,7 +1471,7 @@
             NOTIFICATION_ALLOWLIST_DURATION_MS = mDefaultNotificationAllowlistDurationMs;
             WAIT_FOR_UNLOCK = mDefaultWaitForUnlock;
             USE_WINDOW_ALARMS = mDefaultUseWindowAlarms;
-            USE_BODY_SENSOR = mDefaultUseBodySensor;
+            USE_MODE_MANAGER = mDefaultUseModeManager;
         }
 
         private long getTimeout(long defTimeout, long compTimeout) {
@@ -1661,9 +1633,9 @@
                             USE_WINDOW_ALARMS = properties.getBoolean(
                                     KEY_USE_WINDOW_ALARMS, mDefaultUseWindowAlarms);
                             break;
-                        case KEY_USE_BODY_SENSOR:
-                            USE_BODY_SENSOR = properties.getBoolean(
-                                    KEY_USE_BODY_SENSOR, mDefaultUseBodySensor);
+                        case KEY_USE_MODE_MANAGER:
+                            USE_MODE_MANAGER = properties.getBoolean(
+                                    KEY_USE_MODE_MANAGER, mDefaultUseModeManager);
                             break;
                         default:
                             Slog.e(TAG, "Unknown configuration key: " + name);
@@ -1802,8 +1774,8 @@
             pw.print("    "); pw.print(KEY_USE_WINDOW_ALARMS); pw.print("=");
             pw.println(USE_WINDOW_ALARMS);
 
-            pw.print("    "); pw.print(KEY_USE_BODY_SENSOR); pw.print("=");
-            pw.println(USE_BODY_SENSOR);
+            pw.print("    "); pw.print(KEY_USE_MODE_MANAGER); pw.print("=");
+            pw.println(USE_MODE_MANAGER);
         }
     }
 
@@ -2668,8 +2640,15 @@
                         mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
                 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
 
-                if (mConstants.USE_BODY_SENSOR) {
-                    mLowLatencyOffBodyListener.registerLocked();
+                if (mConstants.USE_MODE_MANAGER) {
+                    WearModeManagerInternal modeManagerInternal = LocalServices.getService(
+                            WearModeManagerInternal.class);
+                    if (modeManagerInternal != null) {
+                        modeManagerInternal.addActiveStateChangeListener(
+                                WearModeManagerInternal.QUICK_DOZE_REQUEST_IDENTIFIER,
+                                AppSchedulingModuleThread.getExecutor(),
+                                mModeManagerQuickDozeRequestConsumer);
+                    }
                 }
                 mLocalPowerManager.registerLowPowerModeObserver(ServiceType.QUICK_DOZE,
                         state -> {
@@ -3374,9 +3353,10 @@
     /** Calls to {@link #updateQuickDozeFlagLocked(boolean)} by considering appropriate signals. */
     @GuardedBy("this")
     private void updateQuickDozeFlagLocked() {
-        if (mConstants.USE_BODY_SENSOR) {
-            // Only disable the quick doze flag when the device is on body and battery saver is off.
-            updateQuickDozeFlagLocked(mIsOffBody || mBatterySaverEnabled);
+        if (mConstants.USE_MODE_MANAGER) {
+            // Only disable the quick doze flag when mode manager request is false and
+            // battery saver is off.
+            updateQuickDozeFlagLocked(mModeManagerRequestedQuickDoze || mBatterySaverEnabled);
         } else {
             updateQuickDozeFlagLocked(mBatterySaverEnabled);
         }
@@ -4482,7 +4462,7 @@
         pw.println("  unforce");
         pw.println(
                 "    Resume normal functioning after force-idle or force-inactive or "
-                        + "force-offbody or force-onbody.");
+                        + "force-modemanager-quickdoze.");
         pw.println("  get [light|deep|force|screen|charging|network|offbody|forcebodystate]");
         pw.println("    Retrieve the current given state.");
         pw.println("  disable [light|deep|all]");
@@ -4517,14 +4497,9 @@
                 + "and any [-d] is ignored");
         pw.println("  motion");
         pw.println("    Simulate a motion event to bring the device out of deep doze");
-        pw.println("  force-offbody");
-        pw.println(
-                "    Simulate a low latency body sensor detecting a device is offbody. "
-                        + "mForceBodyState will be set to true to ignore body sensor reading.");
-        pw.println("  force-onbody");
-        pw.println(
-                "    Simulate a low latency body sensor detecting a device is onbody. "
-                        + "mForceBodyState will be set to true to ignore body sensor reading.");
+        pw.println("  force-modemanager-quickdoze [true|false]");
+        pw.println("    Simulate mode manager request to enable (true) or disable (false) "
+                + "quick doze. Mode manager changes will be ignored until unforce is called.");
     }
 
     class Shell extends ShellCommand {
@@ -4656,8 +4631,9 @@
                     pw.print(lightStateToString(mLightState));
                     pw.print(", deep state: ");
                     pw.println(stateToString(mState));
-                    mForceBodyState = false;
-                    pw.println("mForceBodyState: " + mForceBodyState);
+                    mForceModeManagerQuickDozeRequest = false;
+                    pw.println("mForceModeManagerQuickDozeRequest: "
+                            + mForceModeManagerQuickDozeRequest);
                 } finally {
                     Binder.restoreCallingIdentity(token);
                 }
@@ -4678,8 +4654,12 @@
                             case "screen": pw.println(mScreenOn); break;
                             case "charging": pw.println(mCharging); break;
                             case "network": pw.println(mNetworkConnected); break;
-                            case "offbody": pw.println(mIsOffBody); break;
-                            case "forcebodystate": pw.println(mForceBodyState); break;
+                            case "modemanagerquick":
+                                pw.println(mModeManagerRequestedQuickDoze);
+                                break;
+                            case "forcemodemanagerquick":
+                                pw.println(mForceModeManagerQuickDozeRequest);
+                                break;
                             default: pw.println("Unknown get option: " + arg); break;
                         }
                     } finally {
@@ -4976,35 +4956,31 @@
                     Binder.restoreCallingIdentity(token);
                 }
             }
-        } else if ("force-offbody".equals(cmd)) {
+        } else if ("force-modemanager-quickdoze".equals(cmd)) {
             getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
                     null);
-            synchronized (DeviceIdleController.this) {
-                final long token = Binder.clearCallingIdentity();
-                try {
-                    mForceBodyState = true;
-                    pw.println("mForceBodyState: " + mForceBodyState);
-                    mIsOffBody = true;
-                    pw.println("mIsOffBody: " + mIsOffBody);
-                    mLowLatencyOffBodyListener.onOffBodyChangedLocked();
-                } finally {
-                    Binder.restoreCallingIdentity(token);
+            String arg = shell.getNextArg();
+
+            if ("true".equalsIgnoreCase(arg) || "false".equalsIgnoreCase(arg)) {
+                boolean enabled = Boolean.parseBoolean(arg);
+
+                synchronized (DeviceIdleController.this) {
+                    final long token = Binder.clearCallingIdentity();
+                    try {
+                        mForceModeManagerQuickDozeRequest = true;
+                        pw.println("mForceModeManagerQuickDozeRequest: "
+                                + mForceModeManagerQuickDozeRequest);
+                        mModeManagerRequestedQuickDoze = enabled;
+                        pw.println("mModeManagerRequestedQuickDoze: "
+                                + mModeManagerRequestedQuickDoze);
+                        mModeManagerQuickDozeRequestConsumer.onModeManagerRequestChangedLocked();
+                    } finally {
+                        Binder.restoreCallingIdentity(token);
+                    }
                 }
-            }
-        } else if ("force-onbody".equals(cmd)) {
-            getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
-                    null);
-            synchronized (DeviceIdleController.this) {
-                final long token = Binder.clearCallingIdentity();
-                try {
-                    mForceBodyState = true;
-                    pw.println("mForceBodyState: " + mForceBodyState);
-                    mIsOffBody = false;
-                    pw.println("mIsOffBody: " + mIsOffBody);
-                    mLowLatencyOffBodyListener.onOffBodyChangedLocked();
-                } finally {
-                    Binder.restoreCallingIdentity(token);
-                }
+            } else {
+                pw.println("Provide true or false argument after force-modemanager-quickdoze");
+                return -1;
             }
         } else {
             return shell.handleDefaultCommands(cmd);
diff --git a/apex/jobscheduler/service/java/com/android/server/usage/TEST_MAPPING b/apex/jobscheduler/service/java/com/android/server/usage/TEST_MAPPING
index 6a4a52a..9ec799f 100644
--- a/apex/jobscheduler/service/java/com/android/server/usage/TEST_MAPPING
+++ b/apex/jobscheduler/service/java/com/android/server/usage/TEST_MAPPING
@@ -4,7 +4,6 @@
       "name": "CtsUsageStatsTestCases",
       "options": [
         {"include-filter": "android.app.usage.cts.UsageStatsTest"},
-        {"include-filter": "android.app.usage.cts.BroadcastResponseStatsTest"},
         {"exclude-annotation": "android.platform.test.annotations.FlakyTest"},
         {"exclude-annotation": "androidx.test.filters.FlakyTest"},
         {"exclude-annotation": "androidx.test.filters.MediumTest"},
@@ -12,6 +11,13 @@
       ]
     },
     {
+      "name": "CtsBRSTestCases",
+      "options": [
+        {"exclude-annotation": "androidx.test.filters.FlakyTest"},
+        {"exclude-annotation": "org.junit.Ignore"}
+      ]
+    },
+    {
       "name": "FrameworksServicesTests",
       "options": [
         {"include-filter": "com.android.server.usage"},
diff --git a/api/StubLibraries.bp b/api/StubLibraries.bp
index 9a0053f..c37ff97 100644
--- a/api/StubLibraries.bp
+++ b/api/StubLibraries.bp
@@ -483,6 +483,22 @@
 }
 
 java_library {
+    name: "android_test_frameworks_core_stubs_current.from-source",
+    static_libs: [
+        "all-updatable-modules-system-stubs",
+        "android-non-updatable.stubs.test",
+        "private-stub-annotations-jar",
+    ],
+    defaults: [
+        "android.jar_defaults",
+        "android_stubs_dists_default",
+    ],
+    dist: {
+        dir: "apistubs/android/test-core",
+    },
+}
+
+java_library {
     name: "android_module_lib_stubs_current.from-source",
     defaults: [
         "android.jar_defaults",
@@ -572,6 +588,170 @@
     },
 }
 
+//
+// Java API defaults and libraries for single tree build
+//
+
+java_defaults {
+    name: "stub-annotation-defaults",
+    libs: [
+        "stub-annotations",
+    ],
+    static_libs: [
+        // stub annotations do not contribute to the API surfaces but are statically
+        // linked in the stubs for API surfaces (see frameworks/base/StubLibraries.bp).
+        // This is because annotation processors insist on loading the classes for any
+        // annotations found, thus should exist inside android.jar.
+        "private-stub-annotations-jar",
+    ],
+}
+
+// Listing of API domains contribution and dependencies per API surfaces
+java_defaults {
+    name: "android_test_stubs_current_contributions",
+    api_surface: "test",
+    api_contributions: [
+        "test-api-stubs-docs-non-updatable.api.contribution",
+        "framework-virtualization.stubs.source.test.api.contribution",
+    ],
+}
+
+java_defaults {
+    name: "android_test_frameworks_core_stubs_current_contributions",
+    api_surface: "test",
+    api_contributions: [
+        "test-api-stubs-docs-non-updatable.api.contribution",
+    ],
+}
+
+java_defaults {
+    name: "android_module_lib_stubs_current_contributions",
+    api_surface: "module-lib",
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
+        "module-lib-api-stubs-docs-non-updatable.api.contribution",
+        "art.module.public.api.stubs.source.api.contribution",
+        "art.module.public.api.stubs.source.system.api.contribution",
+        "art.module.public.api.stubs.source.module_lib.api.contribution",
+        "i18n.module.public.api.stubs.source.api.contribution",
+        "i18n.module.public.api.stubs.source.system.api.contribution",
+        "i18n.module.public.api.stubs.source.module_lib.api.contribution",
+    ],
+}
+
+// Java API library definitions per API surface
+java_api_library {
+    name: "android_stubs_current.from-text",
+    api_surface: "public",
+    defaults: [
+        // This module is dynamically created at frameworks/base/api/api.go
+        // instead of being written out, in order to minimize edits in the codebase
+        // when there is a change in the list of modules.
+        // that contributes to an api surface.
+        "android_stubs_current_contributions",
+        "stub-annotation-defaults",
+    ],
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+    ],
+    visibility: ["//visibility:public"],
+}
+
+java_api_library {
+    name: "android_system_stubs_current.from-text",
+    api_surface: "system",
+    defaults: [
+        "android_stubs_current_contributions",
+        "android_system_stubs_current_contributions",
+        "stub-annotation-defaults",
+    ],
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
+    ],
+    visibility: ["//visibility:public"],
+}
+
+java_api_library {
+    name: "android_test_stubs_current.from-text",
+    api_surface: "test",
+    defaults: [
+        "android_stubs_current_contributions",
+        "android_system_stubs_current_contributions",
+        "android_test_stubs_current_contributions",
+        "stub-annotation-defaults",
+    ],
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
+    ],
+    visibility: ["//visibility:public"],
+}
+
+java_api_library {
+    name: "android_test_frameworks_core_stubs_current.from-text",
+    api_surface: "test",
+    defaults: [
+        "android_stubs_current_contributions",
+        "android_system_stubs_current_contributions",
+        "android_test_frameworks_core_stubs_current_contributions",
+        "stub-annotation-defaults",
+    ],
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
+    ],
+}
+
+java_api_library {
+    name: "android_module_lib_stubs_current_full.from-text",
+    api_surface: "module-lib",
+    defaults: [
+        "android_stubs_current_contributions",
+        "android_system_stubs_current_contributions",
+        "android_module_lib_stubs_current_contributions_full",
+    ],
+    libs: [
+        "stub-annotations",
+    ],
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
+        "module-lib-api-stubs-docs-non-updatable.api.contribution",
+    ],
+    visibility: ["//visibility:public"],
+}
+
+java_api_library {
+    name: "android_module_lib_stubs_current.from-text",
+    api_surface: "module-lib",
+    defaults: [
+        "android_module_lib_stubs_current_contributions",
+    ],
+    libs: [
+        "android_module_lib_stubs_current_full.from-text",
+        "stub-annotations",
+    ],
+    visibility: ["//visibility:public"],
+}
+
+java_api_library {
+    name: "android_system_server_stubs_current.from-text",
+    api_surface: "system-server",
+    api_contributions: [
+        "services-non-updatable-stubs.api.contribution",
+    ],
+    libs: [
+        "android_module_lib_stubs_current.from-text",
+        "stub-annotations",
+    ],
+    static_libs: [
+        "android_module_lib_stubs_current.from-text",
+    ],
+    visibility: ["//visibility:public"],
+}
+
 ////////////////////////////////////////////////////////////////////////
 // api-versions.xml generation, for public and system. This API database
 // also contains the android.test.* APIs.
diff --git a/api/api.go b/api/api.go
index c568a45..d5c6145 100644
--- a/api/api.go
+++ b/api/api.go
@@ -110,6 +110,7 @@
 	Api_surface         *string
 	Api_contributions   []string
 	Defaults_visibility []string
+	Previous_api        *string
 }
 
 type Bazel_module struct {
@@ -145,7 +146,7 @@
 	metalavaCmd := "$(location metalava)"
 	// Silence reflection warnings. See b/168689341
 	metalavaCmd += " -J--add-opens=java.base/java.util=ALL-UNNAMED "
-	metalavaCmd += " --quiet --no-banner --format=v2 "
+	metalavaCmd += " --quiet merge-signatures --format=v2 "
 
 	filename := txt.TxtFilename
 	if txt.Scope != "public" {
@@ -155,7 +156,7 @@
 	props.Name = proptools.StringPtr(ctx.ModuleName() + "-" + filename)
 	props.Tools = []string{"metalava"}
 	props.Out = []string{filename}
-	props.Cmd = proptools.StringPtr(metalavaCmd + "$(in) --api $(out)")
+	props.Cmd = proptools.StringPtr(metalavaCmd + "$(in) --out $(out)")
 	props.Srcs = append([]string{txt.BaseTxt}, createSrcs(txt.Modules, txt.ModuleTag)...)
 	props.Dists = []android.Dist{
 		{
@@ -359,6 +360,7 @@
 		props.Api_contributions = transformArray(
 			modules, "", fmt.Sprintf(".stubs.source%s.api.contribution", apiSuffix))
 		props.Defaults_visibility = []string{"//visibility:public"}
+		props.Previous_api = proptools.StringPtr(":android.api.public.latest")
 		ctx.CreateModule(java.DefaultsFactory, &props)
 	}
 }
@@ -368,6 +370,7 @@
 		"android_stubs_current",
 		"android_system_stubs_current",
 		"android_test_stubs_current",
+		"android_test_frameworks_core_stubs_current",
 		"android_module_lib_stubs_current",
 		"android_system_server_stubs_current",
 	}
diff --git a/cmds/bootanimation/BootAnimation.cpp b/cmds/bootanimation/BootAnimation.cpp
index 10ce3b8..774ba74 100644
--- a/cmds/bootanimation/BootAnimation.cpp
+++ b/cmds/bootanimation/BootAnimation.cpp
@@ -1565,6 +1565,7 @@
     for (size_t i=0 ; i<pcount ; i++) {
         const Animation::Part& part(animation.parts[i]);
         const size_t fcount = part.frames.size();
+        glBindTexture(GL_TEXTURE_2D, 0);
 
         // Handle animation package
         if (part.animation != nullptr) {
@@ -1641,8 +1642,10 @@
                 if (r > 0) {
                     glBindTexture(GL_TEXTURE_2D, frame.tid);
                 } else {
-                    glGenTextures(1, &frame.tid);
-                    glBindTexture(GL_TEXTURE_2D, frame.tid);
+                    if (part.count != 1) {
+                        glGenTextures(1, &frame.tid);
+                        glBindTexture(GL_TEXTURE_2D, frame.tid);
+                    }
                     int w, h;
                     // Set decoding option to alpha unpremultiplied so that the R, G, B channels
                     // of transparent pixels are preserved.
diff --git a/cmds/idmap2/idmap2d/Idmap2Service.cpp b/cmds/idmap2/idmap2d/Idmap2Service.cpp
index b94b3b4..d76ca5b 100644
--- a/cmds/idmap2/idmap2d/Idmap2Service.cpp
+++ b/cmds/idmap2/idmap2d/Idmap2Service.cpp
@@ -265,7 +265,8 @@
             res.configuration.value_or(std::string()));
     } else if (res.binaryData.has_value()) {
       builder.SetResourceValue(res.resourceName, res.binaryData->get(),
-            res.configuration.value_or(std::string()));
+                               res.binaryDataOffset, res.binaryDataSize,
+                               res.configuration.value_or(std::string()));
     } else {
       builder.SetResourceValue(res.resourceName, res.dataType, res.data,
             res.configuration.value_or(std::string()));
diff --git a/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl b/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl
index 3ad6d58..8ebd454 100644
--- a/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl
+++ b/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl
@@ -26,4 +26,6 @@
     @nullable @utf8InCpp String stringData;
     @nullable ParcelFileDescriptor binaryData;
     @nullable @utf8InCpp String configuration;
+    long binaryDataOffset;
+    long binaryDataSize;
 }
\ No newline at end of file
diff --git a/cmds/idmap2/include/idmap2/FabricatedOverlay.h b/cmds/idmap2/include/idmap2/FabricatedOverlay.h
index a29fa8f..1e7d4c2 100644
--- a/cmds/idmap2/include/idmap2/FabricatedOverlay.h
+++ b/cmds/idmap2/include/idmap2/FabricatedOverlay.h
@@ -49,6 +49,8 @@
 
     Builder& SetResourceValue(const std::string& resource_name,
                               std::optional<android::base::borrowed_fd>&& binary_value,
+                              off64_t data_binary_offset,
+                              size_t data_binary_size,
                               const std::string& configuration);
 
     inline Builder& setFrroPath(std::string frro_path) {
@@ -65,6 +67,8 @@
       DataValue data_value;
       std::string data_string_value;
       std::optional<android::base::borrowed_fd> data_binary_value;
+      off64_t data_binary_offset;
+      size_t data_binary_size;
       std::string configuration;
     };
 
@@ -76,6 +80,12 @@
     std::vector<Entry> entries_;
   };
 
+  struct BinaryData {
+    android::base::borrowed_fd file_descriptor;
+    off64_t offset;
+    size_t size;
+  };
+
   Result<Unit> ToBinaryStream(std::ostream& stream) const;
   static Result<FabricatedOverlay> FromBinaryStream(std::istream& stream);
 
@@ -92,13 +102,13 @@
 
   explicit FabricatedOverlay(pb::FabricatedOverlay&& overlay,
                              std::string&& string_pool_data_,
-                             std::vector<android::base::borrowed_fd> binary_files_,
+                             std::vector<FabricatedOverlay::BinaryData> binary_files_,
                              off_t total_binary_bytes_,
                              std::optional<uint32_t> crc_from_disk = {});
 
   pb::FabricatedOverlay overlay_pb_;
   std::string string_pool_data_;
-  std::vector<android::base::borrowed_fd> binary_files_;
+  std::vector<FabricatedOverlay::BinaryData> binary_files_;
   uint32_t total_binary_bytes_;
   std::optional<uint32_t> crc_from_disk_;
   mutable std::optional<SerializedData> data_;
diff --git a/cmds/idmap2/include/idmap2/ResourceUtils.h b/cmds/idmap2/include/idmap2/ResourceUtils.h
index c2b0abe..d4490ef4 100644
--- a/cmds/idmap2/include/idmap2/ResourceUtils.h
+++ b/cmds/idmap2/include/idmap2/ResourceUtils.h
@@ -43,6 +43,8 @@
   DataValue data_value;
   std::string data_string_value;
   std::optional<android::base::borrowed_fd> data_binary_value;
+  off64_t data_binary_offset;
+  size_t data_binary_size;
 };
 
 struct TargetValueWithConfig {
diff --git a/cmds/idmap2/libidmap2/FabricatedOverlay.cpp b/cmds/idmap2/libidmap2/FabricatedOverlay.cpp
index dd5be21c..47daf23 100644
--- a/cmds/idmap2/libidmap2/FabricatedOverlay.cpp
+++ b/cmds/idmap2/libidmap2/FabricatedOverlay.cpp
@@ -55,7 +55,7 @@
 
 FabricatedOverlay::FabricatedOverlay(pb::FabricatedOverlay&& overlay,
                                      std::string&& string_pool_data,
-                                     std::vector<android::base::borrowed_fd> binary_files,
+                                     std::vector<FabricatedOverlay::BinaryData> binary_files,
                                      off_t total_binary_bytes,
                                      std::optional<uint32_t> crc_from_disk)
     : overlay_pb_(std::forward<pb::FabricatedOverlay>(overlay)),
@@ -81,7 +81,7 @@
     const std::string& resource_name, uint8_t data_type, uint32_t data_value,
     const std::string& configuration) {
   entries_.emplace_back(
-      Entry{resource_name, data_type, data_value, "", std::nullopt, configuration});
+      Entry{resource_name, data_type, data_value, "", std::nullopt, 0, 0, configuration});
   return *this;
 }
 
@@ -89,14 +89,15 @@
     const std::string& resource_name, uint8_t data_type, const std::string& data_string_value,
     const std::string& configuration) {
   entries_.emplace_back(
-      Entry{resource_name, data_type, 0, data_string_value, std::nullopt, configuration});
+      Entry{resource_name, data_type, 0, data_string_value, std::nullopt, 0, 0, configuration});
   return *this;
 }
 
 FabricatedOverlay::Builder& FabricatedOverlay::Builder::SetResourceValue(
     const std::string& resource_name, std::optional<android::base::borrowed_fd>&& binary_value,
-    const std::string& configuration) {
-  entries_.emplace_back(Entry{resource_name, 0, 0, "", binary_value, configuration});
+    off64_t data_binary_offset, size_t data_binary_size, const std::string& configuration) {
+  entries_.emplace_back(Entry{resource_name, 0, 0, "", binary_value,
+                              data_binary_offset, data_binary_size, configuration});
   return *this;
 }
 
@@ -148,7 +149,8 @@
     }
 
     value->second = TargetValue{res_entry.data_type, res_entry.data_value,
-        res_entry.data_string_value, res_entry.data_binary_value};
+                                res_entry.data_string_value, res_entry.data_binary_value,
+                                res_entry.data_binary_offset, res_entry.data_binary_size};
   }
 
   pb::FabricatedOverlay overlay_pb;
@@ -157,7 +159,7 @@
   overlay_pb.set_target_package_name(target_package_name_);
   overlay_pb.set_target_overlayable(target_overlayable_);
 
-  std::vector<android::base::borrowed_fd> binary_files;
+  std::vector<FabricatedOverlay::BinaryData> binary_files;
   size_t total_binary_bytes = 0;
   // 16 for the number of bytes in the frro file before the binary data
   const size_t FRRO_HEADER_SIZE = 16;
@@ -182,16 +184,15 @@
             pb_value->set_data_value(ref.index());
           } else if (value.second.data_binary_value.has_value()) {
               pb_value->set_data_type(Res_value::TYPE_STRING);
-              struct stat s;
-              if (fstat(value.second.data_binary_value->get(), &s) == -1) {
-                return Error("unable to get size of binary file: %d", errno);
-              }
               std::string uri
                   = StringPrintf("frro:/%s?offset=%d&size=%d", frro_path_.c_str(),
                                  static_cast<int> (FRRO_HEADER_SIZE + total_binary_bytes),
-                                 static_cast<int> (s.st_size));
-              total_binary_bytes += s.st_size;
-              binary_files.emplace_back(value.second.data_binary_value->get());
+                                 static_cast<int> (value.second.data_binary_size));
+              total_binary_bytes += value.second.data_binary_size;
+              binary_files.emplace_back(FabricatedOverlay::BinaryData{
+                  value.second.data_binary_value->get(),
+                  value.second.data_binary_offset,
+                  value.second.data_binary_size});
               auto ref = string_pool.MakeRef(std::move(uri));
               pb_value->set_data_value(ref.index());
           } else {
@@ -310,8 +311,9 @@
   Write32(stream, (*data)->pb_crc);
   Write32(stream, total_binary_bytes_);
   std::string file_contents;
-  for (const android::base::borrowed_fd fd : binary_files_) {
-    if (!ReadFdToString(fd, &file_contents)) {
+  for (const FabricatedOverlay::BinaryData fd : binary_files_) {
+    file_contents.resize(fd.size);
+    if (!ReadFullyAtOffset(fd.file_descriptor, file_contents.data(), fd.size, fd.offset)) {
       return Error("Failed to read binary file data.");
     }
     stream.write(file_contents.data(), file_contents.length());
diff --git a/cmds/idmap2/self_targeting/SelfTargeting.cpp b/cmds/idmap2/self_targeting/SelfTargeting.cpp
index a8aa033..c7f5cf3 100644
--- a/cmds/idmap2/self_targeting/SelfTargeting.cpp
+++ b/cmds/idmap2/self_targeting/SelfTargeting.cpp
@@ -52,6 +52,7 @@
         const auto dataType = entry_params.data_type;
         if (entry_params.data_binary_value.has_value()) {
             builder.SetResourceValue(entry_params.resource_name, *entry_params.data_binary_value,
+                                     entry_params.binary_data_offset, entry_params.binary_data_size,
                                      entry_params.configuration);
         } else  if (dataType >= Res_value::TYPE_FIRST_INT && dataType <= Res_value::TYPE_LAST_INT) {
            builder.SetResourceValue(entry_params.resource_name, dataType,
diff --git a/cmds/idmap2/tests/FabricatedOverlayTests.cpp b/cmds/idmap2/tests/FabricatedOverlayTests.cpp
index e13a0eb..b460bb3 100644
--- a/cmds/idmap2/tests/FabricatedOverlayTests.cpp
+++ b/cmds/idmap2/tests/FabricatedOverlayTests.cpp
@@ -59,7 +59,7 @@
               Res_value::TYPE_STRING,
               "foobar",
               "en-rUS-normal-xxhdpi-v21")
-          .SetResourceValue("com.example.target:drawable/dr1", fd, "port-xxhdpi-v7")
+          .SetResourceValue("com.example.target:drawable/dr1", fd, 0, 8341, "port-xxhdpi-v7")
           .setFrroPath("/foo/bar/biz.frro")
           .Build();
   ASSERT_TRUE(overlay);
diff --git a/cmds/idmap2/tests/IdmapTests.cpp b/cmds/idmap2/tests/IdmapTests.cpp
index f6e48ba..a3448fd 100644
--- a/cmds/idmap2/tests/IdmapTests.cpp
+++ b/cmds/idmap2/tests/IdmapTests.cpp
@@ -269,7 +269,7 @@
                   .SetResourceValue("integer/int1", Res_value::TYPE_INT_DEC, 2U, "land-xxhdpi-v7")
                   .SetResourceValue("string/str1", Res_value::TYPE_REFERENCE, 0x7f010000, "land")
                   .SetResourceValue("string/str2", Res_value::TYPE_STRING, "foobar", "xxhdpi-v7")
-                  .SetResourceValue("drawable/dr1", fd, "port-xxhdpi-v7")
+                  .SetResourceValue("drawable/dr1", fd, 0, 8341, "port-xxhdpi-v7")
                   .setFrroPath("/foo/bar/biz.frro")
                   .Build();
 
diff --git a/cmds/idmap2/tests/ResourceMappingTests.cpp b/cmds/idmap2/tests/ResourceMappingTests.cpp
index 380e462..40f98c2 100644
--- a/cmds/idmap2/tests/ResourceMappingTests.cpp
+++ b/cmds/idmap2/tests/ResourceMappingTests.cpp
@@ -212,7 +212,7 @@
                   .SetResourceValue("integer/int1", Res_value::TYPE_INT_DEC, 2U, "")
                   .SetResourceValue("string/str1", Res_value::TYPE_REFERENCE, 0x7f010000, "")
                   .SetResourceValue("string/str2", Res_value::TYPE_STRING, "foobar", "")
-                  .SetResourceValue("drawable/dr1", fd, "")
+                  .SetResourceValue("drawable/dr1", fd, 0, 8341, "")
                   .setFrroPath("/foo/bar/biz.frro")
                   .Build();
 
diff --git a/cmds/uinput/README.md b/cmds/uinput/README.md
index bdec8b9..82df555 100644
--- a/cmds/uinput/README.md
+++ b/cmds/uinput/README.md
@@ -128,7 +128,9 @@
 that time will be dropped. If you are controlling `uinput` by sending commands through standard
 input from an app, you need to wait for [`onInputDeviceAdded`][onInputDeviceAdded] to be called on
 an `InputDeviceListener` before issuing commands to the device. If you are passing a file to
-`uinput`, add a `delay` after the `register` command to let registration complete.
+`uinput`, add a `delay` after the `register` command to let registration complete. You can add a
+`sync` in certain positions, like at the end of the file to get a response when all commands have
+finished processing.
 
 [onInputDeviceAdded]: https://developer.android.com/reference/android/hardware/input/InputManager.InputDeviceListener.html
 
@@ -187,6 +189,38 @@
 }
 ```
 
+### `sync`
+
+A command used to get a response once the command is processed. When several `inject` and `delay`
+commands are used in a row, the `sync` command can be used to track the progress of the command
+queue.
+
+|    Field    |  Type   | Description                                  |
+|:-----------:|:-------:|:---------------------------------------------|
+|    `id`     | integer | Device ID                                    |
+|  `command`  | string  | Must be set to "sync"                        |
+| `syncToken` | string  | The token used to identify this sync command |
+
+Example:
+
+```json5
+{
+  "id": 1,
+  "command": "syncToken",
+  "syncToken": "finished_injecting_events"
+}
+```
+
+This command will result in the following response when it is processed:
+
+```json5
+{
+  "id": 1,
+  "result": "sync",
+  "syncToken": "finished_injecting_events"
+}
+```
+
 ## Notes
 
 The `getevent` utility can used to print out the key events for debugging purposes.
diff --git a/cmds/uinput/src/com/android/commands/uinput/Device.java b/cmds/uinput/src/com/android/commands/uinput/Device.java
index 6458eef..ad5e70f 100644
--- a/cmds/uinput/src/com/android/commands/uinput/Device.java
+++ b/cmds/uinput/src/com/android/commands/uinput/Device.java
@@ -45,6 +45,7 @@
     private static final int MSG_OPEN_UINPUT_DEVICE = 1;
     private static final int MSG_CLOSE_UINPUT_DEVICE = 2;
     private static final int MSG_INJECT_EVENT = 3;
+    private static final int MSG_SYNC_EVENT = 4;
 
     private final int mId;
     private final HandlerThread mThread;
@@ -122,6 +123,16 @@
     }
 
     /**
+     * Synchronize the uinput command queue by writing a sync response with the provided syncToken
+     * to the output stream when this event is processed.
+     *
+     * @param syncToken  The token for this sync command.
+     */
+    public void syncEvent(String syncToken) {
+        mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_SYNC_EVENT, syncToken), mTimeToSend);
+    }
+
+    /**
      * Close an uinput device.
      *
      */
@@ -174,6 +185,9 @@
                         mCond.notify();
                     }
                     break;
+                case MSG_SYNC_EVENT:
+                    handleSyncEvent((String) msg.obj);
+                    break;
                 default:
                     throw new IllegalArgumentException("Unknown device message");
             }
@@ -187,6 +201,18 @@
             getLooper().myQueue().removeSyncBarrier(mBarrierToken);
             mBarrierToken = 0;
         }
+
+        private void handleSyncEvent(String syncToken) {
+            final JSONObject json = new JSONObject();
+            try {
+                json.put("reason", "sync");
+                json.put("id", mId);
+                json.put("syncToken", syncToken);
+            } catch (JSONException e) {
+                throw new RuntimeException("Could not create JSON object ", e);
+            }
+            writeOutputObject(json);
+        }
     }
 
     private class DeviceCallback {
@@ -214,7 +240,7 @@
         }
 
         public void onDeviceVibrating(int value) {
-            JSONObject json = new JSONObject();
+            final JSONObject json = new JSONObject();
             try {
                 json.put("reason", "vibrating");
                 json.put("id", mId);
@@ -222,12 +248,7 @@
             } catch (JSONException e) {
                 throw new RuntimeException("Could not create JSON object ", e);
             }
-            try {
-                mOutputStream.write(json.toString().getBytes());
-                mOutputStream.flush();
-            } catch (IOException e) {
-                throw new RuntimeException(e);
-            }
+            writeOutputObject(json);
         }
 
         public void onDeviceError() {
@@ -238,6 +259,15 @@
         }
     }
 
+    private void writeOutputObject(JSONObject json) {
+        try {
+            mOutputStream.write(json.toString().getBytes());
+            mOutputStream.flush();
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
     static int getEvdevEventTypeByLabel(String label) {
         final var type = nativeGetEvdevEventTypeByLabel(label);
         if (type < 0) {
diff --git a/cmds/uinput/src/com/android/commands/uinput/Event.java b/cmds/uinput/src/com/android/commands/uinput/Event.java
index cddb407..9d8f1f4 100644
--- a/cmds/uinput/src/com/android/commands/uinput/Event.java
+++ b/cmds/uinput/src/com/android/commands/uinput/Event.java
@@ -39,9 +39,19 @@
 public class Event {
     private static final String TAG = "UinputEvent";
 
-    public static final String COMMAND_REGISTER = "register";
-    public static final String COMMAND_DELAY = "delay";
-    public static final String COMMAND_INJECT = "inject";
+    enum Command {
+        REGISTER("register"),
+        DELAY("delay"),
+        INJECT("inject"),
+        SYNC("sync");
+
+        final String mCommandName;
+
+        Command(String command) {
+            mCommandName = command;
+        }
+    }
+
     private static final int EV_KEY = 0x01;
     private static final int EV_REL = 0x02;
     private static final int EV_ABS = 0x03;
@@ -87,7 +97,7 @@
     }
 
     private int mId;
-    private String mCommand;
+    private Command mCommand;
     private String mName;
     private int mVid;
     private int mPid;
@@ -98,12 +108,13 @@
     private int mFfEffectsMax = 0;
     private String mInputport;
     private SparseArray<InputAbsInfo> mAbsInfo;
+    private String mSyncToken;
 
     public int getId() {
         return mId;
     }
 
-    public String getCommand() {
+    public Command getCommand() {
         return mCommand;
     }
 
@@ -147,6 +158,10 @@
         return mInputport;
     }
 
+    public String getSyncToken() {
+        return mSyncToken;
+    }
+
     /**
      * Convert an event to String.
      */
@@ -177,7 +192,14 @@
         }
 
         private void setCommand(String command) {
-            mEvent.mCommand = command;
+            Objects.requireNonNull(command, "Command must not be null");
+            for (Command cmd : Command.values()) {
+                if (cmd.mCommandName.equals(command)) {
+                    mEvent.mCommand = cmd;
+                    return;
+                }
+            }
+            throw new IllegalStateException("Unrecognized command: " + command);
         }
 
         public void setName(String name) {
@@ -220,27 +242,38 @@
             mEvent.mInputport = port;
         }
 
+        public void setSyncToken(String syncToken) {
+            mEvent.mSyncToken = Objects.requireNonNull(syncToken, "Sync token must not be null");
+        }
+
         public Event build() {
             if (mEvent.mId == -1) {
                 throw new IllegalStateException("No event id");
             } else if (mEvent.mCommand == null) {
                 throw new IllegalStateException("Event does not contain a command");
             }
-            if (COMMAND_REGISTER.equals(mEvent.mCommand)) {
-                if (mEvent.mConfiguration == null) {
-                    throw new IllegalStateException(
-                            "Device registration is missing configuration");
+            switch (mEvent.mCommand) {
+                case REGISTER -> {
+                    if (mEvent.mConfiguration == null) {
+                        throw new IllegalStateException(
+                                "Device registration is missing configuration");
+                    }
                 }
-            } else if (COMMAND_DELAY.equals(mEvent.mCommand)) {
-                if (mEvent.mDuration <= 0) {
-                    throw new IllegalStateException("Delay has missing or invalid duration");
+                case DELAY -> {
+                    if (mEvent.mDuration <= 0) {
+                        throw new IllegalStateException("Delay has missing or invalid duration");
+                    }
                 }
-            } else if (COMMAND_INJECT.equals(mEvent.mCommand)) {
-                if (mEvent.mInjections  == null) {
-                    throw new IllegalStateException("Inject command is missing injection data");
+                case INJECT -> {
+                    if (mEvent.mInjections == null) {
+                        throw new IllegalStateException("Inject command is missing injection data");
+                    }
                 }
-            } else {
-                throw new IllegalStateException("Unknown command " + mEvent.mCommand);
+                case SYNC -> {
+                    if (mEvent.mSyncToken == null) {
+                        throw new IllegalStateException("Sync command is missing sync token");
+                    }
+                }
             }
             return mEvent;
         }
@@ -307,6 +340,9 @@
                             case "port":
                                 eb.setInputport(mReader.nextString());
                                 break;
+                            case "syncToken":
+                                eb.setSyncToken(mReader.nextString());
+                                break;
                             default:
                                 mReader.skipValue();
                         }
diff --git a/cmds/uinput/src/com/android/commands/uinput/Uinput.java b/cmds/uinput/src/com/android/commands/uinput/Uinput.java
index 740578e..47b7a354 100644
--- a/cmds/uinput/src/com/android/commands/uinput/Uinput.java
+++ b/cmds/uinput/src/com/android/commands/uinput/Uinput.java
@@ -25,6 +25,7 @@
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.UnsupportedEncodingException;
+import java.util.Objects;
 
 /**
  * Uinput class encapsulates execution of "uinput" command. It parses the provided input stream
@@ -96,28 +97,27 @@
 
     private void process(Event e) {
         final int index = mDevices.indexOfKey(e.getId());
-        if (index >= 0) {
-            Device d = mDevices.valueAt(index);
-            if (Event.COMMAND_DELAY.equals(e.getCommand())) {
-                d.addDelay(e.getDuration());
-            } else if (Event.COMMAND_INJECT.equals(e.getCommand())) {
-                d.injectEvent(e.getInjections());
-            } else {
-                if (Event.COMMAND_REGISTER.equals(e.getCommand())) {
-                    error("Device id=" + e.getId() + " is already registered. Ignoring event.");
-                } else {
-                    error("Unknown command \"" + e.getCommand() + "\". Ignoring event.");
-                }
+        if (index < 0) {
+            if (e.getCommand() != Event.Command.REGISTER) {
+                Log.e(TAG, "Unknown device id specified. Ignoring event.");
+                return;
             }
-        } else if (Event.COMMAND_REGISTER.equals(e.getCommand())) {
             registerDevice(e);
-        } else {
-            Log.e(TAG, "Unknown device id specified. Ignoring event.");
+            return;
+        }
+
+        final Device d = mDevices.valueAt(index);
+        switch (Objects.requireNonNull(e.getCommand())) {
+            case REGISTER ->
+                    error("Device id=" + e.getId() + " is already registered. Ignoring event.");
+            case INJECT -> d.injectEvent(e.getInjections());
+            case DELAY -> d.addDelay(e.getDuration());
+            case SYNC -> d.syncEvent(e.getSyncToken());
         }
     }
 
     private void registerDevice(Event e) {
-        if (!Event.COMMAND_REGISTER.equals(e.getCommand())) {
+        if (!Event.Command.REGISTER.equals(e.getCommand())) {
             throw new IllegalStateException(
                     "Tried to send command \"" + e.getCommand() + "\" to an unregistered device!");
         }
diff --git a/core/api/current.txt b/core/api/current.txt
index 3392d25..a3d8978 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -9410,8 +9410,8 @@
     method @NonNull public java.util.List<android.appwidget.AppWidgetProviderInfo> getInstalledProvidersForProfile(@Nullable android.os.UserHandle);
     method public static android.appwidget.AppWidgetManager getInstance(android.content.Context);
     method public boolean isRequestPinAppWidgetSupported();
-    method public void notifyAppWidgetViewDataChanged(int[], int);
-    method public void notifyAppWidgetViewDataChanged(int, int);
+    method @Deprecated public void notifyAppWidgetViewDataChanged(int[], int);
+    method @Deprecated public void notifyAppWidgetViewDataChanged(int, int);
     method public void partiallyUpdateAppWidget(int[], android.widget.RemoteViews);
     method public void partiallyUpdateAppWidget(int, android.widget.RemoteViews);
     method public boolean requestPinAppWidget(@NonNull android.content.ComponentName, @Nullable android.os.Bundle, @Nullable android.app.PendingIntent);
@@ -9530,6 +9530,7 @@
     method @Nullable public CharSequence getDisplayName();
     method public int getId();
     method public int getSystemDataSyncFlags();
+    method @Nullable public String getTag();
     method public void writeToParcel(@NonNull android.os.Parcel, int);
     field @NonNull public static final android.os.Parcelable.Creator<android.companion.AssociationInfo> CREATOR;
   }
@@ -9599,6 +9600,7 @@
     method @RequiresPermission(android.Manifest.permission.DELIVER_COMPANION_MESSAGES) public void attachSystemDataTransport(int, @NonNull java.io.InputStream, @NonNull java.io.OutputStream) throws android.companion.DeviceNotAssociatedException;
     method @Nullable public android.content.IntentSender buildAssociationCancellationIntent();
     method @Nullable public android.content.IntentSender buildPermissionTransferUserConsentIntent(int) throws android.companion.DeviceNotAssociatedException;
+    method public void clearAssociationTag(int);
     method @RequiresPermission(android.Manifest.permission.DELIVER_COMPANION_MESSAGES) public void detachSystemDataTransport(int) throws android.companion.DeviceNotAssociatedException;
     method public void disableSystemDataSyncForTypes(int, int);
     method @Deprecated public void disassociate(@NonNull String);
@@ -9608,6 +9610,7 @@
     method @NonNull public java.util.List<android.companion.AssociationInfo> getMyAssociations();
     method @Deprecated public boolean hasNotificationAccess(android.content.ComponentName);
     method public void requestNotificationAccess(android.content.ComponentName);
+    method public void setAssociationTag(int, @NonNull String);
     method @RequiresPermission(android.Manifest.permission.REQUEST_OBSERVE_COMPANION_DEVICE_PRESENCE) public void startObservingDevicePresence(@NonNull String) throws android.companion.DeviceNotAssociatedException;
     method public void startSystemDataTransfer(int, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Void,android.companion.CompanionException>) throws android.companion.DeviceNotAssociatedException;
     method @RequiresPermission(android.Manifest.permission.REQUEST_OBSERVE_COMPANION_DEVICE_PRESENCE) public void stopObservingDevicePresence(@NonNull String) throws android.companion.DeviceNotAssociatedException;
@@ -11699,6 +11702,7 @@
     method @NonNull public void setResourceValue(@NonNull String, @IntRange(from=android.util.TypedValue.TYPE_FIRST_INT, to=android.util.TypedValue.TYPE_LAST_INT) int, int, @Nullable String);
     method @NonNull public void setResourceValue(@NonNull String, int, @NonNull String, @Nullable String);
     method @NonNull public void setResourceValue(@NonNull String, @NonNull android.os.ParcelFileDescriptor, @Nullable String);
+    method @NonNull public void setResourceValue(@NonNull String, @NonNull android.content.res.AssetFileDescriptor, @Nullable String);
     method public void setTargetOverlayable(@Nullable String);
   }
 
@@ -12826,7 +12830,7 @@
     field public static final String FEATURE_TELEPHONY_RADIO_ACCESS = "android.hardware.telephony.radio.access";
     field public static final String FEATURE_TELEPHONY_SUBSCRIPTION = "android.hardware.telephony.subscription";
     field @Deprecated public static final String FEATURE_TELEVISION = "android.hardware.type.television";
-    field public static final String FEATURE_THREADNETWORK = "android.hardware.threadnetwork";
+    field public static final String FEATURE_THREAD_NETWORK = "android.hardware.thread_network";
     field public static final String FEATURE_TOUCHSCREEN = "android.hardware.touchscreen";
     field public static final String FEATURE_TOUCHSCREEN_MULTITOUCH = "android.hardware.touchscreen.multitouch";
     field public static final String FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT = "android.hardware.touchscreen.multitouch.distinct";
@@ -14347,11 +14351,13 @@
     method public void execSQL(String, Object[]) throws android.database.SQLException;
     method public static String findEditTable(String);
     method public java.util.List<android.util.Pair<java.lang.String,java.lang.String>> getAttachedDbs();
+    method public long getLastChangedRowCount();
     method public long getLastInsertRowId();
     method public long getMaximumSize();
     method public long getPageSize();
     method public String getPath();
     method @Deprecated public java.util.Map<java.lang.String,java.lang.String> getSyncedTables();
+    method public long getTotalChangedRowCount();
     method public int getVersion();
     method public boolean inTransaction();
     method public long insert(String, String, android.content.ContentValues);
@@ -15645,6 +15651,7 @@
 
   public final class Gainmap implements android.os.Parcelable {
     ctor public Gainmap(@NonNull android.graphics.Bitmap);
+    ctor public Gainmap(@NonNull android.graphics.Gainmap, @NonNull android.graphics.Bitmap);
     method public int describeContents();
     method @NonNull public float getDisplayRatioForFullHdr();
     method @NonNull public float[] getEpsilonHdr();
@@ -33662,6 +33669,7 @@
   public static class PerformanceHintManager.Session implements java.io.Closeable {
     method public void close();
     method public void reportActualWorkDuration(long);
+    method public void setPreferPowerEfficiency(boolean);
     method public void setThreads(@NonNull int[]);
     method public void updateTargetWorkDuration(long);
   }
@@ -33699,7 +33707,7 @@
     method public boolean isInteractive();
     method public boolean isLowPowerStandbyEnabled();
     method public boolean isPowerSaveMode();
-    method public boolean isRebootingUserspaceSupported();
+    method @Deprecated public boolean isRebootingUserspaceSupported();
     method @Deprecated public boolean isScreenOn();
     method public boolean isSustainedPerformanceModeSupported();
     method public boolean isWakeLockLevelSupported(int);
@@ -44999,6 +45007,7 @@
     field public static final int NR_STATE_RESTRICTED = 1; // 0x1
     field public static final int SERVICE_TYPE_DATA = 2; // 0x2
     field public static final int SERVICE_TYPE_EMERGENCY = 5; // 0x5
+    field public static final int SERVICE_TYPE_MMS = 6; // 0x6
     field public static final int SERVICE_TYPE_SMS = 3; // 0x3
     field public static final int SERVICE_TYPE_UNKNOWN = 0; // 0x0
     field public static final int SERVICE_TYPE_VIDEO = 4; // 0x4
@@ -47263,9 +47272,9 @@
   }
 
   public class BoringLayout extends android.text.Layout implements android.text.TextUtils.EllipsizeCallback {
-    ctor public BoringLayout(CharSequence, android.text.TextPaint, int, android.text.Layout.Alignment, float, float, android.text.BoringLayout.Metrics, boolean);
-    ctor public BoringLayout(CharSequence, android.text.TextPaint, int, android.text.Layout.Alignment, float, float, android.text.BoringLayout.Metrics, boolean, android.text.TextUtils.TruncateAt, int);
-    ctor public BoringLayout(@NonNull CharSequence, @NonNull android.text.TextPaint, @IntRange(from=0) int, @NonNull android.text.Layout.Alignment, float, float, @NonNull android.text.BoringLayout.Metrics, boolean, @Nullable android.text.TextUtils.TruncateAt, @IntRange(from=0) int, boolean);
+    ctor @Deprecated public BoringLayout(CharSequence, android.text.TextPaint, int, android.text.Layout.Alignment, float, float, android.text.BoringLayout.Metrics, boolean);
+    ctor @Deprecated public BoringLayout(CharSequence, android.text.TextPaint, int, android.text.Layout.Alignment, float, float, android.text.BoringLayout.Metrics, boolean, android.text.TextUtils.TruncateAt, int);
+    ctor @Deprecated public BoringLayout(@NonNull CharSequence, @NonNull android.text.TextPaint, @IntRange(from=0) int, @NonNull android.text.Layout.Alignment, float, float, @NonNull android.text.BoringLayout.Metrics, boolean, @Nullable android.text.TextUtils.TruncateAt, @IntRange(from=0) int, boolean);
     method public void ellipsized(int, int);
     method public int getBottomPadding();
     method public int getEllipsisCount(int);
@@ -47278,12 +47287,12 @@
     method public int getLineTop(int);
     method public int getParagraphDirection(int);
     method public int getTopPadding();
-    method public static android.text.BoringLayout.Metrics isBoring(CharSequence, android.text.TextPaint);
-    method public static android.text.BoringLayout.Metrics isBoring(CharSequence, android.text.TextPaint, android.text.BoringLayout.Metrics);
-    method @Nullable public static android.text.BoringLayout.Metrics isBoring(@NonNull CharSequence, @NonNull android.text.TextPaint, @NonNull android.text.TextDirectionHeuristic, boolean, @Nullable android.text.BoringLayout.Metrics);
-    method public static android.text.BoringLayout make(CharSequence, android.text.TextPaint, int, android.text.Layout.Alignment, float, float, android.text.BoringLayout.Metrics, boolean);
-    method public static android.text.BoringLayout make(CharSequence, android.text.TextPaint, int, android.text.Layout.Alignment, float, float, android.text.BoringLayout.Metrics, boolean, android.text.TextUtils.TruncateAt, int);
-    method @NonNull public static android.text.BoringLayout make(@NonNull CharSequence, @NonNull android.text.TextPaint, @IntRange(from=0) int, @NonNull android.text.Layout.Alignment, @NonNull android.text.BoringLayout.Metrics, boolean, @Nullable android.text.TextUtils.TruncateAt, @IntRange(from=0) int, boolean);
+    method @Deprecated public static android.text.BoringLayout.Metrics isBoring(CharSequence, android.text.TextPaint);
+    method @Deprecated public static android.text.BoringLayout.Metrics isBoring(CharSequence, android.text.TextPaint, android.text.BoringLayout.Metrics);
+    method @Deprecated @Nullable public static android.text.BoringLayout.Metrics isBoring(@NonNull CharSequence, @NonNull android.text.TextPaint, @NonNull android.text.TextDirectionHeuristic, boolean, @Nullable android.text.BoringLayout.Metrics);
+    method @Deprecated public static android.text.BoringLayout make(CharSequence, android.text.TextPaint, int, android.text.Layout.Alignment, float, float, android.text.BoringLayout.Metrics, boolean);
+    method @Deprecated public static android.text.BoringLayout make(CharSequence, android.text.TextPaint, int, android.text.Layout.Alignment, float, float, android.text.BoringLayout.Metrics, boolean, android.text.TextUtils.TruncateAt, int);
+    method @Deprecated @NonNull public static android.text.BoringLayout make(@NonNull CharSequence, @NonNull android.text.TextPaint, @IntRange(from=0) int, @NonNull android.text.Layout.Alignment, @NonNull android.text.BoringLayout.Metrics, boolean, @Nullable android.text.TextUtils.TruncateAt, @IntRange(from=0) int, boolean);
     method public android.text.BoringLayout replaceOrMake(CharSequence, android.text.TextPaint, int, android.text.Layout.Alignment, float, float, android.text.BoringLayout.Metrics, boolean);
     method @NonNull public android.text.BoringLayout replaceOrMake(@NonNull CharSequence, @NonNull android.text.TextPaint, @IntRange(from=0) int, @NonNull android.text.Layout.Alignment, @NonNull android.text.BoringLayout.Metrics, boolean, @Nullable android.text.TextUtils.TruncateAt, @IntRange(from=0) int, boolean);
     method public android.text.BoringLayout replaceOrMake(CharSequence, android.text.TextPaint, int, android.text.Layout.Alignment, float, float, android.text.BoringLayout.Metrics, boolean, android.text.TextUtils.TruncateAt, int);
@@ -47308,7 +47317,6 @@
     method public int getBottomPadding();
     method public int getEllipsisCount(int);
     method public int getEllipsisStart(int);
-    method @NonNull public android.graphics.text.LineBreakConfig getLineBreakConfig();
     method public boolean getLineContainsTab(int);
     method public int getLineCount();
     method public int getLineDescent(int);
@@ -47481,20 +47489,26 @@
     method public void drawBackground(@NonNull android.graphics.Canvas);
     method public void drawText(@NonNull android.graphics.Canvas);
     method public void fillCharacterBounds(@IntRange(from=0) int, @IntRange(from=0) int, @NonNull float[], @IntRange(from=0) int);
-    method public final android.text.Layout.Alignment getAlignment();
+    method @NonNull public final android.text.Layout.Alignment getAlignment();
     method public abstract int getBottomPadding();
+    method public final int getBreakStrategy();
     method public void getCursorPath(int, android.graphics.Path, CharSequence);
     method public static float getDesiredWidth(CharSequence, android.text.TextPaint);
     method public static float getDesiredWidth(CharSequence, int, int, android.text.TextPaint);
     method public abstract int getEllipsisCount(int);
     method public abstract int getEllipsisStart(int);
-    method public int getEllipsizedWidth();
+    method @Nullable public final android.text.TextUtils.TruncateAt getEllipsize();
+    method @IntRange(from=0) public int getEllipsizedWidth();
     method public int getHeight();
+    method public final int getHyphenationFrequency();
+    method public final int getJustificationMode();
+    method @Nullable public final int[] getLeftIndents();
     method public final int getLineAscent(int);
     method public final int getLineBaseline(int);
     method public final int getLineBottom(int);
     method public int getLineBottom(int, boolean);
     method public int getLineBounds(int, android.graphics.Rect);
+    method @NonNull public android.graphics.text.LineBreakConfig getLineBreakConfig();
     method public abstract boolean getLineContainsTab(int);
     method public abstract int getLineCount();
     method public abstract int getLineDescent(int);
@@ -47505,29 +47519,35 @@
     method public float getLineLeft(int);
     method public float getLineMax(int);
     method public float getLineRight(int);
+    method public final float getLineSpacingAmount();
+    method public final float getLineSpacingMultiplier();
     method public abstract int getLineStart(int);
     method public abstract int getLineTop(int);
     method public int getLineVisibleEnd(int);
     method public float getLineWidth(int);
+    method @IntRange(from=1) public final int getMaxLines();
     method public int getOffsetForHorizontal(int, float);
     method public int getOffsetToLeftOf(int);
     method public int getOffsetToRightOf(int);
-    method public final android.text.TextPaint getPaint();
+    method @NonNull public final android.text.TextPaint getPaint();
     method public final android.text.Layout.Alignment getParagraphAlignment(int);
     method public abstract int getParagraphDirection(int);
     method public final int getParagraphLeft(int);
     method public final int getParagraphRight(int);
     method public float getPrimaryHorizontal(int);
     method @Nullable public int[] getRangeForRect(@NonNull android.graphics.RectF, @NonNull android.text.SegmentFinder, @NonNull android.text.Layout.TextInclusionStrategy);
+    method @Nullable public final int[] getRightIndents();
     method public float getSecondaryHorizontal(int);
     method public void getSelectionPath(int, int, android.graphics.Path);
     method public final float getSpacingAdd();
     method public final float getSpacingMultiplier();
-    method public final CharSequence getText();
+    method @NonNull public final CharSequence getText();
+    method @NonNull public final android.text.TextDirectionHeuristic getTextDirectionHeuristic();
     method public abstract int getTopPadding();
-    method public final int getWidth();
+    method @IntRange(from=0) public final int getWidth();
     method public final void increaseWidthTo(int);
     method public boolean isFallbackLineSpacingEnabled();
+    method public final boolean isIncludeFontPadding();
     method public boolean isRtlCharAt(int);
     method protected final boolean isSpanned();
     field public static final int BREAK_STRATEGY_BALANCED = 2; // 0x2
@@ -47555,6 +47575,26 @@
     enum_constant public static final android.text.Layout.Alignment ALIGN_OPPOSITE;
   }
 
+  public static final class Layout.Builder {
+    ctor public Layout.Builder(@NonNull CharSequence, @IntRange(from=0) int, @IntRange(from=0) int, @NonNull android.text.TextPaint, @IntRange(from=0) int);
+    method @NonNull public android.text.Layout build();
+    method @NonNull public android.text.Layout.Builder setAlignment(@NonNull android.text.Layout.Alignment);
+    method @NonNull public android.text.Layout.Builder setBreakStrategy(int);
+    method @NonNull public android.text.Layout.Builder setEllipsize(@Nullable android.text.TextUtils.TruncateAt);
+    method @NonNull public android.text.Layout.Builder setEllipsizedWidth(@IntRange(from=0) int);
+    method @NonNull public android.text.Layout.Builder setFallbackLineSpacingEnabled(boolean);
+    method @NonNull public android.text.Layout.Builder setHyphenationFrequency(int);
+    method @NonNull public android.text.Layout.Builder setIncludeFontPadding(boolean);
+    method @NonNull public android.text.Layout.Builder setJustificationMode(int);
+    method @NonNull public android.text.Layout.Builder setLeftIndents(@Nullable int[]);
+    method @NonNull public android.text.Layout.Builder setLineBreakConfig(@NonNull android.graphics.text.LineBreakConfig);
+    method @NonNull public android.text.Layout.Builder setLineSpacingAmount(float);
+    method @NonNull public android.text.Layout.Builder setLineSpacingMultiplier(float);
+    method @NonNull public android.text.Layout.Builder setMaxLines(@IntRange(from=1) int);
+    method @NonNull public android.text.Layout.Builder setRightIndents(@Nullable int[]);
+    method @NonNull public android.text.Layout.Builder setTextDirectionHeuristic(@NonNull android.text.TextDirectionHeuristic);
+  }
+
   public static class Layout.Directions {
   }
 
diff --git a/core/api/module-lib-current.txt b/core/api/module-lib-current.txt
index cda9ae3..b1feb41 100644
--- a/core/api/module-lib-current.txt
+++ b/core/api/module-lib-current.txt
@@ -15,6 +15,7 @@
 
   @UiContext public class Activity extends android.view.ContextThemeWrapper implements android.content.ComponentCallbacks2 android.view.KeyEvent.Callback android.view.LayoutInflater.Factory2 android.view.View.OnCreateContextMenuListener android.view.Window.Callback {
     method public final boolean addDumpable(@NonNull android.util.Dumpable);
+    method public final boolean isResumed();
   }
 
   public class ActivityManager {
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index a02fd84..6141583 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -6276,11 +6276,13 @@
   }
 
   public final class GnssMeasurementRequest implements android.os.Parcelable {
+    method @NonNull public android.os.WorkSource getWorkSource();
     method public boolean isCorrelationVectorOutputsEnabled();
   }
 
   public static final class GnssMeasurementRequest.Builder {
     method @NonNull public android.location.GnssMeasurementRequest.Builder setCorrelationVectorOutputsEnabled(boolean);
+    method @NonNull @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS) public android.location.GnssMeasurementRequest.Builder setWorkSource(@Nullable android.os.WorkSource);
   }
 
   public final class GnssReflectingPlane implements android.os.Parcelable {
@@ -10387,6 +10389,7 @@
     field public static final int BUGREPORT_FLAG_USE_PREDUMPED_UI_DATA = 1; // 0x1
     field public static final int BUGREPORT_MODE_FULL = 0; // 0x0
     field public static final int BUGREPORT_MODE_INTERACTIVE = 1; // 0x1
+    field public static final int BUGREPORT_MODE_ONBOARDING = 7; // 0x7
     field public static final int BUGREPORT_MODE_REMOTE = 2; // 0x2
     field public static final int BUGREPORT_MODE_TELEPHONY = 4; // 0x4
     field public static final int BUGREPORT_MODE_WEAR = 3; // 0x3
@@ -10748,7 +10751,7 @@
     field @RequiresPermission(android.Manifest.permission.MANAGE_LOW_POWER_STANDBY) public static final String ACTION_LOW_POWER_STANDBY_PORTS_CHANGED = "android.os.action.LOW_POWER_STANDBY_PORTS_CHANGED";
     field public static final int POWER_SAVE_MODE_TRIGGER_DYNAMIC = 1; // 0x1
     field public static final int POWER_SAVE_MODE_TRIGGER_PERCENTAGE = 0; // 0x0
-    field public static final String REBOOT_USERSPACE = "userspace";
+    field @Deprecated public static final String REBOOT_USERSPACE = "userspace";
     field public static final int SOUND_TRIGGER_MODE_ALL_DISABLED = 2; // 0x2
     field public static final int SOUND_TRIGGER_MODE_ALL_ENABLED = 0; // 0x0
     field public static final int SOUND_TRIGGER_MODE_CRITICAL_ONLY = 1; // 0x1
diff --git a/core/api/test-current.txt b/core/api/test-current.txt
index 833d9c6..e61c39f 100644
--- a/core/api/test-current.txt
+++ b/core/api/test-current.txt
@@ -2358,6 +2358,7 @@
   public final class PowerManager {
     method public boolean areAutoPowerSaveModesEnabled();
     method @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_LOW_POWER_STANDBY, android.Manifest.permission.DEVICE_POWER}) public void forceLowPowerStandbyActive(boolean);
+    method public boolean isBatterySaverSupported();
     field public static final String ACTION_ENHANCED_DISCHARGE_PREDICTION_CHANGED = "android.os.action.ENHANCED_DISCHARGE_PREDICTION_CHANGED";
     field @RequiresPermission(android.Manifest.permission.DEVICE_POWER) public static final int SYSTEM_WAKELOCK = -2147483648; // 0x80000000
   }
@@ -3285,6 +3286,9 @@
     field @Deprecated protected int mCapabilities;
   }
 
+  public static class MmTelFeature.MmTelCapabilities extends android.telephony.ims.feature.ImsFeature.Capabilities {
+  }
+
 }
 
 package android.text {
@@ -3864,15 +3868,21 @@
   public final class InputMethodManager {
     method @RequiresPermission(android.Manifest.permission.TEST_INPUT_METHOD) public void addVirtualStylusIdForTestSession();
     method public int getDisplayId();
+    method @NonNull @RequiresPermission(value=android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, conditional=true) public java.util.List<android.view.inputmethod.InputMethodInfo> getEnabledInputMethodListAsUser(@NonNull android.os.UserHandle);
+    method @NonNull @RequiresPermission(value=android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, conditional=true) public java.util.List<android.view.inputmethod.InputMethodSubtype> getEnabledInputMethodSubtypeListAsUser(@NonNull String, boolean, @NonNull android.os.UserHandle);
     method @NonNull @RequiresPermission(value=android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, conditional=true) public java.util.List<android.view.inputmethod.InputMethodInfo> getInputMethodListAsUser(int);
     method public boolean hasActiveInputConnection(@Nullable android.view.View);
     method @RequiresPermission(android.Manifest.permission.TEST_INPUT_METHOD) public boolean hasPendingImeVisibilityRequests();
     method @RequiresPermission(android.Manifest.permission.TEST_INPUT_METHOD) public boolean isCurrentRootView(@NonNull android.view.View);
     method @RequiresPermission(android.Manifest.permission.TEST_INPUT_METHOD) public boolean isInputMethodPickerShown();
+    method @NonNull @RequiresPermission(value=android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, conditional=true) public boolean isStylusHandwritingAvailableAsUser(@NonNull android.os.UserHandle);
     method @RequiresPermission(android.Manifest.permission.TEST_INPUT_METHOD) public void setStylusWindowIdleTimeoutForTest(long);
     field public static final long CLEAR_SHOW_FORCED_FLAG_WHEN_LEAVING = 214016041L; // 0xcc1a029L
   }
 
+  public final class InsertModeGesture extends android.view.inputmethod.CancellableHandwritingGesture implements android.os.Parcelable {
+  }
+
 }
 
 package android.view.inspector {
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index a5acf03..a366464 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -2049,7 +2049,7 @@
      * indicator that the activity became active and ready to receive input. This sometimes could
      * also be a transit state toward another resting state. For instance, an activity may be
      * relaunched to {@link #onPause} due to configuration changes and the activity was visible,
-     * but wasn’t the top-most activity of an activity task. {@link #onResume} is guaranteed to be
+     * but wasn't the top-most activity of an activity task. {@link #onResume} is guaranteed to be
      * called before {@link #onPause} in this case which honors the activity lifecycle policy and
      * the activity eventually rests in {@link #onPause}.
      *
@@ -9063,6 +9063,7 @@
      * @hide
      */
     @UnsupportedAppUsage
+    @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
     public final boolean isResumed() {
         return mResumed;
     }
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index a09d7dc..cc716ec 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -34,7 +34,6 @@
 import static android.window.ConfigurationHelper.freeTextLayoutCachesIfNeeded;
 import static android.window.ConfigurationHelper.isDifferentDisplay;
 import static android.window.ConfigurationHelper.shouldUpdateResources;
-import static android.window.ConfigurationHelper.shouldUpdateWindowMetricsBounds;
 
 import static com.android.internal.annotations.VisibleForTesting.Visibility.PACKAGE;
 import static com.android.internal.os.SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL;
@@ -6163,11 +6162,6 @@
     public static boolean shouldReportChange(@Nullable Configuration currentConfig,
             @NonNull Configuration newConfig, @Nullable SizeConfigurationBuckets sizeBuckets,
             int handledConfigChanges, boolean alwaysReportChange) {
-        // Always report changes in window configuration bounds
-        if (shouldUpdateWindowMetricsBounds(currentConfig, newConfig)) {
-            return true;
-        }
-
         final int publicDiff = currentConfig.diffPublicOnly(newConfig);
         // Don't report the change if there's no public diff between current and new config.
         if (publicDiff == 0) {
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index 9121cf0..0255860 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -179,6 +179,10 @@
     @GuardedBy("mDelegates")
     private final ArrayList<MoveCallbackDelegate> mDelegates = new ArrayList<>();
 
+    @NonNull
+    @GuardedBy("mPackageMonitorCallbacks")
+    private final ArraySet<IRemoteCallback> mPackageMonitorCallbacks = new ArraySet<>();
+
     UserManager getUserManager() {
         if (mUserManager == null) {
             mUserManager = UserManager.get(mContext);
@@ -2872,16 +2876,25 @@
         final SuspendDialogInfo dialogInfo = !TextUtils.isEmpty(dialogMessage)
                 ? new SuspendDialogInfo.Builder().setMessage(dialogMessage).build()
                 : null;
-        return setPackagesSuspended(packageNames, suspended, appExtras, launcherExtras, dialogInfo);
+        return setPackagesSuspended(packageNames, suspended, appExtras, launcherExtras,
+                dialogInfo, 0);
     }
 
     @Override
     public String[] setPackagesSuspended(String[] packageNames, boolean suspended,
             PersistableBundle appExtras, PersistableBundle launcherExtras,
             SuspendDialogInfo dialogInfo) {
+        return setPackagesSuspended(packageNames, suspended, appExtras, launcherExtras,
+                dialogInfo, 0);
+    }
+
+    @Override
+    public String[] setPackagesSuspended(String[] packageNames, boolean suspended,
+            PersistableBundle appExtras, PersistableBundle launcherExtras,
+            SuspendDialogInfo dialogInfo, int flags) {
         try {
             return mPM.setPackagesSuspendedAsUser(packageNames, suspended, appExtras,
-                    launcherExtras, dialogInfo, mContext.getOpPackageName(),
+                    launcherExtras, dialogInfo, flags, mContext.getOpPackageName(),
                     getUserId());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
@@ -3926,6 +3939,14 @@
         Objects.requireNonNull(callback);
         try {
             mPM.registerPackageMonitorCallback(callback, userId);
+            synchronized (mPackageMonitorCallbacks) {
+                if (mPackageMonitorCallbacks.contains(callback)) {
+                    throw new IllegalStateException(
+                            "registerPackageMonitorCallback: callback already registered: "
+                                    + callback);
+                }
+                mPackageMonitorCallbacks.add(callback);
+            }
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
@@ -3936,6 +3957,9 @@
         Objects.requireNonNull(callback);
         try {
             mPM.unregisterPackageMonitorCallback(callback);
+            synchronized (mPackageMonitorCallbacks) {
+                mPackageMonitorCallbacks.remove(callback);
+            }
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
diff --git a/core/java/android/app/Dialog.java b/core/java/android/app/Dialog.java
index 4851279..d0d76a4 100644
--- a/core/java/android/app/Dialog.java
+++ b/core/java/android/app/Dialog.java
@@ -454,12 +454,11 @@
      */
     protected void onStart() {
         if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
-        if (mContext != null
+        if (allowsRegisterDefaultOnBackInvokedCallback() && mContext != null
                 && WindowOnBackInvokedDispatcher.isOnBackInvokedCallbackEnabled(mContext)) {
             // Add onBackPressed as default back behavior.
             mDefaultBackCallback = this::onBackPressed;
             getOnBackInvokedDispatcher().registerSystemOnBackInvokedCallback(mDefaultBackCallback);
-            mDefaultBackCallback = null;
         }
     }
 
@@ -470,9 +469,18 @@
         if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
         if (mDefaultBackCallback != null) {
             getOnBackInvokedDispatcher().unregisterOnBackInvokedCallback(mDefaultBackCallback);
+            mDefaultBackCallback = null;
         }
     }
 
+    /**
+     * Whether this dialog allows to register the default onBackInvokedCallback.
+     * @hide
+     */
+    protected boolean allowsRegisterDefaultOnBackInvokedCallback() {
+        return true;
+    }
+
     private static final String DIALOG_SHOWING_TAG = "android:dialogShowing";
     private static final String DIALOG_HIERARCHY_TAG = "android:dialogHierarchy";
 
@@ -697,7 +705,8 @@
         if (event.isTracking() && !event.isCanceled()) {
             switch (keyCode) {
                 case KeyEvent.KEYCODE_BACK:
-                    if (!WindowOnBackInvokedDispatcher.isOnBackInvokedCallbackEnabled(mContext)) {
+                    if (!WindowOnBackInvokedDispatcher.isOnBackInvokedCallbackEnabled(mContext)
+                            || !allowsRegisterDefaultOnBackInvokedCallback()) {
                         onBackPressed();
                         return true;
                     }
diff --git a/core/java/android/app/IWindowToken.aidl b/core/java/android/app/IWindowToken.aidl
deleted file mode 100644
index 3627b0f..0000000
--- a/core/java/android/app/IWindowToken.aidl
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- ** Copyright 2020, The Android Open Source Project
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT WARRANTIES 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.res.Configuration;
-import android.view.IWindow;
-
-/**
- * Callback to receive configuration changes from {@link com.android.server.WindowToken}.
- * WindowToken can be regarded to as a group of {@link android.view.IWindow} added from the same
- * visual context, such as {@link Activity} or one created with
- * {@link android.content.Context#createWindowContext(int)}. When WindowToken receives configuration
- * changes and/or when it is moved between displays, it will propagate the changes to client side
- * via this interface.
- * @see android.content.Context#createWindowContext(int)
- * {@hide}
- */
-oneway interface IWindowToken {
-    void onConfigurationChanged(in Configuration newConfig, int newDisplayId);
-
-    void onWindowTokenRemoved();
-}
diff --git a/core/java/android/app/LocaleConfig.java b/core/java/android/app/LocaleConfig.java
index 0857c96..729e555 100644
--- a/core/java/android/app/LocaleConfig.java
+++ b/core/java/android/app/LocaleConfig.java
@@ -40,7 +40,7 @@
 import java.lang.annotation.RetentionPolicy;
 import java.util.Arrays;
 import java.util.Collections;
-import java.util.LinkedHashSet;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Locale;
 import java.util.Set;
@@ -195,8 +195,7 @@
         XmlUtils.beginDocument(parser, TAG_LOCALE_CONFIG);
         int outerDepth = parser.getDepth();
         AttributeSet attrs = Xml.asAttributeSet(parser);
-        // LinkedHashSet to preserve insertion order
-        Set<String> localeNames = new LinkedHashSet<>();
+        Set<String> localeNames = new HashSet<String>();
         while (XmlUtils.nextElementWithin(parser, outerDepth)) {
             if (TAG_LOCALE.equals(parser.getName())) {
                 final TypedArray attributes = res.obtainAttributes(
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 892b45e..6cad578 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -1628,6 +1628,14 @@
      */
     public static final int GROUP_ALERT_CHILDREN = 2;
 
+    /**
+     * Constant for the {@link Builder#setGroup(String) group key} that is added to notifications
+     * that are not already grouped when {@link Builder#setSilent()} is used.
+     *
+     * @hide
+     */
+    public static final String GROUP_KEY_SILENT = "silent";
+
     private int mGroupAlertBehavior = GROUP_ALERT_ALL;
 
     /**
@@ -4290,6 +4298,35 @@
         }
 
         /**
+         * If {@code true}, silences this instance of the notification, regardless of the sounds or
+         * vibrations set on the notification or notification channel. If {@code false}, then the
+         * normal sound and vibration logic applies.
+         *
+         * @hide
+         */
+        public @NonNull Builder setSilent(boolean silent) {
+            if (!silent) {
+                return this;
+            }
+            if (mN.isGroupSummary()) {
+                setGroupAlertBehavior(GROUP_ALERT_CHILDREN);
+            } else {
+                setGroupAlertBehavior(GROUP_ALERT_SUMMARY);
+            }
+
+            setVibrate(null);
+            setSound(null);
+            mN.defaults &= ~DEFAULT_SOUND;
+            mN.defaults &= ~DEFAULT_VIBRATE;
+            setDefaults(mN.defaults);
+
+            if (TextUtils.isEmpty(mN.mGroupKey)) {
+                setGroup(GROUP_KEY_SILENT);
+            }
+            return this;
+        }
+
+        /**
          * Set the first line of text in the platform notification template.
          */
         @NonNull
@@ -12819,7 +12856,6 @@
                 } else {
                     mBackgroundColor = rawColor;
                 }
-                mProtectionColor = COLOR_INVALID;  // filled in at the end
                 mPrimaryTextColor = ContrastColorUtil.findAlphaToMeetContrast(
                         ContrastColorUtil.resolvePrimaryColor(ctx, mBackgroundColor, nightMode),
                         mBackgroundColor, 4.5);
@@ -12836,7 +12872,6 @@
             } else {
                 int[] attrs = {
                         R.attr.colorSurface,
-                        R.attr.colorBackgroundFloating,
                         R.attr.textColorPrimary,
                         R.attr.textColorSecondary,
                         R.attr.colorAccent,
@@ -12848,15 +12883,14 @@
                 };
                 try (TypedArray ta = obtainDayNightAttributes(ctx, attrs)) {
                     mBackgroundColor = getColor(ta, 0, nightMode ? Color.BLACK : Color.WHITE);
-                    mProtectionColor = getColor(ta, 1, COLOR_INVALID);
-                    mPrimaryTextColor = getColor(ta, 2, COLOR_INVALID);
-                    mSecondaryTextColor = getColor(ta, 3, COLOR_INVALID);
-                    mPrimaryAccentColor = getColor(ta, 4, COLOR_INVALID);
-                    mSecondaryAccentColor = getColor(ta, 5, COLOR_INVALID);
-                    mTertiaryAccentColor = getColor(ta, 6, COLOR_INVALID);
-                    mOnAccentTextColor = getColor(ta, 7, COLOR_INVALID);
-                    mErrorColor = getColor(ta, 8, COLOR_INVALID);
-                    mRippleAlpha = Color.alpha(getColor(ta, 9, 0x33ffffff));
+                    mPrimaryTextColor = getColor(ta, 1, COLOR_INVALID);
+                    mSecondaryTextColor = getColor(ta, 2, COLOR_INVALID);
+                    mPrimaryAccentColor = getColor(ta, 3, COLOR_INVALID);
+                    mSecondaryAccentColor = getColor(ta, 4, COLOR_INVALID);
+                    mTertiaryAccentColor = getColor(ta, 5, COLOR_INVALID);
+                    mOnAccentTextColor = getColor(ta, 6, COLOR_INVALID);
+                    mErrorColor = getColor(ta, 7, COLOR_INVALID);
+                    mRippleAlpha = Color.alpha(getColor(ta, 8, 0x33ffffff));
                 }
                 mContrastColor = calculateContrastColor(ctx, rawColor, mPrimaryAccentColor,
                         mBackgroundColor, nightMode);
@@ -12889,9 +12923,7 @@
                 }
             }
             // make sure every color has a valid value
-            if (mProtectionColor == COLOR_INVALID) {
-                mProtectionColor = ColorUtils.blendARGB(mPrimaryTextColor, mBackgroundColor, 0.8f);
-            }
+            mProtectionColor = ColorUtils.blendARGB(mPrimaryTextColor, mBackgroundColor, 0.9f);
         }
 
         /** calculates the contrast color for the non-colorized notifications */
diff --git a/core/java/android/app/NotificationChannel.java b/core/java/android/app/NotificationChannel.java
index d8cedb8..7ee1332 100644
--- a/core/java/android/app/NotificationChannel.java
+++ b/core/java/android/app/NotificationChannel.java
@@ -26,12 +26,14 @@
 import android.content.Intent;
 import android.content.pm.ShortcutInfo;
 import android.media.AudioAttributes;
+import android.media.RingtoneManager;
 import android.net.Uri;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.provider.Settings;
 import android.service.notification.NotificationListenerService;
 import android.text.TextUtils;
+import android.util.Log;
 import android.util.proto.ProtoOutputStream;
 
 import com.android.internal.util.Preconditions;
@@ -54,6 +56,7 @@
  * A representation of settings that apply to a collection of similarly themed notifications.
  */
 public final class NotificationChannel implements Parcelable {
+    private static final String TAG = "NotificationChannel";
 
     /**
      * The id of the default channel for an app. This id is reserved by the system. All
@@ -959,8 +962,11 @@
         setLockscreenVisibility(safeInt(parser, ATT_VISIBILITY, DEFAULT_VISIBILITY));
 
         Uri sound = safeUri(parser, ATT_SOUND);
-        setSound(forRestore ? restoreSoundUri(context, sound, pkgInstalled) : sound,
-                safeAudioAttributes(parser));
+
+        final AudioAttributes audioAttributes = safeAudioAttributes(parser);
+        final int usage = audioAttributes.getUsage();
+        setSound(forRestore ? restoreSoundUri(context, sound, pkgInstalled, usage) : sound,
+                audioAttributes);
 
         enableLights(safeBool(parser, ATT_LIGHTS, false));
         setLightColor(safeInt(parser, ATT_LIGHT_COLOR, DEFAULT_LIGHT_COLOR));
@@ -1010,18 +1016,34 @@
         if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
             return uri;
         }
-
         return contentResolver.canonicalize(uri);
     }
 
     @Nullable
-    private Uri getUncanonicalizedSoundUri(ContentResolver contentResolver, @NonNull Uri uri) {
+    private Uri getUncanonicalizedSoundUri(
+            ContentResolver contentResolver, @NonNull Uri uri, int usage) {
         if (Settings.System.DEFAULT_NOTIFICATION_URI.equals(uri)
                 || ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri.getScheme())
                 || ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
             return uri;
         }
-        return contentResolver.uncanonicalize(uri);
+        int ringtoneType = 0;
+
+        // Consistent with UI(SoundPreferenceController.handlePreferenceTreeClick).
+        if (AudioAttributes.USAGE_ALARM == usage) {
+            ringtoneType = RingtoneManager.TYPE_ALARM;
+        } else if (AudioAttributes.USAGE_NOTIFICATION_RINGTONE == usage) {
+            ringtoneType = RingtoneManager.TYPE_RINGTONE;
+        } else {
+            ringtoneType = RingtoneManager.TYPE_NOTIFICATION;
+        }
+        try {
+            return RingtoneManager.getRingtoneUriForRestore(
+                    contentResolver, uri.toString(), ringtoneType);
+        } catch (Exception e) {
+            Log.e(TAG, "Failed to uncanonicalized sound uri for " + uri + " " + e);
+            return Settings.System.DEFAULT_NOTIFICATION_URI;
+        }
     }
 
     /**
@@ -1033,7 +1055,8 @@
      * @hide
      */
     @Nullable
-    public Uri restoreSoundUri(Context context, @Nullable Uri uri, boolean pkgInstalled) {
+    public Uri restoreSoundUri(
+            Context context, @Nullable Uri uri, boolean pkgInstalled, int usage) {
         if (uri == null || Uri.EMPTY.equals(uri)) {
             return null;
         }
@@ -1060,7 +1083,7 @@
             }
         }
         mSoundRestored = true;
-        return getUncanonicalizedSoundUri(contentResolver, canonicalizedUri);
+        return getUncanonicalizedSoundUri(contentResolver, canonicalizedUri, usage);
     }
 
     /**
diff --git a/core/java/android/app/SharedPreferencesImpl.java b/core/java/android/app/SharedPreferencesImpl.java
index 1ebf565..a87187b 100644
--- a/core/java/android/app/SharedPreferencesImpl.java
+++ b/core/java/android/app/SharedPreferencesImpl.java
@@ -55,6 +55,11 @@
 import java.util.Set;
 import java.util.WeakHashMap;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
 
 final class SharedPreferencesImpl implements SharedPreferences {
     private static final String TAG = "SharedPreferencesImpl";
@@ -119,6 +124,10 @@
     private final ExponentiallyBucketedHistogram mSyncTimes = new ExponentiallyBucketedHistogram(16);
     private int mNumSync = 0;
 
+    private static final ThreadPoolExecutor sLoadExecutor = new ThreadPoolExecutor(0, 1, 10L,
+            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
+            new SharedPreferencesThreadFactory());
+
     @UnsupportedAppUsage
     SharedPreferencesImpl(File file, int mode) {
         mFile = file;
@@ -135,11 +144,10 @@
         synchronized (mLock) {
             mLoaded = false;
         }
-        new Thread("SharedPreferencesImpl-load") {
-            public void run() {
-                loadFromDisk();
-            }
-        }.start();
+
+        sLoadExecutor.execute(() -> {
+            loadFromDisk();
+        });
     }
 
     private void loadFromDisk() {
@@ -874,4 +882,14 @@
         }
         mcr.setDiskWriteResult(false, false);
     }
+
+
+    private static final class SharedPreferencesThreadFactory implements ThreadFactory {
+        @Override
+        public Thread newThread(Runnable runnable) {
+            Thread thread = Executors.defaultThreadFactory().newThread(runnable);
+            thread.setName("SharedPreferences");
+            return thread;
+        }
+    }
 }
diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java
index 8647dd2..e578499 100644
--- a/core/java/android/app/SystemServiceRegistry.java
+++ b/core/java/android/app/SystemServiceRegistry.java
@@ -237,8 +237,6 @@
 import android.view.contentcapture.IContentCaptureManager;
 import android.view.displayhash.DisplayHashManager;
 import android.view.inputmethod.InputMethodManager;
-import android.view.selectiontoolbar.ISelectionToolbarManager;
-import android.view.selectiontoolbar.SelectionToolbarManager;
 import android.view.textclassifier.TextClassificationManager;
 import android.view.textservice.TextServicesManager;
 import android.view.translation.ITranslationManager;
@@ -379,17 +377,6 @@
                 return new TextClassificationManager(ctx);
             }});
 
-        registerService(Context.SELECTION_TOOLBAR_SERVICE, SelectionToolbarManager.class,
-                new CachedServiceFetcher<SelectionToolbarManager>() {
-                    @Override
-                    public SelectionToolbarManager createService(ContextImpl ctx)
-                            throws ServiceNotFoundException {
-                        IBinder b = ServiceManager.getServiceOrThrow(
-                                Context.SELECTION_TOOLBAR_SERVICE);
-                        return new SelectionToolbarManager(ctx.getOuterContext(),
-                                ISelectionToolbarManager.Stub.asInterface(b));
-                    }});
-
         registerService(Context.FONT_SERVICE, FontManager.class,
                 new CachedServiceFetcher<FontManager>() {
             @Override
diff --git a/core/java/android/app/TaskInfo.java b/core/java/android/app/TaskInfo.java
index 2b5175c..634089b 100644
--- a/core/java/android/app/TaskInfo.java
+++ b/core/java/android/app/TaskInfo.java
@@ -248,6 +248,13 @@
     public boolean topActivityEligibleForUserAspectRatioButton;
 
     /**
+     * Whether the user has forced the activity to be fullscreen through the user aspect ratio
+     * settings.
+     * @hide
+     */
+    public boolean isUserFullscreenOverrideEnabled;
+
+    /**
      * Hint about the letterbox state of the top activity.
      * @hide
      */
@@ -543,7 +550,8 @@
                 && isSleeping == that.isSleeping
                 && Objects.equals(mTopActivityLocusId, that.mTopActivityLocusId)
                 && parentTaskId == that.parentTaskId
-                && Objects.equals(topActivity, that.topActivity);
+                && Objects.equals(topActivity, that.topActivity)
+                && isUserFullscreenOverrideEnabled == that.isUserFullscreenOverrideEnabled;
     }
 
     /**
@@ -574,7 +582,8 @@
                 && (!hasCompatUI() || configuration.getLayoutDirection()
                     == that.configuration.getLayoutDirection())
                 && (!hasCompatUI() || configuration.uiMode == that.configuration.uiMode)
-                && (!hasCompatUI() || isVisible == that.isVisible);
+                && (!hasCompatUI() || isVisible == that.isVisible)
+                && isUserFullscreenOverrideEnabled == that.isUserFullscreenOverrideEnabled;
     }
 
     /**
@@ -630,6 +639,7 @@
         topActivityLetterboxHorizontalPosition = source.readInt();
         topActivityLetterboxWidth = source.readInt();
         topActivityLetterboxHeight = source.readInt();
+        isUserFullscreenOverrideEnabled = source.readBoolean();
     }
 
     /**
@@ -686,6 +696,7 @@
         dest.writeInt(topActivityLetterboxHorizontalPosition);
         dest.writeInt(topActivityLetterboxWidth);
         dest.writeInt(topActivityLetterboxHeight);
+        dest.writeBoolean(isUserFullscreenOverrideEnabled);
     }
 
     @Override
@@ -732,6 +743,7 @@
                         + topActivityLetterboxHorizontalPosition
                 + " topActivityLetterboxWidth=" + topActivityLetterboxWidth
                 + " topActivityLetterboxHeight=" + topActivityLetterboxHeight
+                + " isUserFullscreenOverrideEnabled=" + isUserFullscreenOverrideEnabled
                 + " locusId=" + mTopActivityLocusId
                 + " displayAreaFeatureId=" + displayAreaFeatureId
                 + " cameraCompatControlState="
diff --git a/core/java/android/app/UiAutomation.java b/core/java/android/app/UiAutomation.java
index b0180c1..b0edc3d 100644
--- a/core/java/android/app/UiAutomation.java
+++ b/core/java/android/app/UiAutomation.java
@@ -1206,12 +1206,14 @@
             return null;
         }
 
-        final ScreenshotHardwareBuffer screenshotBuffer =
-                syncScreenCapture.getBuffer();
+        final ScreenshotHardwareBuffer screenshotBuffer = syncScreenCapture.getBuffer();
+        if (screenshotBuffer == null) {
+            Log.e(LOG_TAG, "Failed to take screenshot for display=" + mDisplayId);
+            return null;
+        }
         Bitmap screenShot = screenshotBuffer.asBitmap();
         if (screenShot == null) {
-            Log.e(LOG_TAG, "mUiAutomationConnection.takeScreenshot() returned null for display "
-                    + mDisplayId);
+            Log.e(LOG_TAG, "Failed to take screenshot for display=" + mDisplayId);
             return null;
         }
         Bitmap swBitmap;
@@ -1263,16 +1265,23 @@
                 ScreenCapture.createSyncCaptureListener();
         try {
             if (!mUiAutomationConnection.takeSurfaceControlScreenshot(sc, syncScreenCapture)) {
+                Log.e(LOG_TAG, "Failed to take screenshot for window=" + window);
                 return null;
             }
-
         } catch (RemoteException re) {
             Log.e(LOG_TAG, "Error while taking screenshot!", re);
             return null;
         }
-        ScreenCapture.ScreenshotHardwareBuffer captureBuffer =
-                syncScreenCapture.getBuffer();
+        ScreenCapture.ScreenshotHardwareBuffer captureBuffer = syncScreenCapture.getBuffer();
+        if (captureBuffer == null) {
+            Log.e(LOG_TAG, "Failed to take screenshot for window=" + window);
+            return null;
+        }
         Bitmap screenShot = captureBuffer.asBitmap();
+        if (screenShot == null) {
+            Log.e(LOG_TAG, "Failed to take screenshot for window=" + window);
+            return null;
+        }
         Bitmap swBitmap;
         try (HardwareBuffer buffer = captureBuffer.getHardwareBuffer()) {
             swBitmap = screenShot.copy(Bitmap.Config.ARGB_8888, false);
diff --git a/core/java/android/app/admin/EnterprisePlatformSecurity_OWNERS b/core/java/android/app/admin/EnterprisePlatformSecurity_OWNERS
index 270cb18..62ad8c0 100644
--- a/core/java/android/app/admin/EnterprisePlatformSecurity_OWNERS
+++ b/core/java/android/app/admin/EnterprisePlatformSecurity_OWNERS
@@ -1,4 +1,3 @@
+file:EnterprisePlatform_OWNERS
 rubinxu@google.com
 pgrafov@google.com
-ayushsha@google.com
-alexkershaw@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
diff --git a/core/java/android/app/admin/EnterprisePlatformTest_OWNERS b/core/java/android/app/admin/EnterprisePlatformTest_OWNERS
new file mode 100644
index 0000000..eb23a03
--- /dev/null
+++ b/core/java/android/app/admin/EnterprisePlatformTest_OWNERS
@@ -0,0 +1,5 @@
+# Bug template url: https://b.corp.google.com/issues/new?component=1337891&template=1814288
+# Assign bugs to aep-automated-tests@google.com
+
+file:EnterprisePlatform_OWNERS
+scottjonathan@google.com
\ No newline at end of file
diff --git a/core/java/android/app/admin/EnterprisePlatform_OWNERS b/core/java/android/app/admin/EnterprisePlatform_OWNERS
index 6ce25cc..4d1ed590 100644
--- a/core/java/android/app/admin/EnterprisePlatform_OWNERS
+++ b/core/java/android/app/admin/EnterprisePlatform_OWNERS
@@ -1,5 +1,2 @@
-# Assign bugs to android-enterprise-triage@google.com
-file:WorkDeviceExperience_OWNERS
-file:Provisioning_OWNERS
-file:WorkProfile_OWNERS
-file:EnterprisePlatformSecurity_OWNERS
\ No newline at end of file
+sandness@google.com #{LAST_RESORT_SUGGESTION}
+scottjonathan@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
diff --git a/core/java/android/app/admin/OWNERS b/core/java/android/app/admin/OWNERS
index 10a5f14..308f1d6 100644
--- a/core/java/android/app/admin/OWNERS
+++ b/core/java/android/app/admin/OWNERS
@@ -1,5 +1,7 @@
 # Bug component: 142675
+# Assign bugs to device-policy-manager-triage@google.com
 
-file:EnterprisePlatform_OWNERS
+file:WorkDeviceExperience_OWNERS
+file:EnterprisePlatformSecurity_OWNERS
 
 yamasani@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
diff --git a/core/java/android/app/admin/Provisioning_OWNERS b/core/java/android/app/admin/Provisioning_OWNERS
index 2e5c2df..fa0a1f0 100644
--- a/core/java/android/app/admin/Provisioning_OWNERS
+++ b/core/java/android/app/admin/Provisioning_OWNERS
@@ -1,5 +1,4 @@
 # Assign bugs to android-enterprise-triage@google.com
 mdb.ae-provisioning-reviews@google.com
-petuska@google.com #{LAST_RESORT_SUGGESTION}
-nupursn@google.com #{LAST_RESORT_SUGGESTION}
-shreyacsingh@google.com #{LAST_RESORT_SUGGESTION}
+file:EnterprisePlatform_OWNERS
+petuska@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
diff --git a/core/java/android/app/admin/WorkDeviceExperience_OWNERS b/core/java/android/app/admin/WorkDeviceExperience_OWNERS
index 2033343..10ac59a 100644
--- a/core/java/android/app/admin/WorkDeviceExperience_OWNERS
+++ b/core/java/android/app/admin/WorkDeviceExperience_OWNERS
@@ -1,7 +1,5 @@
 # Assign bugs to android-enterprise-triage@google.com
 work-device-experience+reviews@google.com
-scottjonathan@google.com #{LAST_RESORT_SUGGESTION}
-eliselliott@google.com #{LAST_RESORT_SUGGESTION}
+file:EnterprisePlatform_OWNERS
 kholoudm@google.com #{LAST_RESORT_SUGGESTION}
 acjohnston@google.com #{LAST_RESORT_SUGGESTION}
-alexkershaw@google.com #{LAST_RESORT_SUGGESTION}
diff --git a/core/java/android/app/admin/WorkProfile_OWNERS b/core/java/android/app/admin/WorkProfile_OWNERS
index 260b672..e9bcce2 100644
--- a/core/java/android/app/admin/WorkProfile_OWNERS
+++ b/core/java/android/app/admin/WorkProfile_OWNERS
@@ -1,5 +1,3 @@
 # Assign bugs to android-enterprise-triage@google.com
-liahav@google.com
-olit@google.com
-scottjonathan@google.com #{LAST_RESORT_SUGGESTION}
-alexkershaw@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
+file:EnterprisePlatform_OWNERS
+liahav@google.com
\ No newline at end of file
diff --git a/core/java/android/app/assist/AssistStructure.java b/core/java/android/app/assist/AssistStructure.java
index b7ec7b5..d66fca8 100644
--- a/core/java/android/app/assist/AssistStructure.java
+++ b/core/java/android/app/assist/AssistStructure.java
@@ -22,6 +22,7 @@
 import android.os.RemoteException;
 import android.os.SystemClock;
 import android.service.autofill.FillRequest;
+import android.text.Spanned;
 import android.text.TextUtils;
 import android.util.Log;
 import android.util.Pair;
@@ -1557,6 +1558,10 @@
         /**
          * Returns any text associated with the node that is displayed to the user, or null
          * if there is none.
+         *
+         * <p> The text will be stripped of any spans that could potentially contain reference to
+         * the activity context, to avoid memory leak. If the text contained a span, a plain
+         * string version of the text will be returned.
          */
         @Nullable
         public CharSequence getText() {
@@ -1996,14 +2001,16 @@
         @Override
         public void setText(CharSequence text) {
             ViewNodeText t = getNodeText();
-            t.mText = TextUtils.trimNoCopySpans(text);
+            // Strip spans from the text to avoid memory leak
+            t.mText = TextUtils.trimToParcelableSize(stripAllSpansFromText(text));
             t.mTextSelectionStart = t.mTextSelectionEnd = -1;
         }
 
         @Override
         public void setText(CharSequence text, int selectionStart, int selectionEnd) {
             ViewNodeText t = getNodeText();
-            t.mText = TextUtils.trimNoCopySpans(text);
+            // Strip spans from the text to avoid memory leak
+            t.mText = stripAllSpansFromText(text);
             t.mTextSelectionStart = selectionStart;
             t.mTextSelectionEnd = selectionEnd;
         }
@@ -2222,6 +2229,13 @@
         public void setHtmlInfo(@NonNull HtmlInfo htmlInfo) {
             mNode.mHtmlInfo = htmlInfo;
         }
+
+        private CharSequence stripAllSpansFromText(CharSequence text) {
+            if (text instanceof Spanned) {
+                return text.toString();
+            }
+            return text;
+        }
     }
 
     private static final class HtmlInfoNode extends HtmlInfo implements Parcelable {
diff --git a/core/java/android/appwidget/AppWidgetManager.java b/core/java/android/appwidget/AppWidgetManager.java
index b159321..3927b40 100644
--- a/core/java/android/appwidget/AppWidgetManager.java
+++ b/core/java/android/appwidget/AppWidgetManager.java
@@ -781,7 +781,18 @@
      *
      * @param appWidgetIds  The AppWidget instances to notify of view data changes.
      * @param viewId        The collection view id.
+     * @deprecated The corresponding API
+     * {@link RemoteViews#setRemoteAdapter(int, Intent)} associated with this method has been
+     * deprecated. Moving forward please use
+     * {@link RemoteViews#setRemoteAdapter(int, android.widget.RemoteViews.RemoteCollectionItems)}
+     * instead to set {@link android.widget.RemoteViews.RemoteCollectionItems} for the remote
+     * adapter and update the widget views by calling {@link #updateAppWidget(int[], RemoteViews)},
+     * {@link #updateAppWidget(int, RemoteViews)},
+     * {@link #updateAppWidget(ComponentName, RemoteViews)},
+     * {@link #partiallyUpdateAppWidget(int[], RemoteViews)},
+     * or {@link #partiallyUpdateAppWidget(int, RemoteViews)}, whichever applicable.
      */
+    @Deprecated
     public void notifyAppWidgetViewDataChanged(int[] appWidgetIds, int viewId) {
         if (mService == null) {
             return;
@@ -817,7 +828,18 @@
      *
      * @param appWidgetId  The AppWidget instance to notify of view data changes.
      * @param viewId       The collection view id.
+     * @deprecated The corresponding API
+     * {@link RemoteViews#setRemoteAdapter(int, Intent)} associated with this method has been
+     * deprecated. Moving forward please use
+     * {@link RemoteViews#setRemoteAdapter(int, android.widget.RemoteViews.RemoteCollectionItems)}
+     * instead to set {@link android.widget.RemoteViews.RemoteCollectionItems} for the remote
+     * adapter and update the widget views by calling {@link #updateAppWidget(int[], RemoteViews)},
+     * {@link #updateAppWidget(int, RemoteViews)},
+     * {@link #updateAppWidget(ComponentName, RemoteViews)},
+     * {@link #partiallyUpdateAppWidget(int[], RemoteViews)},
+     * or {@link #partiallyUpdateAppWidget(int, RemoteViews)}, whichever applicable.
      */
+    @Deprecated
     public void notifyAppWidgetViewDataChanged(int appWidgetId, int viewId) {
         if (mService == null) {
             return;
diff --git a/core/java/android/companion/AssociationInfo.java b/core/java/android/companion/AssociationInfo.java
index 0958a806..7d62c79 100644
--- a/core/java/android/companion/AssociationInfo.java
+++ b/core/java/android/companion/AssociationInfo.java
@@ -57,6 +57,7 @@
     private final boolean mSelfManaged;
     private final boolean mNotifyOnDeviceNearby;
     private final int mSystemDataSyncFlags;
+    private final String mTag;
 
     /**
      * Indicates that the association has been revoked (removed), but we keep the association
@@ -78,10 +79,11 @@
      * @hide
      */
     public AssociationInfo(int id, @UserIdInt int userId, @NonNull String packageName,
-            @Nullable MacAddress macAddress, @Nullable CharSequence displayName,
-            @Nullable String deviceProfile, @Nullable AssociatedDevice associatedDevice,
-            boolean selfManaged, boolean notifyOnDeviceNearby, boolean revoked,
-            long timeApprovedMs, long lastTimeConnectedMs, int systemDataSyncFlags) {
+            @Nullable String tag, @Nullable MacAddress macAddress,
+            @Nullable CharSequence displayName, @Nullable String deviceProfile,
+            @Nullable AssociatedDevice associatedDevice, boolean selfManaged,
+            boolean notifyOnDeviceNearby, boolean revoked, long timeApprovedMs,
+            long lastTimeConnectedMs, int systemDataSyncFlags) {
         if (id <= 0) {
             throw new IllegalArgumentException("Association ID should be greater than 0");
         }
@@ -97,6 +99,7 @@
 
         mDeviceMacAddress = macAddress;
         mDisplayName = displayName;
+        mTag = tag;
         mDeviceProfile = deviceProfile;
         mAssociatedDevice = associatedDevice;
 
@@ -116,6 +119,14 @@
     }
 
     /**
+     * @return the tag of this association.
+     * @see CompanionDeviceManager#setAssociationTag(int, String)
+     */
+    public @Nullable String getTag() {
+        return mTag;
+    }
+
+    /**
      * @return the ID of the user who "owns" this association.
      * @hide
      */
@@ -287,6 +298,7 @@
                 + "mId=" + mId
                 + ", mUserId=" + mUserId
                 + ", mPackageName='" + mPackageName + '\''
+                + ", mTag='" + mTag + '\''
                 + ", mDeviceMacAddress=" + mDeviceMacAddress
                 + ", mDisplayName='" + mDisplayName + '\''
                 + ", mDeviceProfile='" + mDeviceProfile + '\''
@@ -315,6 +327,7 @@
                 && mTimeApprovedMs == that.mTimeApprovedMs
                 && mLastTimeConnectedMs == that.mLastTimeConnectedMs
                 && Objects.equals(mPackageName, that.mPackageName)
+                && Objects.equals(mTag, that.mTag)
                 && Objects.equals(mDeviceMacAddress, that.mDeviceMacAddress)
                 && Objects.equals(mDisplayName, that.mDisplayName)
                 && Objects.equals(mDeviceProfile, that.mDeviceProfile)
@@ -324,7 +337,7 @@
 
     @Override
     public int hashCode() {
-        return Objects.hash(mId, mUserId, mPackageName, mDeviceMacAddress, mDisplayName,
+        return Objects.hash(mId, mUserId, mPackageName, mTag, mDeviceMacAddress, mDisplayName,
                 mDeviceProfile, mAssociatedDevice, mSelfManaged, mNotifyOnDeviceNearby, mRevoked,
                 mTimeApprovedMs, mLastTimeConnectedMs, mSystemDataSyncFlags);
     }
@@ -340,6 +353,7 @@
 
         dest.writeInt(mUserId);
         dest.writeString(mPackageName);
+        dest.writeString(mTag);
 
         dest.writeTypedObject(mDeviceMacAddress, 0);
         dest.writeCharSequence(mDisplayName);
@@ -359,6 +373,7 @@
 
         mUserId = in.readInt();
         mPackageName = in.readString();
+        mTag = in.readString();
 
         mDeviceMacAddress = in.readTypedObject(MacAddress.CREATOR);
         mDisplayName = in.readCharSequence();
@@ -413,9 +428,11 @@
         private boolean mRevoked;
         private long mLastTimeConnectedMs;
         private int mSystemDataSyncFlags;
+        private String mTag;
 
         private Builder(@NonNull AssociationInfo info) {
             mOriginalInfo = info;
+            mTag = info.mTag;
             mNotifyOnDeviceNearby = info.mNotifyOnDeviceNearby;
             mRevoked = info.mRevoked;
             mLastTimeConnectedMs = info.mLastTimeConnectedMs;
@@ -460,12 +477,21 @@
         }
 
         /** @hide */
+        @Override
+        @NonNull
+        public Builder setTag(String tag) {
+            mTag = tag;
+            return this;
+        }
+
+        /** @hide */
         @NonNull
         public AssociationInfo build() {
             return new AssociationInfo(
                     mOriginalInfo.mId,
                     mOriginalInfo.mUserId,
                     mOriginalInfo.mPackageName,
+                    mTag,
                     mOriginalInfo.mDeviceMacAddress,
                     mOriginalInfo.mDisplayName,
                     mOriginalInfo.mDeviceProfile,
@@ -508,5 +534,8 @@
         /** @hide */
         @NonNull
         Builder setSystemDataSyncFlags(int flags);
+
+        /** @hide */
+        Builder setTag(String tag);
     }
 }
diff --git a/core/java/android/companion/CompanionDeviceManager.java b/core/java/android/companion/CompanionDeviceManager.java
index 69e1653..3aa2877 100644
--- a/core/java/android/companion/CompanionDeviceManager.java
+++ b/core/java/android/companion/CompanionDeviceManager.java
@@ -1372,6 +1372,50 @@
         }
     }
 
+    /**
+     * Sets the {@link AssociationInfo#getTag() tag} for this association.
+     *
+     * <p>The length of the tag must be at most 20 characters.
+     *
+     * <p>This allows to store useful information about the associated devices.
+     *
+     * @param associationId The unique {@link AssociationInfo#getId ID} assigned to the Association
+     *                          of the companion device recorded by CompanionDeviceManager
+     * @param tag the tag of this association
+     */
+    @UserHandleAware
+    public void setAssociationTag(int associationId, @NonNull String tag) {
+        Objects.requireNonNull(tag, "tag cannot be null");
+
+        if (tag.length() > 20) {
+            throw new IllegalArgumentException("Length of the tag must be at most 20 characters");
+        }
+
+        try {
+            mService.setAssociationTag(associationId, tag);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Clears the {@link AssociationInfo#getTag() tag} for this association.
+     *
+     * <p>The tag will be set to null for this association when calling this API.
+     *
+     * @param associationId The unique {@link AssociationInfo#getId ID} assigned to the Association
+     *                          of the companion device recorded by CompanionDeviceManager
+     * @see CompanionDeviceManager#setAssociationTag(int, String)
+     */
+    @UserHandleAware
+    public void clearAssociationTag(int associationId) {
+        try {
+            mService.clearAssociationTag(associationId);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
     private boolean checkFeaturePresent() {
         boolean featurePresent = mService != null;
         if (!featurePresent && DEBUG) {
diff --git a/core/java/android/companion/ICompanionDeviceManager.aidl b/core/java/android/companion/ICompanionDeviceManager.aidl
index 463dba2..a3b202a 100644
--- a/core/java/android/companion/ICompanionDeviceManager.aidl
+++ b/core/java/android/companion/ICompanionDeviceManager.aidl
@@ -115,4 +115,12 @@
 
     @EnforcePermission("MANAGE_COMPANION_DEVICES")
     void enableSecureTransport(boolean enabled);
+
+    void setAssociationTag(int associationId, String tag);
+
+    void clearAssociationTag(int associationId);
+
+    byte[] getBackupPayload(int userId);
+
+    void applyRestoredPayload(in byte[] payload, int userId);
 }
diff --git a/core/java/android/companion/virtual/IVirtualDeviceManager.aidl b/core/java/android/companion/virtual/IVirtualDeviceManager.aidl
index ee7836f..ed8484f 100644
--- a/core/java/android/companion/virtual/IVirtualDeviceManager.aidl
+++ b/core/java/android/companion/virtual/IVirtualDeviceManager.aidl
@@ -21,6 +21,7 @@
 import android.companion.virtual.IVirtualDeviceSoundEffectListener;
 import android.companion.virtual.VirtualDevice;
 import android.companion.virtual.VirtualDeviceParams;
+import android.content.AttributionSource;
 import android.hardware.display.IVirtualDisplayCallback;
 import android.hardware.display.VirtualDisplayConfig;
 
@@ -46,7 +47,7 @@
      */
     @EnforcePermission("CREATE_VIRTUAL_DEVICE")
     IVirtualDevice createVirtualDevice(
-            in IBinder token, String packageName, int associationId,
+            in IBinder token, in AttributionSource attributionSource, int associationId,
             in VirtualDeviceParams params, in IVirtualDeviceActivityListener activityListener,
             in IVirtualDeviceSoundEffectListener soundEffectListener);
 
diff --git a/core/java/android/companion/virtual/VirtualDeviceInternal.java b/core/java/android/companion/virtual/VirtualDeviceInternal.java
index f68cfff..d13bfd4 100644
--- a/core/java/android/companion/virtual/VirtualDeviceInternal.java
+++ b/core/java/android/companion/virtual/VirtualDeviceInternal.java
@@ -145,7 +145,7 @@
         mContext = context.getApplicationContext();
         mVirtualDevice = service.createVirtualDevice(
                 new Binder(),
-                mContext.getPackageName(),
+                mContext.getAttributionSource(),
                 associationId,
                 params,
                 mActivityListenerBinder,
diff --git a/core/java/android/companion/virtual/VirtualDeviceParams.java b/core/java/android/companion/virtual/VirtualDeviceParams.java
index 45d6dc6..b6d8375 100644
--- a/core/java/android/companion/virtual/VirtualDeviceParams.java
+++ b/core/java/android/companion/virtual/VirtualDeviceParams.java
@@ -43,6 +43,7 @@
 import android.util.SparseArray;
 import android.util.SparseIntArray;
 
+import java.io.PrintWriter;
 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -501,6 +502,26 @@
                 + ")";
     }
 
+    /**
+     * Dumps debugging information about the VirtualDeviceParams
+     * @hide
+     */
+    public void dump(PrintWriter pw, String prefix) {
+        pw.println(prefix + "mName=" + mName);
+        pw.println(prefix + "mLockState=" + mLockState);
+        pw.println(prefix + "mUsersWithMatchingAccounts=" + mUsersWithMatchingAccounts);
+        pw.println(prefix + "mAllowedCrossTaskNavigations=" + mAllowedCrossTaskNavigations);
+        pw.println(prefix + "mBlockedCrossTaskNavigations=" + mBlockedCrossTaskNavigations);
+        pw.println(prefix + "mAllowedActivities=" + mAllowedActivities);
+        pw.println(prefix + "mBlockedActivities=" + mBlockedActivities);
+        pw.println(prefix + "mDevicePolicies=" + mDevicePolicies);
+        pw.println(prefix + "mDefaultNavigationPolicy=" + mDefaultNavigationPolicy);
+        pw.println(prefix + "mDefaultActivityPolicy=" + mDefaultActivityPolicy);
+        pw.println(prefix + "mVirtualSensorConfigs=" + mVirtualSensorConfigs);
+        pw.println(prefix + "mAudioPlaybackSessionId=" + mAudioPlaybackSessionId);
+        pw.println(prefix + "mAudioRecordingSessionId=" + mAudioRecordingSessionId);
+    }
+
     @NonNull
     public static final Parcelable.Creator<VirtualDeviceParams> CREATOR =
             new Parcelable.Creator<VirtualDeviceParams>() {
diff --git a/core/java/android/companion/virtual/sensor/VirtualSensorConfig.java b/core/java/android/companion/virtual/sensor/VirtualSensorConfig.java
index 3bdf9aa..0dbe411 100644
--- a/core/java/android/companion/virtual/sensor/VirtualSensorConfig.java
+++ b/core/java/android/companion/virtual/sensor/VirtualSensorConfig.java
@@ -104,6 +104,11 @@
         parcel.writeInt(mFlags);
     }
 
+    @Override
+    public String toString() {
+        return "VirtualSensorConfig{" + "mType=" + mType + ", mName='" + mName + '\'' + '}';
+    }
+
     /**
      * Returns the type of the sensor.
      *
diff --git a/core/java/android/content/AttributionSource.java b/core/java/android/content/AttributionSource.java
index d0bb2b9..8f35ca2 100644
--- a/core/java/android/content/AttributionSource.java
+++ b/core/java/android/content/AttributionSource.java
@@ -517,7 +517,11 @@
     }
 
     /**
-     * The device ID for which permissions are checked.
+     * Gets the device ID for this attribution source. Attribution source can set the device ID
+     * using {@link Builder#setDeviceId(int)}, the default device ID is
+     * {@link Context#DEVICE_ID_DEFAULT}.
+     * <p>
+     * This device ID is used for permissions checking during attribution source validation.
      */
     public int getDeviceId() {
         return mAttributionSourceState.deviceId;
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index c11a8fc..5ef7b11 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -323,6 +323,7 @@
             // Make sure no flag uses the sign bit (most significant bit) of the long integer,
             // to avoid future confusion.
             BIND_BYPASS_USER_NETWORK_RESTRICTIONS,
+            BIND_FILTER_OUT_QUARANTINED_COMPONENTS,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface BindServiceFlagsLongBits {}
@@ -697,6 +698,13 @@
      */
     public static final long BIND_BYPASS_USER_NETWORK_RESTRICTIONS = 0x1_0000_0000L;
 
+    /**
+     * Flag for {@link #bindService}.
+     *
+     * @hide
+     */
+    public static final long BIND_FILTER_OUT_QUARANTINED_COMPONENTS = 0x2_0000_0000L;
+
 
     /**
      * These bind flags reduce the strength of the binding such that we shouldn't
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index fe108a5..afeb3d29 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -6383,6 +6383,15 @@
             "android.intent.extra.changed_uid_list";
 
     /**
+     * This field is part of
+     * {@link android.content.Intent#ACTION_PACKAGES_SUSPENDED},
+     * and only present if the packages were quarantined.
+     * @hide
+     */
+    public static final String EXTRA_QUARANTINED =
+            "android.intent.extra.quarantined";
+
+    /**
      * An integer denoting a bitwise combination of restrictions set on distracting packages via
      * {@link PackageManager#setDistractingPackageRestrictions(String[], int)}
      *
diff --git a/core/java/android/content/om/FabricatedOverlay.java b/core/java/android/content/om/FabricatedOverlay.java
index 7e787c9..c4547b8 100644
--- a/core/java/android/content/om/FabricatedOverlay.java
+++ b/core/java/android/content/om/FabricatedOverlay.java
@@ -20,6 +20,7 @@
 import android.annotation.IntRange;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.content.res.AssetFileDescriptor;
 import android.os.FabricatedOverlayInternal;
 import android.os.FabricatedOverlayInternalEntry;
 import android.os.ParcelFileDescriptor;
@@ -269,7 +270,7 @@
          * @param configuration The string representation of the config this overlay is enabled for
          * @return the builder itself
          * @deprecated Framework should use {@link FabricatedOverlay#setResourceValue(String,
-                       ParcelFileDescriptor, String)} instead.
+                ParcelFileDescriptor, String)} instead.
          * @hide
          */
         @Deprecated(since = "Please use FabricatedOverlay#setResourceValue instead")
@@ -285,6 +286,30 @@
         }
 
         /**
+         * Sets the value of the fabricated overlay for the file descriptor type.
+         *
+         * @param resourceName name of the target resource to overlay (in the form
+         *     [package]:type/entry)
+         * @param value the file descriptor whose contents are the value of the frro
+         * @param configuration The string representation of the config this overlay is enabled for
+         * @return the builder itself
+         * @deprecated Framework should use {@link FabricatedOverlay#setResourceValue(String,
+                ParcelFileDescriptor, String)} instead.
+         * @hide
+         */
+        @Deprecated(since = "Please use FabricatedOverlay#setResourceValue instead")
+        @NonNull
+        public Builder setResourceValue(
+                @NonNull String resourceName,
+                @NonNull AssetFileDescriptor value,
+                @Nullable String configuration) {
+            ensureValidResourceName(resourceName);
+            mEntries.add(
+                    generateFabricatedOverlayInternalEntry(resourceName, value, configuration));
+            return this;
+        }
+
+        /**
          * Builds an immutable fabricated overlay.
          *
          * @return the fabricated overlay
@@ -421,6 +446,21 @@
         entry.resourceName = resourceName;
         entry.binaryData = Objects.requireNonNull(parcelFileDescriptor);
         entry.configuration = configuration;
+        entry.binaryDataOffset = 0;
+        entry.binaryDataSize = parcelFileDescriptor.getStatSize();
+        return entry;
+    }
+
+    @NonNull
+    private static FabricatedOverlayInternalEntry generateFabricatedOverlayInternalEntry(
+            @NonNull String resourceName, @NonNull AssetFileDescriptor assetFileDescriptor,
+            @Nullable String configuration) {
+        final FabricatedOverlayInternalEntry entry = new FabricatedOverlayInternalEntry();
+        entry.resourceName = resourceName;
+        entry.binaryData = Objects.requireNonNull(assetFileDescriptor.getParcelFileDescriptor());
+        entry.binaryDataOffset = assetFileDescriptor.getStartOffset();
+        entry.binaryDataSize = assetFileDescriptor.getLength();
+        entry.configuration = configuration;
         return entry;
     }
 
@@ -495,4 +535,23 @@
         mOverlay.entries.add(
                 generateFabricatedOverlayInternalEntry(resourceName, value, configuration));
     }
+
+    /**
+     * Sets the resource value in the fabricated overlay for the file descriptor type with the
+     * configuration.
+     *
+     * @param resourceName name of the target resource to overlay (in the form
+     *     [package]:type/entry)
+     * @param value the file descriptor whose contents are the value of the frro
+     * @param configuration The string representation of the config this overlay is enabled for
+     */
+    @NonNull
+    public void setResourceValue(
+            @NonNull String resourceName,
+            @NonNull AssetFileDescriptor value,
+            @Nullable String configuration) {
+        ensureValidResourceName(resourceName);
+        mOverlay.entries.add(
+                generateFabricatedOverlayInternalEntry(resourceName, value, configuration));
+    }
 }
diff --git a/core/java/android/content/pm/CrossProfileApps.java b/core/java/android/content/pm/CrossProfileApps.java
index c3df17d..529363f 100644
--- a/core/java/android/content/pm/CrossProfileApps.java
+++ b/core/java/android/content/pm/CrossProfileApps.java
@@ -344,15 +344,22 @@
         // If there is a label for the launcher intent, then use that as it is typically shorter.
         // Otherwise, just use the top-level application name.
         Intent launchIntent = pm.getLaunchIntentForPackage(mContext.getPackageName());
+        if (launchIntent == null) {
+            return getDefaultCallingApplicationLabel();
+        }
         List<ResolveInfo> infos =
                 pm.queryIntentActivities(
                         launchIntent, PackageManager.ResolveInfoFlags.of(MATCH_DEFAULT_ONLY));
         if (infos.size() > 0) {
             return infos.get(0).loadLabel(pm);
         }
+        return getDefaultCallingApplicationLabel();
+    }
+
+    private CharSequence getDefaultCallingApplicationLabel() {
         return mContext.getApplicationInfo()
                 .loadSafeLabel(
-                        pm,
+                        mContext.getPackageManager(),
                         /* ellipsizeDip= */ 0,
                         TextUtils.SAFE_STRING_FLAG_SINGLE_LINE
                                 | TextUtils.SAFE_STRING_FLAG_TRIM);
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index 7c9ccba..ea0f5ff 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -298,12 +298,14 @@
 
     String[] setPackagesSuspendedAsUser(in String[] packageNames, boolean suspended,
             in PersistableBundle appExtras, in PersistableBundle launcherExtras,
-            in SuspendDialogInfo dialogInfo, String callingPackage, int userId);
+            in SuspendDialogInfo dialogInfo, int flags, String callingPackage, int userId);
 
     String[] getUnsuspendablePackagesForUser(in String[] packageNames, int userId);
 
     boolean isPackageSuspendedForUser(String packageName, int userId);
 
+    boolean isPackageQuarantinedForUser(String packageName, int userId);
+
     Bundle getSuspendedPackageAppExtras(String packageName, int userId);
 
     /**
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 33d37bb..885e67e1 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -834,6 +834,7 @@
             GET_DISABLED_COMPONENTS,
             GET_DISABLED_UNTIL_USED_COMPONENTS,
             GET_UNINSTALLED_PACKAGES,
+            FILTER_OUT_QUARANTINED_COMPONENTS,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface ComponentInfoFlagsBits {}
@@ -857,7 +858,8 @@
             GET_DISABLED_COMPONENTS,
             GET_DISABLED_UNTIL_USED_COMPONENTS,
             GET_UNINSTALLED_PACKAGES,
-            MATCH_CLONE_PROFILE
+            MATCH_CLONE_PROFILE,
+            FILTER_OUT_QUARANTINED_COMPONENTS,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface ResolveInfoFlagsBits {}
@@ -1233,6 +1235,11 @@
     public static final long GET_ATTRIBUTIONS_LONG = 0x80000000L;
 
     /**
+     * @hide
+     */
+    public static final long FILTER_OUT_QUARANTINED_COMPONENTS = 0x100000000L;
+
+    /**
      * Flag for {@link #addCrossProfileIntentFilter}: if this flag is set: when
      * resolving an intent that matches the {@code CrossProfileIntentFilter},
      * the current profile will be skipped. Only activities in the target user
@@ -1685,7 +1692,7 @@
     /** @hide */
     @IntDef(flag = true, value = {
             DONT_KILL_APP,
-            SYNCHRONOUS
+            SYNCHRONOUS,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface EnabledFlags {}
@@ -1708,6 +1715,24 @@
     public static final int SYNCHRONOUS = 0x00000002;
 
     /** @hide */
+    @IntDef(flag = true, value = {
+            FLAG_SUSPEND_QUARANTINED,
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface SuspendedFlags {}
+
+    /**
+     * Flag parameter {@link #setPackagesSuspended(String[], boolean, PersistableBundle,
+     * PersistableBundle, android.content.pm.SuspendDialogInfo, int)}:
+     * Apps in this state not only appear suspended for all user visible purposes (eg, Launcher,
+     * ShareSheet), but also individual components of the app can behave as disabled depending on
+     * the importance of the calling app.
+     *
+     * @hide
+     */
+    public static final int FLAG_SUSPEND_QUARANTINED = 0x00000001;
+
+    /** @hide */
     @IntDef(prefix = { "INSTALL_REASON_" }, value = {
             INSTALL_REASON_UNKNOWN,
             INSTALL_REASON_POLICY,
@@ -3708,12 +3733,12 @@
             "android.hardware.telephony.subscription";
 
     /**
-     * Feature for {@link #getSystemAvailableFeatures} and
-     * {@link #hasSystemFeature}: The device is capable of communicating with
-     * other devices via Thread network.
+     * Feature for {@link #getSystemAvailableFeatures} and {@link #hasSystemFeature}:
+     * The device is capable of communicating with other devices via
+     * <a href="https://www.threadgroup.org">Thread</a> networking protocol.
      */
     @SdkConstant(SdkConstantType.FEATURE)
-    public static final String FEATURE_THREADNETWORK = "android.hardware.threadnetwork";
+    public static final String FEATURE_THREAD_NETWORK = "android.hardware.thread_network";
 
     /**
      * Feature for {@link #getSystemAvailableFeatures} and
@@ -9654,6 +9679,63 @@
     }
 
     /**
+     * Puts the given packages in a suspended state, where attempts at starting activities are
+     * denied.
+     *
+     * <p>The suspended application's notifications and all of its windows will be hidden, any
+     * of its started activities will be stopped and it won't be able to ring the device.
+     * It doesn't remove the data or the actual package file.
+     *
+     * <p>When the user tries to launch a suspended app, a system dialog alerting them that the app
+     * is suspended will be shown instead.
+     * The caller can optionally customize the dialog by passing a {@link SuspendDialogInfo} object
+     * to this API. This dialog will have a button that starts the
+     * {@link Intent#ACTION_SHOW_SUSPENDED_APP_DETAILS} intent if the suspending app declares an
+     * activity which handles this action.
+     *
+     * <p>The packages being suspended must already be installed. If a package is uninstalled, it
+     * will no longer be suspended.
+     *
+     * <p>Optionally, the suspending app can provide extra information in the form of
+     * {@link PersistableBundle} objects to be shared with the apps being suspended and the
+     * launcher to support customization that they might need to handle the suspended state.
+     *
+     * <p>The caller must hold {@link Manifest.permission#SUSPEND_APPS} to use this API except for
+     * device owner and profile owner.
+     *
+     * @param packageNames The names of the packages to set the suspended status.
+     * @param suspended If set to {@code true}, the packages will be suspended, if set to
+     * {@code false}, the packages will be unsuspended.
+     * @param appExtras An optional {@link PersistableBundle} that the suspending app can provide
+     *                  which will be shared with the apps being suspended. Ignored if
+     *                  {@code suspended} is false.
+     * @param launcherExtras An optional {@link PersistableBundle} that the suspending app can
+     *                       provide which will be shared with the launcher. Ignored if
+     *                       {@code suspended} is false.
+     * @param dialogInfo An optional {@link SuspendDialogInfo} object describing the dialog that
+     *                   should be shown to the user when they try to launch a suspended app.
+     *                   Ignored if {@code suspended} is false.
+     * @param flags Optional behavior flags.
+     *
+     * @return an array of package names for which the suspended status could not be set as
+     * requested in this method. Returns {@code null} if {@code packageNames} was {@code null}.
+     *
+     * @see #isPackageSuspended
+     * @see SuspendDialogInfo
+     * @see SuspendDialogInfo.Builder
+     * @see Intent#ACTION_SHOW_SUSPENDED_APP_DETAILS
+     *
+     * @hide
+     */
+    @RequiresPermission(value=Manifest.permission.SUSPEND_APPS, conditional=true)
+    @Nullable
+    public String[] setPackagesSuspended(@Nullable String[] packageNames, boolean suspended,
+            @Nullable PersistableBundle appExtras, @Nullable PersistableBundle launcherExtras,
+            @Nullable SuspendDialogInfo dialogInfo, @SuspendedFlags int flags) {
+        throw new UnsupportedOperationException("setPackagesSuspended not implemented");
+    }
+
+    /**
      * Returns any packages in a given set of packages that cannot be suspended via a call to {@link
      * #setPackagesSuspended(String[], boolean, PersistableBundle, PersistableBundle,
      * SuspendDialogInfo) setPackagesSuspended}. The platform prevents suspending certain critical
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 508eeed..9387ae1 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -1456,8 +1456,8 @@
 
     private static AssetManager newConfiguredAssetManager() {
         AssetManager assetManager = new AssetManager();
-        assetManager.setConfiguration(0, 0, null, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-                0, 0, 0, Build.VERSION.RESOURCES_SDK_INT);
+        assetManager.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                Build.VERSION.RESOURCES_SDK_INT);
         return assetManager;
     }
 
@@ -8005,7 +8005,7 @@
             ai.enabled = true;
         } else if (state.getEnabledState()
                 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
-            ai.enabled = (flags&PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS) != 0;
+            ai.enabled = (flags & PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS) != 0;
         } else if (state.getEnabledState() == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                 || state.getEnabledState()
                 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
@@ -9011,8 +9011,8 @@
             }
 
             AssetManager assets = new AssetManager();
-            assets.setConfiguration(0, 0, null, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-                    0, 0, 0, Build.VERSION.RESOURCES_SDK_INT);
+            assets.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                    Build.VERSION.RESOURCES_SDK_INT);
             assets.setApkAssets(apkAssets, false /*invalidateCaches*/);
 
             mCachedAssetManager = assets;
@@ -9086,8 +9086,8 @@
 
         private static AssetManager createAssetManagerWithAssets(ApkAssets[] apkAssets) {
             final AssetManager assets = new AssetManager();
-            assets.setConfiguration(0, 0, null, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-                    0, 0, 0, Build.VERSION.RESOURCES_SDK_INT);
+            assets.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                    Build.VERSION.RESOURCES_SDK_INT);
             assets.setApkAssets(apkAssets, false /*invalidateCaches*/);
             return assets;
         }
diff --git a/core/java/android/content/pm/TEST_MAPPING b/core/java/android/content/pm/TEST_MAPPING
index 7e30157..ea21d51 100644
--- a/core/java/android/content/pm/TEST_MAPPING
+++ b/core/java/android/content/pm/TEST_MAPPING
@@ -125,6 +125,9 @@
                 },
                 {
                     "exclude-annotation":"org.junit.Ignore"
+                },
+                {
+                    "exclude-filter": "android.content.pm.cts.PackageManagerShellCommandMultiUserTest"
                 }
             ]
         },
@@ -162,6 +165,14 @@
         },
         {
             "name":"CtsInstallHostTestCases"
+        },
+        {
+            "name": "CtsPackageManagerTestCases",
+            "options": [
+                {
+                    "include-filter": "android.content.pm.cts.PackageManagerShellCommandMultiUserTest"
+                }
+            ]
         }
     ]
 }
diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java
index 23b9d0b..b225de4 100644
--- a/core/java/android/content/res/AssetManager.java
+++ b/core/java/android/content/res/AssetManager.java
@@ -1480,13 +1480,9 @@
             int screenWidth, int screenHeight, int smallestScreenWidthDp, int screenWidthDp,
             int screenHeightDp, int screenLayout, int uiMode, int colorMode, int grammaticalGender,
             int majorVersion) {
-        if (locale != null) {
-            setConfiguration(mcc, mnc, null, new String[]{locale}, orientation, touchscreen,
-                    density, keyboard, keyboardHidden, navigation, screenWidth, screenHeight,
-                    smallestScreenWidthDp, screenWidthDp, screenHeightDp, screenLayout, uiMode,
-                    colorMode, grammaticalGender, majorVersion);
-        } else {
-            setConfiguration(mcc, mnc, null, null, orientation, touchscreen, density,
+        synchronized (this) {
+            ensureValidLocked();
+            nativeSetConfiguration(mObject, mcc, mnc, locale, orientation, touchscreen, density,
                     keyboard, keyboardHidden, navigation, screenWidth, screenHeight,
                     smallestScreenWidthDp, screenWidthDp, screenHeightDp, screenLayout, uiMode,
                     colorMode, grammaticalGender, majorVersion);
@@ -1494,25 +1490,6 @@
     }
 
     /**
-     * Change the configuration used when retrieving resources.  Not for use by
-     * applications.
-     * @hide
-     */
-    public void setConfiguration(int mcc, int mnc, String defaultLocale, String[] locales,
-            int orientation, int touchscreen, int density, int keyboard, int keyboardHidden,
-            int navigation, int screenWidth, int screenHeight, int smallestScreenWidthDp,
-            int screenWidthDp, int screenHeightDp, int screenLayout, int uiMode, int colorMode,
-            int grammaticalGender, int majorVersion) {
-        synchronized (this) {
-            ensureValidLocked();
-            nativeSetConfiguration(mObject, mcc, mnc, defaultLocale, locales, orientation,
-                    touchscreen, density, keyboard, keyboardHidden, navigation, screenWidth,
-                    screenHeight, smallestScreenWidthDp, screenWidthDp, screenHeightDp,
-                    screenLayout, uiMode, colorMode, grammaticalGender, majorVersion);
-        }
-    }
-
-    /**
      * @hide
      */
     @UnsupportedAppUsage
@@ -1595,11 +1572,10 @@
     private static native void nativeSetApkAssets(long ptr, @NonNull ApkAssets[] apkAssets,
             boolean invalidateCaches);
     private static native void nativeSetConfiguration(long ptr, int mcc, int mnc,
-            @Nullable String defaultLocale, @NonNull String[] locales, int orientation,
-            int touchscreen, int density, int keyboard, int keyboardHidden, int navigation,
-            int screenWidth, int screenHeight, int smallestScreenWidthDp, int screenWidthDp,
-            int screenHeightDp, int screenLayout, int uiMode, int colorMode, int grammaticalGender,
-            int majorVersion);
+            @Nullable String locale, int orientation, int touchscreen, int density, int keyboard,
+            int keyboardHidden, int navigation, int screenWidth, int screenHeight,
+            int smallestScreenWidthDp, int screenWidthDp, int screenHeightDp, int screenLayout,
+            int uiMode, int colorMode, int grammaticalGender, int majorVersion);
     private static native @NonNull SparseArray<String> nativeGetAssignedPackageIdentifiers(
             long ptr, boolean includeOverlays, boolean includeLoaders);
 
diff --git a/core/java/android/content/res/Element.java b/core/java/android/content/res/Element.java
index a86c0c9..e931fe8 100644
--- a/core/java/android/content/res/Element.java
+++ b/core/java/android/content/res/Element.java
@@ -42,6 +42,8 @@
     public static final int MAX_ATTR_LEN_PATH = 4000;
     public static final int MAX_ATTR_LEN_DATA_VALUE = 4000;
 
+    private static final String BAD_COMPONENT_NAME_CHARS = ";,[](){}:?-%^*|/\\";
+
     private static final String TAG = "PackageParsing";
     protected static final String TAG_ACTION = "action";
     protected static final String TAG_ACTIVITY = "activity";
@@ -128,6 +130,7 @@
     protected static final String TAG_ATTR_VALUE = "value";
     protected static final String TAG_ATTR_VERSION_NAME = "versionName";
     protected static final String TAG_ATTR_WRITE_PERMISSION = "writePermission";
+    protected static final String TAG_ATTR_ZYGOTE_PRELOAD_NAME = "zygotePreloadName";
 
     // The length of mTagCounters corresponds to the number of tags defined in getCounterIdx. If new
     // tags are added then the size here should be increased to match.
@@ -374,6 +377,7 @@
             case TAG_ATTR_TASK_AFFINITY:
             case TAG_ATTR_WRITE_PERMISSION:
             case TAG_ATTR_VERSION_NAME:
+            case TAG_ATTR_ZYGOTE_PRELOAD_NAME:
                 return MAX_ATTR_LEN_NAME;
             case TAG_ATTR_PATH:
             case TAG_ATTR_PATH_ADVANCED_PATTERN:
@@ -488,6 +492,7 @@
             case R.styleable.AndroidManifestApplication_requiredAccountType:
             case R.styleable.AndroidManifestApplication_restrictedAccountType:
             case R.styleable.AndroidManifestApplication_taskAffinity:
+            case R.styleable.AndroidManifestApplication_zygotePreloadName:
                 return MAX_ATTR_LEN_NAME;
             default:
                 return DEFAULT_MAX_STRING_ATTR_LENGTH;
@@ -738,6 +743,7 @@
                 switch (name) {
                     case TAG_ATTR_BACKUP_AGENT:
                     case TAG_ATTR_NAME:
+                    case TAG_ATTR_ZYGOTE_PRELOAD_NAME:
                         return true;
                     default:
                         return false;
@@ -766,7 +772,8 @@
                 return index == R.styleable.AndroidManifestActivityAlias_targetActivity;
             case TAG_APPLICATION:
                 return index == R.styleable.AndroidManifestApplication_backupAgent
-                        || index == R.styleable.AndroidManifestApplication_name;
+                        || index == R.styleable.AndroidManifestApplication_name
+                        || index == R.styleable.AndroidManifestApplication_zygotePreloadName;
             case TAG_INSTRUMENTATION:
                 return index ==  R.styleable.AndroidManifestInstrumentation_name;
             case TAG_PROVIDER:
@@ -785,33 +792,13 @@
     }
 
     void validateComponentName(CharSequence name) {
-        int i = 0;
-        if (name.charAt(0) == '.') {
-            i = 1;
-        }
         boolean isStart = true;
-        for (; i < name.length(); i++) {
-            if (name.charAt(i) == '.') {
-                if (isStart) {
-                    break;
-                }
-                isStart = true;
-            } else {
-                if (isStart) {
-                    if (Character.isJavaIdentifierStart(name.charAt(i))) {
-                        isStart = false;
-                    } else {
-                        break;
-                    }
-                } else if (!Character.isJavaIdentifierPart(name.charAt(i))) {
-                    break;
-                }
+        for (int i = 0; i < name.length(); i++) {
+            if (BAD_COMPONENT_NAME_CHARS.indexOf(name.charAt(i)) >= 0) {
+                Slog.e(TAG, name + " is not a valid Java class name");
+                throw new SecurityException(name + " is not a valid Java class name");
             }
         }
-        if ((i < name.length()) || (name.charAt(name.length() - 1) == '.')) {
-            Slog.e(TAG, name + " is not a valid Java class name");
-            throw new SecurityException(name + " is not a valid Java class name");
-        }
     }
 
     void validateStrAttr(String attrName, String attrValue) {
diff --git a/core/java/android/content/res/ResourcesImpl.java b/core/java/android/content/res/ResourcesImpl.java
index a937832..395fef2 100644
--- a/core/java/android/content/res/ResourcesImpl.java
+++ b/core/java/android/content/res/ResourcesImpl.java
@@ -425,12 +425,14 @@
                     mConfiguration.setLocales(locales);
                 }
 
-                String[] selectedLocales = null;
-                String defaultLocale = null;
                 if ((configChanges & ActivityInfo.CONFIG_LOCALE) != 0) {
                     if (locales.size() > 1) {
                         String[] availableLocales;
-                        if (ResourcesManager.getInstance().getLocaleList().isEmpty()) {
+
+                        LocaleList localeList = ResourcesManager.getInstance().getLocaleList();
+                        if (!localeList.isEmpty()) {
+                            availableLocales = localeList.toLanguageTags().split(",");
+                        } else {
                             // The LocaleList has changed. We must query the AssetManager's
                             // available Locales and figure out the best matching Locale in the new
                             // LocaleList.
@@ -442,30 +444,14 @@
                                     availableLocales = null;
                                 }
                             }
-                            if (availableLocales != null) {
-                                final Locale bestLocale = locales.getFirstMatchWithEnglishSupported(
-                                        availableLocales);
-                                if (bestLocale != null) {
-                                    selectedLocales = new String[]{
-                                            adjustLanguageTag(bestLocale.toLanguageTag())};
-                                    if (!bestLocale.equals(locales.get(0))) {
-                                        mConfiguration.setLocales(
-                                                new LocaleList(bestLocale, locales));
-                                    }
-                                }
-                            }
-                        } else {
-                            selectedLocales = locales.getIntersection(
-                                    ResourcesManager.getInstance().getLocaleList());
-                            defaultLocale = ResourcesManager.getInstance()
-                                    .getLocaleList().get(0).toLanguageTag();
                         }
-                    }
-                }
-                if (selectedLocales == null) {
-                    selectedLocales = new String[locales.size()];
-                    for (int i = 0; i < locales.size(); i++) {
-                        selectedLocales[i] = adjustLanguageTag(locales.get(i).toLanguageTag());
+                        if (availableLocales != null) {
+                            final Locale bestLocale = locales.getFirstMatchWithEnglishSupported(
+                                    availableLocales);
+                            if (bestLocale != null && bestLocale != locales.get(0)) {
+                                mConfiguration.setLocales(new LocaleList(bestLocale, locales));
+                            }
+                        }
                     }
                 }
 
@@ -502,8 +488,7 @@
                 }
 
                 mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc,
-                        defaultLocale,
-                        selectedLocales,
+                        adjustLanguageTag(mConfiguration.getLocales().get(0).toLanguageTag()),
                         mConfiguration.orientation,
                         mConfiguration.touchscreen,
                         mConfiguration.densityDpi, mConfiguration.keyboard,
diff --git a/core/java/android/credentials/CreateCredentialRequest.java b/core/java/android/credentials/CreateCredentialRequest.java
index fc3dc79..946b5f3 100644
--- a/core/java/android/credentials/CreateCredentialRequest.java
+++ b/core/java/android/credentials/CreateCredentialRequest.java
@@ -261,7 +261,10 @@
 
         /**
          * @param type the type of the credential to be stored
-         * @param credentialData the full credential creation request data
+         * @param credentialData the full credential creation request data, which must at minimum
+         * contain the required fields observed at the
+         * {@link androidx.credentials.CreateCredentialRequest} Bundle conversion static methods,
+         * because they are required for properly displaying the system credential selector UI
          * @param candidateQueryData the partial request data that will be sent to the provider
          *                           during the initial creation candidate query stage
          */
diff --git a/core/java/android/credentials/CredentialManager.java b/core/java/android/credentials/CredentialManager.java
index c2a0062..eedb25b 100644
--- a/core/java/android/credentials/CredentialManager.java
+++ b/core/java/android/credentials/CredentialManager.java
@@ -123,7 +123,7 @@
      * credential, display a picker when multiple credentials exist, etc.
      * Callers (e.g. browsers) may optionally set origin in {@link GetCredentialRequest} for an
      * app different from their own, to be able to get credentials on behalf of that app. They would
-     * need additional permission {@link CREDENTIAL_MANAGER_SET_ORIGIN}
+     * need additional permission {@code CREDENTIAL_MANAGER_SET_ORIGIN}
      * to use this functionality
      *
      * @param context the context used to launch any UI needed; use an activity context to make sure
@@ -209,9 +209,9 @@
      *
      * <p>This API doesn't invoke any UI. It only performs the preparation work so that you can
      * later launch the remaining get-credential operation (involves UIs) through the {@link
-     * #getCredential(PrepareGetCredentialResponse.PendingGetCredentialHandle, Context,
+     * #getCredential(Context, PrepareGetCredentialResponse.PendingGetCredentialHandle,
      * CancellationSignal, Executor, OutcomeReceiver)} API which incurs less latency compared to
-     * the {@link #getCredential(GetCredentialRequest, Context, CancellationSignal, Executor,
+     * the {@link #getCredential(Context, GetCredentialRequest, CancellationSignal, Executor,
      * OutcomeReceiver)} API that executes the whole operation in one call.
      *
      * @param request            the request specifying type(s) of credentials to get from the user
@@ -261,7 +261,7 @@
      * storing the new credential, etc.
      * Callers (e.g. browsers) may optionally set origin in {@link CreateCredentialRequest} for an
      * app different from their own, to be able to get credentials on behalf of that app. They would
-     * need additional permission {@link CREDENTIAL_MANAGER_SET_ORIGIN}
+     * need additional permission {@code CREDENTIAL_MANAGER_SET_ORIGIN}
      * to use this functionality
      *
      * @param context the context used to launch any UI needed; use an activity context to make sure
diff --git a/core/java/android/database/sqlite/SQLiteConnection.java b/core/java/android/database/sqlite/SQLiteConnection.java
index 706e75e..f2980f4 100644
--- a/core/java/android/database/sqlite/SQLiteConnection.java
+++ b/core/java/android/database/sqlite/SQLiteConnection.java
@@ -1875,7 +1875,7 @@
      * statement
      * @hide
      */
-    long getLastChangedRowsCount() {
+    long getLastChangedRowCount() {
         try {
             return nativeChanges(mConnectionPtr);
         } finally {
@@ -1887,7 +1887,7 @@
      * Return the total number of database changes made on the current connection.
      * @hide
      */
-    long getTotalChangedRowsCount() {
+    long getTotalChangedRowCount() {
         try {
             return nativeTotalChanges(mConnectionPtr);
         } finally {
diff --git a/core/java/android/database/sqlite/SQLiteDatabase.java b/core/java/android/database/sqlite/SQLiteDatabase.java
index a3f8383..5b80e6a 100644
--- a/core/java/android/database/sqlite/SQLiteDatabase.java
+++ b/core/java/android/database/sqlite/SQLiteDatabase.java
@@ -956,7 +956,7 @@
      * Open the database according to the flags {@link #OPEN_READWRITE}
      * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
      *
-     * <p>Sets the locale of the database to the  the system's current locale.
+     * <p>Sets the locale of the database to the system's current locale.
      * Call {@link #setLocale} if you would like something else.</p>
      *
      * @param path to database file to open and/or create
@@ -1002,7 +1002,7 @@
      * Open the database according to the flags {@link #OPEN_READWRITE}
      * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
      *
-     * <p>Sets the locale of the database to the  the system's current locale.
+     * <p>Sets the locale of the database to the system's current locale.
      * Call {@link #setLocale} if you would like something else.</p>
      *
      * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be
@@ -1163,7 +1163,7 @@
      * Create a memory backed SQLite database.  Its contents will be destroyed
      * when the database is closed.
      *
-     * <p>Sets the locale of the database to the  the system's current locale.
+     * <p>Sets the locale of the database to the system's current locale.
      * Call {@link #setLocale} if you would like something else.</p>
      *
      * @param factory an optional factory class that is called to instantiate a
@@ -1182,7 +1182,7 @@
      * Create a memory backed SQLite database.  Its contents will be destroyed
      * when the database is closed.
      *
-     * <p>Sets the locale of the database to the  the system's current locale.
+     * <p>Sets the locale of the database to the system's current locale.
      * Call {@link #setLocale} if you would like something else.</p>
      * @param openParams configuration parameters that are used for opening SQLiteDatabase
      * @return a SQLiteDatabase instance
@@ -2208,10 +2208,9 @@
      *
      * @return The number of rows changed by the most recent sql statement
      * @throws IllegalStateException if there is no current transaction.
-     * @hide
      */
-    public long getLastChangedRowsCount() {
-        return getThreadSession().getLastChangedRowsCount();
+    public long getLastChangedRowCount() {
+        return getThreadSession().getLastChangedRowCount();
     }
 
     /**
@@ -2223,9 +2222,9 @@
      * <code><pre>
      *    database.beginTransaction();
      *    try {
-     *        long initialValue = database.getTotalChangedRowsCount();
+     *        long initialValue = database.getTotalChangedRowCount();
      *        // Execute SQL statements
-     *        long changedRows = database.getTotalChangedRowsCount() - initialValue;
+     *        long changedRows = database.getTotalChangedRowCount() - initialValue;
      *        // changedRows counts the total number of rows updated in the transaction.
      *    } finally {
      *        database.endTransaction();
@@ -2236,10 +2235,9 @@
      *
      * @return The number of rows changed on the current connection.
      * @throws IllegalStateException if there is no current transaction.
-     * @hide
      */
-    public long getTotalChangedRowsCount() {
-        return getThreadSession().getTotalChangedRowsCount();
+    public long getTotalChangedRowCount() {
+        return getThreadSession().getTotalChangedRowCount();
     }
 
     /**
diff --git a/core/java/android/database/sqlite/SQLiteSession.java b/core/java/android/database/sqlite/SQLiteSession.java
index ef1a9cb..7d9f02d 100644
--- a/core/java/android/database/sqlite/SQLiteSession.java
+++ b/core/java/android/database/sqlite/SQLiteSession.java
@@ -998,9 +998,9 @@
      * this connection.
      * @hide
      */
-    long getLastChangedRowsCount() {
+    long getLastChangedRowCount() {
         throwIfNoTransaction();
-        return mConnection.getLastChangedRowsCount();
+        return mConnection.getLastChangedRowCount();
     }
 
     /**
@@ -1008,9 +1008,9 @@
      * it was created.
      * @hide
      */
-    long getTotalChangedRowsCount() {
+    long getTotalChangedRowCount() {
         throwIfNoTransaction();
-        return mConnection.getTotalChangedRowsCount();
+        return mConnection.getTotalChangedRowCount();
     }
 
     /**
diff --git a/core/java/android/hardware/HardwareBuffer.java b/core/java/android/hardware/HardwareBuffer.java
index 889a43c..5ff0e7a 100644
--- a/core/java/android/hardware/HardwareBuffer.java
+++ b/core/java/android/hardware/HardwareBuffer.java
@@ -22,6 +22,7 @@
 import android.annotation.NonNull;
 import android.compat.annotation.UnsupportedAppUsage;
 import android.graphics.GraphicBuffer;
+import android.os.BadParcelableException;
 import android.os.Build;
 import android.os.Parcel;
 import android.os.Parcelable;
@@ -399,11 +400,14 @@
     public static final @android.annotation.NonNull Parcelable.Creator<HardwareBuffer> CREATOR =
             new Parcelable.Creator<HardwareBuffer>() {
         public HardwareBuffer createFromParcel(Parcel in) {
+            if (in == null) {
+                throw new NullPointerException("null passed to createFromParcel");
+            }
             long nativeObject = nReadHardwareBufferFromParcel(in);
             if (nativeObject != 0) {
                 return new HardwareBuffer(nativeObject);
             }
-            return null;
+            throw new BadParcelableException("Failed to read hardware buffer");
         }
 
         public HardwareBuffer[] newArray(int size) {
diff --git a/core/java/android/hardware/camera2/CameraManager.java b/core/java/android/hardware/camera2/CameraManager.java
index c2fe080..c80124c 100644
--- a/core/java/android/hardware/camera2/CameraManager.java
+++ b/core/java/android/hardware/camera2/CameraManager.java
@@ -31,6 +31,7 @@
 import android.content.pm.PackageManager;
 import android.graphics.Point;
 import android.hardware.CameraExtensionSessionStats;
+import android.hardware.CameraIdRemapping;
 import android.hardware.CameraStatus;
 import android.hardware.ICameraService;
 import android.hardware.ICameraServiceListener;
@@ -1730,6 +1731,17 @@
     }
 
     /**
+     * Remaps Camera Ids in the CameraService.
+     *
+     * @hide
+    */
+    @RequiresPermission(android.Manifest.permission.CAMERA_INJECT_EXTERNAL_CAMERA)
+    public void remapCameraIds(@NonNull CameraIdRemapping cameraIdRemapping)
+            throws CameraAccessException, SecurityException, IllegalArgumentException {
+        CameraManagerGlobal.get().remapCameraIds(cameraIdRemapping);
+    }
+
+    /**
      * Reports {@link CameraExtensionSessionStats} to the {@link ICameraService} to be logged for
      * currently active session. Validation is done downstream.
      *
@@ -1802,6 +1814,13 @@
 
         private final Object mLock = new Object();
 
+        /**
+         * The active CameraIdRemapping. This will be used to refresh the cameraIdRemapping state
+         * in the CameraService every time we connect to it, including when the CameraService
+         * Binder dies and we reconnect to it.
+         */
+        @Nullable private CameraIdRemapping mActiveCameraIdRemapping;
+
         // Access only through getCameraService to deal with binder death
         private ICameraService mCameraService;
         private boolean mHasOpenCloseListenerPermission = false;
@@ -1944,6 +1963,41 @@
             } catch (RemoteException e) {
                 // Camera service died in all probability
             }
+
+            if (mActiveCameraIdRemapping != null) {
+                try {
+                    cameraService.remapCameraIds(mActiveCameraIdRemapping);
+                } catch (ServiceSpecificException e) {
+                    // Unexpected failure, ignore and continue.
+                    Log.e(TAG, "Unable to remap camera Ids in the camera service");
+                } catch (RemoteException e) {
+                    // Camera service died in all probability
+                }
+            }
+        }
+
+        /** Updates the cameraIdRemapping state in the CameraService. */
+        public void remapCameraIds(@NonNull CameraIdRemapping cameraIdRemapping)
+                throws CameraAccessException, SecurityException {
+            synchronized (mLock) {
+                ICameraService cameraService = getCameraService();
+                if (cameraService == null) {
+                    throw new CameraAccessException(
+                            CameraAccessException.CAMERA_DISCONNECTED,
+                            "Camera service is currently unavailable.");
+                }
+
+                try {
+                    cameraService.remapCameraIds(cameraIdRemapping);
+                    mActiveCameraIdRemapping = cameraIdRemapping;
+                } catch (ServiceSpecificException e) {
+                    throwAsPublicException(e);
+                } catch (RemoteException e) {
+                    throw new CameraAccessException(
+                            CameraAccessException.CAMERA_DISCONNECTED,
+                            "Camera service is currently unavailable.");
+                }
+            }
         }
 
         private String[] extractCameraIdListLocked() {
diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java
index c872516..5940819 100644
--- a/core/java/android/hardware/camera2/CaptureRequest.java
+++ b/core/java/android/hardware/camera2/CaptureRequest.java
@@ -4194,9 +4194,8 @@
      * <p>This control allows Camera extension clients to configure the strength of the applied
      * extension effect. Strength equal to 0 means that the extension must not apply any
      * post-processing and return a regular captured frame. Strength equal to 100 is the
-     * default level of post-processing applied when the control is not supported or not set
-     * by the client. Values between 0 and 100 will have different effect depending on the
-     * extension type as described below:</p>
+     * maximum level of post-processing. Values between 0 and 100 will have different effect
+     * depending on the extension type as described below:</p>
      * <ul>
      * <li>{@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_BOKEH BOKEH} -
      * the strength is expected to control the amount of blur.</li>
@@ -4211,7 +4210,9 @@
      * {@link android.hardware.camera2.CameraExtensionCharacteristics#getAvailableCaptureRequestKeys }.
      * The control is only defined and available to clients sending capture requests via
      * {@link android.hardware.camera2.CameraExtensionSession }.
-     * The default value is 100.</p>
+     * If the client doesn't specify the extension strength value, then a default value will
+     * be set by the extension. Clients can retrieve the default value by checking the
+     * corresponding capture result.</p>
      * <p><b>Range of valid values:</b><br>
      * 0 - 100</p>
      * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java
index 57f7bca..905f98d 100644
--- a/core/java/android/hardware/camera2/CaptureResult.java
+++ b/core/java/android/hardware/camera2/CaptureResult.java
@@ -5694,9 +5694,8 @@
      * <p>This control allows Camera extension clients to configure the strength of the applied
      * extension effect. Strength equal to 0 means that the extension must not apply any
      * post-processing and return a regular captured frame. Strength equal to 100 is the
-     * default level of post-processing applied when the control is not supported or not set
-     * by the client. Values between 0 and 100 will have different effect depending on the
-     * extension type as described below:</p>
+     * maximum level of post-processing. Values between 0 and 100 will have different effect
+     * depending on the extension type as described below:</p>
      * <ul>
      * <li>{@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_BOKEH BOKEH} -
      * the strength is expected to control the amount of blur.</li>
@@ -5711,7 +5710,9 @@
      * {@link android.hardware.camera2.CameraExtensionCharacteristics#getAvailableCaptureRequestKeys }.
      * The control is only defined and available to clients sending capture requests via
      * {@link android.hardware.camera2.CameraExtensionSession }.
-     * The default value is 100.</p>
+     * If the client doesn't specify the extension strength value, then a default value will
+     * be set by the extension. Clients can retrieve the default value by checking the
+     * corresponding capture result.</p>
      * <p><b>Range of valid values:</b><br>
      * 0 - 100</p>
      * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
diff --git a/core/java/android/hardware/camera2/params/OutputConfiguration.java b/core/java/android/hardware/camera2/params/OutputConfiguration.java
index 21540bf..5e53373 100644
--- a/core/java/android/hardware/camera2/params/OutputConfiguration.java
+++ b/core/java/android/hardware/camera2/params/OutputConfiguration.java
@@ -1193,12 +1193,12 @@
         String physicalCameraId = source.readString();
         boolean isMultiResolutionOutput = source.readInt() == 1;
         int[] sensorPixelModesUsed = source.createIntArray();
-        long streamUseCase = source.readLong();
 
         checkArgumentInRange(rotation, ROTATION_0, ROTATION_270, "Rotation constant");
         long dynamicRangeProfile = source.readLong();
         DynamicRangeProfiles.checkProfileValue(dynamicRangeProfile);
         int colorSpace = source.readInt();
+        long streamUseCase = source.readLong();
 
         int timestampBase = source.readInt();
         int mirrorMode = source.readInt();
diff --git a/core/java/android/hardware/display/DisplayManagerInternal.java b/core/java/android/hardware/display/DisplayManagerInternal.java
index 94bff89..4700720 100644
--- a/core/java/android/hardware/display/DisplayManagerInternal.java
+++ b/core/java/android/hardware/display/DisplayManagerInternal.java
@@ -370,8 +370,9 @@
 
     /**
      * Returns the default size of the surface associated with the display, or null if the surface
-     * is not provided for layer mirroring by SurfaceFlinger.
-     * Only used for mirroring started from MediaProjection.
+     * is not provided for layer mirroring by SurfaceFlinger. Size is rotated to reflect the current
+     * display device orientation.
+     * Used for mirroring from MediaProjection, or a physical display based on display flags.
      */
     public abstract Point getDisplaySurfaceDefaultSize(int displayId);
 
diff --git a/core/java/android/hardware/display/VirtualDisplayConfig.java b/core/java/android/hardware/display/VirtualDisplayConfig.java
index a62d74e..22e3938 100644
--- a/core/java/android/hardware/display/VirtualDisplayConfig.java
+++ b/core/java/android/hardware/display/VirtualDisplayConfig.java
@@ -39,7 +39,8 @@
  * Holds configuration used to create {@link VirtualDisplay} instances.
  *
  * @see DisplayManager#createVirtualDisplay(VirtualDisplayConfig, Handler, VirtualDisplay.Callback)
- * @see MediaProjection#createVirtualDisplay
+ * @see MediaProjection#createVirtualDisplay(String, int, int, int, int, Surface,
+ * VirtualDisplay.Callback, Handler)
  */
 public final class VirtualDisplayConfig implements Parcelable {
 
diff --git a/core/java/android/hardware/fingerprint/FingerprintAuthenticateOptions.java b/core/java/android/hardware/fingerprint/FingerprintAuthenticateOptions.java
index 763246e..dc66542 100644
--- a/core/java/android/hardware/fingerprint/FingerprintAuthenticateOptions.java
+++ b/core/java/android/hardware/fingerprint/FingerprintAuthenticateOptions.java
@@ -21,6 +21,7 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.hardware.biometrics.AuthenticateOptions;
+import android.hardware.biometrics.common.AuthenticateReason;
 import android.os.Parcelable;
 
 import com.android.internal.util.DataClass;
@@ -85,7 +86,16 @@
         return null;
     }
 
-
+    /**
+     * The Vendor extension, if any.
+     *
+     * This option may be present when a vendor would like to send additional information for each
+     * auth attempt.
+     */
+    @Nullable private AuthenticateReason.Vendor mVendorReason;
+    private static AuthenticateReason.Vendor defaultVendorReason() {
+        return null;
+    }
 
     // Code below generated by codegen v1.0.23.
     //
@@ -107,7 +117,8 @@
             boolean ignoreEnrollmentState,
             @AuthenticateOptions.DisplayState int displayState,
             @NonNull String opPackageName,
-            @Nullable String attributionTag) {
+            @Nullable String attributionTag,
+            @Nullable AuthenticateReason.Vendor vendorReason) {
         this.mUserId = userId;
         this.mSensorId = sensorId;
         this.mIgnoreEnrollmentState = ignoreEnrollmentState;
@@ -118,6 +129,7 @@
         com.android.internal.util.AnnotationValidations.validate(
                 NonNull.class, null, mOpPackageName);
         this.mAttributionTag = attributionTag;
+        this.mVendorReason = vendorReason;
 
         // onConstructed(); // You can define this method to get a callback
     }
@@ -176,6 +188,17 @@
     }
 
     /**
+     * The Vendor extension, if any.
+     *
+     * This option may be present when a vendor would like to send additional information for each
+     * auth attempt.
+     */
+    @DataClass.Generated.Member
+    public @Nullable AuthenticateReason.Vendor getVendorReason() {
+        return mVendorReason;
+    }
+
+    /**
      * The sensor id for this operation.
      */
     @DataClass.Generated.Member
@@ -209,6 +232,18 @@
         return this;
     }
 
+    /**
+     * The Vendor extension, if any.
+     *
+     * This option may be present when a vendor would like to send additional information for each
+     * auth attempt.
+     */
+    @DataClass.Generated.Member
+    public @NonNull FingerprintAuthenticateOptions setVendorReason(@NonNull AuthenticateReason.Vendor value) {
+        mVendorReason = value;
+        return this;
+    }
+
     @Override
     @DataClass.Generated.Member
     public boolean equals(@Nullable Object o) {
@@ -227,7 +262,8 @@
                 && mIgnoreEnrollmentState == that.mIgnoreEnrollmentState
                 && mDisplayState == that.mDisplayState
                 && java.util.Objects.equals(mOpPackageName, that.mOpPackageName)
-                && java.util.Objects.equals(mAttributionTag, that.mAttributionTag);
+                && java.util.Objects.equals(mAttributionTag, that.mAttributionTag)
+                && java.util.Objects.equals(mVendorReason, that.mVendorReason);
     }
 
     @Override
@@ -243,6 +279,7 @@
         _hash = 31 * _hash + mDisplayState;
         _hash = 31 * _hash + java.util.Objects.hashCode(mOpPackageName);
         _hash = 31 * _hash + java.util.Objects.hashCode(mAttributionTag);
+        _hash = 31 * _hash + java.util.Objects.hashCode(mVendorReason);
         return _hash;
     }
 
@@ -255,12 +292,14 @@
         byte flg = 0;
         if (mIgnoreEnrollmentState) flg |= 0x4;
         if (mAttributionTag != null) flg |= 0x20;
+        if (mVendorReason != null) flg |= 0x40;
         dest.writeByte(flg);
         dest.writeInt(mUserId);
         dest.writeInt(mSensorId);
         dest.writeInt(mDisplayState);
         dest.writeString(mOpPackageName);
         if (mAttributionTag != null) dest.writeString(mAttributionTag);
+        if (mVendorReason != null) dest.writeTypedObject(mVendorReason, flags);
     }
 
     @Override
@@ -281,6 +320,7 @@
         int displayState = in.readInt();
         String opPackageName = in.readString();
         String attributionTag = (flg & 0x20) == 0 ? null : in.readString();
+        AuthenticateReason.Vendor vendorReason = (flg & 0x40) == 0 ? null : (AuthenticateReason.Vendor) in.readTypedObject(AuthenticateReason.Vendor.CREATOR);
 
         this.mUserId = userId;
         this.mSensorId = sensorId;
@@ -292,6 +332,7 @@
         com.android.internal.util.AnnotationValidations.validate(
                 NonNull.class, null, mOpPackageName);
         this.mAttributionTag = attributionTag;
+        this.mVendorReason = vendorReason;
 
         // onConstructed(); // You can define this method to get a callback
     }
@@ -323,6 +364,7 @@
         private @AuthenticateOptions.DisplayState int mDisplayState;
         private @NonNull String mOpPackageName;
         private @Nullable String mAttributionTag;
+        private @Nullable AuthenticateReason.Vendor mVendorReason;
 
         private long mBuilderFieldsSet = 0L;
 
@@ -400,10 +442,24 @@
             return this;
         }
 
+        /**
+         * The Vendor extension, if any.
+         *
+         * This option may be present when a vendor would like to send additional information for each
+         * auth attempt.
+         */
+        @DataClass.Generated.Member
+        public @NonNull Builder setVendorReason(@NonNull AuthenticateReason.Vendor value) {
+            checkNotUsed();
+            mBuilderFieldsSet |= 0x40;
+            mVendorReason = value;
+            return this;
+        }
+
         /** Builds the instance. This builder should not be touched after calling this! */
         public @NonNull FingerprintAuthenticateOptions build() {
             checkNotUsed();
-            mBuilderFieldsSet |= 0x40; // Mark builder used
+            mBuilderFieldsSet |= 0x80; // Mark builder used
 
             if ((mBuilderFieldsSet & 0x1) == 0) {
                 mUserId = defaultUserId();
@@ -423,18 +479,22 @@
             if ((mBuilderFieldsSet & 0x20) == 0) {
                 mAttributionTag = defaultAttributionTag();
             }
+            if ((mBuilderFieldsSet & 0x40) == 0) {
+                mVendorReason = defaultVendorReason();
+            }
             FingerprintAuthenticateOptions o = new FingerprintAuthenticateOptions(
                     mUserId,
                     mSensorId,
                     mIgnoreEnrollmentState,
                     mDisplayState,
                     mOpPackageName,
-                    mAttributionTag);
+                    mAttributionTag,
+                    mVendorReason);
             return o;
         }
 
         private void checkNotUsed() {
-            if ((mBuilderFieldsSet & 0x40) != 0) {
+            if ((mBuilderFieldsSet & 0x80) != 0) {
                 throw new IllegalStateException(
                         "This Builder should not be reused. Use a new Builder instance instead");
             }
@@ -442,10 +502,10 @@
     }
 
     @DataClass.Generated(
-            time = 1677119626721L,
+            time = 1689703591032L,
             codegenVersion = "1.0.23",
             sourceFile = "frameworks/base/core/java/android/hardware/fingerprint/FingerprintAuthenticateOptions.java",
-            inputSignatures = "private final  int mUserId\nprivate  int mSensorId\nprivate final  boolean mIgnoreEnrollmentState\nprivate final @android.hardware.biometrics.AuthenticateOptions.DisplayState int mDisplayState\nprivate @android.annotation.NonNull java.lang.String mOpPackageName\nprivate @android.annotation.Nullable java.lang.String mAttributionTag\nprivate static  int defaultUserId()\nprivate static  int defaultSensorId()\nprivate static  boolean defaultIgnoreEnrollmentState()\nprivate static  int defaultDisplayState()\nprivate static  java.lang.String defaultOpPackageName()\nprivate static  java.lang.String defaultAttributionTag()\nclass FingerprintAuthenticateOptions extends java.lang.Object implements [android.hardware.biometrics.AuthenticateOptions, android.os.Parcelable]\n@com.android.internal.util.DataClass(genParcelable=true, genAidl=true, genBuilder=true, genSetters=true, genEqualsHashCode=true)")
+            inputSignatures = "private final  int mUserId\nprivate  int mSensorId\nprivate final  boolean mIgnoreEnrollmentState\nprivate final @android.hardware.biometrics.AuthenticateOptions.DisplayState int mDisplayState\nprivate @android.annotation.NonNull java.lang.String mOpPackageName\nprivate @android.annotation.Nullable java.lang.String mAttributionTag\nprivate @android.annotation.Nullable android.hardware.biometrics.common.AuthenticateReason.Vendor mVendorReason\nprivate static  int defaultUserId()\nprivate static  int defaultSensorId()\nprivate static  boolean defaultIgnoreEnrollmentState()\nprivate static  int defaultDisplayState()\nprivate static  java.lang.String defaultOpPackageName()\nprivate static  java.lang.String defaultAttributionTag()\nprivate static  android.hardware.biometrics.common.AuthenticateReason.Vendor defaultVendorReason()\nclass FingerprintAuthenticateOptions extends java.lang.Object implements [android.hardware.biometrics.AuthenticateOptions, android.os.Parcelable]\n@com.android.internal.util.DataClass(genParcelable=true, genAidl=true, genBuilder=true, genSetters=true, genEqualsHashCode=true)")
     @Deprecated
     private void __metadata() {}
 
diff --git a/core/java/android/hardware/usb/UsbConfiguration.java b/core/java/android/hardware/usb/UsbConfiguration.java
index 66269cb..b25f47b 100644
--- a/core/java/android/hardware/usb/UsbConfiguration.java
+++ b/core/java/android/hardware/usb/UsbConfiguration.java
@@ -172,7 +172,8 @@
             String name = in.readString();
             int attributes = in.readInt();
             int maxPower = in.readInt();
-            Parcelable[] interfaces = in.readParcelableArray(UsbInterface.class.getClassLoader());
+            Parcelable[] interfaces = in.readParcelableArray(
+                    UsbInterface.class.getClassLoader(), UsbInterface.class);
             UsbConfiguration configuration = new UsbConfiguration(id, name, attributes, maxPower);
             configuration.setInterfaces(interfaces);
             return configuration;
diff --git a/core/java/android/inputmethodservice/InputMethodService.java b/core/java/android/inputmethodservice/InputMethodService.java
index 795eb4a..8f653b3 100644
--- a/core/java/android/inputmethodservice/InputMethodService.java
+++ b/core/java/android/inputmethodservice/InputMethodService.java
@@ -576,6 +576,12 @@
     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
     public static final long DISALLOW_INPUT_METHOD_INTERFACE_OVERRIDE = 148086656L;
 
+    /**
+     * Enable the logic to allow hiding the IME caption bar ("fake" IME navigation bar).
+     * @hide
+     */
+    public static final boolean ENABLE_HIDE_IME_CAPTION_BAR = true;
+
     LayoutInflater mInflater;
     TypedArray mThemeAttrs;
     @UnsupportedAppUsage
diff --git a/core/java/android/inputmethodservice/NavigationBarController.java b/core/java/android/inputmethodservice/NavigationBarController.java
index 78388ef..c01664e 100644
--- a/core/java/android/inputmethodservice/NavigationBarController.java
+++ b/core/java/android/inputmethodservice/NavigationBarController.java
@@ -16,6 +16,8 @@
 
 package android.inputmethodservice;
 
+import static android.inputmethodservice.InputMethodService.ENABLE_HIDE_IME_CAPTION_BAR;
+import static android.view.WindowInsets.Type.captionBar;
 import static android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS;
 
 import android.animation.ValueAnimator;
@@ -230,6 +232,16 @@
 
             setIconTintInternal(calculateTargetDarkIntensity(mAppearance,
                     mDrawLegacyNavigationBarBackground));
+
+            if (ENABLE_HIDE_IME_CAPTION_BAR) {
+                mNavigationBarFrame.setOnApplyWindowInsetsListener((view, insets) -> {
+                    if (mNavigationBarFrame != null) {
+                        boolean visible = insets.isVisible(captionBar());
+                        mNavigationBarFrame.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
+                    }
+                    return view.onApplyWindowInsets(insets);
+                });
+            }
         }
 
         private void uninstallNavigationBarFrameIfNecessary() {
@@ -240,6 +252,9 @@
             if (parent instanceof ViewGroup) {
                 ((ViewGroup) parent).removeView(mNavigationBarFrame);
             }
+            if (ENABLE_HIDE_IME_CAPTION_BAR) {
+                mNavigationBarFrame.setOnApplyWindowInsetsListener(null);
+            }
             mNavigationBarFrame = null;
         }
 
@@ -414,7 +429,9 @@
                         decor.bringChildToFront(mNavigationBarFrame);
                     }
                 }
-                mNavigationBarFrame.setVisibility(View.VISIBLE);
+                if (!ENABLE_HIDE_IME_CAPTION_BAR) {
+                    mNavigationBarFrame.setVisibility(View.VISIBLE);
+                }
             }
         }
 
@@ -435,6 +452,11 @@
                     mShouldShowImeSwitcherWhenImeIsShown;
             mShouldShowImeSwitcherWhenImeIsShown = shouldShowImeSwitcherWhenImeIsShown;
 
+            if (ENABLE_HIDE_IME_CAPTION_BAR) {
+                mService.mWindow.getWindow().getDecorView().getWindowInsetsController()
+                        .setImeCaptionBarInsetsHeight(getImeCaptionBarHeight());
+            }
+
             if (imeDrawsImeNavBar) {
                 installNavigationBarFrameIfNecessary();
                 if (mNavigationBarFrame == null) {
@@ -528,6 +550,16 @@
             return drawLegacyNavigationBarBackground;
         }
 
+        /**
+         * Returns the height of the IME caption bar if this should be shown, or {@code 0} instead.
+         */
+        private int getImeCaptionBarHeight() {
+            return mImeDrawsImeNavBar
+                    ? mService.getResources().getDimensionPixelSize(
+                            com.android.internal.R.dimen.navigation_bar_frame_height)
+                    : 0;
+        }
+
         @Override
         public String toDebugString() {
             return "{mImeDrawsImeNavBar=" + mImeDrawsImeNavBar
diff --git a/core/java/android/inputmethodservice/SoftInputWindow.java b/core/java/android/inputmethodservice/SoftInputWindow.java
index 5704dac..e4a09a6 100644
--- a/core/java/android/inputmethodservice/SoftInputWindow.java
+++ b/core/java/android/inputmethodservice/SoftInputWindow.java
@@ -79,6 +79,13 @@
     @WindowState
     private int mWindowState = WindowState.TOKEN_PENDING;
 
+    @Override
+    protected boolean allowsRegisterDefaultOnBackInvokedCallback() {
+        // Do not register OnBackInvokedCallback from Dialog#onStart, InputMethodService will
+        // register CompatOnBackInvokedCallback for input method window.
+        return false;
+    }
+
     /**
      * Set {@link IBinder} window token to the window.
      *
diff --git a/core/java/android/nfc/NfcAdapter.java b/core/java/android/nfc/NfcAdapter.java
index c111138..36199e5 100644
--- a/core/java/android/nfc/NfcAdapter.java
+++ b/core/java/android/nfc/NfcAdapter.java
@@ -642,6 +642,7 @@
                 try {
                     sTagService = sService.getNfcTagInterface();
                 } catch (RemoteException e) {
+                    sTagService = null;
                     Log.e(TAG, "could not retrieve NFC Tag service");
                     throw new UnsupportedOperationException();
                 }
@@ -650,12 +651,14 @@
                 try {
                     sNfcFCardEmulationService = sService.getNfcFCardEmulationInterface();
                 } catch (RemoteException e) {
+                    sNfcFCardEmulationService = null;
                     Log.e(TAG, "could not retrieve NFC-F card emulation service");
                     throw new UnsupportedOperationException();
                 }
                 try {
                     sCardEmulationService = sService.getNfcCardEmulationInterface();
                 } catch (RemoteException e) {
+                    sCardEmulationService = null;
                     Log.e(TAG, "could not retrieve card emulation service");
                     throw new UnsupportedOperationException();
                 }
@@ -839,30 +842,54 @@
         // assigning to sService is not thread-safe, but this is best-effort code
         // and on a well-behaved system should never happen
         sService = service;
-        try {
-            sTagService = service.getNfcTagInterface();
-        } catch (RemoteException ee) {
-            Log.e(TAG, "could not retrieve NFC tag service during service recovery");
-            // nothing more can be done now, sService is still stale, we'll hit
-            // this recovery path again later
-            return;
+        if (sHasNfcFeature) {
+            try {
+                sTagService = service.getNfcTagInterface();
+            } catch (RemoteException ee) {
+                sTagService = null;
+                Log.e(TAG, "could not retrieve NFC tag service during service recovery");
+                // nothing more can be done now, sService is still stale, we'll hit
+                // this recovery path again later
+                return;
+            }
         }
 
-        try {
-            sCardEmulationService = service.getNfcCardEmulationInterface();
-        } catch (RemoteException ee) {
-            Log.e(TAG, "could not retrieve NFC card emulation service during service recovery");
-        }
+        if (sHasCeFeature) {
+            try {
+                sCardEmulationService = service.getNfcCardEmulationInterface();
+            } catch (RemoteException ee) {
+                sCardEmulationService = null;
+                Log.e(TAG,
+                        "could not retrieve NFC card emulation service during service recovery");
+            }
 
-        try {
-            sNfcFCardEmulationService = service.getNfcFCardEmulationInterface();
-        } catch (RemoteException ee) {
-            Log.e(TAG, "could not retrieve NFC-F card emulation service during service recovery");
+            try {
+                sNfcFCardEmulationService = service.getNfcFCardEmulationInterface();
+            } catch (RemoteException ee) {
+                sNfcFCardEmulationService = null;
+                Log.e(TAG,
+                        "could not retrieve NFC-F card emulation service during service recovery");
+            }
         }
 
         return;
     }
 
+    private boolean isCardEmulationEnabled() {
+        if (sHasCeFeature) {
+            return (sCardEmulationService != null || sNfcFCardEmulationService != null);
+        }
+        return false;
+    }
+
+    private boolean isTagReadingEnabled() {
+        if (sHasNfcFeature) {
+            return sTagService != null;
+        }
+        return false;
+    }
+
+
     /**
      * Return true if this NFC Adapter has any features enabled.
      *
@@ -876,8 +903,9 @@
      * @return true if this NFC Adapter has any features enabled
      */
     public boolean isEnabled() {
+        boolean serviceState = false;
         try {
-            return sService.getState() == STATE_ON;
+            serviceState = sService.getState() == STATE_ON;
         } catch (RemoteException e) {
             attemptDeadServiceRecovery(e);
             // Try one more time
@@ -886,12 +914,12 @@
                 return false;
             }
             try {
-                return sService.getState() == STATE_ON;
+                serviceState = sService.getState() == STATE_ON;
             } catch (RemoteException ee) {
                 Log.e(TAG, "Failed to recover NFC Service.");
             }
-            return false;
         }
+        return serviceState && (isTagReadingEnabled() || isCardEmulationEnabled());
     }
 
     /**
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index 43219bc..42c5626 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -1656,6 +1656,8 @@
     public abstract CpuScalingPolicies getCpuScalingPolicies();
 
     public final static class HistoryTag {
+        public static final int HISTORY_TAG_POOL_OVERFLOW = -1;
+
         public String string;
         public int uid;
 
@@ -6826,10 +6828,11 @@
                     if (bd.mask == HistoryItem.STATE_WAKE_LOCK_FLAG && wakelockTag != null) {
                         didWake = true;
                         sb.append("=");
-                        if (longNames) {
+                        if (longNames
+                                || wakelockTag.poolIdx == HistoryTag.HISTORY_TAG_POOL_OVERFLOW) {
                             UserHandle.formatUid(sb, wakelockTag.uid);
                             sb.append(":\"");
-                            sb.append(wakelockTag.string);
+                            sb.append(wakelockTag.string.replace("\"", "\"\""));
                             sb.append("\"");
                         } else {
                             sb.append(wakelockTag.poolIdx);
@@ -6849,7 +6852,7 @@
         }
         if (!didWake && wakelockTag != null) {
             sb.append(longNames ? " wake_lock=" : ",w=");
-            if (longNames) {
+            if (longNames || wakelockTag.poolIdx == HistoryTag.HISTORY_TAG_POOL_OVERFLOW) {
                 UserHandle.formatUid(sb, wakelockTag.uid);
                 sb.append(":\"");
                 sb.append(wakelockTag.string);
@@ -7110,7 +7113,14 @@
                 if (rec.wakeReasonTag != null) {
                     if (checkin) {
                         item.append(",wr=");
-                        item.append(rec.wakeReasonTag.poolIdx);
+                        if (rec.wakeReasonTag.poolIdx == HistoryTag.HISTORY_TAG_POOL_OVERFLOW) {
+                            item.append(sUidToString.applyAsString(rec.wakeReasonTag.uid));
+                            item.append(":\"");
+                            item.append(rec.wakeReasonTag.string.replace("\"", "\"\""));
+                            item.append("\"");
+                        } else {
+                            item.append(rec.wakeReasonTag.poolIdx);
+                        }
                     } else {
                         item.append(" wake_reason=");
                         item.append(rec.wakeReasonTag.uid);
@@ -7138,7 +7148,15 @@
                     }
                     item.append("=");
                     if (checkin) {
-                        item.append(rec.eventTag.poolIdx);
+                        if (rec.eventTag.poolIdx == HistoryTag.HISTORY_TAG_POOL_OVERFLOW) {
+                            item.append(HISTORY_EVENT_INT_FORMATTERS[idx]
+                                    .applyAsString(rec.eventTag.uid));
+                            item.append(":\"");
+                            item.append(rec.eventTag.string.replace("\"", "\"\""));
+                            item.append("\"");
+                        } else {
+                            item.append(rec.eventTag.poolIdx);
+                        }
                     } else {
                         item.append(HISTORY_EVENT_INT_FORMATTERS[idx]
                                 .applyAsString(rec.eventTag.uid));
diff --git a/core/java/android/os/BugreportParams.java b/core/java/android/os/BugreportParams.java
index d9d14b0..0456a33 100644
--- a/core/java/android/os/BugreportParams.java
+++ b/core/java/android/os/BugreportParams.java
@@ -81,7 +81,8 @@
             BUGREPORT_MODE_REMOTE,
             BUGREPORT_MODE_WEAR,
             BUGREPORT_MODE_TELEPHONY,
-            BUGREPORT_MODE_WIFI
+            BUGREPORT_MODE_WIFI,
+            BUGREPORT_MODE_ONBOARDING
     })
     public @interface BugreportMode {}
 
@@ -121,6 +122,11 @@
     public static final int BUGREPORT_MODE_WIFI = IDumpstate.BUGREPORT_MODE_WIFI;
 
     /**
+     * Options for a lightweight bugreport intended to be taken for onboarding-related flows.
+     */
+    public static final int BUGREPORT_MODE_ONBOARDING = IDumpstate.BUGREPORT_MODE_ONBOARDING;
+
+    /**
      * Defines acceptable flags for customizing bugreport requests.
      * @hide
      */
diff --git a/core/java/android/os/GraphicsEnvironment.java b/core/java/android/os/GraphicsEnvironment.java
index 538ed42..a07735e 100644
--- a/core/java/android/os/GraphicsEnvironment.java
+++ b/core/java/android/os/GraphicsEnvironment.java
@@ -178,23 +178,6 @@
     }
 
     /**
-     * Query to determine if the Game Mode has enabled ANGLE.
-     */
-    private boolean isAngleEnabledByGameMode(Context context, String packageName) {
-        try {
-            final boolean gameModeEnabledAngle =
-                    (mGameManager != null) && mGameManager.isAngleEnabled(packageName);
-            Log.v(TAG, "ANGLE GameManagerService for " + packageName + ": " + gameModeEnabledAngle);
-            return gameModeEnabledAngle;
-        } catch (SecurityException e) {
-            Log.e(TAG, "Caught exception while querying GameManagerService if ANGLE is enabled "
-                    + "for package: " + packageName);
-        }
-
-        return false;
-    }
-
-    /**
      * Query to determine the ANGLE driver choice.
      */
     private String queryAngleChoice(Context context, Bundle coreSettings,
@@ -422,8 +405,7 @@
      * 2) The per-application switch (i.e. Settings.Global.ANGLE_GL_DRIVER_SELECTION_PKGS and
      *    Settings.Global.ANGLE_GL_DRIVER_SELECTION_VALUES; which corresponds to the
      *    “angle_gl_driver_selection_pkgs” and “angle_gl_driver_selection_values” settings); if it
-     *    forces a choice;
-     * 3) Use ANGLE if isAngleEnabledByGameMode() returns true;
+     *    forces a choice.
      */
     private String queryAngleChoiceInternal(Context context, Bundle bundle,
                                                        String packageName) {
@@ -457,10 +439,6 @@
         Log.v(TAG, "  angle_gl_driver_selection_pkgs=" + optInPackages);
         Log.v(TAG, "  angle_gl_driver_selection_values=" + optInValues);
 
-        final String gameModeChoice = isAngleEnabledByGameMode(context, packageName)
-                                      ? ANGLE_GL_DRIVER_CHOICE_ANGLE
-                                      : ANGLE_GL_DRIVER_CHOICE_DEFAULT;
-
         // Make sure we have good settings to use
         if (optInPackages.size() == 0 || optInPackages.size() != optInValues.size()) {
             Log.v(TAG,
@@ -469,7 +447,7 @@
                             + optInPackages.size() + ", "
                         + "number of values: "
                             + optInValues.size());
-            return gameModeChoice;
+            return ANGLE_GL_DRIVER_CHOICE_DEFAULT;
         }
 
         // See if this application is listed in the per-application settings list
@@ -477,7 +455,7 @@
 
         if (pkgIndex < 0) {
             Log.v(TAG, packageName + " is not listed in per-application setting");
-            return gameModeChoice;
+            return ANGLE_GL_DRIVER_CHOICE_DEFAULT;
         }
         mAngleOptInIndex = pkgIndex;
 
@@ -491,11 +469,9 @@
             return ANGLE_GL_DRIVER_CHOICE_ANGLE;
         } else if (optInValue.equals(ANGLE_GL_DRIVER_CHOICE_NATIVE)) {
             return ANGLE_GL_DRIVER_CHOICE_NATIVE;
-        } else {
-            // The user either chose default or an invalid value; go with the default driver or what
-            // the game mode indicates
-            return gameModeChoice;
         }
+        // The user either chose default or an invalid value; go with the default driver.
+        return ANGLE_GL_DRIVER_CHOICE_DEFAULT;
     }
 
     /**
diff --git a/core/java/android/os/Handler.java b/core/java/android/os/Handler.java
index 2584f04..22d6fcd 100644
--- a/core/java/android/os/Handler.java
+++ b/core/java/android/os/Handler.java
@@ -182,7 +182,7 @@
      *
      * Asynchronous messages represent interrupts or events that do not require global ordering
      * with respect to synchronous messages.  Asynchronous messages are not subject to
-     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
+     * the synchronization barriers introduced by {@link MessageQueue#postSyncBarrier()}.
      *
      * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
      * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
@@ -203,7 +203,7 @@
      *
      * Asynchronous messages represent interrupts or events that do not require global ordering
      * with respect to synchronous messages.  Asynchronous messages are not subject to
-     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
+     * the synchronization barriers introduced by {@link MessageQueue#postSyncBarrier()}.
      *
      * @param callback The callback interface in which to handle messages, or null.
      * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
@@ -751,7 +751,7 @@
         MessageQueue queue = mQueue;
         if (queue == null) {
             RuntimeException e = new RuntimeException(
-                this + " sendMessageAtTime() called with no mQueue");
+                    this + " sendMessageAtFrontOfQueue() called with no mQueue");
             Log.w("Looper", e.getMessage(), e);
             return false;
         }
diff --git a/core/java/android/os/IHintSession.aidl b/core/java/android/os/IHintSession.aidl
index 0d1dde1..6b43e73 100644
--- a/core/java/android/os/IHintSession.aidl
+++ b/core/java/android/os/IHintSession.aidl
@@ -23,4 +23,5 @@
     void reportActualWorkDuration(in long[] actualDurationNanos, in long[] timeStampNanos);
     void close();
     void sendHint(int hint);
+    void setMode(int mode, boolean enabled);
 }
diff --git a/core/java/android/os/IPowerManager.aidl b/core/java/android/os/IPowerManager.aidl
index be7c1e5..dbb6f92 100644
--- a/core/java/android/os/IPowerManager.aidl
+++ b/core/java/android/os/IPowerManager.aidl
@@ -60,6 +60,7 @@
     boolean isPowerSaveMode();
     PowerSaveState getPowerSaveState(int serviceType);
     boolean setPowerSaveModeEnabled(boolean mode);
+    boolean isBatterySaverSupported();
     BatterySaverPolicyConfig getFullPowerSavePolicy();
     boolean setFullPowerSavePolicy(in BatterySaverPolicyConfig config);
     boolean setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold);
diff --git a/core/java/android/os/LocaleList.java b/core/java/android/os/LocaleList.java
index 82cdd28..b74bb33 100644
--- a/core/java/android/os/LocaleList.java
+++ b/core/java/android/os/LocaleList.java
@@ -30,7 +30,6 @@
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Locale;
 
 /**
@@ -152,25 +151,6 @@
     }
 
     /**
-     * Find the intersection between this LocaleList and another
-     * @return a String array of the Locales in both LocaleLists
-     * {@hide}
-     */
-    @NonNull
-    public String[] getIntersection(@NonNull LocaleList other) {
-        List<String> intersection = new ArrayList<>();
-        for (Locale l1 : mList) {
-            for (Locale l2 : other.mList) {
-                if (matchesLanguageAndScript(l2, l1)) {
-                    intersection.add(l1.toLanguageTag());
-                    break;
-                }
-            }
-        }
-        return intersection.toArray(new String[0]);
-    }
-
-    /**
      * Creates a new {@link LocaleList}.
      *
      * If two or more same locales are passed, the repeated locales will be dropped.
diff --git a/core/java/android/os/OWNERS b/core/java/android/os/OWNERS
index 69889c5..8f7725ec 100644
--- a/core/java/android/os/OWNERS
+++ b/core/java/android/os/OWNERS
@@ -10,6 +10,7 @@
 # BatteryStats
 per-file *BatteryConsumer* = file:/BATTERY_STATS_OWNERS
 per-file BatteryManager* = file:/BATTERY_STATS_OWNERS
+per-file PowerMonitor* = file:/BATTERY_STATS_OWNERS
 per-file PowerComponents.java = file:/BATTERY_STATS_OWNERS
 per-file *Stats* = file:/BATTERY_STATS_OWNERS
 
@@ -83,3 +84,6 @@
 # DDM Protocol
 per-file DdmSyncState.java = sanglardf@google.com, rpaquay@google.com
 per-file DdmSyncStageUpdater.java = sanglardf@google.com, rpaquay@google.com
+
+# PerformanceHintManager
+per-file PerformanceHintManager.java = file:/ADPF_OWNERS
diff --git a/core/java/android/os/PerformanceHintManager.java b/core/java/android/os/PerformanceHintManager.java
index 977ef60..cbc9213 100644
--- a/core/java/android/os/PerformanceHintManager.java
+++ b/core/java/android/os/PerformanceHintManager.java
@@ -51,19 +51,33 @@
     }
 
     /**
+     * Get preferred update rate information for this device.
+     *
+     * @return the preferred update rate supported by device software
+     */
+    public long getPreferredUpdateRateNanos() {
+        return nativeGetPreferredUpdateRateNanos(mNativeManagerPtr);
+    }
+
+    /**
      * Creates a {@link Session} for the given set of threads and sets their initial target work
      * duration.
      *
      * @param tids The list of threads to be associated with this session. They must be part of
-     *     this process' thread group.
+     *     this process' thread group
      * @param initialTargetWorkDurationNanos The desired duration in nanoseconds for the new
-     *     session.
+     *     session
      * @return the new session if it is supported on this device, null if hint session is not
-     *     supported on this device.
+     *     supported on this device or the tid doesn't belong to the application
+     * @throws IllegalArgumentException if the thread id list is empty, or
+     *                                  initialTargetWorkDurationNanos is non-positive
      */
     @Nullable
     public Session createHintSession(@NonNull int[] tids, long initialTargetWorkDurationNanos) {
-        Preconditions.checkNotNull(tids, "tids cannot be null");
+        Objects.requireNonNull(tids, "tids cannot be null");
+        if (tids.length == 0) {
+            throw new IllegalArgumentException("thread id list can't be empty.");
+        }
         Preconditions.checkArgumentPositive(initialTargetWorkDurationNanos,
                 "the hint target duration should be positive.");
         long nativeSessionPtr = nativeCreateSession(mNativeManagerPtr, tids,
@@ -73,35 +87,22 @@
     }
 
     /**
-     * Get preferred update rate information for this device.
-     *
-     * @return the preferred update rate supported by device software.
-     */
-    public long getPreferredUpdateRateNanos() {
-        return nativeGetPreferredUpdateRateNanos(mNativeManagerPtr);
-    }
-
-    /**
      * A Session represents a group of threads with an inter-related workload such that hints for
      * their performance should be considered as a unit. The threads in a given session should be
-     * long-life and not created or destroyed dynamically.
+     * long-lived and not created or destroyed dynamically.
      *
-     * <p>Each session is expected to have a periodic workload with a target duration for each
-     * cycle. The cycle duration is likely greater than the target work duration to allow other
-     * parts of the pipeline to run within the available budget. For example, a renderer thread may
-     * work at 60hz in order to produce frames at the display's frame but have a target work
-     * duration of only 6ms.</p>
+     * The work duration API can be used with periodic workloads to dynamically adjust thread
+     * performance and keep the work on schedule while optimizing the available power budget.
+     * When using the work duration API, the starting target duration should be specified
+     * while creating the session, but can later be adjusted with
+     * {@link #updateTargetWorkDuration(long)}. While using the work duration API, the client is be
+     * expected to call {@link #reportActualWorkDuration(long)} each cycle to report the actual
+     * time taken to complete to the system.
      *
-     * <p>Any call in this class will change its internal data, so you must do your own thread
-     * safety to protect from racing.</p>
+     * Any call in this class will change its internal data, so you must do your own thread
+     * safety to protect from racing.
      *
-     * <p>Note that the target work duration can be {@link #updateTargetWorkDuration(long) updated}
-     * if workloads change.</p>
-     *
-     * <p>After each cycle of work, the client is expected to
-     * {@link #reportActualWorkDuration(long) report} the actual time taken to complete.</p>
-     *
-     * <p>All timings should be in {@link SystemClock#elapsedRealtimeNanos()}.</p>
+     * All timings should be in {@link SystemClock#elapsedRealtimeNanos()}.
      */
     public static class Session implements Closeable {
         private long mNativeSessionPtr;
@@ -181,9 +182,9 @@
         /**
          * Reports the actual duration for the last cycle of work.
          *
-         * <p>The system will attempt to adjust the core placement of the threads within the thread
+         * The system will attempt to adjust the core placement of the threads within the thread
          * group and/or the frequency of the core on which they are run to bring the actual duration
-         * close to the target duration.</p>
+         * close to the target duration.
          *
          * @param actualDurationNanos how long the thread group took to complete its last task in
          *     nanoseconds
@@ -197,7 +198,7 @@
         /**
          * Ends the current hint session.
          *
-         * <p>Once called, you should not call anything else on this object.</p>
+         * Once called, you should not call anything else on this object.
          */
         public void close() {
             if (mNativeSessionPtr != 0) {
@@ -209,7 +210,7 @@
         /**
          * Sends performance hints to inform the hint session of changes in the workload.
          *
-         * @param hint The hint to send to the session.
+         * @param hint The hint to send to the session
          *
          * @hide
          */
@@ -225,16 +226,26 @@
         }
 
         /**
+         * This tells the session that these threads can be
+         * safely scheduled to prefer power efficiency over performance.
+         *
+         * @param enabled The flag that sets whether this session uses power-efficient scheduling.
+         */
+        public void setPreferPowerEfficiency(boolean enabled) {
+            nativeSetPreferPowerEfficiency(mNativeSessionPtr, enabled);
+        }
+
+        /**
          * Set a list of threads to the performance hint session. This operation will replace
          * the current list of threads with the given list of threads.
          * Note that this is not an oneway method.
          *
          * @param tids The list of threads to be associated with this session. They must be
-         *     part of this app's thread group.
+         *     part of this app's thread group
          *
-         * @throws IllegalStateException if the hint session is not in the foreground.
-         * @throws IllegalArgumentException if the thread id list is empty.
-         * @throws SecurityException if any thread id doesn't belong to the application.
+         * @throws IllegalStateException if the hint session is not in the foreground
+         * @throws IllegalArgumentException if the thread id list is empty
+         * @throws SecurityException if any thread id doesn't belong to the application
          */
         public void setThreads(@NonNull int[] tids) {
             if (mNativeSessionPtr == 0) {
@@ -270,4 +281,6 @@
     private static native void nativeCloseSession(long nativeSessionPtr);
     private static native void nativeSendHint(long nativeSessionPtr, int hint);
     private static native void nativeSetThreads(long nativeSessionPtr, int[] tids);
+    private static native void nativeSetPreferPowerEfficiency(long nativeSessionPtr,
+            boolean enabled);
 }
diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java
index c6b9d20..4174c1c 100644
--- a/core/java/android/os/PowerManager.java
+++ b/core/java/android/os/PowerManager.java
@@ -33,7 +33,6 @@
 import android.compat.annotation.UnsupportedAppUsage;
 import android.content.Context;
 import android.service.dreams.Sandman;
-import android.sysprop.InitProperties;
 import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.Log;
@@ -868,6 +867,8 @@
 
     /**
      * The 'reason' value used for rebooting userspace.
+     *
+     * @deprecated userspace reboot is not supported
      * @hide
      */
     @SystemApi
@@ -1824,16 +1825,18 @@
      * <p>This method exists solely for the sake of re-using same logic between {@code PowerManager}
      * and {@code PowerManagerService}.
      *
+     * @deprecated TODO(b/292469129): remove this method.
      * @hide
      */
     public static boolean isRebootingUserspaceSupportedImpl() {
-        return InitProperties.is_userspace_reboot_supported().orElse(false);
+        return false;
     }
 
     /**
      * Returns {@code true} if this device supports rebooting userspace.
+     *
+     * @deprecated userspace reboot is deprecated, this method always returns {@code false}.
      */
-    // TODO(b/138605180): add link to documentation once it's ready.
     public boolean isRebootingUserspaceSupported() {
         return isRebootingUserspaceSupportedImpl();
     }
@@ -1933,6 +1936,20 @@
     }
 
     /**
+     * Returns true if Battery Saver is supported on this device.
+     *
+     * @hide
+     */
+    @TestApi
+    public boolean isBatterySaverSupported() {
+        try {
+            return mService.isBatterySaverSupported();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Gets the current policy for full power save mode.
      *
      * @return The {@link BatterySaverPolicyConfig} which is currently set for the full power save
diff --git a/core/java/android/os/PowerMonitor.java b/core/java/android/os/PowerMonitor.java
index ebdd463..5fb0df7 100644
--- a/core/java/android/os/PowerMonitor.java
+++ b/core/java/android/os/PowerMonitor.java
@@ -23,6 +23,10 @@
 import java.lang.annotation.RetentionPolicy;
 
 /**
+ * A PowerMonitor represents either a Channel aka ODPM rail (on-device power monitor) or an
+ * EnergyConsumer, as defined in
+ * <a href="https://android.googlesource.com/platform/hardware/interfaces/+/refs/heads/main/power/stats/aidl/aidl_api/android.hardware.power.stats/current/android/hardware/power/stats">android.hardware.power.stats</a>
+ *
  * @hide
  */
 public final class PowerMonitor implements Parcelable {
@@ -92,6 +96,7 @@
         return 0;
     }
 
+    @NonNull
     public static final Creator<PowerMonitor> CREATOR = new Creator<>() {
         @Override
         public PowerMonitor createFromParcel(@NonNull Parcel in) {
diff --git a/core/java/android/os/PowerMonitorReadings.java b/core/java/android/os/PowerMonitorReadings.java
index 3d7f859..e767059 100644
--- a/core/java/android/os/PowerMonitorReadings.java
+++ b/core/java/android/os/PowerMonitorReadings.java
@@ -16,6 +16,7 @@
 
 package android.os;
 
+import android.annotation.ElapsedRealtimeLong;
 import android.annotation.NonNull;
 
 import java.util.Arrays;
@@ -43,8 +44,8 @@
      * @param powerMonitors array of power monitor (ODPM) rails, sorted by PowerMonitor.index
      * @hide
      */
-    public PowerMonitorReadings(PowerMonitor[] powerMonitors,
-            long[] energyUws, long[] timestampsMs) {
+    public PowerMonitorReadings(@NonNull PowerMonitor[] powerMonitors,
+            @NonNull long[] energyUws, @NonNull long[] timestampsMs) {
         mPowerMonitors = powerMonitors;
         mEnergyUws = energyUws;
         mTimestampsMs = timestampsMs;
@@ -55,7 +56,7 @@
      * Does not persist across reboots.
      * Represents total energy: both on-battery and plugged-in.
      */
-    public long getConsumedEnergyUws(PowerMonitor powerMonitor) {
+    public long getConsumedEnergyUws(@NonNull PowerMonitor powerMonitor) {
         int offset = Arrays.binarySearch(mPowerMonitors, powerMonitor, POWER_MONITOR_COMPARATOR);
         if (offset >= 0) {
             return mEnergyUws[offset];
@@ -64,9 +65,10 @@
     }
 
     /**
-     * Elapsed realtime when the snapshot was taken.
+     * Elapsed realtime, in milliseconds, when the snapshot was taken.
      */
-    public long getTimestampMs(PowerMonitor powerMonitor) {
+    @ElapsedRealtimeLong
+    public long getTimestamp(@NonNull PowerMonitor powerMonitor) {
         int offset = Arrays.binarySearch(mPowerMonitors, powerMonitor, POWER_MONITOR_COMPARATOR);
         if (offset >= 0) {
             return mTimestampsMs[offset];
diff --git a/core/java/android/os/StrictMode.java b/core/java/android/os/StrictMode.java
index 180735b..81d4e3a 100644
--- a/core/java/android/os/StrictMode.java
+++ b/core/java/android/os/StrictMode.java
@@ -1462,7 +1462,7 @@
 
         if (Build.IS_USER || DISABLE || SystemProperties.getBoolean(DISABLE_PROPERTY, false)) {
             // Detect nothing extra
-        } else if (Build.IS_USERDEBUG) {
+        } else if (Build.IS_USERDEBUG || Build.IS_ENG) {
             // Detect everything in bundled apps
             if (isBundledSystemApp(ai)) {
                 builder.detectAll();
@@ -1470,14 +1470,9 @@
                 if (SystemProperties.getBoolean(VISUAL_PROPERTY, false)) {
                     builder.penaltyFlashScreen();
                 }
-            }
-        } else if (Build.IS_ENG) {
-            // Detect everything in bundled apps
-            if (isBundledSystemApp(ai)) {
-                builder.detectAll();
-                builder.penaltyDropBox();
-                builder.penaltyLog();
-                builder.penaltyFlashScreen();
+                if (Build.IS_ENG) {
+                    builder.penaltyLog();
+                }
             }
         }
 
diff --git a/core/java/android/os/TEST_MAPPING b/core/java/android/os/TEST_MAPPING
index dae9b5e..60622f18 100644
--- a/core/java/android/os/TEST_MAPPING
+++ b/core/java/android/os/TEST_MAPPING
@@ -99,13 +99,10 @@
         "BatteryStats[^/]*\\.java",
         "BatteryUsageStats[^/]*\\.java",
         "PowerComponents\\.java",
+        "PowerMonitor[^/]*\\.java",
         "[^/]*BatteryConsumer[^/]*\\.java"
       ],
-      "name": "FrameworksServicesTests",
-      "options": [
-        { "include-filter": "com.android.server.power.stats" },
-        { "exclude-filter": "com.android.server.power.stats.BatteryStatsTests" }
-      ]
+      "name": "PowerStatsTests"
     },
     {
       "file_patterns": [
diff --git a/core/java/android/os/UserHandle.java b/core/java/android/os/UserHandle.java
index 0527ed6..cac7f3b 100644
--- a/core/java/android/os/UserHandle.java
+++ b/core/java/android/os/UserHandle.java
@@ -125,7 +125,8 @@
     public static final int MIN_SECONDARY_USER_ID = 10;
 
     /** @hide */
-    public static final int MAX_SECONDARY_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
+    public static final int MAX_SECONDARY_USER_ID =
+            Integer.MAX_VALUE / UserHandle.PER_USER_RANGE - 1;
 
     /**
      * (Arbitrary) user handle cache size.
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index ba1f979..d8cf4de 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -4618,6 +4618,26 @@
     }
 
     /**
+     * Returns number of full users on the device.
+     * @hide
+     */
+    @RequiresPermission(anyOf = {
+            android.Manifest.permission.MANAGE_USERS,
+            android.Manifest.permission.CREATE_USERS
+    })
+    public int getFullUserCount() {
+        List<UserInfo> users = getUsers(/* excludePartial= */ true, /* excludeDying= */ true,
+                /* excludePreCreated= */ true);
+        int count = 0;
+        for (UserInfo user : users) {
+            if (user.isFull()) {
+                count++;
+            }
+        }
+        return count;
+    }
+
+    /**
      * @deprecated use {@link #getAliveUsers()} for {@code getUsers(true)}, or
      * {@link #getUsers()} for @code getUsers(false)}.
      *
diff --git a/core/java/android/os/VibrationEffect.java b/core/java/android/os/VibrationEffect.java
index b24b45d..08b32bf 100644
--- a/core/java/android/os/VibrationEffect.java
+++ b/core/java/android/os/VibrationEffect.java
@@ -525,14 +525,14 @@
     public abstract long getDuration();
 
     /**
-     * Checks if a given {@link Vibrator} can play this effect as intended.
+     * Checks if a vibrator with a given {@link VibratorInfo} can play this effect as intended.
      *
-     * <p>See @link Vibrator#areVibrationFeaturesSupported(VibrationEffect)} for more information
-     * about what counts as supported by a vibrator, and what counts as not.
+     * <p>See {@link VibratorInfo#areVibrationFeaturesSupported(VibrationEffect)} for more
+     * information about what counts as supported by a vibrator, and what counts as not.
      *
      * @hide
      */
-    public abstract boolean areVibrationFeaturesSupported(@NonNull Vibrator vibrator);
+    public abstract boolean areVibrationFeaturesSupported(@NonNull VibratorInfo vibratorInfo);
 
     /**
      * Returns true if this effect could represent a touch haptic feedback.
@@ -813,9 +813,9 @@
 
         /** @hide */
         @Override
-        public boolean areVibrationFeaturesSupported(@NonNull Vibrator vibrator) {
+        public boolean areVibrationFeaturesSupported(@NonNull VibratorInfo vibratorInfo) {
             for (VibrationEffectSegment segment : mSegments) {
-                if (!segment.areVibrationFeaturesSupported(vibrator)) {
+                if (!segment.areVibrationFeaturesSupported(vibratorInfo)) {
                     return false;
                 }
             }
diff --git a/core/java/android/os/Vibrator.java b/core/java/android/os/Vibrator.java
index 4e852e3..79e0ca8 100644
--- a/core/java/android/os/Vibrator.java
+++ b/core/java/android/os/Vibrator.java
@@ -216,9 +216,7 @@
      */
     @TestApi
     public boolean hasFrequencyControl() {
-        // We currently can only control frequency of the vibration using the compose PWLE method.
-        return getInfo().hasCapability(
-                IVibrator.CAP_FREQUENCY_CONTROL | IVibrator.CAP_COMPOSE_PWLE_EFFECTS);
+        return getInfo().hasFrequencyControl();
     }
 
     /**
@@ -240,7 +238,7 @@
      * @hide
      */
     public boolean areVibrationFeaturesSupported(@NonNull VibrationEffect effect) {
-        return effect.areVibrationFeaturesSupported(this);
+        return getInfo().areVibrationFeaturesSupported(effect);
     }
 
     /**
diff --git a/core/java/android/os/VibratorInfo.java b/core/java/android/os/VibratorInfo.java
index 02e6856..0b7d7c3 100644
--- a/core/java/android/os/VibratorInfo.java
+++ b/core/java/android/os/VibratorInfo.java
@@ -242,6 +242,17 @@
     }
 
     /**
+     * Check whether the vibrator has frequency control.
+     *
+     * @return True if the hardware can control the frequency of the vibrations, otherwise false.
+     */
+    public boolean hasFrequencyControl() {
+        // We currently can only control frequency of the vibration using the compose PWLE method.
+        return hasCapability(
+                IVibrator.CAP_FREQUENCY_CONTROL | IVibrator.CAP_COMPOSE_PWLE_EFFECTS);
+    }
+
+    /**
      * Returns a default value to be applied to composed PWLE effects for braking.
      *
      * @return a supported braking value, one of android.hardware.vibrator.Braking.*
@@ -323,6 +334,23 @@
     }
 
     /**
+     * Query whether or not the vibrator supports all components of a given {@link VibrationEffect}
+     * (i.e. the vibrator can play the given effect as intended).
+     *
+     * <p>See {@link Vibrator#areVibrationFeaturesSupported(VibrationEffect)} for more
+     * information on how the vibrator support is determined.
+     *
+     * @param effect the {@link VibrationEffect} to check if it is supported
+     * @return {@code true} if the vibrator can play the given {@code effect} as intended,
+     *         {@code false} otherwise.
+     *
+     * @hide
+     */
+    public boolean areVibrationFeaturesSupported(@NonNull VibrationEffect effect) {
+        return effect.areVibrationFeaturesSupported(this);
+    }
+
+    /**
      * Query the estimated duration of given primitive.
      *
      * @param primitiveId Which primitives to query for.
diff --git a/core/java/android/os/health/SystemHealthManager.java b/core/java/android/os/health/SystemHealthManager.java
index ab30a8b..dfc43f4 100644
--- a/core/java/android/os/health/SystemHealthManager.java
+++ b/core/java/android/os/health/SystemHealthManager.java
@@ -24,6 +24,8 @@
 import android.os.BatteryStats;
 import android.os.Build;
 import android.os.Bundle;
+import android.os.ConditionVariable;
+import android.os.Handler;
 import android.os.IPowerStatsService;
 import android.os.PowerMonitor;
 import android.os.PowerMonitorReadings;
@@ -36,8 +38,8 @@
 
 import java.util.Arrays;
 import java.util.Comparator;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ExecutionException;
+import java.util.List;
+import java.util.function.Consumer;
 
 /**
  * Provides access to data about how various system resources are used by applications.
@@ -62,7 +64,8 @@
     private final IBatteryStats mBatteryStats;
     @Nullable
     private final IPowerStatsService mPowerStats;
-    private PowerMonitor[] mPowerMonitorsInfo;
+    private List<PowerMonitor> mPowerMonitorsInfo;
+    private final Object mPowerMonitorsLock = new Object();
 
     /**
      * Construct a new SystemHealthManager object.
@@ -161,53 +164,68 @@
      * @hide
      */
     @NonNull
-    public PowerMonitor[] getSupportedPowerMonitors() {
-        synchronized (this) {
+    public List<PowerMonitor> getSupportedPowerMonitors() {
+        synchronized (mPowerMonitorsLock) {
             if (mPowerMonitorsInfo != null) {
                 return mPowerMonitorsInfo;
             }
+        }
+        ConditionVariable lock = new ConditionVariable();
+        // Populate mPowerMonitorsInfo by side-effect
+        getSupportedPowerMonitors(null, unused -> lock.open());
+        lock.block();
 
-            CompletableFuture<PowerMonitor[]> future = new CompletableFuture<>();
-            getSupportedPowerMonitors(future);
-            try {
-                return future.get();
-            } catch (InterruptedException | ExecutionException e) {
-                throw new RuntimeException(e);
-            }
+        synchronized (mPowerMonitorsLock) {
+            return mPowerMonitorsInfo;
         }
     }
 
     /**
-     * Retrieves a list of supported power monitors, see {@link #getSupportedPowerMonitors()}
+     * Asynchronously retrieves a list of supported power monitors, see
+     * {@link #getSupportedPowerMonitors()}
+     *
+     * @param handler optional Handler to deliver the callback. If not supplied, the callback
+     *                may be invoked on an arbitrary thread.
+     * @param onResult callback for the result
      *
      * @hide
      */
-    public void getSupportedPowerMonitors(@NonNull CompletableFuture<PowerMonitor[]> future) {
-        synchronized (this) {
+    public void getSupportedPowerMonitors(@Nullable Handler handler,
+            @NonNull Consumer<List<PowerMonitor>> onResult) {
+        final List<PowerMonitor> result;
+        synchronized (mPowerMonitorsLock) {
             if (mPowerMonitorsInfo != null) {
-                future.complete(mPowerMonitorsInfo);
-                return;
+                result = mPowerMonitorsInfo;
+            } else if (mPowerStats == null) {
+                mPowerMonitorsInfo = List.of();
+                result = mPowerMonitorsInfo;
+            } else {
+                result = null;
             }
-            try {
-                if (mPowerStats == null) {
-                    mPowerMonitorsInfo = new PowerMonitor[0];
-                    future.complete(mPowerMonitorsInfo);
-                    return;
-                }
-
-                mPowerStats.getSupportedPowerMonitors(new ResultReceiver(null) {
-                    @Override
-                    protected void onReceiveResult(int resultCode, Bundle resultData) {
-                        synchronized (this) {
-                            mPowerMonitorsInfo = resultData.getParcelableArray(
-                                    IPowerStatsService.KEY_MONITORS, PowerMonitor.class);
-                        }
-                        future.complete(mPowerMonitorsInfo);
+        }
+        if (result != null) {
+            if (handler != null) {
+                handler.post(() -> onResult.accept(result));
+            } else {
+                onResult.accept(result);
+            }
+            return;
+        }
+        try {
+            mPowerStats.getSupportedPowerMonitors(new ResultReceiver(handler) {
+                @Override
+                protected void onReceiveResult(int resultCode, Bundle resultData) {
+                    PowerMonitor[] array = resultData.getParcelableArray(
+                            IPowerStatsService.KEY_MONITORS, PowerMonitor.class);
+                    List<PowerMonitor> result = array != null ? Arrays.asList(array) : List.of();
+                    synchronized (mPowerMonitorsLock) {
+                        mPowerMonitorsInfo = result;
                     }
-                });
-            } catch (RemoteException e) {
-                throw e.rethrowFromSystemServer();
-            }
+                    onResult.accept(result);
+                }
+            });
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
         }
     }
 
@@ -215,54 +233,74 @@
      * Retrieves the accumulated power consumption reported by the specified power monitors.
      *
      * @param powerMonitors power monitors to be returned.
+     *
      * @hide
      */
     @NonNull
-    public PowerMonitorReadings getPowerMonitorReadings(@NonNull PowerMonitor[] powerMonitors) {
-        CompletableFuture<PowerMonitorReadings> future = new CompletableFuture<>();
-        getPowerMonitorReadings(powerMonitors, future);
-        try {
-            return future.get();
-        } catch (InterruptedException | ExecutionException e) {
-            throw new RuntimeException(e);
+    public PowerMonitorReadings getPowerMonitorReadings(@NonNull List<PowerMonitor> powerMonitors) {
+        PowerMonitorReadings[] outReadings = new PowerMonitorReadings[1];
+        RuntimeException[] outException = new RuntimeException[1];
+        ConditionVariable lock = new ConditionVariable();
+        getPowerMonitorReadings(powerMonitors, null,
+                pms -> {
+                    outReadings[0] = pms;
+                    lock.open();
+                },
+                error -> {
+                    outException[0] = error;
+                    lock.open();
+                }
+        );
+        lock.block();
+        if (outException[0] != null) {
+            throw outException[0];
         }
+        return outReadings[0];
     }
 
     private static final Comparator<PowerMonitor> POWER_MONITOR_COMPARATOR =
             Comparator.comparingInt(pm -> pm.index);
 
     /**
+     * Asynchronously retrieves the accumulated power consumption reported by the specified power
+     * monitors.
+     *
      * @param powerMonitors power monitors to be retrieved.
+     * @param handler       optional Handler to deliver the callbacks. If not supplied, the callback
+     *                      may be invoked on an arbitrary thread.
+     * @param onSuccess     callback for the result
+     * @param onError       callback invoked in case of an error
+     *
      * @hide
      */
-    public void getPowerMonitorReadings(@NonNull PowerMonitor[] powerMonitors,
-            @NonNull CompletableFuture<PowerMonitorReadings> future) {
+    public void getPowerMonitorReadings(@NonNull List<PowerMonitor> powerMonitors,
+            @Nullable Handler handler, @NonNull Consumer<PowerMonitorReadings> onSuccess,
+            @NonNull Consumer<RuntimeException> onError) {
         if (mPowerStats == null) {
-            future.completeExceptionally(
-                    new IllegalArgumentException("Unsupported power monitor"));
+            onError.accept(new IllegalArgumentException("Unsupported power monitor"));
             return;
         }
 
-        Arrays.sort(powerMonitors, POWER_MONITOR_COMPARATOR);
-        int[] indices = new int[powerMonitors.length];
-        for (int i = 0; i < powerMonitors.length; i++) {
-            indices[i] = powerMonitors[i].index;
+        PowerMonitor[] powerMonitorsArray =
+                powerMonitors.toArray(new PowerMonitor[powerMonitors.size()]);
+        Arrays.sort(powerMonitorsArray, POWER_MONITOR_COMPARATOR);
+        int[] indices = new int[powerMonitors.size()];
+        for (int i = 0; i < powerMonitors.size(); i++) {
+            indices[i] = powerMonitorsArray[i].index;
         }
         try {
-            mPowerStats.getPowerMonitorReadings(indices, new ResultReceiver(null) {
+            mPowerStats.getPowerMonitorReadings(indices, new ResultReceiver(handler) {
                 @Override
                 protected void onReceiveResult(int resultCode, Bundle resultData) {
                     if (resultCode == IPowerStatsService.RESULT_SUCCESS) {
-                        future.complete(new PowerMonitorReadings(powerMonitors,
+                        onSuccess.accept(new PowerMonitorReadings(powerMonitorsArray,
                                 resultData.getLongArray(IPowerStatsService.KEY_ENERGY),
                                 resultData.getLongArray(IPowerStatsService.KEY_TIMESTAMPS)));
                     } else if (resultCode == IPowerStatsService.RESULT_UNSUPPORTED_POWER_MONITOR) {
-                        future.completeExceptionally(
-                                new IllegalArgumentException("Unsupported power monitor"));
+                        onError.accept(new IllegalArgumentException("Unsupported power monitor"));
                     } else {
-                        future.completeExceptionally(
-                                new IllegalStateException(
-                                        "Unrecognized result code " + resultCode));
+                        onError.accept(new IllegalStateException(
+                                "Unrecognized result code " + resultCode));
                     }
                 }
             });
diff --git a/core/java/android/os/storage/StorageManagerInternal.java b/core/java/android/os/storage/StorageManagerInternal.java
index 059bd84..22e8251 100644
--- a/core/java/android/os/storage/StorageManagerInternal.java
+++ b/core/java/android/os/storage/StorageManagerInternal.java
@@ -19,6 +19,7 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.UserIdInt;
+import android.content.pm.UserInfo;
 import android.os.IVold;
 
 import java.util.List;
@@ -169,4 +170,19 @@
      */
     public abstract void registerCloudProviderChangeListener(
             @NonNull CloudProviderChangeListener listener);
+
+    /**
+     * Prepares user data directories before moving storage or apps. This is required as adoptable
+     * storage unlock is tied to the prepare user data and storage needs to be unlocked before
+     * performing any operations on it. This will also create user data directories before
+     * initiating the move operations, which essential for ensuring the directories to have correct
+     * SELinux labels and permissions.
+     *
+     * @param fromVolumeUuid the source volume UUID from which content needs to be transferred
+     * @param toVolumeUuid the destination volume UUID to which contents are to be transferred
+     * @param users a list of users for whom to prepare storage
+     */
+    public abstract void prepareUserStorageForMove(String fromVolumeUuid, String toVolumeUuid,
+            List<UserInfo> users);
+
 }
diff --git a/core/java/android/os/vibrator/PrebakedSegment.java b/core/java/android/os/vibrator/PrebakedSegment.java
index 42b6c2da..a035092 100644
--- a/core/java/android/os/vibrator/PrebakedSegment.java
+++ b/core/java/android/os/vibrator/PrebakedSegment.java
@@ -23,6 +23,7 @@
 import android.os.Parcelable;
 import android.os.VibrationEffect;
 import android.os.Vibrator;
+import android.os.VibratorInfo;
 
 import java.util.Objects;
 
@@ -77,8 +78,8 @@
 
     /** @hide */
     @Override
-    public boolean areVibrationFeaturesSupported(@NonNull Vibrator vibrator) {
-        if (vibrator.areAllEffectsSupported(mEffectId) == Vibrator.VIBRATION_EFFECT_SUPPORT_YES) {
+    public boolean areVibrationFeaturesSupported(@NonNull VibratorInfo vibratorInfo) {
+        if (vibratorInfo.isEffectSupported(mEffectId) == Vibrator.VIBRATION_EFFECT_SUPPORT_YES) {
             return true;
         }
         if (!mFallback) {
diff --git a/core/java/android/os/vibrator/PrimitiveSegment.java b/core/java/android/os/vibrator/PrimitiveSegment.java
index c52a09c..95d97bf 100644
--- a/core/java/android/os/vibrator/PrimitiveSegment.java
+++ b/core/java/android/os/vibrator/PrimitiveSegment.java
@@ -22,7 +22,7 @@
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.VibrationEffect;
-import android.os.Vibrator;
+import android.os.VibratorInfo;
 
 import com.android.internal.util.Preconditions;
 
@@ -77,8 +77,8 @@
 
     /** @hide */
     @Override
-    public boolean areVibrationFeaturesSupported(@NonNull Vibrator vibrator) {
-        return vibrator.areAllPrimitivesSupported(mPrimitiveId);
+    public boolean areVibrationFeaturesSupported(@NonNull VibratorInfo vibratorInfo) {
+        return vibratorInfo.isPrimitiveSupported(mPrimitiveId);
     }
 
     /** @hide */
diff --git a/core/java/android/os/vibrator/RampSegment.java b/core/java/android/os/vibrator/RampSegment.java
index e997bcd..5f9d102 100644
--- a/core/java/android/os/vibrator/RampSegment.java
+++ b/core/java/android/os/vibrator/RampSegment.java
@@ -20,7 +20,7 @@
 import android.annotation.TestApi;
 import android.os.Parcel;
 import android.os.VibrationEffect;
-import android.os.Vibrator;
+import android.os.VibratorInfo;
 
 import com.android.internal.util.Preconditions;
 
@@ -96,7 +96,7 @@
 
     /** @hide */
     @Override
-    public boolean areVibrationFeaturesSupported(@NonNull Vibrator vibrator) {
+    public boolean areVibrationFeaturesSupported(@NonNull VibratorInfo vibratorInfo) {
         boolean areFeaturesSupported = true;
         // If the start/end frequencies are not the same, require frequency control since we need to
         // ramp up/down the frequency.
@@ -104,7 +104,7 @@
                 // If there is no frequency ramping, make sure that the one frequency used does not
                 // require frequency control.
                 || frequencyRequiresFrequencyControl(mStartFrequencyHz)) {
-            areFeaturesSupported &= vibrator.hasFrequencyControl();
+            areFeaturesSupported &= vibratorInfo.hasFrequencyControl();
         }
         // If the start/end amplitudes are not the same, require amplitude control since we need to
         // ramp up/down the amplitude.
@@ -112,7 +112,7 @@
                 // If there is no amplitude ramping, make sure that the amplitude used does not
                 // require amplitude control.
                 || amplitudeRequiresAmplitudeControl(mStartAmplitude)) {
-            areFeaturesSupported &= vibrator.hasAmplitudeControl();
+            areFeaturesSupported &= vibratorInfo.hasAmplitudeControl();
         }
         return areFeaturesSupported;
     }
diff --git a/core/java/android/os/vibrator/StepSegment.java b/core/java/android/os/vibrator/StepSegment.java
index a585aa8..9576a5b 100644
--- a/core/java/android/os/vibrator/StepSegment.java
+++ b/core/java/android/os/vibrator/StepSegment.java
@@ -21,7 +21,7 @@
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.VibrationEffect;
-import android.os.Vibrator;
+import android.os.VibratorInfo;
 
 import com.android.internal.util.Preconditions;
 
@@ -82,13 +82,13 @@
 
     /** @hide */
     @Override
-    public boolean areVibrationFeaturesSupported(@NonNull Vibrator vibrator) {
+    public boolean areVibrationFeaturesSupported(@NonNull VibratorInfo vibratorInfo) {
         boolean areFeaturesSupported = true;
         if (frequencyRequiresFrequencyControl(mFrequencyHz)) {
-            areFeaturesSupported &= vibrator.hasFrequencyControl();
+            areFeaturesSupported &= vibratorInfo.hasFrequencyControl();
         }
         if (amplitudeRequiresAmplitudeControl(mAmplitude)) {
-            areFeaturesSupported &= vibrator.hasAmplitudeControl();
+            areFeaturesSupported &= vibratorInfo.hasAmplitudeControl();
         }
         return areFeaturesSupported;
     }
diff --git a/core/java/android/os/vibrator/VibrationEffectSegment.java b/core/java/android/os/vibrator/VibrationEffectSegment.java
index 3b286a7..17ac36f 100644
--- a/core/java/android/os/vibrator/VibrationEffectSegment.java
+++ b/core/java/android/os/vibrator/VibrationEffectSegment.java
@@ -21,7 +21,7 @@
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.VibrationEffect;
-import android.os.Vibrator;
+import android.os.VibratorInfo;
 
 /**
  * Representation of a single segment of a {@link VibrationEffect}.
@@ -65,7 +65,7 @@
      *
      * @hide
      */
-    public abstract boolean areVibrationFeaturesSupported(@NonNull Vibrator vibrator);
+    public abstract boolean areVibrationFeaturesSupported(@NonNull VibratorInfo vibratorInfo);
 
     /**
      * Returns true if this segment could be a haptic feedback effect candidate.
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 2abf02e..abc8bf5 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -5627,7 +5627,7 @@
         public static final String SHOW_TOUCHES = "show_touches";
 
         /**
-         * Show key presses and other events dispatched to focused windows on the screen.
+         * Show key presses dispatched to focused windows on the screen.
          * 0 = no
          * 1 = yes
          * @hide
@@ -5635,6 +5635,14 @@
         public static final String SHOW_KEY_PRESSES = "show_key_presses";
 
         /**
+         * Show rotary input dispatched to focused windows on the screen.
+         * 0 = no
+         * 1 = yes
+         * @hide
+         */
+        public static final String SHOW_ROTARY_INPUT = "show_rotary_input";
+
+        /**
          * Log raw orientation data from
          * {@link com.android.server.policy.WindowOrientationListener} for use with the
          * orientationplot.py tool.
@@ -10126,6 +10134,13 @@
         public static final String AUDIO_DEVICE_INVENTORY = "audio_device_inventory";
 
         /**
+         * Stores a boolean that defines whether the CSD as a feature is enabled or not.
+         * @hide
+         */
+        public static final String AUDIO_SAFE_CSD_AS_A_FEATURE_ENABLED =
+                "audio_safe_csd_as_a_feature_enabled";
+
+        /**
          * Indicates whether notification display on the lock screen is enabled.
          * <p>
          * Type: int (0 for false, 1 for true)
@@ -10642,6 +10657,14 @@
                 "assist_long_press_home_enabled";
 
         /**
+         * Whether press and hold on nav handle can trigger search.
+         *
+         * @hide
+         */
+        public static final String SEARCH_PRESS_HOLD_NAV_HANDLE_ENABLED =
+                "search_press_hold_nav_handle_enabled";
+
+        /**
          * Control whether Trust Agents are in active unlock or extend unlock mode.
          * @hide
          */
@@ -11265,6 +11288,19 @@
                 "navigation_mode";
 
         /**
+         * The value is from another(source) device's {@link #NAVIGATION_MODE} during restore.
+         * It's supposed to be written only by
+         * {@link com.android.providers.settings.SettingsHelper}.
+         * This setting should not be added into backup array.
+         * <p>Value: -1 = Can't get value from restore(default),
+         *  0 = 3 button,
+         *  1 = 2 button,
+         *  2 = fully gestural.
+         * @hide
+         */
+        public static final String NAVIGATION_MODE_RESTORE = "navigation_mode_restore";
+
+        /**
          * Scale factor for the back gesture inset size on the left side of the screen.
          * @hide
          */
@@ -11836,6 +11872,13 @@
                 "accessibility_display_magnification_edge_haptic_enabled";
 
         /**
+         * If 1, DND default allowed packages have been updated
+         *
+         *  @hide
+         */
+        public static final String DND_CONFIGS_MIGRATED = "dnd_settings_migrated";
+
+        /**
          * These entries are considered common between the personal and the managed profile,
          * since the managed profile doesn't get to change them.
          */
@@ -17096,6 +17139,12 @@
                 ArrayMap<String, Integer> readableKeysWithMaxTargetSdk) {
             getPublicSettingsForClass(Global.class, allKeys, readableKeys,
                     readableKeysWithMaxTargetSdk);
+            // Add Global.Wearable keys on watches.
+            if (ActivityThread.currentApplication().getApplicationContext().getPackageManager()
+                    .hasSystemFeature(PackageManager.FEATURE_WATCH)) {
+                getPublicSettingsForClass(Global.Wearable.class, allKeys, readableKeys,
+                        readableKeysWithMaxTargetSdk);
+            }
         }
 
         /**
@@ -18280,7 +18329,7 @@
          * Settings migrated from Wear OS settings provider.
          * @hide
          */
-        public static class Wearable {
+        public static final class Wearable extends NameValueTable {
             /**
              * Whether the user has any pay tokens on their watch.
              * @hide
@@ -18603,6 +18652,7 @@
              * What OS does paired device has.
              * @hide
              */
+            @Readable
             public static final String PAIRED_DEVICE_OS_TYPE = "paired_device_os_type";
 
             // Possible values of PAIRED_DEVICE_OS_TYPE
@@ -19175,6 +19225,14 @@
              * @hide
              */
             public static final String WEAR_LAUNCHER_UI_MODE = "wear_launcher_ui_mode";
+
+            /** Whether Wear Power Anomaly Service is enabled.
+             *
+             * (0 = false, 1 = true)
+             * @hide
+             */
+            public static final String WEAR_POWER_ANOMALY_SERVICE_ENABLED =
+                    "wear_power_anomaly_service_enabled";
         }
     }
 
diff --git a/core/java/android/provider/Telephony.java b/core/java/android/provider/Telephony.java
index 59b945c..cf3707b 100644
--- a/core/java/android/provider/Telephony.java
+++ b/core/java/android/provider/Telephony.java
@@ -4905,6 +4905,16 @@
          */
         public static final String COLUMN_SATELLITE_ENABLED = "satellite_enabled";
 
+        /**
+         * TelephonyProvider column name for satellite attach enabled for carrier. The value of this
+         * column is set based on user settings.
+         * By default, it's disabled.
+         *
+         * @hide
+         */
+        public static final String COLUMN_SATELLITE_ATTACH_ENABLED_FOR_CARRIER =
+                "satellite_attach_enabled_for_carrier";
+
         /** All columns in {@link SimInfo} table. */
         private static final List<String> ALL_COLUMNS = List.of(
                 COLUMN_UNIQUE_KEY_SUBSCRIPTION_ID,
@@ -4974,7 +4984,8 @@
                 COLUMN_USAGE_SETTING,
                 COLUMN_TP_MESSAGE_REF,
                 COLUMN_USER_HANDLE,
-                COLUMN_SATELLITE_ENABLED
+                COLUMN_SATELLITE_ENABLED,
+                COLUMN_SATELLITE_ATTACH_ENABLED_FOR_CARRIER
         );
 
         /**
diff --git a/core/java/android/security/OWNERS b/core/java/android/security/OWNERS
index f6b1235..4e8d6e7 100644
--- a/core/java/android/security/OWNERS
+++ b/core/java/android/security/OWNERS
@@ -6,5 +6,4 @@
 per-file NetworkSecurityPolicy.java = klyubin@google.com
 per-file FrameworkNetworkSecurityPolicy.java = cbrubaker@google.com
 per-file FrameworkNetworkSecurityPolicy.java = klyubin@google.com
-per-file Confirmation*.java = jdanis@google.com
-per-file Confirmation*.java = swillden@google.com
+per-file Confirmation*.java = file:/keystore/OWNERS
diff --git a/core/java/android/security/keystore/OWNERS b/core/java/android/security/keystore/OWNERS
index 65129a4..d9e0116 100644
--- a/core/java/android/security/keystore/OWNERS
+++ b/core/java/android/security/keystore/OWNERS
@@ -1,5 +1 @@
-# Bug component: 189335
-
-swillden@google.com
-jdanis@google.com
-jbires@google.com
+include /keystore/OWNERS
diff --git a/core/java/android/security/keystore/recovery/OWNERS b/core/java/android/security/keystore/recovery/OWNERS
deleted file mode 100644
index 65129a4..0000000
--- a/core/java/android/security/keystore/recovery/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-# Bug component: 189335
-
-swillden@google.com
-jdanis@google.com
-jbires@google.com
diff --git a/core/java/android/service/controls/ControlsProviderService.java b/core/java/android/service/controls/ControlsProviderService.java
index b85cf6d..fce87db 100644
--- a/core/java/android/service/controls/ControlsProviderService.java
+++ b/core/java/android/service/controls/ControlsProviderService.java
@@ -25,6 +25,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
+import android.os.DeadObjectException;
 import android.os.Handler;
 import android.os.IBinder;
 import android.os.Looper;
@@ -285,6 +286,7 @@
         private IControlsSubscriber mCs;
         private boolean mEnforceStateless;
         private Context mContext;
+        private SubscriptionAdapter mSubscription;
 
         SubscriberProxy(boolean enforceStateless, IBinder token, IControlsSubscriber cs) {
             mEnforceStateless = enforceStateless;
@@ -300,11 +302,14 @@
 
         public void onSubscribe(Subscription subscription) {
             try {
-                mCs.onSubscribe(mToken, new SubscriptionAdapter(subscription));
+                SubscriptionAdapter subscriptionAdapter = new SubscriptionAdapter(subscription);
+                mCs.onSubscribe(mToken, subscriptionAdapter);
+                mSubscription = subscriptionAdapter;
             } catch (RemoteException ex) {
-                ex.rethrowAsRuntimeException();
+                handleRemoteException(ex);
             }
         }
+
         public void onNext(@NonNull Control control) {
             Preconditions.checkNotNull(control);
             try {
@@ -318,20 +323,36 @@
                 }
                 mCs.onNext(mToken, control);
             } catch (RemoteException ex) {
-                ex.rethrowAsRuntimeException();
+                handleRemoteException(ex);
             }
         }
+
         public void onError(Throwable t) {
             try {
                 mCs.onError(mToken, t.toString());
+                mSubscription = null;
             } catch (RemoteException ex) {
-                ex.rethrowAsRuntimeException();
+                handleRemoteException(ex);
             }
         }
+
         public void onComplete() {
             try {
                 mCs.onComplete(mToken);
+                mSubscription = null;
             } catch (RemoteException ex) {
+                handleRemoteException(ex);
+            }
+        }
+
+        private void handleRemoteException(RemoteException ex) {
+            if (ex instanceof DeadObjectException) {
+                // System UI crashed or is restarting. There is no need to rethrow this
+                SubscriptionAdapter subscriptionAdapter = mSubscription;
+                if (subscriptionAdapter != null) {
+                    subscriptionAdapter.cancel();
+                }
+            } else {
                 ex.rethrowAsRuntimeException();
             }
         }
diff --git a/core/java/android/service/gatekeeper/OWNERS b/core/java/android/service/gatekeeper/OWNERS
index 2ca52cd..7c4f285 100644
--- a/core/java/android/service/gatekeeper/OWNERS
+++ b/core/java/android/service/gatekeeper/OWNERS
@@ -1,3 +1,2 @@
-swillden@google.com
-jdanis@google.com
-jbires@google.com
+include platform/system/gatekeeper:/OWNERS
+include /services/core/java/com/android/server/locksettings/OWNERS
diff --git a/core/java/android/service/rotationresolver/OWNERS b/core/java/android/service/rotationresolver/OWNERS
index e381d17..5b57fc7 100644
--- a/core/java/android/service/rotationresolver/OWNERS
+++ b/core/java/android/service/rotationresolver/OWNERS
@@ -2,7 +2,6 @@
 
 asalo@google.com
 augale@google.com
-bquezada@google.com
 eejiang@google.com
 payamp@google.com
 siddikap@google.com
diff --git a/core/java/android/service/selectiontoolbar/DefaultSelectionToolbarRenderService.java b/core/java/android/service/selectiontoolbar/DefaultSelectionToolbarRenderService.java
deleted file mode 100644
index ad73a53..0000000
--- a/core/java/android/service/selectiontoolbar/DefaultSelectionToolbarRenderService.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.service.selectiontoolbar;
-
-import static android.view.selectiontoolbar.SelectionToolbarManager.ERROR_DO_NOT_ALLOW_MULTIPLE_TOOL_BAR;
-import static android.view.selectiontoolbar.SelectionToolbarManager.NO_TOOLBAR_ID;
-
-import android.util.Pair;
-import android.util.Slog;
-import android.util.SparseArray;
-import android.view.selectiontoolbar.ShowInfo;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.util.UUID;
-
-/**
- * The default implementation of {@link SelectionToolbarRenderService}.
- *
- * <p><b>NOTE:<b/> The requests are handled on the service main thread.
- *
- *  @hide
- */
-// TODO(b/214122495): fix class not found then move to system service folder
-public final class DefaultSelectionToolbarRenderService extends SelectionToolbarRenderService {
-
-    private static final String TAG = "DefaultSelectionToolbarRenderService";
-
-    // TODO(b/215497659): handle remove if the client process dies.
-    // Only show one toolbar, dismiss the old ones and remove from cache
-    private final SparseArray<Pair<Long, RemoteSelectionToolbar>> mToolbarCache =
-            new SparseArray<>();
-
-    /**
-     * Only allow one package to create one toolbar.
-     */
-    private boolean canShowToolbar(int uid, ShowInfo showInfo) {
-        if (showInfo.getWidgetToken() != NO_TOOLBAR_ID) {
-            return true;
-        }
-        return mToolbarCache.indexOfKey(uid) < 0;
-    }
-
-    @Override
-    public void onShow(int callingUid, ShowInfo showInfo,
-            SelectionToolbarRenderService.RemoteCallbackWrapper callbackWrapper) {
-        if (!canShowToolbar(callingUid, showInfo)) {
-            Slog.e(TAG, "Do not allow multiple toolbar for the app.");
-            callbackWrapper.onError(ERROR_DO_NOT_ALLOW_MULTIPLE_TOOL_BAR);
-            return;
-        }
-        long widgetToken = showInfo.getWidgetToken() == NO_TOOLBAR_ID
-                ? UUID.randomUUID().getMostSignificantBits()
-                : showInfo.getWidgetToken();
-
-        if (mToolbarCache.indexOfKey(callingUid) < 0) {
-            RemoteSelectionToolbar toolbar = new RemoteSelectionToolbar(this,
-                    widgetToken, showInfo,
-                    callbackWrapper, this::transferTouch);
-            mToolbarCache.put(callingUid, new Pair<>(widgetToken, toolbar));
-        }
-        Slog.v(TAG, "onShow() for " + widgetToken);
-        Pair<Long, RemoteSelectionToolbar> toolbarPair = mToolbarCache.get(callingUid);
-        if (toolbarPair.first == widgetToken) {
-            toolbarPair.second.show(showInfo);
-        } else {
-            Slog.w(TAG, "onShow() for unknown " + widgetToken);
-        }
-    }
-
-    @Override
-    public void onHide(long widgetToken) {
-        RemoteSelectionToolbar toolbar = getRemoteSelectionToolbarByTokenLocked(widgetToken);
-        if (toolbar != null) {
-            Slog.v(TAG, "onHide() for " + widgetToken);
-            toolbar.hide(widgetToken);
-        }
-    }
-
-    @Override
-    public void onDismiss(long widgetToken) {
-        RemoteSelectionToolbar toolbar = getRemoteSelectionToolbarByTokenLocked(widgetToken);
-        if (toolbar != null) {
-            Slog.v(TAG, "onDismiss() for " + widgetToken);
-            toolbar.dismiss(widgetToken);
-            removeRemoteSelectionToolbarByTokenLocked(widgetToken);
-        }
-    }
-
-    @Override
-    public void onToolbarShowTimeout(int callingUid) {
-        Slog.w(TAG, "onToolbarShowTimeout for callingUid = " + callingUid);
-        Pair<Long, RemoteSelectionToolbar> toolbarPair = mToolbarCache.get(callingUid);
-        if (toolbarPair != null) {
-            RemoteSelectionToolbar remoteToolbar = toolbarPair.second;
-            remoteToolbar.dismiss(toolbarPair.first);
-            remoteToolbar.onToolbarShowTimeout();
-            mToolbarCache.remove(callingUid);
-        }
-    }
-
-    private RemoteSelectionToolbar getRemoteSelectionToolbarByTokenLocked(long widgetToken) {
-        for (int i = 0; i < mToolbarCache.size(); i++) {
-            Pair<Long, RemoteSelectionToolbar> toolbarPair = mToolbarCache.valueAt(i);
-            if (toolbarPair.first == widgetToken) {
-                return toolbarPair.second;
-            }
-        }
-        return null;
-    }
-
-    private void removeRemoteSelectionToolbarByTokenLocked(long widgetToken) {
-        for (int i = 0; i < mToolbarCache.size(); i++) {
-            Pair<Long, RemoteSelectionToolbar> toolbarPair = mToolbarCache.valueAt(i);
-            if (toolbarPair.first == widgetToken) {
-                mToolbarCache.remove(mToolbarCache.keyAt(i));
-                return;
-            }
-        }
-    }
-
-    @Override
-    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-        int size = mToolbarCache.size();
-        pw.print("number selectionToolbar: "); pw.println(size);
-        String pfx = "  ";
-        for (int i = 0; i < size; i++) {
-            pw.print("#"); pw.println(i);
-            int callingUid = mToolbarCache.keyAt(i);
-            pw.print(pfx); pw.print("callingUid: "); pw.println(callingUid);
-            Pair<Long, RemoteSelectionToolbar> toolbarPair = mToolbarCache.valueAt(i);
-            RemoteSelectionToolbar selectionToolbar = toolbarPair.second;
-            pw.print(pfx); pw.print("selectionToolbar: ");
-            selectionToolbar.dump(pfx, pw);
-            pw.println();
-        }
-    }
-}
-
diff --git a/core/java/android/service/selectiontoolbar/FloatingToolbarRoot.java b/core/java/android/service/selectiontoolbar/FloatingToolbarRoot.java
deleted file mode 100644
index adc9251..0000000
--- a/core/java/android/service/selectiontoolbar/FloatingToolbarRoot.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.service.selectiontoolbar;
-
-import android.annotation.SuppressLint;
-import android.content.Context;
-import android.graphics.Rect;
-import android.os.IBinder;
-import android.util.Log;
-import android.view.MotionEvent;
-import android.widget.LinearLayout;
-
-import java.io.PrintWriter;
-
-/**
- * This class is the root view for the selection toolbar. It is responsible for
- * detecting the click on the item and to also transfer input focus to the application.
- *
- * @hide
- */
-@SuppressLint("ViewConstructor")
-public class FloatingToolbarRoot extends LinearLayout {
-
-    private static final boolean DEBUG = false;
-    private static final String TAG = "FloatingToolbarRoot";
-
-    private final IBinder mTargetInputToken;
-    private final SelectionToolbarRenderService.TransferTouchListener mTransferTouchListener;
-    private final Rect mContentRect = new Rect();
-
-    private int mLastDownX = -1;
-    private int mLastDownY = -1;
-
-    public FloatingToolbarRoot(Context context, IBinder targetInputToken,
-            SelectionToolbarRenderService.TransferTouchListener transferTouchListener) {
-        super(context);
-        mTargetInputToken = targetInputToken;
-        mTransferTouchListener = transferTouchListener;
-        setFocusable(false);
-    }
-
-    /**
-     * Sets the Rect that shows the selection toolbar content.
-     */
-    public void setContentRect(Rect contentRect) {
-        mContentRect.set(contentRect);
-    }
-
-    @Override
-    @SuppressLint("ClickableViewAccessibility")
-    public boolean dispatchTouchEvent(MotionEvent event) {
-        if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
-            mLastDownX = (int) event.getX();
-            mLastDownY = (int) event.getY();
-            if (DEBUG) {
-                Log.d(TAG, "downX=" + mLastDownX + " downY=" + mLastDownY);
-            }
-            // TODO(b/215497659): Check FLAG_WINDOW_IS_PARTIALLY_OBSCURED
-            if (!mContentRect.contains(mLastDownX, mLastDownY)) {
-                if (DEBUG) {
-                    Log.d(TAG, "Transfer touch focus to application.");
-                }
-                mTransferTouchListener.onTransferTouch(getViewRootImpl().getInputToken(),
-                        mTargetInputToken);
-            }
-        }
-        return super.dispatchTouchEvent(event);
-    }
-
-    void dump(String prefix, PrintWriter pw) {
-        pw.print(prefix); pw.println("FloatingToolbarRoot:");
-        pw.print(prefix + "  "); pw.print("last down X: "); pw.println(mLastDownX);
-        pw.print(prefix + "  "); pw.print("last down Y: "); pw.println(mLastDownY);
-    }
-}
diff --git a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderService.aidl b/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderService.aidl
deleted file mode 100644
index 79281b8..0000000
--- a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderService.aidl
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.service.selectiontoolbar;
-
-import android.view.selectiontoolbar.ISelectionToolbarCallback;
-import android.view.selectiontoolbar.ShowInfo;
-
-/**
- * The service to render the selection toolbar menus.
- *
- * @hide
- */
-oneway interface ISelectionToolbarRenderService {
-    void onConnected(in IBinder callback);
-    void onShow(int callingUid, in ShowInfo showInfo, in ISelectionToolbarCallback callback);
-    void onHide(long widgetToken);
-    void onDismiss(int callingUid, long widgetToken);
-}
diff --git a/core/java/android/service/selectiontoolbar/OWNERS b/core/java/android/service/selectiontoolbar/OWNERS
deleted file mode 100644
index 5500b92..0000000
--- a/core/java/android/service/selectiontoolbar/OWNERS
+++ /dev/null
@@ -1,10 +0,0 @@
-# Bug component: 709498
-
-augale@google.com
-joannechung@google.com
-licha@google.com
-lpeter@google.com
-svetoslavganov@google.com
-toki@google.com
-tonymak@google.com
-tymtsai@google.com
\ No newline at end of file
diff --git a/core/java/android/service/selectiontoolbar/RemoteSelectionToolbar.java b/core/java/android/service/selectiontoolbar/RemoteSelectionToolbar.java
deleted file mode 100644
index 59e3a5e..0000000
--- a/core/java/android/service/selectiontoolbar/RemoteSelectionToolbar.java
+++ /dev/null
@@ -1,1398 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.service.selectiontoolbar;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.animation.AnimatorSet;
-import android.animation.ObjectAnimator;
-import android.animation.ValueAnimator;
-import android.content.Context;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.graphics.drawable.AnimatedVectorDrawable;
-import android.graphics.drawable.Drawable;
-import android.os.IBinder;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.Size;
-import android.view.ContextThemeWrapper;
-import android.view.Gravity;
-import android.view.LayoutInflater;
-import android.view.MotionEvent;
-import android.view.SurfaceControlViewHost;
-import android.view.View;
-import android.view.ViewConfiguration;
-import android.view.ViewGroup;
-import android.view.animation.Animation;
-import android.view.animation.AnimationSet;
-import android.view.animation.AnimationUtils;
-import android.view.animation.Interpolator;
-import android.view.animation.Transformation;
-import android.view.selectiontoolbar.ShowInfo;
-import android.view.selectiontoolbar.ToolbarMenuItem;
-import android.view.selectiontoolbar.WidgetInfo;
-import android.widget.ArrayAdapter;
-import android.widget.ImageButton;
-import android.widget.ImageView;
-import android.widget.LinearLayout;
-import android.widget.ListView;
-import android.widget.TextView;
-
-import com.android.internal.R;
-import com.android.internal.util.Preconditions;
-import com.android.internal.widget.floatingtoolbar.FloatingToolbar;
-
-import java.io.PrintWriter;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * This class is responsible for rendering/animation of the selection toolbar in the remote
- * system process. It holds 2 panels (i.e. main panel and overflow panel) and an overflow
- * button to transition between panels.
- *
- *  @hide
- */
-// TODO(b/215497659): share code with LocalFloatingToolbarPopup
-final class RemoteSelectionToolbar {
-    private static final String TAG = "RemoteSelectionToolbar";
-
-    /* Minimum and maximum number of items allowed in the overflow. */
-    private static final int MIN_OVERFLOW_SIZE = 2;
-    private static final int MAX_OVERFLOW_SIZE = 4;
-
-    private final Context mContext;
-
-    /* Margins between the popup window and its content. */
-    private final int mMarginHorizontal;
-    private final int mMarginVertical;
-
-    /* View components */
-    private final ViewGroup mContentContainer;  // holds all contents.
-    private final ViewGroup mMainPanel;  // holds menu items that are initially displayed.
-    // holds menu items hidden in the overflow.
-    private final OverflowPanel mOverflowPanel;
-    private final ImageButton mOverflowButton;  // opens/closes the overflow.
-    /* overflow button drawables. */
-    private final Drawable mArrow;
-    private final Drawable mOverflow;
-    private final AnimatedVectorDrawable mToArrow;
-    private final AnimatedVectorDrawable mToOverflow;
-
-    private final OverflowPanelViewHelper mOverflowPanelViewHelper;
-
-    /* Animation interpolators. */
-    private final Interpolator mLogAccelerateInterpolator;
-    private final Interpolator mFastOutSlowInInterpolator;
-    private final Interpolator mLinearOutSlowInInterpolator;
-    private final Interpolator mFastOutLinearInInterpolator;
-
-    /* Animations. */
-    private final AnimatorSet mShowAnimation;
-    private final AnimatorSet mDismissAnimation;
-    private final AnimatorSet mHideAnimation;
-    private final AnimationSet mOpenOverflowAnimation;
-    private final AnimationSet mCloseOverflowAnimation;
-    private final Animation.AnimationListener mOverflowAnimationListener;
-
-    private final Rect mViewPortOnScreen = new Rect();  // portion of screen we can draw in.
-
-    private final int mLineHeight;
-    private final int mIconTextSpacing;
-
-    private final long mSelectionToolbarToken;
-    private IBinder mHostInputToken;
-    private final SelectionToolbarRenderService.RemoteCallbackWrapper mCallbackWrapper;
-    private final SelectionToolbarRenderService.TransferTouchListener mTransferTouchListener;
-    private int mPopupWidth;
-    private int mPopupHeight;
-    // Coordinates to show the toolbar relative to the specified view port
-    private final Point mRelativeCoordsForToolbar = new Point();
-    private List<ToolbarMenuItem> mMenuItems;
-    private SurfaceControlViewHost mSurfaceControlViewHost;
-    private SurfaceControlViewHost.SurfacePackage mSurfacePackage;
-
-    /**
-     * @see OverflowPanelViewHelper#preparePopupContent().
-     */
-    private final Runnable mPreparePopupContentRTLHelper = new Runnable() {
-        @Override
-        public void run() {
-            setPanelsStatesAtRestingPosition();
-            mContentContainer.setAlpha(1);
-        }
-    };
-
-    private boolean mDismissed = true; // tracks whether this popup is dismissed or dismissing.
-    private boolean mHidden; // tracks whether this popup is hidden or hiding.
-
-    /* Calculated sizes for panels and overflow button. */
-    private final Size mOverflowButtonSize;
-    private Size mOverflowPanelSize;  // Should be null when there is no overflow.
-    private Size mMainPanelSize;
-
-    /* Menu items and click listeners */
-    private final View.OnClickListener mMenuItemButtonOnClickListener;
-
-    private boolean mOpenOverflowUpwards;  // Whether the overflow opens upwards or downwards.
-    private boolean mIsOverflowOpen;
-
-    private int mTransitionDurationScale;  // Used to scale the toolbar transition duration.
-
-    private final Rect mPreviousContentRect = new Rect();
-
-    private final Rect mTempContentRect = new Rect();
-    private final Rect mTempContentRectForRoot = new Rect();
-    private final int[] mTempCoords = new int[2];
-
-    RemoteSelectionToolbar(Context context, long selectionToolbarToken, ShowInfo showInfo,
-            SelectionToolbarRenderService.RemoteCallbackWrapper callbackWrapper,
-            SelectionToolbarRenderService.TransferTouchListener transferTouchListener) {
-        mContext = applyDefaultTheme(context, showInfo.isIsLightTheme());
-        mSelectionToolbarToken = selectionToolbarToken;
-        mCallbackWrapper = callbackWrapper;
-        mTransferTouchListener = transferTouchListener;
-        mHostInputToken = showInfo.getHostInputToken();
-        mContentContainer = createContentContainer(mContext);
-        mMarginHorizontal = mContext.getResources()
-                .getDimensionPixelSize(R.dimen.floating_toolbar_horizontal_margin);
-        mMarginVertical = mContext.getResources()
-                .getDimensionPixelSize(R.dimen.floating_toolbar_vertical_margin);
-        mLineHeight = mContext.getResources()
-                .getDimensionPixelSize(R.dimen.floating_toolbar_height);
-        mIconTextSpacing = mContext.getResources()
-                .getDimensionPixelSize(R.dimen.floating_toolbar_icon_text_spacing);
-
-        // Interpolators
-        mLogAccelerateInterpolator = new LogAccelerateInterpolator();
-        mFastOutSlowInInterpolator = AnimationUtils.loadInterpolator(
-                mContext, android.R.interpolator.fast_out_slow_in);
-        mLinearOutSlowInInterpolator = AnimationUtils.loadInterpolator(
-                mContext, android.R.interpolator.linear_out_slow_in);
-        mFastOutLinearInInterpolator = AnimationUtils.loadInterpolator(
-                mContext, android.R.interpolator.fast_out_linear_in);
-
-        // Drawables. Needed for views.
-        mArrow = mContext.getResources()
-                .getDrawable(R.drawable.ft_avd_tooverflow, mContext.getTheme());
-        mArrow.setAutoMirrored(true);
-        mOverflow = mContext.getResources()
-                .getDrawable(R.drawable.ft_avd_toarrow, mContext.getTheme());
-        mOverflow.setAutoMirrored(true);
-        mToArrow = (AnimatedVectorDrawable) mContext.getResources()
-                .getDrawable(R.drawable.ft_avd_toarrow_animation, mContext.getTheme());
-        mToArrow.setAutoMirrored(true);
-        mToOverflow = (AnimatedVectorDrawable) mContext.getResources()
-                .getDrawable(R.drawable.ft_avd_tooverflow_animation, mContext.getTheme());
-        mToOverflow.setAutoMirrored(true);
-
-        // Views
-        mOverflowButton = createOverflowButton();
-        mOverflowButtonSize = measure(mOverflowButton);
-        mMainPanel = createMainPanel();
-        mOverflowPanelViewHelper = new OverflowPanelViewHelper(mContext, mIconTextSpacing);
-        mOverflowPanel = createOverflowPanel();
-
-        // Animation. Need views.
-        mOverflowAnimationListener = createOverflowAnimationListener();
-        mOpenOverflowAnimation = new AnimationSet(true);
-        mOpenOverflowAnimation.setAnimationListener(mOverflowAnimationListener);
-        mCloseOverflowAnimation = new AnimationSet(true);
-        mCloseOverflowAnimation.setAnimationListener(mOverflowAnimationListener);
-        mShowAnimation = createEnterAnimation(mContentContainer,
-                new AnimatorListenerAdapter() {
-                    @Override
-                    public void onAnimationEnd(Animator animation) {
-                        updateFloatingToolbarRootContentRect();
-                    }
-                });
-        mDismissAnimation = createExitAnimation(
-                mContentContainer,
-                150,  // startDelay
-                new AnimatorListenerAdapter() {
-                    @Override
-                    public void onAnimationEnd(Animator animation) {
-                        // TODO(b/215497659): should dismiss window after animation
-                        mContentContainer.removeAllViews();
-                        mSurfaceControlViewHost.release();
-                        mSurfaceControlViewHost = null;
-                        mSurfacePackage = null;
-                    }
-                });
-        mHideAnimation = createExitAnimation(
-                mContentContainer,
-                0,  // startDelay
-                null); // TODO(b/215497659): should handle hide after animation
-        mMenuItemButtonOnClickListener = v -> {
-            Object tag = v.getTag();
-            if (!(tag instanceof ToolbarMenuItem)) {
-                return;
-            }
-            mCallbackWrapper.onMenuItemClicked((ToolbarMenuItem) tag);
-        };
-    }
-
-    private void updateFloatingToolbarRootContentRect() {
-        if (mSurfaceControlViewHost == null) {
-            return;
-        }
-        final FloatingToolbarRoot root = (FloatingToolbarRoot) mSurfaceControlViewHost.getView();
-        mContentContainer.getLocationOnScreen(mTempCoords);
-        int contentLeft = mTempCoords[0];
-        int contentTop = mTempCoords[1];
-        mTempContentRectForRoot.set(contentLeft, contentTop,
-                contentLeft + mContentContainer.getWidth(),
-                contentTop + mContentContainer.getHeight());
-        root.setContentRect(mTempContentRectForRoot);
-    }
-
-    private WidgetInfo createWidgetInfo() {
-        mTempContentRect.set(mRelativeCoordsForToolbar.x, mRelativeCoordsForToolbar.y,
-                mRelativeCoordsForToolbar.x + mPopupWidth,
-                mRelativeCoordsForToolbar.y + mPopupHeight);
-        return new WidgetInfo(mSelectionToolbarToken, mTempContentRect, getSurfacePackage());
-    }
-
-    private SurfaceControlViewHost.SurfacePackage getSurfacePackage() {
-        if (mSurfaceControlViewHost == null) {
-            final FloatingToolbarRoot contentHolder = new FloatingToolbarRoot(mContext,
-                    mHostInputToken, mTransferTouchListener);
-            contentHolder.addView(mContentContainer);
-            mSurfaceControlViewHost = new SurfaceControlViewHost(mContext, mContext.getDisplay(),
-                    mHostInputToken, "RemoteSelectionToolbar");
-            mSurfaceControlViewHost.setView(contentHolder, mPopupWidth, mPopupHeight);
-        }
-        if (mSurfacePackage == null) {
-            mSurfacePackage = mSurfaceControlViewHost.getSurfacePackage();
-        }
-        return mSurfacePackage;
-    }
-
-    private void layoutMenuItems(
-            List<ToolbarMenuItem> menuItems,
-            int suggestedWidth) {
-        cancelOverflowAnimations();
-        clearPanels();
-
-        menuItems = layoutMainPanelItems(menuItems, getAdjustedToolbarWidth(suggestedWidth));
-        if (!menuItems.isEmpty()) {
-            // Add remaining items to the overflow.
-            layoutOverflowPanelItems(menuItems);
-        }
-        updatePopupSize();
-    }
-
-    public void onToolbarShowTimeout() {
-        mCallbackWrapper.onToolbarShowTimeout();
-    }
-
-    /**
-     * Show the specified selection toolbar.
-     */
-    public void show(ShowInfo showInfo) {
-        debugLog("show() for " + showInfo);
-
-        mMenuItems = showInfo.getMenuItems();
-        mViewPortOnScreen.set(showInfo.getViewPortOnScreen());
-
-        debugLog("show(): layoutRequired=" + showInfo.isLayoutRequired());
-        if (showInfo.isLayoutRequired()) {
-            layoutMenuItems(mMenuItems, showInfo.getSuggestedWidth());
-        }
-        Rect contentRect = showInfo.getContentRect();
-        if (!isShowing()) {
-            show(contentRect);
-        } else if (!mPreviousContentRect.equals(contentRect)) {
-            updateCoordinates(contentRect);
-        }
-        mPreviousContentRect.set(contentRect);
-    }
-
-    private void show(Rect contentRectOnScreen) {
-        Objects.requireNonNull(contentRectOnScreen);
-
-        mHidden = false;
-        mDismissed = false;
-        cancelDismissAndHideAnimations();
-        cancelOverflowAnimations();
-        refreshCoordinatesAndOverflowDirection(contentRectOnScreen);
-        preparePopupContent();
-        mCallbackWrapper.onShown(createWidgetInfo());
-        // TODO(b/215681595): Use Choreographer to coordinate for show between different thread
-        mShowAnimation.start();
-    }
-
-    /**
-     * Dismiss the specified selection toolbar.
-     */
-    public void dismiss(long floatingToolbarToken) {
-        debugLog("dismiss for " + floatingToolbarToken);
-        if (mDismissed) {
-            return;
-        }
-        mHidden = false;
-        mDismissed = true;
-
-        mHideAnimation.cancel();
-        mDismissAnimation.start();
-    }
-
-    /**
-     * Hide the specified selection toolbar.
-     */
-    public void hide(long floatingToolbarToken) {
-        debugLog("hide for " + floatingToolbarToken);
-        if (!isShowing()) {
-            return;
-        }
-
-        mHidden = true;
-        mHideAnimation.start();
-    }
-
-    public boolean isShowing() {
-        return !mDismissed && !mHidden;
-    }
-
-    private void updateCoordinates(Rect contentRectOnScreen) {
-        Objects.requireNonNull(contentRectOnScreen);
-
-        if (!isShowing()) {
-            return;
-        }
-        cancelOverflowAnimations();
-        refreshCoordinatesAndOverflowDirection(contentRectOnScreen);
-        preparePopupContent();
-        WidgetInfo widgetInfo = createWidgetInfo();
-        mSurfaceControlViewHost.relayout(mPopupWidth, mPopupHeight);
-        mCallbackWrapper.onWidgetUpdated(widgetInfo);
-    }
-
-    private void refreshCoordinatesAndOverflowDirection(Rect contentRectOnScreen) {
-        // Initialize x ensuring that the toolbar isn't rendered behind the nav bar in
-        // landscape.
-        final int x = Math.min(
-                contentRectOnScreen.centerX() - mPopupWidth / 2,
-                mViewPortOnScreen.right - mPopupWidth);
-
-        final int y;
-
-        final int availableHeightAboveContent =
-                contentRectOnScreen.top - mViewPortOnScreen.top;
-        final int availableHeightBelowContent =
-                mViewPortOnScreen.bottom - contentRectOnScreen.bottom;
-
-        final int margin = 2 * mMarginVertical;
-        final int toolbarHeightWithVerticalMargin = mLineHeight + margin;
-
-        if (!hasOverflow()) {
-            if (availableHeightAboveContent >= toolbarHeightWithVerticalMargin) {
-                // There is enough space at the top of the content.
-                y = contentRectOnScreen.top - toolbarHeightWithVerticalMargin;
-            } else if (availableHeightBelowContent >= toolbarHeightWithVerticalMargin) {
-                // There is enough space at the bottom of the content.
-                y = contentRectOnScreen.bottom;
-            } else if (availableHeightBelowContent >= mLineHeight) {
-                // Just enough space to fit the toolbar with no vertical margins.
-                y = contentRectOnScreen.bottom - mMarginVertical;
-            } else {
-                // Not enough space. Prefer to position as high as possible.
-                y = Math.max(
-                        mViewPortOnScreen.top,
-                        contentRectOnScreen.top - toolbarHeightWithVerticalMargin);
-            }
-        } else {
-            // Has an overflow.
-            final int minimumOverflowHeightWithMargin =
-                    calculateOverflowHeight(MIN_OVERFLOW_SIZE) + margin;
-            final int availableHeightThroughContentDown =
-                    mViewPortOnScreen.bottom - contentRectOnScreen.top
-                            + toolbarHeightWithVerticalMargin;
-            final int availableHeightThroughContentUp =
-                    contentRectOnScreen.bottom - mViewPortOnScreen.top
-                            + toolbarHeightWithVerticalMargin;
-
-            if (availableHeightAboveContent >= minimumOverflowHeightWithMargin) {
-                // There is enough space at the top of the content rect for the overflow.
-                // Position above and open upwards.
-                updateOverflowHeight(availableHeightAboveContent - margin);
-                y = contentRectOnScreen.top - mPopupHeight;
-                mOpenOverflowUpwards = true;
-            } else if (availableHeightAboveContent >= toolbarHeightWithVerticalMargin
-                    && availableHeightThroughContentDown >= minimumOverflowHeightWithMargin) {
-                // There is enough space at the top of the content rect for the main panel
-                // but not the overflow.
-                // Position above but open downwards.
-                updateOverflowHeight(availableHeightThroughContentDown - margin);
-                y = contentRectOnScreen.top - toolbarHeightWithVerticalMargin;
-                mOpenOverflowUpwards = false;
-            } else if (availableHeightBelowContent >= minimumOverflowHeightWithMargin) {
-                // There is enough space at the bottom of the content rect for the overflow.
-                // Position below and open downwards.
-                updateOverflowHeight(availableHeightBelowContent - margin);
-                y = contentRectOnScreen.bottom;
-                mOpenOverflowUpwards = false;
-            } else if (availableHeightBelowContent >= toolbarHeightWithVerticalMargin
-                    && mViewPortOnScreen.height() >= minimumOverflowHeightWithMargin) {
-                // There is enough space at the bottom of the content rect for the main panel
-                // but not the overflow.
-                // Position below but open upwards.
-                updateOverflowHeight(availableHeightThroughContentUp - margin);
-                y = contentRectOnScreen.bottom + toolbarHeightWithVerticalMargin
-                        - mPopupHeight;
-                mOpenOverflowUpwards = true;
-            } else {
-                // Not enough space.
-                // Position at the top of the view port and open downwards.
-                updateOverflowHeight(mViewPortOnScreen.height() - margin);
-                y = mViewPortOnScreen.top;
-                mOpenOverflowUpwards = false;
-            }
-        }
-        mRelativeCoordsForToolbar.set(x, y);
-    }
-
-    private void cancelDismissAndHideAnimations() {
-        mDismissAnimation.cancel();
-        mHideAnimation.cancel();
-    }
-
-    private void cancelOverflowAnimations() {
-        mContentContainer.clearAnimation();
-        mMainPanel.animate().cancel();
-        mOverflowPanel.animate().cancel();
-        mToArrow.stop();
-        mToOverflow.stop();
-    }
-
-    private void openOverflow() {
-        final int targetWidth = mOverflowPanelSize.getWidth();
-        final int targetHeight = mOverflowPanelSize.getHeight();
-        final int startWidth = mContentContainer.getWidth();
-        final int startHeight = mContentContainer.getHeight();
-        final float startY = mContentContainer.getY();
-        final float left = mContentContainer.getX();
-        final float right = left + mContentContainer.getWidth();
-        Animation widthAnimation = new Animation() {
-            @Override
-            protected void applyTransformation(float interpolatedTime, Transformation t) {
-                int deltaWidth = (int) (interpolatedTime * (targetWidth - startWidth));
-                setWidth(mContentContainer, startWidth + deltaWidth);
-                if (isInRTLMode()) {
-                    mContentContainer.setX(left);
-
-                    // Lock the panels in place.
-                    mMainPanel.setX(0);
-                    mOverflowPanel.setX(0);
-                } else {
-                    mContentContainer.setX(right - mContentContainer.getWidth());
-
-                    // Offset the panels' positions so they look like they're locked in place
-                    // on the screen.
-                    mMainPanel.setX(mContentContainer.getWidth() - startWidth);
-                    mOverflowPanel.setX(mContentContainer.getWidth() - targetWidth);
-                }
-            }
-        };
-        Animation heightAnimation = new Animation() {
-            @Override
-            protected void applyTransformation(float interpolatedTime, Transformation t) {
-                int deltaHeight = (int) (interpolatedTime * (targetHeight - startHeight));
-                setHeight(mContentContainer, startHeight + deltaHeight);
-                if (mOpenOverflowUpwards) {
-                    mContentContainer.setY(
-                            startY - (mContentContainer.getHeight() - startHeight));
-                    positionContentYCoordinatesIfOpeningOverflowUpwards();
-                }
-            }
-        };
-        final float overflowButtonStartX = mOverflowButton.getX();
-        final float overflowButtonTargetX =
-                isInRTLMode() ? overflowButtonStartX + targetWidth - mOverflowButton.getWidth()
-                        : overflowButtonStartX - targetWidth + mOverflowButton.getWidth();
-        Animation overflowButtonAnimation = new Animation() {
-            @Override
-            protected void applyTransformation(float interpolatedTime, Transformation t) {
-                float overflowButtonX = overflowButtonStartX
-                        + interpolatedTime * (overflowButtonTargetX - overflowButtonStartX);
-                float deltaContainerWidth =
-                        isInRTLMode() ? 0 : mContentContainer.getWidth() - startWidth;
-                float actualOverflowButtonX = overflowButtonX + deltaContainerWidth;
-                mOverflowButton.setX(actualOverflowButtonX);
-                updateFloatingToolbarRootContentRect();
-            }
-        };
-        widthAnimation.setInterpolator(mLogAccelerateInterpolator);
-        widthAnimation.setDuration(getAnimationDuration());
-        heightAnimation.setInterpolator(mFastOutSlowInInterpolator);
-        heightAnimation.setDuration(getAnimationDuration());
-        overflowButtonAnimation.setInterpolator(mFastOutSlowInInterpolator);
-        overflowButtonAnimation.setDuration(getAnimationDuration());
-        mOpenOverflowAnimation.getAnimations().clear();
-        mOpenOverflowAnimation.addAnimation(widthAnimation);
-        mOpenOverflowAnimation.addAnimation(heightAnimation);
-        mOpenOverflowAnimation.addAnimation(overflowButtonAnimation);
-        mContentContainer.startAnimation(mOpenOverflowAnimation);
-        mIsOverflowOpen = true;
-        mMainPanel.animate()
-                .alpha(0).withLayer()
-                .setInterpolator(mLinearOutSlowInInterpolator)
-                .setDuration(250)
-                .start();
-        mOverflowPanel.setAlpha(1); // fadeIn in 0ms.
-    }
-
-    private void closeOverflow() {
-        final int targetWidth = mMainPanelSize.getWidth();
-        final int startWidth = mContentContainer.getWidth();
-        final float left = mContentContainer.getX();
-        final float right = left + mContentContainer.getWidth();
-        Animation widthAnimation = new Animation() {
-            @Override
-            protected void applyTransformation(float interpolatedTime, Transformation t) {
-                int deltaWidth = (int) (interpolatedTime * (targetWidth - startWidth));
-                setWidth(mContentContainer, startWidth + deltaWidth);
-                if (isInRTLMode()) {
-                    mContentContainer.setX(left);
-
-                    // Lock the panels in place.
-                    mMainPanel.setX(0);
-                    mOverflowPanel.setX(0);
-                } else {
-                    mContentContainer.setX(right - mContentContainer.getWidth());
-
-                    // Offset the panels' positions so they look like they're locked in place
-                    // on the screen.
-                    mMainPanel.setX(mContentContainer.getWidth() - targetWidth);
-                    mOverflowPanel.setX(mContentContainer.getWidth() - startWidth);
-                }
-            }
-        };
-        final int targetHeight = mMainPanelSize.getHeight();
-        final int startHeight = mContentContainer.getHeight();
-        final float bottom = mContentContainer.getY() + mContentContainer.getHeight();
-        Animation heightAnimation = new Animation() {
-            @Override
-            protected void applyTransformation(float interpolatedTime, Transformation t) {
-                int deltaHeight = (int) (interpolatedTime * (targetHeight - startHeight));
-                setHeight(mContentContainer, startHeight + deltaHeight);
-                if (mOpenOverflowUpwards) {
-                    mContentContainer.setY(bottom - mContentContainer.getHeight());
-                    positionContentYCoordinatesIfOpeningOverflowUpwards();
-                }
-            }
-        };
-        final float overflowButtonStartX = mOverflowButton.getX();
-        final float overflowButtonTargetX =
-                isInRTLMode() ? overflowButtonStartX - startWidth + mOverflowButton.getWidth()
-                        : overflowButtonStartX + startWidth - mOverflowButton.getWidth();
-        Animation overflowButtonAnimation = new Animation() {
-            @Override
-            protected void applyTransformation(float interpolatedTime, Transformation t) {
-                float overflowButtonX = overflowButtonStartX
-                        + interpolatedTime * (overflowButtonTargetX - overflowButtonStartX);
-                float deltaContainerWidth =
-                        isInRTLMode() ? 0 : mContentContainer.getWidth() - startWidth;
-                float actualOverflowButtonX = overflowButtonX + deltaContainerWidth;
-                mOverflowButton.setX(actualOverflowButtonX);
-                updateFloatingToolbarRootContentRect();
-            }
-        };
-        widthAnimation.setInterpolator(mFastOutSlowInInterpolator);
-        widthAnimation.setDuration(getAnimationDuration());
-        heightAnimation.setInterpolator(mLogAccelerateInterpolator);
-        heightAnimation.setDuration(getAnimationDuration());
-        overflowButtonAnimation.setInterpolator(mFastOutSlowInInterpolator);
-        overflowButtonAnimation.setDuration(getAnimationDuration());
-        mCloseOverflowAnimation.getAnimations().clear();
-        mCloseOverflowAnimation.addAnimation(widthAnimation);
-        mCloseOverflowAnimation.addAnimation(heightAnimation);
-        mCloseOverflowAnimation.addAnimation(overflowButtonAnimation);
-        mContentContainer.startAnimation(mCloseOverflowAnimation);
-        mIsOverflowOpen = false;
-        mMainPanel.animate()
-                .alpha(1).withLayer()
-                .setInterpolator(mFastOutLinearInInterpolator)
-                .setDuration(100)
-                .start();
-        mOverflowPanel.animate()
-                .alpha(0).withLayer()
-                .setInterpolator(mLinearOutSlowInInterpolator)
-                .setDuration(150)
-                .start();
-    }
-
-    /**
-     * Defines the position of the floating toolbar popup panels when transition animation has
-     * stopped.
-     */
-    private void setPanelsStatesAtRestingPosition() {
-        mOverflowButton.setEnabled(true);
-        mOverflowPanel.awakenScrollBars();
-
-        if (mIsOverflowOpen) {
-            // Set open state.
-            final Size containerSize = mOverflowPanelSize;
-            setSize(mContentContainer, containerSize);
-            mMainPanel.setAlpha(0);
-            mMainPanel.setVisibility(View.INVISIBLE);
-            mOverflowPanel.setAlpha(1);
-            mOverflowPanel.setVisibility(View.VISIBLE);
-            mOverflowButton.setImageDrawable(mArrow);
-            mOverflowButton.setContentDescription(mContext.getString(
-                    R.string.floating_toolbar_close_overflow_description));
-
-            // Update x-coordinates depending on RTL state.
-            if (isInRTLMode()) {
-                mContentContainer.setX(mMarginHorizontal);  // align left
-                mMainPanel.setX(0);  // align left
-                mOverflowButton.setX(// align right
-                        containerSize.getWidth() - mOverflowButtonSize.getWidth());
-                mOverflowPanel.setX(0);  // align left
-            } else {
-                mContentContainer.setX(// align right
-                        mPopupWidth - containerSize.getWidth() - mMarginHorizontal);
-                mMainPanel.setX(-mContentContainer.getX());  // align right
-                mOverflowButton.setX(0);  // align left
-                mOverflowPanel.setX(0);  // align left
-            }
-
-            // Update y-coordinates depending on overflow's open direction.
-            if (mOpenOverflowUpwards) {
-                mContentContainer.setY(mMarginVertical);  // align top
-                mMainPanel.setY(// align bottom
-                        containerSize.getHeight() - mContentContainer.getHeight());
-                mOverflowButton.setY(// align bottom
-                        containerSize.getHeight() - mOverflowButtonSize.getHeight());
-                mOverflowPanel.setY(0);  // align top
-            } else {
-                // opens downwards.
-                mContentContainer.setY(mMarginVertical);  // align top
-                mMainPanel.setY(0);  // align top
-                mOverflowButton.setY(0);  // align top
-                mOverflowPanel.setY(mOverflowButtonSize.getHeight());  // align bottom
-            }
-        } else {
-            // Overflow not open. Set closed state.
-            final Size containerSize = mMainPanelSize;
-            setSize(mContentContainer, containerSize);
-            mMainPanel.setAlpha(1);
-            mMainPanel.setVisibility(View.VISIBLE);
-            mOverflowPanel.setAlpha(0);
-            mOverflowPanel.setVisibility(View.INVISIBLE);
-            mOverflowButton.setImageDrawable(mOverflow);
-            mOverflowButton.setContentDescription(mContext.getString(
-                    R.string.floating_toolbar_open_overflow_description));
-
-            if (hasOverflow()) {
-                // Update x-coordinates depending on RTL state.
-                if (isInRTLMode()) {
-                    mContentContainer.setX(mMarginHorizontal);  // align left
-                    mMainPanel.setX(0);  // align left
-                    mOverflowButton.setX(0);  // align left
-                    mOverflowPanel.setX(0);  // align left
-                } else {
-                    mContentContainer.setX(// align right
-                            mPopupWidth - containerSize.getWidth() - mMarginHorizontal);
-                    mMainPanel.setX(0);  // align left
-                    mOverflowButton.setX(// align right
-                            containerSize.getWidth() - mOverflowButtonSize.getWidth());
-                    mOverflowPanel.setX(// align right
-                            containerSize.getWidth() - mOverflowPanelSize.getWidth());
-                }
-
-                // Update y-coordinates depending on overflow's open direction.
-                if (mOpenOverflowUpwards) {
-                    mContentContainer.setY(// align bottom
-                            mMarginVertical + mOverflowPanelSize.getHeight()
-                                    - containerSize.getHeight());
-                    mMainPanel.setY(0);  // align top
-                    mOverflowButton.setY(0);  // align top
-                    mOverflowPanel.setY(// align bottom
-                            containerSize.getHeight() - mOverflowPanelSize.getHeight());
-                } else {
-                    // opens downwards.
-                    mContentContainer.setY(mMarginVertical);  // align top
-                    mMainPanel.setY(0);  // align top
-                    mOverflowButton.setY(0);  // align top
-                    mOverflowPanel.setY(mOverflowButtonSize.getHeight());  // align bottom
-                }
-            } else {
-                // No overflow.
-                mContentContainer.setX(mMarginHorizontal);  // align left
-                mContentContainer.setY(mMarginVertical);  // align top
-                mMainPanel.setX(0);  // align left
-                mMainPanel.setY(0);  // align top
-            }
-        }
-    }
-
-    private void updateOverflowHeight(int suggestedHeight) {
-        if (hasOverflow()) {
-            final int maxItemSize =
-                    (suggestedHeight - mOverflowButtonSize.getHeight()) / mLineHeight;
-            final int newHeight = calculateOverflowHeight(maxItemSize);
-            if (mOverflowPanelSize.getHeight() != newHeight) {
-                mOverflowPanelSize = new Size(mOverflowPanelSize.getWidth(), newHeight);
-            }
-            setSize(mOverflowPanel, mOverflowPanelSize);
-            if (mIsOverflowOpen) {
-                setSize(mContentContainer, mOverflowPanelSize);
-                if (mOpenOverflowUpwards) {
-                    final int deltaHeight = mOverflowPanelSize.getHeight() - newHeight;
-                    mContentContainer.setY(mContentContainer.getY() + deltaHeight);
-                    mOverflowButton.setY(mOverflowButton.getY() - deltaHeight);
-                }
-            } else {
-                setSize(mContentContainer, mMainPanelSize);
-            }
-            updatePopupSize();
-        }
-    }
-
-    private void updatePopupSize() {
-        int width = 0;
-        int height = 0;
-        if (mMainPanelSize != null) {
-            width = Math.max(width, mMainPanelSize.getWidth());
-            height = Math.max(height, mMainPanelSize.getHeight());
-        }
-        if (mOverflowPanelSize != null) {
-            width = Math.max(width, mOverflowPanelSize.getWidth());
-            height = Math.max(height, mOverflowPanelSize.getHeight());
-        }
-
-        mPopupWidth = width + mMarginHorizontal * 2;
-        mPopupHeight = height + mMarginVertical * 2;
-        maybeComputeTransitionDurationScale();
-    }
-
-    private int getAdjustedToolbarWidth(int suggestedWidth) {
-        int width = suggestedWidth;
-        int maximumWidth = mViewPortOnScreen.width() - 2 * mContext.getResources()
-                .getDimensionPixelSize(R.dimen.floating_toolbar_horizontal_margin);
-        if (width <= 0) {
-            width = mContext.getResources()
-                    .getDimensionPixelSize(R.dimen.floating_toolbar_preferred_width);
-        }
-        return Math.min(width, maximumWidth);
-    }
-
-    private boolean isInRTLMode() {
-        return mContext.getApplicationInfo().hasRtlSupport()
-                && mContext.getResources().getConfiguration().getLayoutDirection()
-                == View.LAYOUT_DIRECTION_RTL;
-    }
-
-    private boolean hasOverflow() {
-        return mOverflowPanelSize != null;
-    }
-
-    /**
-     * Fits as many menu items in the main panel and returns a list of the menu items that
-     * were not fit in.
-     *
-     * @return The menu items that are not included in this main panel.
-     */
-    private List<ToolbarMenuItem> layoutMainPanelItems(List<ToolbarMenuItem> menuItems,
-            int toolbarWidth) {
-        final LinkedList<ToolbarMenuItem> remainingMenuItems = new LinkedList<>();
-        // add the overflow menu items to the end of the remainingMenuItems list.
-        final LinkedList<ToolbarMenuItem> overflowMenuItems = new LinkedList();
-        for (ToolbarMenuItem menuItem : menuItems) {
-            if (menuItem.getItemId() != android.R.id.textAssist
-                    && menuItem.getPriority() == ToolbarMenuItem.PRIORITY_OVERFLOW) {
-                overflowMenuItems.add(menuItem);
-            } else {
-                remainingMenuItems.add(menuItem);
-            }
-        }
-        remainingMenuItems.addAll(overflowMenuItems);
-
-        mMainPanel.removeAllViews();
-        mMainPanel.setPaddingRelative(0, 0, 0, 0);
-
-        int availableWidth = toolbarWidth;
-        boolean isFirstItem = true;
-        while (!remainingMenuItems.isEmpty()) {
-            ToolbarMenuItem menuItem = remainingMenuItems.peek();
-            // if this is the first item, regardless of requiresOverflow(), it should be
-            // displayed on the main panel. Otherwise all items including this one will be
-            // overflow items, and should be displayed in overflow panel.
-            if (!isFirstItem && menuItem.getPriority() == ToolbarMenuItem.PRIORITY_OVERFLOW) {
-                break;
-            }
-            final boolean showIcon = isFirstItem && menuItem.getItemId() == R.id.textAssist;
-            final View menuItemButton = createMenuItemButton(
-                    mContext, menuItem, mIconTextSpacing, showIcon);
-            if (!showIcon && menuItemButton instanceof LinearLayout) {
-                ((LinearLayout) menuItemButton).setGravity(Gravity.CENTER);
-            }
-            // Adding additional start padding for the first button to even out button spacing.
-            if (isFirstItem) {
-                menuItemButton.setPaddingRelative(
-                        (int) (1.5 * menuItemButton.getPaddingStart()),
-                        menuItemButton.getPaddingTop(),
-                        menuItemButton.getPaddingEnd(),
-                        menuItemButton.getPaddingBottom());
-            }
-            // Adding additional end padding for the last button to even out button spacing.
-            boolean isLastItem = remainingMenuItems.size() == 1;
-            if (isLastItem) {
-                menuItemButton.setPaddingRelative(
-                        menuItemButton.getPaddingStart(),
-                        menuItemButton.getPaddingTop(),
-                        (int) (1.5 * menuItemButton.getPaddingEnd()),
-                        menuItemButton.getPaddingBottom());
-            }
-            menuItemButton.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
-            final int menuItemButtonWidth = Math.min(
-                    menuItemButton.getMeasuredWidth(), toolbarWidth);
-            // Check if we can fit an item while reserving space for the overflowButton.
-            final boolean canFitWithOverflow =
-                    menuItemButtonWidth <= availableWidth - mOverflowButtonSize.getWidth();
-            final boolean canFitNoOverflow =
-                    isLastItem && menuItemButtonWidth <= availableWidth;
-            if (canFitWithOverflow || canFitNoOverflow) {
-                menuItemButton.setTag(menuItem);
-                menuItemButton.setOnClickListener(mMenuItemButtonOnClickListener);
-                // Set tooltips for main panel items, but not overflow items (b/35726766).
-                menuItemButton.setTooltipText(menuItem.getTooltipText());
-                mMainPanel.addView(menuItemButton);
-                final ViewGroup.LayoutParams params = menuItemButton.getLayoutParams();
-                params.width = menuItemButtonWidth;
-                menuItemButton.setLayoutParams(params);
-                availableWidth -= menuItemButtonWidth;
-                remainingMenuItems.pop();
-            } else {
-                break;
-            }
-            isFirstItem = false;
-        }
-        if (!remainingMenuItems.isEmpty()) {
-            // Reserve space for overflowButton.
-            mMainPanel.setPaddingRelative(0, 0, mOverflowButtonSize.getWidth(), 0);
-        }
-        mMainPanelSize = measure(mMainPanel);
-
-        return remainingMenuItems;
-    }
-
-    private void layoutOverflowPanelItems(List<ToolbarMenuItem> menuItems) {
-        ArrayAdapter<ToolbarMenuItem> overflowPanelAdapter =
-                (ArrayAdapter<ToolbarMenuItem>) mOverflowPanel.getAdapter();
-        overflowPanelAdapter.clear();
-        final int size = menuItems.size();
-        for (int i = 0; i < size; i++) {
-            overflowPanelAdapter.add(menuItems.get(i));
-        }
-        mOverflowPanel.setAdapter(overflowPanelAdapter);
-        if (mOpenOverflowUpwards) {
-            mOverflowPanel.setY(0);
-        } else {
-            mOverflowPanel.setY(mOverflowButtonSize.getHeight());
-        }
-        int width = Math.max(getOverflowWidth(), mOverflowButtonSize.getWidth());
-        int height = calculateOverflowHeight(MAX_OVERFLOW_SIZE);
-        mOverflowPanelSize = new Size(width, height);
-        setSize(mOverflowPanel, mOverflowPanelSize);
-    }
-
-    /**
-     * Resets the content container and appropriately position it's panels.
-     */
-    private void preparePopupContent() {
-        mContentContainer.removeAllViews();
-        // Add views in the specified order so they stack up as expected.
-        // Order: overflowPanel, mainPanel, overflowButton.
-        if (hasOverflow()) {
-            mContentContainer.addView(mOverflowPanel);
-        }
-        mContentContainer.addView(mMainPanel);
-        if (hasOverflow()) {
-            mContentContainer.addView(mOverflowButton);
-        }
-        setPanelsStatesAtRestingPosition();
-
-        // The positioning of contents in RTL is wrong when the view is first rendered.
-        // Hide the view and post a runnable to recalculate positions and render the view.
-        // TODO: Investigate why this happens and fix.
-        if (isInRTLMode()) {
-            mContentContainer.setAlpha(0);
-            mContentContainer.post(mPreparePopupContentRTLHelper);
-        }
-    }
-
-    /**
-     * Clears out the panels and their container. Resets their calculated sizes.
-     */
-    private void clearPanels() {
-        mIsOverflowOpen = false;
-        mMainPanelSize = null;
-        mMainPanel.removeAllViews();
-        mOverflowPanelSize = null;
-        ArrayAdapter<ToolbarMenuItem> overflowPanelAdapter =
-                (ArrayAdapter<ToolbarMenuItem>) mOverflowPanel.getAdapter();
-        overflowPanelAdapter.clear();
-        mOverflowPanel.setAdapter(overflowPanelAdapter);
-        mContentContainer.removeAllViews();
-    }
-
-    private void positionContentYCoordinatesIfOpeningOverflowUpwards() {
-        if (mOpenOverflowUpwards) {
-            mMainPanel.setY(mContentContainer.getHeight() - mMainPanelSize.getHeight());
-            mOverflowButton.setY(mContentContainer.getHeight() - mOverflowButton.getHeight());
-            mOverflowPanel.setY(mContentContainer.getHeight() - mOverflowPanelSize.getHeight());
-        }
-    }
-
-    private int getOverflowWidth() {
-        int overflowWidth = 0;
-        final int count = mOverflowPanel.getAdapter().getCount();
-        for (int i = 0; i < count; i++) {
-            ToolbarMenuItem menuItem = (ToolbarMenuItem) mOverflowPanel.getAdapter().getItem(i);
-            overflowWidth =
-                    Math.max(mOverflowPanelViewHelper.calculateWidth(menuItem), overflowWidth);
-        }
-        return overflowWidth;
-    }
-
-    private int calculateOverflowHeight(int maxItemSize) {
-        // Maximum of 4 items, minimum of 2 if the overflow has to scroll.
-        int actualSize = Math.min(
-                MAX_OVERFLOW_SIZE,
-                Math.min(
-                        Math.max(MIN_OVERFLOW_SIZE, maxItemSize),
-                        mOverflowPanel.getCount()));
-        int extension = 0;
-        if (actualSize < mOverflowPanel.getCount()) {
-            // The overflow will require scrolling to get to all the items.
-            // Extend the height so that part of the hidden items is displayed.
-            extension = (int) (mLineHeight * 0.5f);
-        }
-        return actualSize * mLineHeight
-                + mOverflowButtonSize.getHeight()
-                + extension;
-    }
-
-    /**
-     * NOTE: Use only in android.view.animation.* animations. Do not use in android.animation.*
-     * animations. See comment about this in the code.
-     */
-    private int getAnimationDuration() {
-        if (mTransitionDurationScale < 150) {
-            // For smaller transition, decrease the time.
-            return 200;
-        } else if (mTransitionDurationScale > 300) {
-            // For bigger transition, increase the time.
-            return 300;
-        }
-
-        // Scale the animation duration with getDurationScale(). This allows
-        // android.view.animation.* animations to scale just like android.animation.* animations
-        // when  animator duration scale is adjusted in "Developer Options".
-        // For this reason, do not use this method for android.animation.* animations.
-        return (int) (250 * ValueAnimator.getDurationScale());
-    }
-
-    private void maybeComputeTransitionDurationScale() {
-        if (mMainPanelSize != null && mOverflowPanelSize != null) {
-            int w = mMainPanelSize.getWidth() - mOverflowPanelSize.getWidth();
-            int h = mOverflowPanelSize.getHeight() - mMainPanelSize.getHeight();
-            mTransitionDurationScale = (int) (Math.sqrt(w * w + h * h)
-                    / mContentContainer.getContext().getResources().getDisplayMetrics().density);
-        }
-    }
-
-    private ViewGroup createMainPanel() {
-        return new LinearLayout(mContext) {
-            @Override
-            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
-                if (isOverflowAnimating()) {
-                    // Update widthMeasureSpec to make sure that this view is not clipped
-                    // as we offset its coordinates with respect to its parent.
-                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(
-                            mMainPanelSize.getWidth(),
-                            MeasureSpec.EXACTLY);
-                }
-                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
-            }
-
-            @Override
-            public boolean onInterceptTouchEvent(MotionEvent ev) {
-                // Intercept the touch event while the overflow is animating.
-                return isOverflowAnimating();
-            }
-        };
-    }
-
-    private ImageButton createOverflowButton() {
-        final ImageButton overflowButton = (ImageButton) LayoutInflater.from(mContext)
-                .inflate(R.layout.floating_popup_overflow_button, null);
-        overflowButton.setImageDrawable(mOverflow);
-        overflowButton.setOnClickListener(v -> {
-            if (isShowing()) {
-                preparePopupContent();
-                WidgetInfo widgetInfo = createWidgetInfo();
-                mSurfaceControlViewHost.relayout(mPopupWidth, mPopupHeight);
-                mCallbackWrapper.onWidgetUpdated(widgetInfo);
-            }
-            if (mIsOverflowOpen) {
-                overflowButton.setImageDrawable(mToOverflow);
-                mToOverflow.start();
-                closeOverflow();
-            } else {
-                overflowButton.setImageDrawable(mToArrow);
-                mToArrow.start();
-                openOverflow();
-            }
-        });
-        return overflowButton;
-    }
-
-    private OverflowPanel createOverflowPanel() {
-        final OverflowPanel overflowPanel = new OverflowPanel(this);
-        overflowPanel.setLayoutParams(new ViewGroup.LayoutParams(
-                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
-        overflowPanel.setDivider(null);
-        overflowPanel.setDividerHeight(0);
-
-        final ArrayAdapter adapter =
-                new ArrayAdapter<ToolbarMenuItem>(mContext, 0) {
-                    @Override
-                    public View getView(int position, View convertView, ViewGroup parent) {
-                        return mOverflowPanelViewHelper.getView(
-                                getItem(position), mOverflowPanelSize.getWidth(), convertView);
-                    }
-                };
-        overflowPanel.setAdapter(adapter);
-        overflowPanel.setOnItemClickListener((parent, view, position, id) -> {
-            ToolbarMenuItem menuItem =
-                    (ToolbarMenuItem) overflowPanel.getAdapter().getItem(position);
-            mCallbackWrapper.onMenuItemClicked(menuItem);
-        });
-        return overflowPanel;
-    }
-
-    private boolean isOverflowAnimating() {
-        final boolean overflowOpening = mOpenOverflowAnimation.hasStarted()
-                && !mOpenOverflowAnimation.hasEnded();
-        final boolean overflowClosing = mCloseOverflowAnimation.hasStarted()
-                && !mCloseOverflowAnimation.hasEnded();
-        return overflowOpening || overflowClosing;
-    }
-
-    private Animation.AnimationListener createOverflowAnimationListener() {
-        return new Animation.AnimationListener() {
-            @Override
-            public void onAnimationStart(Animation animation) {
-                // Disable the overflow button while it's animating.
-                // It will be re-enabled when the animation stops.
-                mOverflowButton.setEnabled(false);
-                // Ensure both panels have visibility turned on when the overflow animation
-                // starts.
-                mMainPanel.setVisibility(View.VISIBLE);
-                mOverflowPanel.setVisibility(View.VISIBLE);
-            }
-
-            @Override
-            public void onAnimationEnd(Animation animation) {
-                // Posting this because it seems like this is called before the animation
-                // actually ends.
-                mContentContainer.post(() -> {
-                    setPanelsStatesAtRestingPosition();
-                });
-            }
-
-            @Override
-            public void onAnimationRepeat(Animation animation) {
-            }
-        };
-    }
-
-    private static Size measure(View view) {
-        Preconditions.checkState(view.getParent() == null);
-        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
-        return new Size(view.getMeasuredWidth(), view.getMeasuredHeight());
-    }
-
-    private static void setSize(View view, int width, int height) {
-        view.setMinimumWidth(width);
-        view.setMinimumHeight(height);
-        ViewGroup.LayoutParams params = view.getLayoutParams();
-        params = (params == null) ? new ViewGroup.LayoutParams(0, 0) : params;
-        params.width = width;
-        params.height = height;
-        view.setLayoutParams(params);
-    }
-
-    private static void setSize(View view, Size size) {
-        setSize(view, size.getWidth(), size.getHeight());
-    }
-
-    private static void setWidth(View view, int width) {
-        ViewGroup.LayoutParams params = view.getLayoutParams();
-        setSize(view, width, params.height);
-    }
-
-    private static void setHeight(View view, int height) {
-        ViewGroup.LayoutParams params = view.getLayoutParams();
-        setSize(view, params.width, height);
-    }
-
-    /**
-     * A custom ListView for the overflow panel.
-     */
-    private static final class OverflowPanel extends ListView {
-
-        private final RemoteSelectionToolbar mPopup;
-
-        OverflowPanel(RemoteSelectionToolbar popup) {
-            super(Objects.requireNonNull(popup).mContext);
-            this.mPopup = popup;
-            setScrollBarDefaultDelayBeforeFade(ViewConfiguration.getScrollDefaultDelay() * 3);
-            setScrollIndicators(View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_BOTTOM);
-        }
-
-        @Override
-        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
-            // Update heightMeasureSpec to make sure that this view is not clipped
-            // as we offset it's coordinates with respect to its parent.
-            int height = mPopup.mOverflowPanelSize.getHeight()
-                    - mPopup.mOverflowButtonSize.getHeight();
-            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
-            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
-        }
-
-        @Override
-        public boolean dispatchTouchEvent(MotionEvent ev) {
-            if (mPopup.isOverflowAnimating()) {
-                // Eat the touch event.
-                return true;
-            }
-            return super.dispatchTouchEvent(ev);
-        }
-
-        @Override
-        protected boolean awakenScrollBars() {
-            return super.awakenScrollBars();
-        }
-    }
-
-    /**
-     * A custom interpolator used for various floating toolbar animations.
-     */
-    private static final class LogAccelerateInterpolator implements Interpolator {
-
-        private static final int BASE = 100;
-        private static final float LOGS_SCALE = 1f / computeLog(1, BASE);
-
-        private static float computeLog(float t, int base) {
-            return (float) (1 - Math.pow(base, -t));
-        }
-
-        @Override
-        public float getInterpolation(float t) {
-            return 1 - computeLog(1 - t, BASE) * LOGS_SCALE;
-        }
-    }
-
-    /**
-     * A helper for generating views for the overflow panel.
-     */
-    private static final class OverflowPanelViewHelper {
-        private final Context mContext;
-        private final View mCalculator;
-        private final int mIconTextSpacing;
-        private final int mSidePadding;
-
-        OverflowPanelViewHelper(Context context, int iconTextSpacing) {
-            mContext = Objects.requireNonNull(context);
-            mIconTextSpacing = iconTextSpacing;
-            mSidePadding = context.getResources()
-                    .getDimensionPixelSize(R.dimen.floating_toolbar_overflow_side_padding);
-            mCalculator = createMenuButton(null);
-        }
-
-        public View getView(ToolbarMenuItem menuItem, int minimumWidth, View convertView) {
-            Objects.requireNonNull(menuItem);
-            if (convertView != null) {
-                updateMenuItemButton(
-                        convertView, menuItem, mIconTextSpacing, shouldShowIcon(menuItem));
-            } else {
-                convertView = createMenuButton(menuItem);
-            }
-            convertView.setMinimumWidth(minimumWidth);
-            return convertView;
-        }
-
-        public int calculateWidth(ToolbarMenuItem menuItem) {
-            updateMenuItemButton(
-                    mCalculator, menuItem, mIconTextSpacing, shouldShowIcon(menuItem));
-            mCalculator.measure(
-                    View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
-            return mCalculator.getMeasuredWidth();
-        }
-
-        private View createMenuButton(ToolbarMenuItem menuItem) {
-            View button = createMenuItemButton(
-                    mContext, menuItem, mIconTextSpacing, shouldShowIcon(menuItem));
-            button.setPadding(mSidePadding, 0, mSidePadding, 0);
-            return button;
-        }
-
-        private boolean shouldShowIcon(ToolbarMenuItem menuItem) {
-            if (menuItem != null) {
-                return menuItem.getGroupId() == android.R.id.textAssist;
-            }
-            return  false;
-        }
-    }
-
-    /**
-     * Creates and returns a menu button for the specified menu item.
-     */
-    private static View createMenuItemButton(
-            Context context, ToolbarMenuItem menuItem, int iconTextSpacing, boolean showIcon) {
-        final View menuItemButton = LayoutInflater.from(context)
-                .inflate(R.layout.floating_popup_menu_button, null);
-        if (menuItem != null) {
-            updateMenuItemButton(menuItemButton, menuItem, iconTextSpacing, showIcon);
-        }
-        return menuItemButton;
-    }
-
-    /**
-     * Updates the specified menu item button with the specified menu item data.
-     */
-    private static void updateMenuItemButton(View menuItemButton, ToolbarMenuItem menuItem,
-            int iconTextSpacing, boolean showIcon) {
-        final TextView buttonText = menuItemButton.findViewById(
-                R.id.floating_toolbar_menu_item_text);
-        buttonText.setEllipsize(null);
-        if (TextUtils.isEmpty(menuItem.getTitle())) {
-            buttonText.setVisibility(View.GONE);
-        } else {
-            buttonText.setVisibility(View.VISIBLE);
-            buttonText.setText(menuItem.getTitle());
-        }
-        final ImageView buttonIcon = menuItemButton.findViewById(
-                R.id.floating_toolbar_menu_item_image);
-        if (menuItem.getIcon() == null || !showIcon) {
-            buttonIcon.setVisibility(View.GONE);
-            buttonText.setPaddingRelative(0, 0, 0, 0);
-        } else {
-            buttonIcon.setVisibility(View.VISIBLE);
-            buttonIcon.setImageDrawable(
-                    menuItem.getIcon().loadDrawable(menuItemButton.getContext()));
-            buttonText.setPaddingRelative(iconTextSpacing, 0, 0, 0);
-        }
-        final CharSequence contentDescription = menuItem.getContentDescription();
-        if (TextUtils.isEmpty(contentDescription)) {
-            menuItemButton.setContentDescription(menuItem.getTitle());
-        } else {
-            menuItemButton.setContentDescription(contentDescription);
-        }
-    }
-
-    private static ViewGroup createContentContainer(Context context) {
-        ViewGroup contentContainer = (ViewGroup) LayoutInflater.from(context)
-                .inflate(R.layout.floating_popup_container, null);
-        contentContainer.setLayoutParams(new ViewGroup.LayoutParams(
-                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
-        contentContainer.setTag(FloatingToolbar.FLOATING_TOOLBAR_TAG);
-        contentContainer.setClipToOutline(true);
-        return contentContainer;
-    }
-
-    /**
-     * Creates an "appear" animation for the specified view.
-     *
-     * @param view  The view to animate
-     */
-    private static AnimatorSet createEnterAnimation(View view, Animator.AnimatorListener listener) {
-        AnimatorSet animation = new AnimatorSet();
-        animation.playTogether(
-                ObjectAnimator.ofFloat(view, View.ALPHA, 0, 1).setDuration(150));
-        animation.addListener(listener);
-        return animation;
-    }
-
-    /**
-     * Creates a "disappear" animation for the specified view.
-     *
-     * @param view  The view to animate
-     * @param startDelay  The start delay of the animation
-     * @param listener  The animation listener
-     */
-    private static AnimatorSet createExitAnimation(
-            View view, int startDelay, Animator.AnimatorListener listener) {
-        AnimatorSet animation =  new AnimatorSet();
-        animation.playTogether(
-                ObjectAnimator.ofFloat(view, View.ALPHA, 1, 0).setDuration(100));
-        animation.setStartDelay(startDelay);
-        if (listener != null) {
-            animation.addListener(listener);
-        }
-        return animation;
-    }
-
-    /**
-     * Returns a re-themed context with controlled look and feel for views.
-     */
-    private static Context applyDefaultTheme(Context originalContext, boolean isLightTheme) {
-        int themeId =
-                isLightTheme ? R.style.Theme_DeviceDefault_Light : R.style.Theme_DeviceDefault;
-        return new ContextThemeWrapper(originalContext, themeId);
-    }
-
-    private static void debugLog(String message) {
-        if (Log.isLoggable(FloatingToolbar.FLOATING_TOOLBAR_TAG, Log.DEBUG)) {
-            Log.v(TAG, message);
-        }
-    }
-
-    void dump(String prefix, PrintWriter pw) {
-        pw.print(prefix); pw.print("toolbar token: "); pw.println(mSelectionToolbarToken);
-        pw.print(prefix); pw.print("dismissed: "); pw.println(mDismissed);
-        pw.print(prefix); pw.print("hidden: "); pw.println(mHidden);
-        pw.print(prefix); pw.print("popup width: "); pw.println(mPopupWidth);
-        pw.print(prefix); pw.print("popup height: "); pw.println(mPopupHeight);
-        pw.print(prefix); pw.print("relative coords: "); pw.println(mRelativeCoordsForToolbar);
-        pw.print(prefix); pw.print("main panel size: "); pw.println(mMainPanelSize);
-        boolean hasOverflow = hasOverflow();
-        pw.print(prefix); pw.print("has overflow: "); pw.println(hasOverflow);
-        if (hasOverflow) {
-            pw.print(prefix); pw.print("overflow open: "); pw.println(mIsOverflowOpen);
-            pw.print(prefix); pw.print("overflow size: "); pw.println(mOverflowPanelSize);
-        }
-        if (mSurfaceControlViewHost != null) {
-            FloatingToolbarRoot root = (FloatingToolbarRoot) mSurfaceControlViewHost.getView();
-            root.dump(prefix, pw);
-        }
-        if (mMenuItems != null) {
-            int menuItemSize = mMenuItems.size();
-            pw.print(prefix); pw.print("number menu items: "); pw.println(menuItemSize);
-            for (int i = 0; i < menuItemSize; i++) {
-                pw.print(prefix); pw.print("#"); pw.println(i);
-                pw.print(prefix + "  "); pw.println(mMenuItems.get(i));
-            }
-        }
-    }
-}
diff --git a/core/java/android/service/selectiontoolbar/SelectionToolbarRenderCallback.java b/core/java/android/service/selectiontoolbar/SelectionToolbarRenderCallback.java
deleted file mode 100644
index a10b6a8..0000000
--- a/core/java/android/service/selectiontoolbar/SelectionToolbarRenderCallback.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.service.selectiontoolbar;
-
-import android.view.selectiontoolbar.ToolbarMenuItem;
-import android.view.selectiontoolbar.WidgetInfo;
-
-/**
- * The callback that the render service uses to communicate with the host of the selection toolbar
- * container.
- *
- * @hide
- */
-public interface SelectionToolbarRenderCallback {
-    /**
-     * The selection toolbar is shown.
-     */
-    void onShown(WidgetInfo widgetInfo);
-    /**
-     * The selection toolbar has changed.
-     */
-    void onWidgetUpdated(WidgetInfo info);
-    /**
-     * The menu item on the selection toolbar has been clicked.
-     */
-    void onMenuItemClicked(ToolbarMenuItem item);
-    /**
-     * The toolbar doesn't be dismissed after showing on a given timeout.
-     */
-    void onToolbarShowTimeout();
-    /**
-     * The error occurred when operating on the selection toolbar.
-     */
-    void onError(int errorCode);
-}
diff --git a/core/java/android/service/selectiontoolbar/SelectionToolbarRenderService.java b/core/java/android/service/selectiontoolbar/SelectionToolbarRenderService.java
deleted file mode 100644
index f33feae..0000000
--- a/core/java/android/service/selectiontoolbar/SelectionToolbarRenderService.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.service.selectiontoolbar;
-
-import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
-
-import android.annotation.CallSuper;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.app.Service;
-import android.content.Intent;
-import android.os.Handler;
-import android.os.IBinder;
-import android.os.Looper;
-import android.os.RemoteException;
-import android.util.Log;
-import android.util.Pair;
-import android.util.SparseArray;
-import android.view.selectiontoolbar.ISelectionToolbarCallback;
-import android.view.selectiontoolbar.ShowInfo;
-import android.view.selectiontoolbar.ToolbarMenuItem;
-import android.view.selectiontoolbar.WidgetInfo;
-
-/**
- * Service for rendering selection toolbar.
- *
- * @hide
- */
-public abstract class SelectionToolbarRenderService extends Service {
-
-    private static final String TAG = "SelectionToolbarRenderService";
-
-    // TODO(b/215497659): read from DeviceConfig
-    // The timeout to clean the cache if the client forgot to call dismiss()
-    private static final int CACHE_CLEAN_AFTER_SHOW_TIMEOUT_IN_MS = 10 * 60 * 1000; // 10 minutes
-
-    /**
-     * The {@link Intent} that must be declared as handled by the service.
-     *
-     * <p>To be supported, the service must also require the
-     * {@link android.Manifest.permission#BIND_SELECTION_TOOLBAR_RENDER_SERVICE} permission so
-     * that other applications can not abuse it.
-     */
-    public static final String SERVICE_INTERFACE =
-            "android.service.selectiontoolbar.SelectionToolbarRenderService";
-
-    private Handler mHandler;
-    private ISelectionToolbarRenderServiceCallback mServiceCallback;
-
-    private final SparseArray<Pair<RemoteCallbackWrapper, CleanCacheRunnable>> mCache =
-            new SparseArray<>();
-
-    /**
-     * Binder to receive calls from system server.
-     */
-    private final ISelectionToolbarRenderService mInterface =
-            new ISelectionToolbarRenderService.Stub() {
-
-        @Override
-        public void onShow(int callingUid, ShowInfo showInfo, ISelectionToolbarCallback callback) {
-            if (mCache.indexOfKey(callingUid) < 0) {
-                mCache.put(callingUid, new Pair<>(new RemoteCallbackWrapper(callback),
-                        new CleanCacheRunnable(callingUid)));
-            }
-            Pair<RemoteCallbackWrapper, CleanCacheRunnable> toolbarPair = mCache.get(callingUid);
-            CleanCacheRunnable cleanRunnable = toolbarPair.second;
-            mHandler.removeCallbacks(cleanRunnable);
-            mHandler.sendMessage(obtainMessage(SelectionToolbarRenderService::onShow,
-                    SelectionToolbarRenderService.this, callingUid, showInfo,
-                    toolbarPair.first));
-            mHandler.postDelayed(cleanRunnable, CACHE_CLEAN_AFTER_SHOW_TIMEOUT_IN_MS);
-        }
-
-        @Override
-        public void onHide(long widgetToken) {
-            mHandler.sendMessage(obtainMessage(SelectionToolbarRenderService::onHide,
-                    SelectionToolbarRenderService.this, widgetToken));
-        }
-
-        @Override
-        public void onDismiss(int callingUid, long widgetToken) {
-            mHandler.sendMessage(obtainMessage(SelectionToolbarRenderService::onDismiss,
-                    SelectionToolbarRenderService.this, widgetToken));
-            Pair<RemoteCallbackWrapper, CleanCacheRunnable> toolbarPair = mCache.get(callingUid);
-            if (toolbarPair != null) {
-                mHandler.removeCallbacks(toolbarPair.second);
-                mCache.remove(callingUid);
-            }
-        }
-
-        @Override
-        public void onConnected(IBinder callback) {
-            mHandler.sendMessage(obtainMessage(SelectionToolbarRenderService::handleOnConnected,
-                    SelectionToolbarRenderService.this, callback));
-        }
-    };
-
-    @CallSuper
-    @Override
-    public void onCreate() {
-        super.onCreate();
-        mHandler = new Handler(Looper.getMainLooper(), null, true);
-    }
-
-    @Override
-    @Nullable
-    public final IBinder onBind(@NonNull Intent intent) {
-        if (SERVICE_INTERFACE.equals(intent.getAction())) {
-            return mInterface.asBinder();
-        }
-        Log.w(TAG, "Tried to bind to wrong intent (should be " + SERVICE_INTERFACE + ": " + intent);
-        return null;
-    }
-
-    private void handleOnConnected(@NonNull IBinder callback) {
-        mServiceCallback = ISelectionToolbarRenderServiceCallback.Stub.asInterface(callback);
-    }
-
-    protected void transferTouch(@NonNull IBinder source, @NonNull IBinder target) {
-        final ISelectionToolbarRenderServiceCallback callback = mServiceCallback;
-        if (callback == null) {
-            Log.e(TAG, "transferTouch(): no server callback");
-            return;
-        }
-        try {
-            callback.transferTouch(source, target);
-        } catch (RemoteException e) {
-            // no-op
-        }
-    }
-
-    /**
-     * Called when showing the selection toolbar.
-     */
-    public abstract void onShow(int callingUid, ShowInfo showInfo,
-            RemoteCallbackWrapper callbackWrapper);
-
-    /**
-     * Called when hiding the selection toolbar.
-     */
-    public abstract void onHide(long widgetToken);
-
-
-    /**
-     * Called when dismissing the selection toolbar.
-     */
-    public abstract void onDismiss(long widgetToken);
-
-    /**
-     * Called when showing the selection toolbar for a specific timeout. This avoids the client
-     * forgot to call dismiss to clean the state.
-     */
-    public void onToolbarShowTimeout(int callingUid) {
-        // no-op
-    }
-
-    /**
-     * Callback to notify the client toolbar events.
-     */
-    public static final class RemoteCallbackWrapper implements SelectionToolbarRenderCallback {
-
-        private final ISelectionToolbarCallback mRemoteCallback;
-
-        RemoteCallbackWrapper(ISelectionToolbarCallback remoteCallback) {
-            // TODO(b/215497659): handle if the binder dies.
-            mRemoteCallback = remoteCallback;
-        }
-
-        @Override
-        public void onShown(WidgetInfo widgetInfo) {
-            try {
-                mRemoteCallback.onShown(widgetInfo);
-            } catch (RemoteException e) {
-                // no-op
-            }
-        }
-
-        @Override
-        public void onToolbarShowTimeout() {
-            try {
-                mRemoteCallback.onToolbarShowTimeout();
-            } catch (RemoteException e) {
-                // no-op
-            }
-        }
-
-        @Override
-        public void onWidgetUpdated(WidgetInfo widgetInfo) {
-            try {
-                mRemoteCallback.onWidgetUpdated(widgetInfo);
-            } catch (RemoteException e) {
-                // no-op
-            }
-        }
-
-        @Override
-        public void onMenuItemClicked(ToolbarMenuItem item) {
-            try {
-                mRemoteCallback.onMenuItemClicked(item);
-            } catch (RemoteException e) {
-                // no-op
-            }
-        }
-
-        @Override
-        public void onError(int errorCode) {
-            try {
-                mRemoteCallback.onError(errorCode);
-            } catch (RemoteException e) {
-                // no-op
-            }
-        }
-    }
-
-    private class CleanCacheRunnable implements Runnable {
-
-        int mCleanUid;
-
-        CleanCacheRunnable(int cleanUid) {
-            mCleanUid = cleanUid;
-        }
-
-        @Override
-        public void run() {
-            Pair<RemoteCallbackWrapper, CleanCacheRunnable> toolbarPair = mCache.get(mCleanUid);
-            if (toolbarPair != null) {
-                Log.w(TAG, "CleanCacheRunnable: remove " + mCleanUid + " from cache.");
-                mCache.remove(mCleanUid);
-                onToolbarShowTimeout(mCleanUid);
-            }
-        }
-    }
-
-    /**
-     * A listener to notify the service to the transfer touch focus.
-     */
-    public interface TransferTouchListener {
-        /**
-         * Notify the service to transfer the touch focus.
-         */
-        void onTransferTouch(IBinder source, IBinder target);
-    }
-}
diff --git a/core/java/android/service/voice/AlwaysOnHotwordDetector.java b/core/java/android/service/voice/AlwaysOnHotwordDetector.java
index 21f676e..94d8516 100644
--- a/core/java/android/service/voice/AlwaysOnHotwordDetector.java
+++ b/core/java/android/service/voice/AlwaysOnHotwordDetector.java
@@ -67,6 +67,7 @@
 import com.android.internal.app.IHotwordRecognitionStatusCallback;
 import com.android.internal.app.IVoiceInteractionManagerService;
 import com.android.internal.app.IVoiceInteractionSoundTriggerSession;
+import com.android.internal.infra.AndroidFuture;
 
 import java.io.PrintWriter;
 import java.lang.annotation.Retention;
@@ -1710,6 +1711,11 @@
             Slog.i(TAG, "onProcessRestarted");
             mHandler.sendEmptyMessage(MSG_PROCESS_RESTARTED);
         }
+
+        @Override
+        public void onOpenFile(String filename, AndroidFuture future) throws RemoteException {
+            throw new UnsupportedOperationException("Hotword cannot access files from the disk.");
+        }
     }
 
     void onDetectorRemoteException() {
diff --git a/core/java/android/service/voice/HotwordDetectionService.java b/core/java/android/service/voice/HotwordDetectionService.java
index d9ee859..ccf8b67 100644
--- a/core/java/android/service/voice/HotwordDetectionService.java
+++ b/core/java/android/service/voice/HotwordDetectionService.java
@@ -227,6 +227,12 @@
         public void stopDetection() {
             HotwordDetectionService.this.onStopDetection();
         }
+
+        @Override
+        public void registerRemoteStorageService(IDetectorSessionStorageService
+                detectorSessionStorageService) {
+            throw new UnsupportedOperationException("Hotword cannot access files from the disk.");
+        }
     };
 
     @Override
diff --git a/core/java/android/service/voice/IDetectorSessionStorageService.aidl b/core/java/android/service/voice/IDetectorSessionStorageService.aidl
new file mode 100644
index 0000000..592373e
--- /dev/null
+++ b/core/java/android/service/voice/IDetectorSessionStorageService.aidl
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.service.voice;
+
+import com.android.internal.infra.AndroidFuture;
+
+/**
+ * @hide
+ */
+oneway interface IDetectorSessionStorageService {
+    /**
+     * Called when a file open request is sent. Only files with the given names under the internal
+     * app storage, i.e., {@link Context#getFilesDir()} can be opened.
+     */
+    void openFile(in String filename, in AndroidFuture future);
+}
diff --git a/core/java/android/service/voice/ISandboxedDetectionService.aidl b/core/java/android/service/voice/ISandboxedDetectionService.aidl
index 098536d..c76ac28 100644
--- a/core/java/android/service/voice/ISandboxedDetectionService.aidl
+++ b/core/java/android/service/voice/ISandboxedDetectionService.aidl
@@ -24,6 +24,7 @@
 import android.os.ParcelFileDescriptor;
 import android.os.PersistableBundle;
 import android.os.SharedMemory;
+import android.service.voice.IDetectorSessionStorageService;
 import android.service.voice.IDetectorSessionVisualQueryDetectionCallback;
 import android.service.voice.IDspHotwordDetectionCallback;
 import android.view.contentcapture.IContentCaptureManager;
@@ -71,4 +72,10 @@
     void ping(in IRemoteCallback callback);
 
     void stopDetection();
+
+    /**
+     * Registers the interface stub to talk to the voice interaction service for initialization/
+     * detection unrelated functionalities.
+     */
+    void registerRemoteStorageService(in IDetectorSessionStorageService detectorSessionStorageService);
 }
diff --git a/core/java/android/service/voice/SoftwareHotwordDetector.java b/core/java/android/service/voice/SoftwareHotwordDetector.java
index 128bc0d..f1bc792 100644
--- a/core/java/android/service/voice/SoftwareHotwordDetector.java
+++ b/core/java/android/service/voice/SoftwareHotwordDetector.java
@@ -36,6 +36,7 @@
 
 import com.android.internal.app.IHotwordRecognitionStatusCallback;
 import com.android.internal.app.IVoiceInteractionManagerService;
+import com.android.internal.infra.AndroidFuture;
 
 import java.io.PrintWriter;
 import java.util.concurrent.Executor;
@@ -302,6 +303,11 @@
             Binder.withCleanCallingIdentity(() -> mExecutor.execute(
                     () -> mCallback.onHotwordDetectionServiceRestarted()));
         }
+
+        @Override
+        public void onOpenFile(String filename, AndroidFuture future) throws RemoteException {
+            throw new UnsupportedOperationException("Hotword cannot access files from the disk.");
+        }
     }
 
     /** @hide */
diff --git a/core/java/android/service/voice/VisualQueryDetectionService.java b/core/java/android/service/voice/VisualQueryDetectionService.java
index cbe7666..d184b1e 100644
--- a/core/java/android/service/voice/VisualQueryDetectionService.java
+++ b/core/java/android/service/voice/VisualQueryDetectionService.java
@@ -40,7 +40,12 @@
 import android.view.contentcapture.ContentCaptureManager;
 import android.view.contentcapture.IContentCaptureManager;
 
+import com.android.internal.infra.AndroidFuture;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
 import java.util.Objects;
+import java.util.concurrent.ExecutionException;
 import java.util.function.IntConsumer;
 
 /**
@@ -86,6 +91,8 @@
     private ContentCaptureManager mContentCaptureManager;
     @Nullable
     private IRecognitionServiceManager mIRecognitionServiceManager;
+    @Nullable
+    private IDetectorSessionStorageService mDetectorSessionStorageService;
 
 
     private final ISandboxedDetectionService mInterface = new ISandboxedDetectionService.Stub() {
@@ -154,6 +161,12 @@
         public void updateRecognitionServiceManager(IRecognitionServiceManager manager) {
             mIRecognitionServiceManager = manager;
         }
+
+        @Override
+        public void registerRemoteStorageService(IDetectorSessionStorageService
+                detectorSessionStorageService) {
+            mDetectorSessionStorageService = detectorSessionStorageService;
+        }
     };
 
     @Override
@@ -323,4 +336,23 @@
         }
     }
 
+    /**
+     * Overrides {@link Context#openFileInput} to read files with the given file names under the
+     * internal app storage of the {@link VoiceInteractionService}, i.e., only files stored in
+     * {@link Context#getFilesDir()} can be opened.
+     */
+    @Override
+    public @Nullable FileInputStream openFileInput(@NonNull String filename) throws
+            FileNotFoundException {
+        try {
+            AndroidFuture<ParcelFileDescriptor> future = new AndroidFuture<>();
+            mDetectorSessionStorageService.openFile(filename, future);
+            ParcelFileDescriptor pfd = future.get();
+            return new FileInputStream(pfd.getFileDescriptor());
+        } catch (RemoteException | ExecutionException | InterruptedException e) {
+            Log.w(TAG, "Cannot open file due to remote service failure");
+            throw new FileNotFoundException(e.getMessage());
+        }
+    }
+
 }
diff --git a/core/java/android/service/voice/VisualQueryDetector.java b/core/java/android/service/voice/VisualQueryDetector.java
index 9e0eb4b..b5448d4 100644
--- a/core/java/android/service/voice/VisualQueryDetector.java
+++ b/core/java/android/service/voice/VisualQueryDetector.java
@@ -25,6 +25,7 @@
 import android.annotation.RequiresPermission;
 import android.annotation.SuppressLint;
 import android.annotation.SystemApi;
+import android.content.Context;
 import android.hardware.soundtrigger.SoundTrigger;
 import android.media.AudioFormat;
 import android.os.Binder;
@@ -37,7 +38,10 @@
 
 import com.android.internal.app.IHotwordRecognitionStatusCallback;
 import com.android.internal.app.IVoiceInteractionManagerService;
+import com.android.internal.infra.AndroidFuture;
 
+import java.io.File;
+import java.io.FileNotFoundException;
 import java.io.PrintWriter;
 import java.util.concurrent.Executor;
 import java.util.function.Consumer;
@@ -58,18 +62,20 @@
 
     private final Callback mCallback;
     private final Executor mExecutor;
+    private final Context mContext;
     private final IVoiceInteractionManagerService mManagerService;
     private final VisualQueryDetectorInitializationDelegate mInitializationDelegate;
     private final String mAttributionTag;
 
     VisualQueryDetector(
             IVoiceInteractionManagerService managerService,
-            @NonNull @CallbackExecutor Executor executor,
-            Callback callback, @Nullable String attributionTag) {
+            @NonNull @CallbackExecutor Executor executor, Callback callback, Context context,
+            @Nullable String attributionTag) {
         mManagerService = managerService;
         mCallback = callback;
         mExecutor = executor;
         mInitializationDelegate = new VisualQueryDetectorInitializationDelegate();
+        mContext = context;
         mAttributionTag = attributionTag;
     }
 
@@ -247,7 +253,7 @@
         @Override
         void initialize(@Nullable PersistableBundle options, @Nullable SharedMemory sharedMemory) {
             initAndVerifyDetector(options, sharedMemory,
-                    new InitializationStateListener(mExecutor, mCallback),
+                    new InitializationStateListener(mExecutor, mCallback, mContext),
                     DETECTOR_TYPE_VISUAL_QUERY_DETECTOR, mAttributionTag);
         }
 
@@ -332,9 +338,12 @@
         private final Executor mExecutor;
         private final Callback mCallback;
 
-        InitializationStateListener(Executor executor, Callback callback) {
+        private final Context mContext;
+
+        InitializationStateListener(Executor executor, Callback callback, Context context) {
             this.mExecutor = executor;
             this.mCallback = callback;
+            this.mContext = context;
         }
 
         @Override
@@ -428,5 +437,22 @@
                         !TextUtils.isEmpty(errorMessage) ? errorMessage : "Error data is null");
             }));
         }
+        @Override
+        public void onOpenFile(String filename, AndroidFuture future) throws RemoteException {
+            Slog.v(TAG, "BinderCallback#onOpenFile " + filename);
+            Binder.withCleanCallingIdentity(() -> mExecutor.execute(() -> {
+                Slog.v(TAG, "onOpenFile: " + filename);
+                File f = new File(mContext.getFilesDir(), filename);
+                ParcelFileDescriptor pfd = null;
+                try {
+                    Slog.d(TAG, "opened a file with ParcelFileDescriptor.");
+                    pfd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
+                } catch (FileNotFoundException e) {
+                    Slog.e(TAG, "Cannot open file. No ParcelFileDescriptor returned.");
+                } finally {
+                    future.complete(pfd);
+                }
+            }));
+        }
     }
 }
diff --git a/core/java/android/service/voice/VoiceInteractionService.java b/core/java/android/service/voice/VoiceInteractionService.java
index 8cec17f..b48b7ec 100644
--- a/core/java/android/service/voice/VoiceInteractionService.java
+++ b/core/java/android/service/voice/VoiceInteractionService.java
@@ -965,7 +965,7 @@
             }
 
             VisualQueryDetector visualQueryDetector =
-                    new VisualQueryDetector(mSystemService, executor, callback,
+                    new VisualQueryDetector(mSystemService, executor, callback, this,
                             getAttributionTag());
             HotwordDetector visualQueryDetectorInitializationDelegate =
                     visualQueryDetector.getInitializationDelegate();
diff --git a/core/java/android/speech/OWNERS b/core/java/android/speech/OWNERS
index 162e029..0f2f8ad 100644
--- a/core/java/android/speech/OWNERS
+++ b/core/java/android/speech/OWNERS
@@ -1,5 +1,4 @@
 volnov@google.com
 eugeniom@google.com
 schfan@google.com
-andreaambu@google.com
-hackz@google.com
\ No newline at end of file
+hackz@google.com
diff --git a/core/java/android/speech/RecognitionService.java b/core/java/android/speech/RecognitionService.java
index 9656f36..7f313c1 100644
--- a/core/java/android/speech/RecognitionService.java
+++ b/core/java/android/speech/RecognitionService.java
@@ -38,6 +38,7 @@
 import android.os.RemoteException;
 import android.util.Log;
 
+import com.android.internal.annotations.GuardedBy;
 import com.android.internal.util.function.pooled.PooledLambda;
 
 import java.lang.ref.WeakReference;
@@ -232,39 +233,68 @@
                     intent,
                     attributionSource,
                     new ModelDownloadListener() {
+
+                        private final Object mLock = new Object();
+
+                        @GuardedBy("mLock")
+                        private boolean mIsTerminated = false;
+
                         @Override
                         public void onProgress(int completedPercent) {
-                            try {
-                                listener.onProgress(completedPercent);
-                            } catch (RemoteException e) {
-                                throw e.rethrowFromSystemServer();
+                            synchronized (mLock) {
+                                if (mIsTerminated) {
+                                    return;
+                                }
+                                try {
+                                    listener.onProgress(completedPercent);
+                                } catch (RemoteException e) {
+                                    throw e.rethrowFromSystemServer();
+                                }
                             }
                         }
 
                         @Override
                         public void onSuccess() {
-                            try {
-                                listener.onSuccess();
-                            } catch (RemoteException e) {
-                                throw e.rethrowFromSystemServer();
+                            synchronized (mLock) {
+                                if (mIsTerminated) {
+                                    return;
+                                }
+                                mIsTerminated = true;
+                                try {
+                                    listener.onSuccess();
+                                } catch (RemoteException e) {
+                                    throw e.rethrowFromSystemServer();
+                                }
                             }
                         }
 
                         @Override
                         public void onScheduled() {
-                            try {
-                                listener.onScheduled();
-                            } catch (RemoteException e) {
-                                throw e.rethrowFromSystemServer();
+                            synchronized (mLock) {
+                                if (mIsTerminated) {
+                                    return;
+                                }
+                                mIsTerminated = true;
+                                try {
+                                    listener.onScheduled();
+                                } catch (RemoteException e) {
+                                    throw e.rethrowFromSystemServer();
+                                }
                             }
                         }
 
                         @Override
                         public void onError(int error) {
-                            try {
-                                listener.onError(error);
-                            } catch (RemoteException e) {
-                                throw e.rethrowFromSystemServer();
+                            synchronized (mLock) {
+                                if (mIsTerminated) {
+                                    return;
+                                }
+                                mIsTerminated = true;
+                                try {
+                                    listener.onError(error);
+                                } catch (RemoteException e) {
+                                    throw e.rethrowFromSystemServer();
+                                }
                             }
                         }
                     });
diff --git a/core/java/android/text/BoringLayout.java b/core/java/android/text/BoringLayout.java
index 9ed57c3..7748d5b 100644
--- a/core/java/android/text/BoringLayout.java
+++ b/core/java/android/text/BoringLayout.java
@@ -23,6 +23,7 @@
 import android.graphics.Canvas;
 import android.graphics.Paint;
 import android.graphics.Path;
+import android.graphics.text.LineBreakConfig;
 import android.text.style.ParagraphStyle;
 
 /**
@@ -53,7 +54,9 @@
      *                line width
      * @param includePad set whether to include extra space beyond font ascent and descent which is
      *                   needed to avoid clipping in some scripts
+     * @deprecated Use {@link android.text.Layout.Builder} instead.
      */
+    @Deprecated
     public static BoringLayout make(CharSequence source, TextPaint paint, int outerWidth,
             Alignment align, float spacingMult, float spacingAdd, BoringLayout.Metrics metrics,
             boolean includePad) {
@@ -79,7 +82,9 @@
      * @param ellipsizedWidth the width to which this Layout is ellipsizing. If {@code ellipsize} is
      *                        {@code null}, or is {@link TextUtils.TruncateAt#MARQUEE} this value is
      *                        not used, {@code outerWidth} is used instead
+     * @deprecated Use {@link android.text.Layout.Builder} instead.
      */
+    @Deprecated
     public static BoringLayout make(CharSequence source, TextPaint paint, int outerWidth,
             Alignment align, float spacingmult, float spacingadd, BoringLayout.Metrics metrics,
             boolean includePad, TextUtils.TruncateAt ellipsize, int ellipsizedWidth) {
@@ -111,7 +116,9 @@
      *                              False for keeping the first font's line height. If some glyphs
      *                              requires larger vertical spaces, by passing true to this
      *                              argument, the layout increase the line height to fit all glyphs.
+     * @deprecated Use {@link android.text.Layout.Builder} instead.
      */
+    @Deprecated
     public static @NonNull BoringLayout make(
             @NonNull CharSequence source, @NonNull TextPaint paint,
             @IntRange(from = 0) int outerWidth,
@@ -247,10 +254,17 @@
      *                line width
      * @param includePad set whether to include extra space beyond font ascent and descent which is
      *                   needed to avoid clipping in some scripts
+     * @deprecated Use {@link android.text.Layout.Builder} instead.
      */
+    @Deprecated
     public BoringLayout(CharSequence source, TextPaint paint, int outerwidth, Alignment align,
             float spacingMult, float spacingAdd, BoringLayout.Metrics metrics, boolean includePad) {
-        super(source, paint, outerwidth, align, spacingMult, spacingAdd);
+        super(source, paint, outerwidth, align, TextDirectionHeuristics.LTR, spacingMult,
+                spacingAdd, includePad, false /* fallbackLineSpacing */,
+                outerwidth /* ellipsizedWidth */, null /* ellipsize */, 1 /* maxLines */,
+                BREAK_STRATEGY_SIMPLE, HYPHENATION_FREQUENCY_NONE, null /* leftIndents */,
+                null /* rightIndents */, JUSTIFICATION_MODE_NONE,
+                LineBreakConfig.NONE);
 
         mEllipsizedWidth = outerwidth;
         mEllipsizedStart = 0;
@@ -277,7 +291,9 @@
      * @param ellipsizedWidth the width to which this Layout is ellipsizing. If {@code ellipsize} is
      *                        {@code null}, or is {@link TextUtils.TruncateAt#MARQUEE} this value is
      *                        not used, {@code outerWidth} is used instead
+     * @deprecated Use {@link android.text.Layout.Builder} instead.
      */
+    @Deprecated
     public BoringLayout(CharSequence source, TextPaint paint, int outerWidth, Alignment align,
             float spacingMult, float spacingAdd, BoringLayout.Metrics metrics, boolean includePad,
             TextUtils.TruncateAt ellipsize, int ellipsizedWidth) {
@@ -306,7 +322,9 @@
      *                              False for keeping the first font's line height. If some glyphs
      *                              requires larger vertical spaces, by passing true to this
      *                              argument, the layout increase the line height to fit all glyphs.
+     * @deprecated Use {@link android.text.Layout.Builder} instead.
      */
+    @Deprecated
     public BoringLayout(
             @NonNull CharSequence source, @NonNull TextPaint paint,
             @IntRange(from = 0) int outerWidth, @NonNull Alignment align, float spacingMult,
@@ -318,25 +336,58 @@
          * but we can't use "this" for the callback until the call to
          * super() finishes.
          */
-        super(source, paint, outerWidth, align, spacingMult, spacingAdd);
+        this(source, paint, outerWidth, align, TextDirectionHeuristics.LTR, spacingMult,
+                spacingAdd, includePad, useFallbackLineSpacing,
+                ellipsizedWidth, ellipsize, 1 /* maxLines */,
+                BREAK_STRATEGY_SIMPLE, HYPHENATION_FREQUENCY_NONE, null /* leftIndents */,
+                null /* rightIndents */, JUSTIFICATION_MODE_NONE,
+                LineBreakConfig.NONE, metrics);
+    }
+
+    /* package */ BoringLayout(
+            CharSequence text,
+            TextPaint paint,
+            int width,
+            Alignment align,
+            TextDirectionHeuristic textDir,
+            float spacingMult,
+            float spacingAdd,
+            boolean includePad,
+            boolean fallbackLineSpacing,
+            int ellipsizedWidth,
+            TextUtils.TruncateAt ellipsize,
+            int maxLines,
+            int breakStrategy,
+            int hyphenationFrequency,
+            int[] leftIndents,
+            int[] rightIndents,
+            int justificationMode,
+            LineBreakConfig lineBreakConfig,
+            Metrics metrics) {
+
+        super(text, paint, width, align, textDir, spacingMult, spacingAdd, includePad,
+                fallbackLineSpacing, ellipsizedWidth, ellipsize, maxLines, breakStrategy,
+                hyphenationFrequency, leftIndents, rightIndents, justificationMode,
+                lineBreakConfig);
+
 
         boolean trust;
 
         if (ellipsize == null || ellipsize == TextUtils.TruncateAt.MARQUEE) {
-            mEllipsizedWidth = outerWidth;
+            mEllipsizedWidth = width;
             mEllipsizedStart = 0;
             mEllipsizedCount = 0;
             trust = true;
         } else {
-            replaceWith(TextUtils.ellipsize(source, paint, ellipsizedWidth, ellipsize, true, this),
-                        paint, outerWidth, align, spacingMult, spacingAdd);
+            replaceWith(TextUtils.ellipsize(text, paint, ellipsizedWidth, ellipsize, true, this),
+                        paint, width, align, spacingMult, spacingAdd);
 
             mEllipsizedWidth = ellipsizedWidth;
             trust = false;
         }
 
-        mUseFallbackLineSpacing = useFallbackLineSpacing;
-        init(getText(), paint, align, metrics, includePad, trust, useFallbackLineSpacing);
+        mUseFallbackLineSpacing = fallbackLineSpacing;
+        init(getText(), paint, align, metrics, includePad, trust, fallbackLineSpacing);
     }
 
     /* package */ void init(CharSequence source, TextPaint paint, Alignment align,
@@ -391,7 +442,9 @@
      * @param paint a paint
      * @return layout metric for the given text. null if given text is unable to be handled by
      *         BoringLayout.
+     * @deprecated Use {@link android.text.Layout.Builder} instead.
      */
+    @Deprecated
     public static Metrics isBoring(CharSequence text, TextPaint paint) {
         return isBoring(text, paint, TextDirectionHeuristics.FIRSTSTRONG_LTR, null);
     }
@@ -406,7 +459,9 @@
      * @return layout metric for the given text. If metrics is not null, this method fills values
      *         to given metrics object instead of allocating new metrics object. null if given text
      *         is unable to be handled by BoringLayout.
+     * @deprecated Use {@link android.text.Layout.Builder} instead.
      */
+    @Deprecated
     public static Metrics isBoring(CharSequence text, TextPaint paint, Metrics metrics) {
         return isBoring(text, paint, TextDirectionHeuristics.FIRSTSTRONG_LTR, metrics);
     }
@@ -466,7 +521,9 @@
      *                              argument, the layout increase the line height to fit all glyphs.
      * @param metrics the out metrics.
      * @return metrics on success. null if text cannot be rendered by BoringLayout.
+     * @deprecated Use {@link android.text.Layout.Builder} instead.
      */
+    @Deprecated
     public static @Nullable Metrics isBoring(@NonNull CharSequence text, @NonNull TextPaint paint,
             @NonNull TextDirectionHeuristic textDir, boolean useFallbackLineSpacing,
             @Nullable Metrics metrics) {
diff --git a/core/java/android/text/DynamicLayout.java b/core/java/android/text/DynamicLayout.java
index ba08f25..e287bd9 100644
--- a/core/java/android/text/DynamicLayout.java
+++ b/core/java/android/text/DynamicLayout.java
@@ -388,7 +388,11 @@
                          @Nullable TextUtils.TruncateAt ellipsize,
                          @IntRange(from = 0) int ellipsizedWidth) {
         super(createEllipsizer(ellipsize, display),
-              paint, width, align, textDir, spacingmult, spacingadd);
+              paint, width, align, textDir, spacingmult, spacingadd, includepad,
+                false /* fallbackLineSpacing */, ellipsizedWidth, ellipsize,
+                Integer.MAX_VALUE /* maxLines */, breakStrategy, hyphenationFrequency,
+                null /* leftIndents */, null /* rightIndents */, justificationMode,
+                lineBreakConfig);
 
         final Builder b = Builder.obtain(base, paint, width)
                 .setAlignment(align)
@@ -410,7 +414,11 @@
 
     private DynamicLayout(@NonNull Builder b) {
         super(createEllipsizer(b.mEllipsize, b.mDisplay),
-                b.mPaint, b.mWidth, b.mAlignment, b.mTextDir, b.mSpacingMult, b.mSpacingAdd);
+                b.mPaint, b.mWidth, b.mAlignment, b.mTextDir, b.mSpacingMult, b.mSpacingAdd,
+                b.mIncludePad, b.mFallbackLineSpacing, b.mEllipsizedWidth, b.mEllipsize,
+                Integer.MAX_VALUE /* maxLines */, b.mBreakStrategy, b.mHyphenationFrequency,
+                null /* leftIndents */, null /* rightIndents */, b.mJustificationMode,
+                b.mLineBreakConfig);
 
         mDisplay = b.mDisplay;
         mIncludePad = b.mIncludePad;
@@ -614,8 +622,7 @@
             sBuilder = null;
         }
 
-        if (reflowed == null) {
-            reflowed = new StaticLayout(null);
+        if (b == null) {
             b = StaticLayout.Builder.obtain(text, where, where + after, getPaint(), getWidth());
         }
 
@@ -631,9 +638,10 @@
                 .setHyphenationFrequency(mHyphenationFrequency)
                 .setJustificationMode(mJustificationMode)
                 .setLineBreakConfig(mLineBreakConfig)
-                .setAddLastLineLineSpacing(!islast);
+                .setAddLastLineLineSpacing(!islast)
+                .setIncludePad(false);
 
-        reflowed.generate(b, false /*includepad*/, true /*trackpad*/);
+        reflowed = b.buildPartialStaticLayoutForDynamicLayout(true /* trackpadding */, reflowed);
         int n = reflowed.getLineCount();
         // If the new layout has a blank line at the end, but it is not
         // the very end of the buffer, then we already have a line that
diff --git a/core/java/android/text/Layout.java b/core/java/android/text/Layout.java
index 64dc16d..98b9fee 100644
--- a/core/java/android/text/Layout.java
+++ b/core/java/android/text/Layout.java
@@ -26,6 +26,7 @@
 import android.graphics.Path;
 import android.graphics.Rect;
 import android.graphics.RectF;
+import android.graphics.text.LineBreakConfig;
 import android.graphics.text.LineBreaker;
 import android.os.Build;
 import android.text.method.TextKeyListener;
@@ -278,7 +279,9 @@
                      int width, Alignment align,
                      float spacingMult, float spacingAdd) {
         this(text, paint, width, align, TextDirectionHeuristics.FIRSTSTRONG_LTR,
-                spacingMult, spacingAdd);
+                spacingMult, spacingAdd, false, false, 0, null, Integer.MAX_VALUE,
+                BREAK_STRATEGY_SIMPLE, HYPHENATION_FREQUENCY_NONE, null, null,
+                JUSTIFICATION_MODE_NONE, LineBreakConfig.NONE);
     }
 
     /**
@@ -290,15 +293,44 @@
      * @param width the wrapping width for the text.
      * @param align whether to left, right, or center the text.  Styles can
      * override the alignment.
+     * @param textDir a text direction heuristic.
      * @param spacingMult factor by which to scale the font size to get the
      * default line spacing
      * @param spacingAdd amount to add to the default line spacing
+     * @param includePad true for enabling including font padding
+     * @param fallbackLineSpacing true for enabling fallback line spacing
+     * @param ellipsizedWidth width as used for ellipsizing purpose
+     * @param ellipsize an ellipsize option
+     * @param maxLines a maximum number of lines.
+     * @param breakStrategy a break strategy.
+     * @param hyphenationFrequency a hyphenation frequency
+     * @param leftIndents a visually left margins
+     * @param rightIndents a visually right margins
+     * @param justificationMode a justification mode
+     * @param lineBreakConfig a line break config
      *
      * @hide
      */
-    protected Layout(CharSequence text, TextPaint paint,
-                     int width, Alignment align, TextDirectionHeuristic textDir,
-                     float spacingMult, float spacingAdd) {
+    protected Layout(
+            CharSequence text,
+            TextPaint paint,
+            int width,
+            Alignment align,
+            TextDirectionHeuristic textDir,
+            float spacingMult,
+            float spacingAdd,
+            boolean includePad,
+            boolean fallbackLineSpacing,
+            int ellipsizedWidth,
+            TextUtils.TruncateAt ellipsize,
+            int maxLines,
+            int breakStrategy,
+            int hyphenationFrequency,
+            int[] leftIndents,
+            int[] rightIndents,
+            int justificationMode,
+            LineBreakConfig lineBreakConfig
+    ) {
 
         if (width < 0)
             throw new IllegalArgumentException("Layout: " + width + " < 0");
@@ -320,11 +352,17 @@
         mSpacingAdd = spacingAdd;
         mSpannedText = text instanceof Spanned;
         mTextDir = textDir;
-    }
-
-    /** @hide */
-    protected void setJustificationMode(@JustificationMode int justificationMode) {
+        mIncludePad = includePad;
+        mFallbackLineSpacing = fallbackLineSpacing;
+        mEllipsizedWidth = ellipsize == null ? width : ellipsizedWidth;
+        mEllipsize = ellipsize;
+        mMaxLines = maxLines;
+        mBreakStrategy = breakStrategy;
+        mHyphenationFrequency = hyphenationFrequency;
+        mLeftIndents = leftIndents;
+        mRightIndents = rightIndents;
         mJustificationMode = justificationMode;
+        mLineBreakConfig = lineBreakConfig;
     }
 
     /**
@@ -910,37 +948,6 @@
     }
 
     /**
-     * Return the text that is displayed by this Layout.
-     */
-    public final CharSequence getText() {
-        return mText;
-    }
-
-    /**
-     * Return the base Paint properties for this layout.
-     * Do NOT change the paint, which may result in funny
-     * drawing for this layout.
-     */
-    public final TextPaint getPaint() {
-        return mPaint;
-    }
-
-    /**
-     * Return the width of this layout.
-     */
-    public final int getWidth() {
-        return mWidth;
-    }
-
-    /**
-     * Return the width to which this Layout is ellipsizing, or
-     * {@link #getWidth} if it is not doing anything special.
-     */
-    public int getEllipsizedWidth() {
-        return mWidth;
-    }
-
-    /**
      * Increase the width of this layout to the specified width.
      * Be careful to use this only when you know it is appropriate&mdash;
      * it does not cause the text to reflow to use the full new width.
@@ -972,35 +979,6 @@
     }
 
     /**
-     * Return the base alignment of this layout.
-     */
-    public final Alignment getAlignment() {
-        return mAlignment;
-    }
-
-    /**
-     * Return what the text height is multiplied by to get the line height.
-     */
-    public final float getSpacingMultiplier() {
-        return mSpacingMult;
-    }
-
-    /**
-     * Return the number of units of leading that are added to each line.
-     */
-    public final float getSpacingAdd() {
-        return mSpacingAdd;
-    }
-
-    /**
-     * Return the heuristic used to determine paragraph text direction.
-     * @hide
-     */
-    public final TextDirectionHeuristic getTextDirectionHeuristic() {
-        return mTextDir;
-    }
-
-    /**
      * Return the number of lines of text in this layout.
      */
     public abstract int getLineCount();
@@ -1105,15 +1083,6 @@
     }
 
     /**
-     * Return true if the fallback line space is enabled in this Layout.
-     *
-     * @return true if the fallback line space is enabled. Otherwise returns false.
-     */
-    public boolean isFallbackLineSpacingEnabled() {
-        return false;
-    }
-
-    /**
      * Returns true if the character at offset and the preceding character
      * are at different run levels (and thus there's a split caret).
      * @param offset the offset
@@ -3254,7 +3223,17 @@
     private boolean mSpannedText;
     private TextDirectionHeuristic mTextDir;
     private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
+    private boolean mIncludePad;
+    private boolean mFallbackLineSpacing;
+    private int mEllipsizedWidth;
+    private TextUtils.TruncateAt mEllipsize;
+    private int mMaxLines;
+    private int mBreakStrategy;
+    private int mHyphenationFrequency;
+    private int[] mLeftIndents;
+    private int[] mRightIndents;
     private int mJustificationMode;
+    private LineBreakConfig mLineBreakConfig;
 
     /** @hide */
     @IntDef(prefix = { "DIR_" }, value = {
@@ -3352,4 +3331,683 @@
          */
         boolean isSegmentInside(@NonNull RectF segmentBounds, @NonNull RectF area);
     }
+
+    /**
+     * A builder class for Layout object.
+     *
+     * Different from {@link StaticLayout.Builder}, this builder generates the optimal layout based
+     * on input. If the given text and parameters can be rendered with {@link BoringLayout}, this
+     * builder generates {@link BoringLayout} instance. Otherwise, {@link StaticLayout} instance is
+     * generated.
+     *
+     * @see StaticLayout.Builder
+     */
+    public static final class Builder {
+        /**
+         * Construct a builder class.
+         *
+         * @param text a text to be displayed.
+         * @param start an inclusive start index of the text to be displayed.
+         * @param end an exclusive end index of the text to be displayed.
+         * @param paint a paint object to be used for drawing text.
+         * @param width a width constraint in pixels.
+         */
+        public Builder(
+                @NonNull CharSequence text,
+                @IntRange(from = 0) int start,
+                @IntRange(from = 0) int end,
+                @NonNull TextPaint paint,
+                @IntRange(from = 0) int width) {
+            mText = text;
+            mStart = start;
+            mEnd = end;
+            mPaint = paint;
+            mWidth = width;
+            mEllipsizedWidth = width;
+        }
+
+        /**
+         * Set the text alignment.
+         *
+         * The default value is {@link Layout.Alignment#ALIGN_NORMAL}.
+         *
+         * @param alignment an alignment.
+         * @return this builder instance.
+         * @see Layout.Alignment
+         * @see Layout#getAlignment()
+         * @see StaticLayout.Builder#setAlignment(Alignment)
+         */
+        @NonNull
+        public Builder setAlignment(@NonNull Alignment alignment) {
+            mAlignment = alignment;
+            return this;
+        }
+
+        /**
+         * Set the text direction heuristics.
+         *
+         * The text direction heuristics is used to resolve text direction on the text.
+         *
+         * The default value is {@link TextDirectionHeuristics#FIRSTSTRONG_LTR}
+         *
+         * @param textDirection a text direction heuristic.
+         * @return this builder instance.
+         * @see TextDirectionHeuristics
+         * @see Layout#getTextDirectionHeuristic()
+         * @see StaticLayout.Builder#setTextDirection(TextDirectionHeuristic)
+         */
+        @NonNull
+        public Builder setTextDirectionHeuristic(@NonNull TextDirectionHeuristic textDirection) {
+            mTextDir = textDirection;
+            return this;
+        }
+
+        /**
+         * Set the line spacing amount.
+         *
+         * The specified amount of pixels will be added to each line.
+         *
+         * The default value is {@code 0}.
+         *
+         * @param amount an amount of pixels to be added to line height.
+         * @return this builder instance.
+         * @see Layout#getLineSpacingAmount()
+         * @see Layout#getSpacingAdd()
+         * @see StaticLayout.Builder#setLineSpacing(float, float)
+         */
+        @NonNull
+        public Builder setLineSpacingAmount(float amount) {
+            mSpacingAdd = amount;
+            return this;
+        }
+
+        /**
+         * Set the line spacing multiplier.
+         *
+         * The specified value will be multiplied to each line.
+         *
+         * The default value is {@code 1}.
+         *
+         * @param multiplier a multiplier to be applied to the line height
+         * @return this builder instance.
+         * @see Layout#getLineSpacingMultiplier()
+         * @see Layout#getSpacingMultiplier()
+         * @see StaticLayout.Builder#setLineSpacing(float, float)
+         */
+        @NonNull
+        public Builder setLineSpacingMultiplier(float multiplier) {
+            mSpacingMult = multiplier;
+            return this;
+        }
+
+        /**
+         * Set whether including extra padding into the first and the last line height.
+         *
+         * By setting true, the first line of the text and the last line of the text will have extra
+         * vertical space for avoiding clipping.
+         *
+         * The default value is {@code true}.
+         *
+         * @param includeFontPadding true for including extra space into first and last line.
+         * @return this builder instance.
+         * @see Layout#isIncludeFontPadding()
+         * @see StaticLayout.Builder#setIncludePad(boolean)
+         */
+        @NonNull
+        public Builder setIncludeFontPadding(boolean includeFontPadding) {
+            mIncludePad = includeFontPadding;
+            return this;
+        }
+
+        /**
+         * Set whether to respect the ascent and descent of the fallback fonts.
+         *
+         * Set whether to respect the ascent and descent of the fallback fonts that are used in
+         * displaying the text (which is needed to avoid text from consecutive lines running into
+         * each other). If set, fallback fonts that end up getting used can increase the ascent
+         * and descent of the lines that they are used on.
+         *
+         * The default value is {@code false}
+         *
+         * @param fallbackLineSpacing whether to expand line height based on fallback fonts.
+         * @return this builder instance.
+         * @see Layout#isFallbackLineSpacingEnabled()
+         * @see StaticLayout.Builder#setUseLineSpacingFromFallbacks(boolean)
+         */
+        @NonNull
+        public Builder setFallbackLineSpacingEnabled(boolean fallbackLineSpacing) {
+            mFallbackLineSpacing = fallbackLineSpacing;
+            return this;
+        }
+
+        /**
+         * Set the width as used for ellipsizing purpose in pixels.
+         *
+         * The passed value is ignored and forced to set to the value of width constraint passed in
+         * constructor if no ellipsize option is set.
+         *
+         * The default value is the width constraint.
+         *
+         * @param ellipsizeWidth a ellipsizing width in pixels.
+         * @return this builder instance.
+         * @see Layout#getEllipsizedWidth()
+         * @see StaticLayout.Builder#setEllipsizedWidth(int)
+         */
+        @NonNull
+        public Builder setEllipsizedWidth(@IntRange(from = 0) int ellipsizeWidth) {
+            mEllipsizedWidth = ellipsizeWidth;
+            return this;
+        }
+
+        /**
+         * Set the ellipsizing type.
+         *
+         * By setting null, the ellipsize is disabled.
+         *
+         * The default value is {@code null}.
+         *
+         * @param ellipsize type of the ellipsize. null for disabling ellipsize.
+         * @return this builder instance.
+         * @see Layout#getEllipsize()
+         * @see StaticLayout.Builder#getEllipsize()
+         * @see android.text.TextUtils.TruncateAt
+         */
+        @NonNull
+        public Builder setEllipsize(@Nullable TextUtils.TruncateAt ellipsize) {
+            mEllipsize = ellipsize;
+            return this;
+        }
+
+        /**
+         * Set the maximum number of lines.
+         *
+         * The default value is unlimited.
+         *
+         * @param maxLines maximum number of lines in the layout.
+         * @return this builder instance.
+         * @see Layout#getMaxLines()
+         * @see StaticLayout.Builder#setMaxLines(int)
+         */
+        @NonNull
+        public Builder setMaxLines(@IntRange(from = 1) int maxLines) {
+            mMaxLines = maxLines;
+            return this;
+        }
+
+        /**
+         * Set the line break strategy.
+         *
+         * The default value is {@link Layout#BREAK_STRATEGY_SIMPLE}.
+         *
+         * @param breakStrategy a break strategy for line breaking.
+         * @return this builder instance.
+         * @see Layout#getBreakStrategy()
+         * @see StaticLayout.Builder#setBreakStrategy(int)
+         * @see Layout#BREAK_STRATEGY_SIMPLE
+         * @see Layout#BREAK_STRATEGY_HIGH_QUALITY
+         * @see Layout#BREAK_STRATEGY_BALANCED
+         */
+        @NonNull
+        public Builder setBreakStrategy(@BreakStrategy int breakStrategy) {
+            mBreakStrategy = breakStrategy;
+            return this;
+        }
+
+        /**
+         * Set the hyphenation frequency.
+         *
+         * The default value is {@link Layout#HYPHENATION_FREQUENCY_NONE}.
+         *
+         * @param hyphenationFrequency a hyphenation frequency.
+         * @return this builder instance.
+         * @see Layout#getHyphenationFrequency()
+         * @see StaticLayout.Builder#setHyphenationFrequency(int)
+         * @see Layout#HYPHENATION_FREQUENCY_NONE
+         * @see Layout#HYPHENATION_FREQUENCY_NORMAL
+         * @see Layout#HYPHENATION_FREQUENCY_FULL
+         * @see Layout#HYPHENATION_FREQUENCY_NORMAL_FAST
+         * @see Layout#HYPHENATION_FREQUENCY_FULL_FAST
+         */
+        @NonNull
+        public Builder setHyphenationFrequency(@HyphenationFrequency int hyphenationFrequency) {
+            mHyphenationFrequency = hyphenationFrequency;
+            return this;
+        }
+
+        /**
+         * Set visually left indents in pixels per lines.
+         *
+         * For the lines past the last element in the array, the last element repeats. Passing null
+         * for disabling indents.
+         *
+         * Note that even with the RTL layout, this method reserve spacing at the visually left of
+         * the line.
+         *
+         * The default value is {@code null}.
+         *
+         * @param leftIndents array of indents values for the left margins in pixels.
+         * @return this builder instance.
+         * @see Layout#getLeftIndents()
+         * @see Layout#getRightIndents()
+         * @see Layout.Builder#setRightIndents(int[])
+         * @see StaticLayout.Builder#setIndents(int[], int[])
+         */
+        @NonNull
+        public Builder setLeftIndents(@Nullable int[] leftIndents) {
+            mLeftIndents = leftIndents;
+            return this;
+        }
+
+        /**
+         * Set visually right indents in pixels per lines.
+         *
+         * For the lines past the last element in the array, the last element repeats. Passing null
+         * for disabling indents.
+         *
+         * Note that even with the RTL layout, this method reserve spacing at the visually right of
+         * the line.
+         *
+         * The default value is {@code null}.
+         *
+         * @param rightIndents array of indents values for the right margins in pixels.
+         * @return this builder instance.
+         * @see Layout#getLeftIndents()
+         * @see Layout#getRightIndents()
+         * @see Layout.Builder#setLeftIndents(int[])
+         * @see StaticLayout.Builder#setIndents(int[], int[])
+         */
+        @NonNull
+        public Builder setRightIndents(@Nullable int[] rightIndents) {
+            mRightIndents = rightIndents;
+            return this;
+        }
+
+        /**
+         * Set justification mode.
+         *
+         * When justification mode is {@link Layout#JUSTIFICATION_MODE_INTER_WORD}, the word spacing
+         * on the given Paint passed to the constructor will be ignored. This behavior also affects
+         * spans which change the word spacing.
+         *
+         * The default value is {@link Layout#JUSTIFICATION_MODE_NONE}.
+         *
+         * @param justificationMode justification mode.
+         * @return this builder instance.
+         * @see Layout#getJustificationMode()
+         * @see StaticLayout.Builder#setJustificationMode(int)
+         * @see Layout#JUSTIFICATION_MODE_NONE
+         * @see Layout#JUSTIFICATION_MODE_INTER_WORD
+         */
+        @NonNull
+        public Builder setJustificationMode(@JustificationMode int justificationMode) {
+            mJustificationMode = justificationMode;
+            return this;
+        }
+
+        /**
+         * Set the line break configuration.
+         *
+         * The default value is a LinebreakConfig instance that has
+         * {@link LineBreakConfig#LINE_BREAK_STYLE_NONE} and
+         * {@link LineBreakConfig#LINE_BREAK_WORD_STYLE_NONE}.
+         *
+         * @param lineBreakConfig the line break configuration
+         * @return this builder instance.
+         * @see Layout#getLineBreakConfig()
+         * @see StaticLayout.Builder#setLineBreakConfig(LineBreakConfig)
+         */
+        @NonNull
+        public Builder setLineBreakConfig(@NonNull LineBreakConfig lineBreakConfig) {
+            mLineBreakConfig = lineBreakConfig;
+            return this;
+        }
+
+        private BoringLayout.Metrics isBoring() {
+            if (mStart != 0 || mEnd != mText.length()) {  // BoringLayout only support entire text.
+                return null;
+            }
+            BoringLayout.Metrics metrics = BoringLayout.isBoring(mText, mPaint, mTextDir,
+                    mFallbackLineSpacing, null);
+            if (metrics == null) {
+                return null;
+            }
+            if (metrics.width <= mWidth) {
+                return metrics;
+            }
+            if (mEllipsize != null) {
+                return metrics;
+            }
+            return null;
+        }
+
+        /**
+         * Build a Layout object.
+         */
+        @NonNull
+        public Layout build() {
+            BoringLayout.Metrics metrics = isBoring();
+            if (metrics == null) {  // we cannot use BoringLayout, create StaticLayout.
+                return StaticLayout.Builder.obtain(mText, mStart, mEnd, mPaint, mWidth)
+                        .setAlignment(mAlignment)
+                        .setLineSpacing(mSpacingAdd, mSpacingMult)
+                        .setTextDirection(mTextDir)
+                        .setIncludePad(mIncludePad)
+                        .setUseLineSpacingFromFallbacks(mFallbackLineSpacing)
+                        .setEllipsizedWidth(mEllipsizedWidth)
+                        .setEllipsize(mEllipsize)
+                        .setMaxLines(mMaxLines)
+                        .setBreakStrategy(mBreakStrategy)
+                        .setHyphenationFrequency(mHyphenationFrequency)
+                        .setIndents(mLeftIndents, mRightIndents)
+                        .setJustificationMode(mJustificationMode)
+                        .setLineBreakConfig(mLineBreakConfig)
+                        .build();
+            } else {
+                return new BoringLayout(
+                        mText, mPaint, mWidth, mAlignment, mTextDir, mSpacingMult, mSpacingAdd,
+                        mIncludePad, mFallbackLineSpacing, mEllipsizedWidth, mEllipsize, mMaxLines,
+                        mBreakStrategy, mHyphenationFrequency, mLeftIndents, mRightIndents,
+                        mJustificationMode, mLineBreakConfig, metrics);
+            }
+        }
+
+        private final CharSequence mText;
+        private final int mStart;
+        private final int mEnd;
+        private final TextPaint mPaint;
+        private final int mWidth;
+        private Alignment mAlignment = Alignment.ALIGN_NORMAL;
+        private float mSpacingMult = 1.0f;
+        private float mSpacingAdd = 0.0f;
+        private TextDirectionHeuristic mTextDir = TextDirectionHeuristics.FIRSTSTRONG_LTR;
+        private boolean mIncludePad = true;
+        private boolean mFallbackLineSpacing = false;
+        private int mEllipsizedWidth;
+        private TextUtils.TruncateAt mEllipsize = null;
+        private int mMaxLines = Integer.MAX_VALUE;
+        private int mBreakStrategy = BREAK_STRATEGY_SIMPLE;
+        private int mHyphenationFrequency = HYPHENATION_FREQUENCY_NONE;
+        private int[] mLeftIndents = null;
+        private int[] mRightIndents = null;
+        private int mJustificationMode = JUSTIFICATION_MODE_NONE;
+        private LineBreakConfig mLineBreakConfig = LineBreakConfig.NONE;
+    }
+
+    ///////////////////////////////////////////////////////////////////////////////////////////////
+    // Getters of parameters that is used for building Layout instance
+    ///////////////////////////////////////////////////////////////////////////////////////////////
+
+    /**
+     * Return the text used for creating this layout.
+     *
+     * @return the text used for creating this layout.
+     * @see Layout.Builder
+     */
+    @NonNull
+    public final CharSequence getText() {
+        return mText;
+    }
+
+    /**
+     * Return the paint used for creating this layout.
+     *
+     * Do not modify the returned paint object. This paint object will still be used for
+     * drawing/measuring text.
+     *
+     * @return the paint used for creating this layout.
+     * @see Layout.Builder
+     */
+    @NonNull
+    public final TextPaint getPaint() {
+        return mPaint;
+    }
+
+    /**
+     * Return the width used for creating this layout in pixels.
+     *
+     * @return the width used for creating this layout in pixels.
+     * @see Layout.Builder
+     */
+    @IntRange(from = 0)
+    public final int getWidth() {
+        return mWidth;
+    }
+
+    /**
+     * Returns the alignment used for creating this layout in pixels.
+     *
+     * @return the alignment used for creating this layout.
+     * @see Layout.Builder#setAlignment(Alignment)
+     * @see StaticLayout.Builder#setAlignment(Alignment)
+     */
+    @NonNull
+    public final Alignment getAlignment() {
+        return mAlignment;
+    }
+
+    /**
+     * Returns the text direction heuristic used for creating this layout.
+     *
+     * @return the text direction heuristic used for creating this layout
+     * @see Layout.Builder#setTextDirectionHeuristic(TextDirectionHeuristic)
+     * @see StaticLayout.Builder#setTextDirection(TextDirectionHeuristic)
+     */
+    @NonNull
+    public final TextDirectionHeuristic getTextDirectionHeuristic() {
+        return mTextDir;
+    }
+
+    /**
+     * Returns the multiplier applied to the line height.
+     *
+     * This is an alias of {@link #getLineSpacingMultiplier}.
+     *
+     * @return the line height multiplier.
+     * @see Layout.Builder#setLineSpacingMultiplier(float)
+     * @see StaticLayout.Builder#setLineSpacing(float, float)
+     * @see Layout#getLineSpacingMultiplier()
+     */
+    public final float getSpacingMultiplier() {
+        return getLineSpacingMultiplier();
+    }
+
+    /**
+     * Returns the multiplier applied to the line height.
+     *
+     * @return the line height multiplier.
+     * @see Layout.Builder#setLineSpacingMultiplier(float)
+     * @see StaticLayout.Builder#setLineSpacing(float, float)
+     * @see Layout#getSpacingMultiplier()
+     */
+    public final float getLineSpacingMultiplier() {
+        return mSpacingMult;
+    }
+
+    /**
+     * Returns the amount added to the line height.
+     *
+     * This is an alias of {@link #getLineSpacingAmount()}.
+     *
+     * @return the line height additional amount.
+     * @see Layout.Builder#setLineSpacingAmount(float)
+     * @see StaticLayout.Builder#setLineSpacing(float, float)
+     * @see Layout#getLineSpacingAmount()
+     */
+    public final float getSpacingAdd() {
+        return getLineSpacingAmount();
+    }
+
+    /**
+     * Returns the amount added to the line height.
+     *
+     * @return the line height additional amount.
+     * @see Layout.Builder#setLineSpacingAmount(float)
+     * @see StaticLayout.Builder#setLineSpacing(float, float)
+     * @see Layout#getSpacingAdd()
+     */
+    public final float getLineSpacingAmount() {
+        return mSpacingAdd;
+    }
+
+    /**
+     * Returns true if this layout is created with increased line height.
+     *
+     * @return true if the layout is created with increased line height.
+     * @see Layout.Builder#setIncludeFontPadding(boolean)
+     * @see StaticLayout.Builder#setIncludePad(boolean)
+     */
+    public final boolean isIncludeFontPadding() {
+        return mIncludePad;
+    }
+
+    /**
+     * Return true if the fallback line space is enabled in this Layout.
+     *
+     * @return true if the fallback line space is enabled. Otherwise, returns false.
+     * @see Layout.Builder#setFallbackLineSpacingEnabled(boolean)
+     * @see StaticLayout.Builder#setUseLineSpacingFromFallbacks(boolean)
+     */
+    // not being final because of already published API.
+    public boolean isFallbackLineSpacingEnabled() {
+        return mFallbackLineSpacing;
+    }
+
+    /**
+     * Return the width to which this layout is ellipsized.
+     *
+     * If no ellipsize is applied, the same amount of {@link #getWidth} is returned.
+     *
+     * @return the amount of ellipsized width in pixels.
+     * @see Layout.Builder#setEllipsizedWidth(int)
+     * @see StaticLayout.Builder#setEllipsizedWidth(int)
+     * @see Layout.Builder#setEllipsize(TextUtils.TruncateAt)
+     * @see StaticLayout.Builder#setEllipsize(TextUtils.TruncateAt)
+     * @see Layout#getEllipsize()
+     */
+    @IntRange(from = 0)
+    public int getEllipsizedWidth() {  // not being final because of already published API.
+        return mEllipsizedWidth;
+    }
+
+    /**
+     * Return the ellipsize option used for creating this layout.
+     *
+     * May return null if no ellipsize option was selected.
+     *
+     * @return The ellipsize option used for creating this layout, or null if no ellipsize option
+     * was selected.
+     * @see Layout.Builder#setEllipsize(TextUtils.TruncateAt)
+     * @see StaticLayout.Builder#setEllipsize(TextUtils.TruncateAt)
+     * @see Layout.Builder#setEllipsizedWidth(int)
+     * @see StaticLayout.Builder#setEllipsizedWidth(int)
+     * @see Layout#getEllipsizedWidth()
+     */
+    @Nullable
+    public final TextUtils.TruncateAt getEllipsize() {
+        return mEllipsize;
+    }
+
+    /**
+     * Return the maximum lines allowed used for creating this layout.
+     *
+     * Note that this is not an actual line count of this layout. Use {@link #getLineCount()} for
+     * getting the actual line count of this layout.
+     *
+     * @return the maximum lines allowed used for creating this layout.
+     * @see Layout.Builder#setMaxLines(int)
+     * @see StaticLayout.Builder#setMaxLines(int)
+     */
+    @IntRange(from = 1)
+    public final int getMaxLines() {
+        return mMaxLines;
+    }
+
+    /**
+     * Return the break strategy used for creating this layout.
+     *
+     * @return the break strategy used for creating this layout.
+     * @see Layout.Builder#setBreakStrategy(int)
+     * @see StaticLayout.Builder#setBreakStrategy(int)
+     */
+    @BreakStrategy
+    public final int getBreakStrategy() {
+        return mBreakStrategy;
+    }
+
+    /**
+     * Return the hyphenation frequency used for creating this layout.
+     *
+     * @return the hyphenation frequency used for creating this layout.
+     * @see Layout.Builder#setHyphenationFrequency(int)
+     * @see StaticLayout.Builder#setHyphenationFrequency(int)
+     */
+    @HyphenationFrequency
+    public final int getHyphenationFrequency() {
+        return mHyphenationFrequency;
+    }
+
+    /**
+     * Return a copy of the left indents used for this layout.
+     *
+     * May return null if no left indentation is applied.
+     *
+     * @return the array of left indents in pixels.
+     * @see Layout.Builder#setLeftIndents(int[])
+     * @see Layout.Builder#setRightIndents(int[])
+     * @see StaticLayout.Builder#setIndents(int[], int[])
+     */
+    @Nullable
+    public final int[] getLeftIndents() {
+        if (mLeftIndents == null) {
+            return null;
+        }
+        int[] newArray = new int[mLeftIndents.length];
+        System.arraycopy(mLeftIndents, 0, newArray, 0, newArray.length);
+        return newArray;
+    }
+
+    /**
+     * Return a copy of the right indents used for this layout.
+     *
+     * May return null if no right indentation is applied.
+     *
+     * @return the array of right indents in pixels.
+     * @see Layout.Builder#setLeftIndents(int[])
+     * @see Layout.Builder#setRightIndents(int[])
+     * @see StaticLayout.Builder#setIndents(int[], int[])
+     */
+    @Nullable
+    public final int[] getRightIndents() {
+        if (mRightIndents == null) {
+            return mLeftIndents;
+        }
+        int[] newArray = new int[mRightIndents.length];
+        System.arraycopy(mRightIndents, 0, newArray, 0, newArray.length);
+        return newArray;
+    }
+
+    /**
+     * Return the justification mode used for creating this layout.
+     *
+     * @return the justification mode used for creating this layout.
+     * @see Layout.Builder#setJustificationMode(int)
+     * @see StaticLayout.Builder#setJustificationMode(int)
+     */
+    @JustificationMode
+    public final int getJustificationMode() {
+        return mJustificationMode;
+    }
+
+    /**
+     * Gets the {@link LineBreakConfig} used for creating this layout.
+     *
+     * Do not modify the returned object.
+     *
+     * @return The line break config used for creating this layout.
+     */
+    // not being final because of subclass has already published API.
+    @NonNull
+    public LineBreakConfig getLineBreakConfig() {
+        return mLineBreakConfig;
+    }
 }
diff --git a/core/java/android/text/OWNERS b/core/java/android/text/OWNERS
index a6be687..0935ffd9 100644
--- a/core/java/android/text/OWNERS
+++ b/core/java/android/text/OWNERS
@@ -1,5 +1,6 @@
 set noparent
 
+grantapher@google.com
 halilibo@google.com
 haoyuchang@google.com
 justinghan@google.com
diff --git a/core/java/android/text/StaticLayout.java b/core/java/android/text/StaticLayout.java
index ab9cff0..3d1895c 100644
--- a/core/java/android/text/StaticLayout.java
+++ b/core/java/android/text/StaticLayout.java
@@ -431,11 +431,33 @@
          */
         @NonNull
         public StaticLayout build() {
-            StaticLayout result = new StaticLayout(this);
+            StaticLayout result = new StaticLayout(this, mIncludePad, mEllipsize != null
+                    ? COLUMNS_ELLIPSIZE : COLUMNS_NORMAL);
             Builder.recycle(this);
             return result;
         }
 
+        /**
+         * DO NOT USE THIS METHOD OTHER THAN DynamicLayout.
+         *
+         * This class generates a very weird StaticLayout only for getting a result of line break.
+         * Since DynamicLayout keeps StaticLayout reference in the static context for object
+         * recycling but keeping text reference in static context will end up with leaking Context
+         * due to TextWatcher via TextView.
+         *
+         * So, this is a dirty work around that creating StaticLayout without passing text reference
+         * to the super constructor, but calculating the text layout by calling generate function
+         * directly.
+         */
+        /* package */ @NonNull StaticLayout buildPartialStaticLayoutForDynamicLayout(
+                boolean trackpadding, StaticLayout recycle) {
+            if (recycle == null) {
+                recycle = new StaticLayout();
+            }
+            recycle.generate(this, mIncludePad, trackpadding);
+            return recycle;
+        }
+
         private CharSequence mText;
         private int mStart;
         private int mEnd;
@@ -464,6 +486,37 @@
     }
 
     /**
+     * DO NOT USE THIS CONSTRUCTOR OTHER THAN FOR DYNAMIC LAYOUT.
+     * See Builder#buildPartialStaticLayoutForDynamicLayout for the reason of this constructor.
+     */
+    private StaticLayout() {
+        super(
+                null,  // text
+                null,  // paint
+                0,  // width
+                null, // alignment
+                null, // textDir
+                1, // spacing multiplier
+                0, // spacing amount
+                false, // include font padding
+                false, // fallback line spacing
+                0,  // ellipsized width
+                null, // ellipsize
+                1,  // maxLines
+                BREAK_STRATEGY_SIMPLE,
+                HYPHENATION_FREQUENCY_NONE,
+                null,  // leftIndents
+                null,  // rightIndents
+                JUSTIFICATION_MODE_NONE,
+                null  // lineBreakConfig
+        );
+
+        mColumns = COLUMNS_ELLIPSIZE;
+        mLineDirections = ArrayUtils.newUnpaddedArray(Directions.class, 2);
+        mLines  = ArrayUtils.newUnpaddedIntArray(2 * mColumns);
+    }
+
+    /**
      * @deprecated Use {@link Builder} instead.
      */
     @Deprecated
@@ -515,88 +568,32 @@
                         float spacingmult, float spacingadd,
                         boolean includepad,
                         TextUtils.TruncateAt ellipsize, int ellipsizedWidth, int maxLines) {
-        super((ellipsize == null)
-                ? source
-                : (source instanceof Spanned)
-                    ? new SpannedEllipsizer(source)
-                    : new Ellipsizer(source),
-              paint, outerwidth, align, textDir, spacingmult, spacingadd);
-
-        Builder b = Builder.obtain(source, bufstart, bufend, paint, outerwidth)
-            .setAlignment(align)
-            .setTextDirection(textDir)
-            .setLineSpacing(spacingadd, spacingmult)
-            .setIncludePad(includepad)
-            .setEllipsizedWidth(ellipsizedWidth)
-            .setEllipsize(ellipsize)
-            .setMaxLines(maxLines);
-        /*
-         * This is annoying, but we can't refer to the layout until superclass construction is
-         * finished, and the superclass constructor wants the reference to the display text.
-         *
-         * In other words, the two Ellipsizer classes in Layout.java need a (Dynamic|Static)Layout
-         * as a parameter to do their calculations, but the Ellipsizers also need to be the input
-         * to the superclass's constructor (Layout). In order to go around the circular
-         * dependency, we construct the Ellipsizer with only one of the parameters, the text. And
-         * we fill in the rest of the needed information (layout, width, and method) later, here.
-         *
-         * This will break if the superclass constructor ever actually cares about the content
-         * instead of just holding the reference.
-         */
-        if (ellipsize != null) {
-            Ellipsizer e = (Ellipsizer) getText();
-
-            e.mLayout = this;
-            e.mWidth = ellipsizedWidth;
-            e.mMethod = ellipsize;
-            mEllipsizedWidth = ellipsizedWidth;
-
-            mColumns = COLUMNS_ELLIPSIZE;
-        } else {
-            mColumns = COLUMNS_NORMAL;
-            mEllipsizedWidth = outerwidth;
-        }
-
-        mLineDirections = ArrayUtils.newUnpaddedArray(Directions.class, 2);
-        mLines  = ArrayUtils.newUnpaddedIntArray(2 * mColumns);
-        mMaximumVisibleLineCount = maxLines;
-
-        generate(b, b.mIncludePad, b.mIncludePad);
-
-        Builder.recycle(b);
+        this(Builder.obtain(source, bufstart, bufend, paint, outerwidth)
+                .setAlignment(align)
+                .setTextDirection(textDir)
+                .setLineSpacing(spacingadd, spacingmult)
+                .setIncludePad(includepad)
+                .setEllipsize(ellipsize)
+                .setEllipsizedWidth(ellipsizedWidth)
+                .setMaxLines(maxLines), includepad,
+                ellipsize != null ? COLUMNS_ELLIPSIZE : COLUMNS_NORMAL);
     }
 
-    /**
-     * Used by DynamicLayout.
-     */
-    /* package */ StaticLayout(@Nullable CharSequence text) {
-        super(text, null, 0, null, 0, 0);
+    private StaticLayout(Builder b, boolean trackPadding, int columnSize) {
+        super((b.mEllipsize == null) ? b.mText : (b.mText instanceof Spanned)
+                    ? new SpannedEllipsizer(b.mText) : new Ellipsizer(b.mText),
+                b.mPaint, b.mWidth, b.mAlignment, b.mTextDir, b.mSpacingMult, b.mSpacingAdd,
+                b.mIncludePad, b.mFallbackLineSpacing, b.mEllipsizedWidth, b.mEllipsize,
+                b.mMaxLines, b.mBreakStrategy, b.mHyphenationFrequency, b.mLeftIndents,
+                b.mRightIndents, b.mJustificationMode, b.mLineBreakConfig);
 
-        mColumns = COLUMNS_ELLIPSIZE;
-        mLineDirections = ArrayUtils.newUnpaddedArray(Directions.class, 2);
-        mLines  = ArrayUtils.newUnpaddedIntArray(2 * mColumns);
-    }
-
-    private StaticLayout(Builder b) {
-        super((b.mEllipsize == null)
-                ? b.mText
-                : (b.mText instanceof Spanned)
-                    ? new SpannedEllipsizer(b.mText)
-                    : new Ellipsizer(b.mText),
-                b.mPaint, b.mWidth, b.mAlignment, b.mTextDir, b.mSpacingMult, b.mSpacingAdd);
-
+        mColumns = columnSize;
         if (b.mEllipsize != null) {
             Ellipsizer e = (Ellipsizer) getText();
 
             e.mLayout = this;
             e.mWidth = b.mEllipsizedWidth;
             e.mMethod = b.mEllipsize;
-            mEllipsizedWidth = b.mEllipsizedWidth;
-
-            mColumns = COLUMNS_ELLIPSIZE;
-        } else {
-            mColumns = COLUMNS_NORMAL;
-            mEllipsizedWidth = b.mWidth;
         }
 
         mLineDirections = ArrayUtils.newUnpaddedArray(Directions.class, 2);
@@ -605,9 +602,8 @@
 
         mLeftIndents = b.mLeftIndents;
         mRightIndents = b.mRightIndents;
-        setJustificationMode(b.mJustificationMode);
 
-        generate(b, b.mIncludePad, b.mIncludePad);
+        generate(b, b.mIncludePad, trackPadding);
     }
 
     private static int getBaseHyphenationFrequency(int frequency) {
@@ -648,7 +644,7 @@
         mLineCount = 0;
         mEllipsized = false;
         mMaxLineHeight = mMaximumVisibleLineCount < 1 ? 0 : DEFAULT_MAX_LINE_HEIGHT;
-        mFallbackLineSpacing = b.mFallbackLineSpacing;
+        boolean isFallbackLineSpacing = b.mFallbackLineSpacing;
 
         int v = 0;
         boolean needMultiply = (spacingmult != 1 || spacingadd != 0);
@@ -887,17 +883,17 @@
 
                     boolean moreChars = (endPos < bufEnd);
 
-                    final int ascent = mFallbackLineSpacing
+                    final int ascent = isFallbackLineSpacing
                             ? Math.min(fmAscent, Math.round(ascents[breakIndex]))
                             : fmAscent;
-                    final int descent = mFallbackLineSpacing
+                    final int descent = isFallbackLineSpacing
                             ? Math.max(fmDescent, Math.round(descents[breakIndex]))
                             : fmDescent;
 
                     // The fallback ascent/descent may be larger than top/bottom of the default font
                     // metrics. Adjust top/bottom with ascent/descent for avoiding unexpected
                     // clipping.
-                    if (mFallbackLineSpacing) {
+                    if (isFallbackLineSpacing) {
                         if (ascent < fmTop) {
                             fmTop = ascent;
                         }
@@ -1410,16 +1406,6 @@
         return mLines[mColumns * line + ELLIPSIS_START];
     }
 
-    @Override
-    public int getEllipsizedWidth() {
-        return mEllipsizedWidth;
-    }
-
-    @Override
-    public boolean isFallbackLineSpacingEnabled() {
-        return mFallbackLineSpacing;
-    }
-
     /**
      * Return the total height of this layout.
      *
@@ -1445,8 +1431,6 @@
     private int mTopPadding, mBottomPadding;
     @UnsupportedAppUsage
     private int mColumns;
-    private int mEllipsizedWidth;
-    private boolean mFallbackLineSpacing;
 
     /**
      * Keeps track if ellipsize is applied to the text.
diff --git a/core/java/android/text/TEST_MAPPING b/core/java/android/text/TEST_MAPPING
new file mode 100644
index 0000000..0fe974a
--- /dev/null
+++ b/core/java/android/text/TEST_MAPPING
@@ -0,0 +1,15 @@
+{
+  "presubmit": [
+    {
+      "name": "CtsTextTestCases",
+      "options": [
+          {
+              "exclude-annotation": "android.platform.test.annotations.FlakyTest"
+          },
+          {
+              "exclude-annotation": "androidx.test.filters.LargeTest"
+          }
+      ]
+    }
+  ]
+}
diff --git a/core/java/android/view/Display.java b/core/java/android/view/Display.java
index 4b96d74..0b2b6ce 100644
--- a/core/java/android/view/Display.java
+++ b/core/java/android/view/Display.java
@@ -375,6 +375,14 @@
     public static final int FLAG_REAR = 1 << 13;
 
     /**
+     * Display flag: Indicates that the orientation of this display is not fixed and is coupled to
+     * the orientation of its content.
+     *
+     * @hide
+     */
+    public static final int FLAG_ROTATES_WITH_CONTENT = 1 << 14;
+
+    /**
      * Display flag: Indicates that the contents of the display should not be scaled
      * to fit the physical screen dimensions.  Used for development only to emulate
      * devices with smaller physicals screens while preserving density.
diff --git a/core/java/android/view/HandwritingInitiator.java b/core/java/android/view/HandwritingInitiator.java
index c501f5a..6e73a3c 100644
--- a/core/java/android/view/HandwritingInitiator.java
+++ b/core/java/android/view/HandwritingInitiator.java
@@ -19,7 +19,10 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.content.Context;
+import android.graphics.Matrix;
 import android.graphics.Rect;
+import android.graphics.RectF;
+import android.graphics.Region;
 import android.view.inputmethod.InputMethodManager;
 import android.widget.TextView;
 
@@ -78,11 +81,17 @@
     private int mConnectionCount = 0;
     private final InputMethodManager mImm;
 
+    private final RectF mTempRectF = new RectF();
+
+    private final Region mTempRegion = new Region();
+
+    private final Matrix mTempMatrix = new Matrix();
+
     /**
      * The handwrite-able View that is currently the target of a hovering stylus pointer. This is
      * used to help determine whether the handwriting PointerIcon should be shown in
      * {@link #onResolvePointerIcon(Context, MotionEvent)} so that we can reduce the number of calls
-     * to {@link #findBestCandidateView(float, float)}.
+     * to {@link #findBestCandidateView(float, float, boolean)}.
      */
     @Nullable
     private WeakReference<View> mCachedHoverTarget = null;
@@ -184,8 +193,8 @@
                 final float y = motionEvent.getY(pointerIndex);
                 if (largerThanTouchSlop(x, y, mState.mStylusDownX, mState.mStylusDownY)) {
                     mState.mExceedHandwritingSlop = true;
-                    View candidateView =
-                            findBestCandidateView(mState.mStylusDownX, mState.mStylusDownY);
+                    View candidateView = findBestCandidateView(mState.mStylusDownX,
+                            mState.mStylusDownY, /* isHover */ false);
                     if (candidateView != null) {
                         if (candidateView == getConnectedView()) {
                             if (!candidateView.hasFocus()) {
@@ -203,6 +212,7 @@
                             candidateView.getHandwritingDelegatorCallback().run();
                             mState.mHasPreparedHandwritingDelegation = true;
                         } else {
+                            mState.mPendingConnectedView = new WeakReference<>(candidateView);
                             requestFocusWithoutReveal(candidateView);
                         }
                     }
@@ -264,8 +274,9 @@
                 mShowHoverIconForConnectedView = false;
                 return;
             }
-            if (mState != null && mState.mShouldInitHandwriting) {
-                tryStartHandwriting();
+            if (mState != null && mState.mPendingConnectedView != null
+                    && mState.mPendingConnectedView.get() == view) {
+                startHandwriting(view);
             }
         }
     }
@@ -290,40 +301,6 @@
         }
     }
 
-    /**
-     * Try to initiate handwriting. For this method to successfully send startHandwriting signal,
-     * the following 3 conditions should meet:
-     *   a) The stylus movement exceeds the touchSlop.
-     *   b) A View has built InputConnection with IME.
-     *   c) The stylus event lands into the connected View's boundary.
-     * This method will immediately fail without any side effect if condition a or b is not met.
-     * However, if both condition a and b are met but the condition c is not met, it will reset the
-     * internal states. And HandwritingInitiator won't attempt to call startHandwriting until the
-     * next ACTION_DOWN.
-     */
-    private void tryStartHandwriting() {
-        if (!mState.mExceedHandwritingSlop) {
-            return;
-        }
-        final View connectedView = getConnectedView();
-        if (connectedView == null) {
-            return;
-        }
-
-        if (!connectedView.isAutoHandwritingEnabled()) {
-            clearConnectedView();
-            return;
-        }
-
-        final Rect handwritingArea = getViewHandwritingArea(connectedView);
-        if (isInHandwritingArea(
-                handwritingArea, mState.mStylusDownX, mState.mStylusDownY, connectedView)) {
-            startHandwriting(connectedView);
-        } else {
-            mState.mShouldInitHandwriting = false;
-        }
-    }
-
     /** Starts a stylus handwriting session for the view. */
     @VisibleForTesting
     public void startHandwriting(@NonNull View view) {
@@ -425,13 +402,14 @@
             final View cachedHoverTarget = getCachedHoverTarget();
             if (cachedHoverTarget != null) {
                 final Rect handwritingArea = getViewHandwritingArea(cachedHoverTarget);
-                if (isInHandwritingArea(handwritingArea, hoverX, hoverY, cachedHoverTarget)
+                if (isInHandwritingArea(handwritingArea, hoverX, hoverY, cachedHoverTarget,
+                        /* isHover */ true)
                         && shouldTriggerStylusHandwritingForView(cachedHoverTarget)) {
                     return cachedHoverTarget;
                 }
             }
 
-            final View candidateView = findBestCandidateView(hoverX, hoverY);
+            final View candidateView = findBestCandidateView(hoverX, hoverY, /* isHover */ true);
 
             if (candidateView != null) {
                 mCachedHoverTarget = new WeakReference<>(candidateView);
@@ -461,14 +439,14 @@
      * @param y the y coordinates of the stylus event, in the coordinates of the window.
      */
     @Nullable
-    private View findBestCandidateView(float x, float y) {
+    private View findBestCandidateView(float x, float y, boolean isHover) {
         // If the connectedView is not null and do not set any handwriting area, it will check
         // whether the connectedView's boundary contains the initial stylus position. If true,
         // directly return the connectedView.
         final View connectedView = getConnectedView();
         if (connectedView != null) {
             Rect handwritingArea = getViewHandwritingArea(connectedView);
-            if (isInHandwritingArea(handwritingArea, x, y, connectedView)
+            if (isInHandwritingArea(handwritingArea, x, y, connectedView, isHover)
                     && shouldTriggerStylusHandwritingForView(connectedView)) {
                 return connectedView;
             }
@@ -482,7 +460,7 @@
         for (HandwritableViewInfo viewInfo : handwritableViewInfos) {
             final View view = viewInfo.getView();
             final Rect handwritingArea = viewInfo.getHandwritingArea();
-            if (!isInHandwritingArea(handwritingArea, x, y, view)
+            if (!isInHandwritingArea(handwritingArea, x, y, view, isHover)
                     || !shouldTriggerStylusHandwritingForView(view)) {
                 continue;
             }
@@ -578,15 +556,48 @@
      * Return true if the (x, y) is inside by the given {@link Rect} with the View's
      * handwriting bounds with offsets applied.
      */
-    private static boolean isInHandwritingArea(@Nullable Rect handwritingArea,
-            float x, float y, View view) {
+    private boolean isInHandwritingArea(@Nullable Rect handwritingArea,
+            float x, float y, View view, boolean isHover) {
         if (handwritingArea == null) return false;
 
-        return contains(handwritingArea, x, y,
+        if (!contains(handwritingArea, x, y,
                 view.getHandwritingBoundsOffsetLeft(),
                 view.getHandwritingBoundsOffsetTop(),
                 view.getHandwritingBoundsOffsetRight(),
-                view.getHandwritingBoundsOffsetBottom());
+                view.getHandwritingBoundsOffsetBottom())) {
+            return false;
+        }
+
+        // The returned handwritingArea computed by ViewParent#getChildVisibleRect didn't consider
+        // the case where a view is stacking on top of the editor. (e.g. DrawerLayout, popup)
+        // We must check the hit region of the editor again, and avoid the case where another
+        // view on top of the editor is handling MotionEvents.
+        ViewParent parent = view.getParent();
+        if (parent == null) {
+            return true;
+        }
+
+        Region region = mTempRegion;
+        mTempRegion.set(0, 0, view.getWidth(), view.getHeight());
+        Matrix matrix = mTempMatrix;
+        matrix.reset();
+        if (!parent.getChildLocalHitRegion(view, region, matrix, isHover)) {
+            return false;
+        }
+
+        // It's not easy to extend the region by the given handwritingBoundsOffset. Instead, we
+        // create a rectangle surrounding the motion event location and check if this rectangle
+        // overlaps with the hit region of the editor.
+        float left = x - view.getHandwritingBoundsOffsetRight();
+        float top = y - view.getHandwritingBoundsOffsetBottom();
+        float right = Math.max(x + view.getHandwritingBoundsOffsetLeft(), left + 1);
+        float bottom =  Math.max(y + view.getHandwritingBoundsOffsetTop(), top + 1);
+        RectF rectF = mTempRectF;
+        rectF.set(left, top, right, bottom);
+        matrix.mapRect(rectF);
+
+        return region.op(Math.round(rectF.left), Math.round(rectF.top),
+                Math.round(rectF.right), Math.round(rectF.bottom), Region.Op.INTERSECT);
     }
 
     /**
@@ -626,6 +637,7 @@
         private boolean mHasInitiatedHandwriting;
 
         private boolean mHasPreparedHandwritingDelegation;
+
         /**
          * Whether the current ongoing stylus MotionEvent sequence already exceeds the
          * handwriting slop.
@@ -634,6 +646,12 @@
          */
         private boolean mExceedHandwritingSlop;
 
+        /**
+         * A view which has requested focus and is pending input connection creation. When an input
+         * connection is created for the view, a handwriting session should be started for the view.
+         */
+        private WeakReference<View> mPendingConnectedView = null;
+
         /** The pointer id of the stylus pointer that is being tracked. */
         private final int mStylusPointerId;
         /** The time stamp when the stylus pointer goes down. */
diff --git a/core/java/android/view/InputDevice.java b/core/java/android/view/InputDevice.java
index f81dc5a..c35b690 100644
--- a/core/java/android/view/InputDevice.java
+++ b/core/java/android/view/InputDevice.java
@@ -37,6 +37,7 @@
 import android.os.Parcelable;
 import android.os.Vibrator;
 import android.os.VibratorManager;
+import android.text.TextUtils;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
@@ -483,10 +484,12 @@
         mSources = sources;
         mKeyboardType = keyboardType;
         mKeyCharacterMap = keyCharacterMap;
-        if (keyboardLanguageTag != null) {
-            mKeyboardLanguageTag = ULocale
+        if (!TextUtils.isEmpty(keyboardLanguageTag)) {
+            String langTag;
+            langTag = ULocale
                     .createCanonical(ULocale.forLanguageTag(keyboardLanguageTag))
                     .toLanguageTag();
+            mKeyboardLanguageTag = TextUtils.equals(langTag, "und") ? null : langTag;
         } else {
             mKeyboardLanguageTag = null;
         }
diff --git a/core/java/android/view/InsetsController.java b/core/java/android/view/InsetsController.java
index 4ecfc40..c6d8bd1 100644
--- a/core/java/android/view/InsetsController.java
+++ b/core/java/android/view/InsetsController.java
@@ -16,10 +16,12 @@
 
 package android.view;
 
+import static android.inputmethodservice.InputMethodService.ENABLE_HIDE_IME_CAPTION_BAR;
 import static android.os.Trace.TRACE_TAG_VIEW;
 import static android.view.InsetsControllerProto.CONTROL;
 import static android.view.InsetsControllerProto.STATE;
 import static android.view.InsetsSource.ID_IME;
+import static android.view.InsetsSource.ID_IME_CAPTION_BAR;
 import static android.view.ViewRootImpl.CAPTION_ON_SHELL;
 import static android.view.WindowInsets.Type.FIRST;
 import static android.view.WindowInsets.Type.LAST;
@@ -40,6 +42,7 @@
 import android.content.Context;
 import android.content.res.CompatibilityInfo;
 import android.graphics.Insets;
+import android.graphics.Point;
 import android.graphics.Rect;
 import android.os.CancellationSignal;
 import android.os.Handler;
@@ -652,6 +655,7 @@
     private int mLastWindowingMode;
     private boolean mStartingAnimation;
     private int mCaptionInsetsHeight = 0;
+    private int mImeCaptionBarInsetsHeight = 0;
     private boolean mAnimationsDisabled;
     private boolean mCompatSysUiVisibilityStaled;
 
@@ -693,6 +697,9 @@
                     if (!CAPTION_ON_SHELL && source1.getType() == captionBar()) {
                         return;
                     }
+                    if (source1.getId() == ID_IME_CAPTION_BAR) {
+                        return;
+                    }
 
                     // Don't change the indexes of the sources while traversing. Remove it later.
                     mPendingRemoveIndexes.add(index1);
@@ -823,6 +830,9 @@
         if (mFrame.equals(frame)) {
             return;
         }
+        if (mImeCaptionBarInsetsHeight != 0) {
+            setImeCaptionBarInsetsHeight(mImeCaptionBarInsetsHeight);
+        }
         mHost.notifyInsetsChanged();
         mFrame.set(frame);
     }
@@ -1007,6 +1017,12 @@
         // Ensure to update all existing source consumers
         for (int i = mSourceConsumers.size() - 1; i >= 0; i--) {
             final InsetsSourceConsumer consumer = mSourceConsumers.valueAt(i);
+            if (consumer.getId() == ID_IME_CAPTION_BAR) {
+                // The inset control for the IME caption bar will never be dispatched
+                // by the server.
+                continue;
+            }
+
             final InsetsSourceControl control = mTmpControlArray.get(consumer.getId());
             if (control != null) {
                 controllableTypes |= control.getType();
@@ -1499,7 +1515,8 @@
                 continue;
             }
             final InsetsSourceControl control = consumer.getControl();
-            if (control != null && control.getLeash() != null) {
+            if (control != null
+                    && (control.getLeash() != null || control.getId() == ID_IME_CAPTION_BAR)) {
                 controls.put(control.getId(), new InsetsSourceControl(control));
                 typesReady |= consumer.getType();
             }
@@ -1885,6 +1902,35 @@
     }
 
     @Override
+    public void setImeCaptionBarInsetsHeight(int height) {
+        if (!ENABLE_HIDE_IME_CAPTION_BAR) {
+            return;
+        }
+        Rect newFrame = new Rect(mFrame.left, mFrame.bottom - height, mFrame.right, mFrame.bottom);
+        InsetsSource source = mState.peekSource(ID_IME_CAPTION_BAR);
+        if (mImeCaptionBarInsetsHeight != height
+                || (source != null && !newFrame.equals(source.getFrame()))) {
+            mImeCaptionBarInsetsHeight = height;
+            if (mImeCaptionBarInsetsHeight != 0) {
+                mState.getOrCreateSource(ID_IME_CAPTION_BAR, captionBar())
+                        .setFrame(newFrame);
+                getSourceConsumer(ID_IME_CAPTION_BAR, captionBar()).setControl(
+                        new InsetsSourceControl(ID_IME_CAPTION_BAR, captionBar(),
+                                null /* leash */, false /* initialVisible */,
+                                new Point(), Insets.NONE),
+                        new int[1], new int[1]);
+            } else {
+                mState.removeSource(ID_IME_CAPTION_BAR);
+                InsetsSourceConsumer sourceConsumer = mSourceConsumers.get(ID_IME_CAPTION_BAR);
+                if (sourceConsumer != null) {
+                    sourceConsumer.setControl(null, new int[1], new int[1]);
+                }
+            }
+            mHost.notifyInsetsChanged();
+        }
+    }
+
+    @Override
     public void setSystemBarsBehavior(@Behavior int behavior) {
         mHost.setSystemBarsBehavior(behavior);
     }
diff --git a/core/java/android/view/InsetsSource.java b/core/java/android/view/InsetsSource.java
index 6441186..ff009ed 100644
--- a/core/java/android/view/InsetsSource.java
+++ b/core/java/android/view/InsetsSource.java
@@ -20,6 +20,7 @@
 import static android.view.InsetsSourceProto.TYPE;
 import static android.view.InsetsSourceProto.VISIBLE;
 import static android.view.InsetsSourceProto.VISIBLE_FRAME;
+import static android.view.WindowInsets.Type.captionBar;
 import static android.view.WindowInsets.Type.ime;
 
 import android.annotation.IntDef;
@@ -47,6 +48,9 @@
 
     /** The insets source ID of IME */
     public static final int ID_IME = createId(null, 0, ime());
+    /** The insets source ID of the IME caption bar ("fake" IME navigation bar). */
+    static final int ID_IME_CAPTION_BAR =
+            InsetsSource.createId(null /* owner */, 1 /* index */, captionBar());
 
     /**
      * Controls whether this source suppresses the scrim. If the scrim is ignored, the system won't
@@ -215,8 +219,12 @@
         // During drag-move and drag-resizing, the caption insets position may not get updated
         // before the app frame get updated. To layout the app content correctly during drag events,
         // we always return the insets with the corresponding height covering the top.
+        // However, with the "fake" IME navigation bar treated as a caption bar, we return the
+        // insets with the corresponding height the bottom.
         if (getType() == WindowInsets.Type.captionBar()) {
-            return Insets.of(0, frame.height(), 0, 0);
+            return getId() == ID_IME_CAPTION_BAR
+                    ? Insets.of(0, 0, 0, frame.height())
+                    : Insets.of(0, frame.height(), 0, 0);
         }
         // Checks for whether there is shared edge with insets for 0-width/height window.
         final boolean hasIntersection = relativeFrame.isEmpty()
diff --git a/core/java/android/view/PendingInsetsController.java b/core/java/android/view/PendingInsetsController.java
index e8f62fc..a4cbc52 100644
--- a/core/java/android/view/PendingInsetsController.java
+++ b/core/java/android/view/PendingInsetsController.java
@@ -44,6 +44,7 @@
     private ArrayList<OnControllableInsetsChangedListener> mControllableInsetsChangedListeners
             = new ArrayList<>();
     private int mCaptionInsetsHeight = 0;
+    private int mImeCaptionBarInsetsHeight = 0;
     private WindowInsetsAnimationControlListener mLoggingListener;
     private @InsetsType int mRequestedVisibleTypes = WindowInsets.Type.defaultVisible();
 
@@ -91,6 +92,11 @@
     }
 
     @Override
+    public void setImeCaptionBarInsetsHeight(int height) {
+        mImeCaptionBarInsetsHeight = height;
+    }
+
+    @Override
     public void setSystemBarsBehavior(int behavior) {
         if (mReplayedInsetsController != null) {
             mReplayedInsetsController.setSystemBarsBehavior(behavior);
@@ -168,6 +174,9 @@
         if (mCaptionInsetsHeight != 0) {
             controller.setCaptionInsetsHeight(mCaptionInsetsHeight);
         }
+        if (mImeCaptionBarInsetsHeight != 0) {
+            controller.setImeCaptionBarInsetsHeight(mImeCaptionBarInsetsHeight);
+        }
         if (mAnimationsDisabled) {
             controller.setAnimationsDisabled(true);
         }
diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java
index c11f497..e673676 100644
--- a/core/java/android/view/SurfaceControl.java
+++ b/core/java/android/view/SurfaceControl.java
@@ -47,6 +47,7 @@
 import android.graphics.Rect;
 import android.graphics.Region;
 import android.gui.DropInputMode;
+import android.gui.StalledTransactionInfo;
 import android.hardware.DataSpace;
 import android.hardware.HardwareBuffer;
 import android.hardware.OverlayProperties;
@@ -292,6 +293,7 @@
             long nativeObject, long nativeTpc, TrustedPresentationThresholds thresholds);
     private static native void nativeClearTrustedPresentationCallback(long transactionObj,
             long nativeObject);
+    private static native StalledTransactionInfo nativeGetStalledTransactionInfo(int pid);
 
     /**
      * Transforms that can be applied to buffers as they are displayed to a window.
@@ -4363,4 +4365,11 @@
         callback.accept(fence);
     }
 
+    /**
+     * @hide
+     */
+    public static StalledTransactionInfo getStalledTransactionInfo(int pid) {
+        return nativeGetStalledTransactionInfo(pid);
+    }
+
 }
diff --git a/core/java/android/view/ThreadedRenderer.java b/core/java/android/view/ThreadedRenderer.java
index 2db2132..ad46f2b 100644
--- a/core/java/android/view/ThreadedRenderer.java
+++ b/core/java/android/view/ThreadedRenderer.java
@@ -815,7 +815,7 @@
 
         int syncResult = syncAndDrawFrame(frameInfo);
         if ((syncResult & SYNC_LOST_SURFACE_REWARD_IF_FOUND) != 0) {
-            Log.w("OpenGLRenderer", "Surface lost, forcing relayout");
+            Log.w("HWUI", "Surface lost, forcing relayout");
             // We lost our surface. For a relayout next frame which should give us a new
             // surface from WindowManager, which hopefully will work.
             attachInfo.mViewRootImpl.mForceNextWindowRelayout = true;
diff --git a/core/java/android/view/VelocityTracker.java b/core/java/android/view/VelocityTracker.java
index 4464d19..d31f823 100644
--- a/core/java/android/view/VelocityTracker.java
+++ b/core/java/android/view/VelocityTracker.java
@@ -19,6 +19,7 @@
 import android.annotation.IntDef;
 import android.compat.annotation.UnsupportedAppUsage;
 import android.hardware.input.InputManagerGlobal;
+import android.os.IInputConstants;
 import android.util.ArrayMap;
 import android.util.Pools.SynchronizedPool;
 
@@ -53,11 +54,13 @@
     public @interface VelocityTrackableMotionEventAxis {}
 
     /**
-     * Velocity Tracker Strategy: Invalid.
+     * Use the default Velocity Tracker Strategy. Different axes may use different default
+     * strategies.
      *
      * @hide
      */
-    public static final int VELOCITY_TRACKER_STRATEGY_DEFAULT = -1;
+    public static final int VELOCITY_TRACKER_STRATEGY_DEFAULT =
+            IInputConstants.VELOCITY_TRACKER_STRATEGY_DEFAULT;
 
     /**
      * Velocity Tracker Strategy: Impulse.
@@ -66,7 +69,8 @@
      *
      * @hide
      */
-    public static final int VELOCITY_TRACKER_STRATEGY_IMPULSE = 0;
+    public static final int VELOCITY_TRACKER_STRATEGY_IMPULSE =
+            IInputConstants.VELOCITY_TRACKER_STRATEGY_IMPULSE;
 
     /**
      * Velocity Tracker Strategy: LSQ1.
@@ -77,7 +81,8 @@
      *
      * @hide
      */
-    public static final int VELOCITY_TRACKER_STRATEGY_LSQ1 = 1;
+    public static final int VELOCITY_TRACKER_STRATEGY_LSQ1 =
+            IInputConstants.VELOCITY_TRACKER_STRATEGY_LSQ1;
 
     /**
      * Velocity Tracker Strategy: LSQ2.
@@ -88,7 +93,8 @@
      *
      * @hide
      */
-    public static final int VELOCITY_TRACKER_STRATEGY_LSQ2 = 2;
+    public static final int VELOCITY_TRACKER_STRATEGY_LSQ2 =
+            IInputConstants.VELOCITY_TRACKER_STRATEGY_LSQ2;
 
     /**
      * Velocity Tracker Strategy: LSQ3.
@@ -98,7 +104,8 @@
      *
      * @hide
      */
-    public static final int VELOCITY_TRACKER_STRATEGY_LSQ3 = 3;
+    public static final int VELOCITY_TRACKER_STRATEGY_LSQ3 =
+            IInputConstants.VELOCITY_TRACKER_STRATEGY_LSQ3;
 
     /**
      * Velocity Tracker Strategy: WLSQ2_DELTA.
@@ -106,7 +113,8 @@
      *
      * @hide
      */
-    public static final int VELOCITY_TRACKER_STRATEGY_WLSQ2_DELTA = 4;
+    public static final int VELOCITY_TRACKER_STRATEGY_WLSQ2_DELTA =
+            IInputConstants.VELOCITY_TRACKER_STRATEGY_WLSQ2_DELTA;
 
     /**
      * Velocity Tracker Strategy: WLSQ2_CENTRAL.
@@ -114,7 +122,8 @@
      *
      * @hide
      */
-    public static final int VELOCITY_TRACKER_STRATEGY_WLSQ2_CENTRAL = 5;
+    public static final int VELOCITY_TRACKER_STRATEGY_WLSQ2_CENTRAL =
+            IInputConstants.VELOCITY_TRACKER_STRATEGY_WLSQ2_CENTRAL;
 
     /**
      * Velocity Tracker Strategy: WLSQ2_RECENT.
@@ -122,7 +131,8 @@
      *
      * @hide
      */
-    public static final int VELOCITY_TRACKER_STRATEGY_WLSQ2_RECENT = 6;
+    public static final int VELOCITY_TRACKER_STRATEGY_WLSQ2_RECENT =
+            IInputConstants.VELOCITY_TRACKER_STRATEGY_WLSQ2_RECENT;
 
     /**
      * Velocity Tracker Strategy: INT1.
@@ -134,7 +144,8 @@
      *
      * @hide
      */
-    public static final int VELOCITY_TRACKER_STRATEGY_INT1 = 7;
+    public static final int VELOCITY_TRACKER_STRATEGY_INT1 =
+            IInputConstants.VELOCITY_TRACKER_STRATEGY_INT1;
 
     /**
      * Velocity Tracker Strategy: INT2.
@@ -144,7 +155,8 @@
      *
      * @hide
      */
-    public static final int VELOCITY_TRACKER_STRATEGY_INT2 = 8;
+    public static final int VELOCITY_TRACKER_STRATEGY_INT2 =
+            IInputConstants.VELOCITY_TRACKER_STRATEGY_INT2;
 
     /**
      * Velocity Tracker Strategy: Legacy.
@@ -155,7 +167,8 @@
      *
      * @hide
      */
-    public static final int VELOCITY_TRACKER_STRATEGY_LEGACY = 9;
+    public static final int VELOCITY_TRACKER_STRATEGY_LEGACY =
+            IInputConstants.VELOCITY_TRACKER_STRATEGY_LEGACY;
 
 
     /**
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index e0e8a6b..92509c9 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -16212,7 +16212,27 @@
         if (fg != null && isVisible != fg.isVisible()) {
             fg.setVisible(isVisible, false);
         }
+        notifyAutofillManagerViewVisibilityChanged(isVisible);
+        if (isVisible != oldVisible) {
+            if (isAccessibilityPane()) {
+                notifyViewAccessibilityStateChangedIfNeeded(isVisible
+                        ? AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_APPEARED
+                        : AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED);
+            }
 
+            notifyAppearedOrDisappearedForContentCaptureIfNeeded(isVisible);
+
+            if (!getSystemGestureExclusionRects().isEmpty()) {
+                postUpdate(this::updateSystemGestureExclusionRects);
+            }
+
+            if (!collectPreferKeepClearRects().isEmpty()) {
+                postUpdate(this::updateKeepClearRects);
+            }
+        }
+    }
+
+    private void notifyAutofillManagerViewVisibilityChanged(boolean isVisible) {
         if (isAutofillable()) {
             AutofillManager afm = getAutofillManager();
 
@@ -16236,24 +16256,6 @@
                 }
             }
         }
-
-        if (isVisible != oldVisible) {
-            if (isAccessibilityPane()) {
-                notifyViewAccessibilityStateChangedIfNeeded(isVisible
-                        ? AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_APPEARED
-                        : AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED);
-            }
-
-            notifyAppearedOrDisappearedForContentCaptureIfNeeded(isVisible);
-
-            if (!getSystemGestureExclusionRects().isEmpty()) {
-                postUpdate(this::updateSystemGestureExclusionRects);
-            }
-
-            if (!collectPreferKeepClearRects().isEmpty()) {
-                postUpdate(this::updateKeepClearRects);
-            }
-        }
     }
 
     /**
@@ -22128,6 +22130,8 @@
                     // Invoking onVisibilityAggregated directly here since the subtree
                     // will also receive detached from window
                     onVisibilityAggregated(false);
+                } else {
+                    notifyAutofillManagerViewVisibilityChanged(false);
                 }
             }
         }
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 1b1098d..7bdff8c 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -7361,6 +7361,90 @@
         }
     }
 
+    /**
+     * @hide
+     */
+    @Override
+    public boolean getChildLocalHitRegion(@NonNull View child, @NonNull Region region,
+            @NonNull Matrix matrix, boolean isHover) {
+        if (!child.hasIdentityMatrix()) {
+            matrix.preConcat(child.getInverseMatrix());
+        }
+
+        final int dx = child.mLeft - mScrollX;
+        final int dy = child.mTop - mScrollY;
+        matrix.preTranslate(-dx, -dy);
+
+        final int width = mRight - mLeft;
+        final int height = mBottom - mTop;
+
+        // Map the bounds of this view into the region's coordinates and clip the region.
+        final RectF rect = mAttachInfo != null ? mAttachInfo.mTmpTransformRect : new RectF();
+        rect.set(0, 0, width, height);
+        matrix.mapRect(rect);
+
+        boolean notEmpty = region.op(Math.round(rect.left), Math.round(rect.top),
+                Math.round(rect.right), Math.round(rect.bottom), Region.Op.INTERSECT);
+
+        if (isHover) {
+            HoverTarget target = mFirstHoverTarget;
+            boolean childIsHit = false;
+            while (target != null) {
+                final HoverTarget next = target.next;
+                if (target.child == child) {
+                    childIsHit = true;
+                    break;
+                }
+                target = next;
+            }
+            if (!childIsHit) {
+                target = mFirstHoverTarget;
+                while (notEmpty && target != null) {
+                    final HoverTarget next = target.next;
+                    final View hoveredView = target.child;
+
+                    rect.set(hoveredView.mLeft, hoveredView.mTop, hoveredView.mRight,
+                            hoveredView.mBottom);
+                    matrix.mapRect(rect);
+                    notEmpty = region.op(Math.round(rect.left), Math.round(rect.top),
+                            Math.round(rect.right), Math.round(rect.bottom), Region.Op.DIFFERENCE);
+                    target = next;
+                }
+            }
+        } else {
+            TouchTarget target = mFirstTouchTarget;
+            boolean childIsHit = false;
+            while (target != null) {
+                final TouchTarget next = target.next;
+                if (target.child == child) {
+                    childIsHit = true;
+                    break;
+                }
+                target = next;
+            }
+            if (!childIsHit) {
+                target = mFirstTouchTarget;
+                while (notEmpty && target != null) {
+                    final TouchTarget next = target.next;
+                    final View touchedView = target.child;
+
+                    rect.set(touchedView.mLeft, touchedView.mTop, touchedView.mRight,
+                            touchedView.mBottom);
+                    matrix.mapRect(rect);
+                    notEmpty = region.op(Math.round(rect.left), Math.round(rect.top),
+                            Math.round(rect.right), Math.round(rect.bottom), Region.Op.DIFFERENCE);
+                    target = next;
+                }
+            }
+        }
+
+        if (notEmpty && mParent != null) {
+            notEmpty = mParent.getChildLocalHitRegion(this, region, matrix, isHover);
+        }
+        return notEmpty;
+    }
+
+
     private static void applyOpToRegionByBounds(Region region, View view, Region.Op op) {
         final int[] locationInWindow = new int[2];
         view.getLocationInWindow(locationInWindow);
diff --git a/core/java/android/view/ViewParent.java b/core/java/android/view/ViewParent.java
index 1020d2e..54bc348 100644
--- a/core/java/android/view/ViewParent.java
+++ b/core/java/android/view/ViewParent.java
@@ -18,6 +18,7 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.graphics.Matrix;
 import android.graphics.Rect;
 import android.graphics.Region;
 import android.os.Bundle;
@@ -686,6 +687,36 @@
     }
 
     /**
+     * Compute the region where the child can receive the {@link MotionEvent}s from the root view.
+     *
+     * <p> Given region where the child will accept {@link MotionEvent}s.
+     * Modify the region to the unblocked region where the child can receive the
+     * {@link MotionEvent}s from the view root.
+     * </p>
+     *
+     * <p> The given region is always clipped by the bounds of the parent views. When there are
+     * on-going {@link MotionEvent}s, this method also makes use of the event dispatching results to
+     * determine whether a sibling view will also block the child's hit region.
+     * </p>
+     *
+     * @param child a child View, whose hit region we want to compute.
+     * @param region the initial hit region where the child view will handle {@link MotionEvent}s,
+     *              defined in the child coordinates. Will be overwritten to the result hit region.
+     * @param matrix the matrix that maps the given child view's coordinates to the region
+     *               coordinates. It will be modified to a matrix that maps window coordinates to
+     *               the result region's coordinates.
+     * @param isHover if true it will return the hover events' hit region, otherwise it will
+     *               return the touch events' hit region.
+     * @return true if the returned region is not empty.
+     * @hide
+     */
+    default boolean getChildLocalHitRegion(@NonNull View child, @NonNull Region region,
+            @NonNull Matrix matrix, boolean isHover) {
+        region.setEmpty();
+        return false;
+    }
+
+    /**
      * Unbuffered dispatch has been requested by a child of this view parent.
      * This method is called by the View hierarchy to signal ancestors that a View needs to
      * request unbuffered dispatch.
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 21ee0e7..e6ecd6e 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -128,6 +128,7 @@
 import android.graphics.PorterDuff;
 import android.graphics.RecordingCanvas;
 import android.graphics.Rect;
+import android.graphics.RectF;
 import android.graphics.Region;
 import android.graphics.RenderNode;
 import android.graphics.drawable.Drawable;
@@ -1810,6 +1811,9 @@
                 // Request to update light center.
                 mAttachInfo.mNeedsUpdateLightCenter = true;
             }
+            if ((changes & WindowManager.LayoutParams.COLOR_MODE_CHANGED) != 0) {
+                invalidate();
+            }
             if (mWindowAttributes.packageName == null) {
                 mWindowAttributes.packageName = mBasePackageName;
             }
@@ -2394,6 +2398,22 @@
     }
 
     @Override
+    public boolean getChildLocalHitRegion(@NonNull View child, @NonNull Region region,
+            @NonNull Matrix matrix, boolean isHover) {
+        if (child != mView) {
+            throw new IllegalArgumentException("child " + child + " is not the root view "
+                    + mView + " managed by this ViewRootImpl");
+        }
+
+        RectF rectF = new RectF(0, 0, mWidth, mHeight);
+        matrix.mapRect(rectF);
+        // Note: don't apply scroll offset, because we want to know its
+        // visibility in the virtual canvas being given to the view hierarchy.
+        return region.op(Math.round(rectF.left), Math.round(rectF.top),
+                Math.round(rectF.right), Math.round(rectF.bottom), Region.Op.INTERSECT);
+    }
+
+    @Override
     public void bringChildToFront(View child) {
     }
 
@@ -3792,6 +3812,11 @@
         boolean cancelDueToPreDrawListener = mAttachInfo.mTreeObserver.dispatchOnPreDraw();
         boolean cancelAndRedraw = cancelDueToPreDrawListener
                  || (cancelDraw && mDrewOnceForSync);
+        if (cancelAndRedraw) {
+            Log.d(mTag, "Cancelling draw."
+                    + " cancelDueToPreDrawListener=" + cancelDueToPreDrawListener
+                    + " cancelDueToSync=" + (cancelDraw && mDrewOnceForSync));
+        }
         if (!cancelAndRedraw) {
             // A sync was already requested before the WMS requested sync. This means we need to
             // sync the buffer, regardless if WMS wants to sync the buffer.
@@ -5561,6 +5586,7 @@
         if (desiredRatio != mDesiredHdrSdrRatio) {
             mDesiredHdrSdrRatio = desiredRatio;
             updateRenderHdrSdrRatio();
+            invalidate();
 
             if (mDesiredHdrSdrRatio < 1.01f) {
                 mDisplay.unregisterHdrSdrRatioChangedListener(mHdrSdrRatioChangedListener);
diff --git a/core/java/android/view/WindowInsetsController.java b/core/java/android/view/WindowInsetsController.java
index bc0bab7..cc2cd79 100644
--- a/core/java/android/view/WindowInsetsController.java
+++ b/core/java/android/view/WindowInsetsController.java
@@ -250,6 +250,16 @@
     void setCaptionInsetsHeight(int height);
 
     /**
+     * Sets the insets height for the IME caption bar, which corresponds to the
+     * "fake" IME navigation bar.
+     *
+     * @param height the insets height of the IME caption bar.
+     * @hide
+     */
+    default void setImeCaptionBarInsetsHeight(int height) {
+    }
+
+    /**
      * Controls the behavior of system bars.
      *
      * @param behavior Determines how the bars behave when being hidden by the application.
diff --git a/core/java/android/view/WindowManager.java b/core/java/android/view/WindowManager.java
index 3554483..62e37a4 100644
--- a/core/java/android/view/WindowManager.java
+++ b/core/java/android/view/WindowManager.java
@@ -913,7 +913,6 @@
      * &lt;/application&gt;
      * </pre>
      */
-    // TODO(b/263984287): Add CTS tests.
     String PROPERTY_COMPAT_IGNORE_REQUESTED_ORIENTATION =
             "android.window.PROPERTY_COMPAT_IGNORE_REQUESTED_ORIENTATION";
 
@@ -983,7 +982,6 @@
      * &lt;/application&gt;
      * </pre>
      */
-    // TODO(b/263984287): Make this public API.
     String PROPERTY_COMPAT_ALLOW_SANDBOXING_VIEW_BOUNDS_APIS =
             "android.window.PROPERTY_COMPAT_ALLOW_SANDBOXING_VIEW_BOUNDS_APIS";
 
@@ -1018,7 +1016,6 @@
      * &lt;/application&gt;
      * </pre>
      */
-    // TODO(b/263984287): Add CTS tests.
     String PROPERTY_COMPAT_ENABLE_FAKE_FOCUS = "android.window.PROPERTY_COMPAT_ENABLE_FAKE_FOCUS";
 
     /**
@@ -1056,7 +1053,6 @@
      * &lt;/application&gt;
      * </pre>
      */
-    // TODO(b/263984287): Add CTS tests.
     String PROPERTY_CAMERA_COMPAT_ALLOW_FORCE_ROTATION =
             "android.window.PROPERTY_CAMERA_COMPAT_ALLOW_FORCE_ROTATION";
 
@@ -1102,7 +1098,6 @@
      * &lt;/application&gt;
      * </pre>
      */
-    // TODO(b/263984287): Add CTS tests.
     String PROPERTY_CAMERA_COMPAT_ALLOW_REFRESH =
             "android.window.PROPERTY_CAMERA_COMPAT_ALLOW_REFRESH";
 
@@ -1151,7 +1146,6 @@
      * &lt;/application&gt;
      * </pre>
      */
-    // TODO(b/263984287): Add CTS tests.
     String PROPERTY_CAMERA_COMPAT_ENABLE_REFRESH_VIA_PAUSE =
             "android.window.PROPERTY_CAMERA_COMPAT_ENABLE_REFRESH_VIA_PAUSE";
 
@@ -1189,7 +1183,6 @@
      * &lt;/application&gt;
      * </pre>
      */
-    // TODO(b/263984287): Add CTS tests.
     String PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE =
             "android.window.PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE";
 
@@ -1233,7 +1226,6 @@
      * &lt;/application&gt;
      * </pre>
      */
-    // TODO(b/263984287): Add CTS tests.
     String PROPERTY_COMPAT_ALLOW_DISPLAY_ORIENTATION_OVERRIDE =
             "android.window.PROPERTY_COMPAT_ALLOW_DISPLAY_ORIENTATION_OVERRIDE";
 
@@ -1300,6 +1292,102 @@
             "android.window.PROPERTY_COMPAT_ALLOW_RESIZEABLE_ACTIVITY_OVERRIDES";
 
     /**
+     * Application level
+     * {@link android.content.pm.PackageManager.Property PackageManager.Property}
+     * tag that (when set to false) informs the system the app has opted out of the
+     * user-facing aspect ratio compatibility override.
+     *
+     * <p>The compatibility override enables device users to set the app's aspect
+     * ratio or force the app to fill the display regardless of the aspect
+     * ratio or orientation specified in the app manifest.
+     *
+     * <p>The aspect ratio compatibility override is exposed to users in device
+     * settings. A menu in device settings lists all apps that have not opted out of
+     * the compatibility override. Users select apps from the menu and set the
+     * app aspect ratio on a per-app basis. Typically, the menu is available
+     * only on large screen devices.
+     *
+     * <p>When users apply the aspect ratio override, the minimum aspect ratio
+     * specified in the app manifest is overridden. If users choose a
+     * full-screen aspect ratio, the orientation of the activity is forced to
+     * {@link android.content.pm.ActivityInfo#SCREEN_ORIENTATION_USER};
+     * see {@link #PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_FULLSCREEN_OVERRIDE} to
+     * disable the full-screen option only.
+     *
+     * <p>The user override is intended to improve the app experience on devices
+     * that have the ignore orientation request display setting enabled by OEMs
+     * (enables compatibility mode for fixed orientation on Android 12 (API
+     * level 31) or higher; see
+     * <a href="https://developer.android.com/guide/topics/large-screens/large-screen-app-compatibility">
+     * Large screen app compatibility</a>
+     * for more details).
+     *
+     * <p>To opt out of the user aspect ratio compatibility override, add this property
+     * to your app manifest and set the value to {@code false}. Your app will be excluded
+     * from the list of apps in device settings, and users will not be able to override
+     * the app's aspect ratio.
+     *
+     * <p>Not setting this property at all, or setting this property to {@code true} has no effect.
+     *
+     * <p><b>Syntax:</b>
+     * <pre>
+     * &lt;application&gt;
+     *   &lt;property
+     *     android:name="android.window.PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_OVERRIDE"
+     *     android:value="false"/&gt;
+     * &lt;/application&gt;
+     * </pre>
+     * @hide
+     */
+    // TODO(b/294227289): Make this public API
+    String PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_OVERRIDE =
+            "android.window.PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_OVERRIDE";
+
+    /**
+     * Application level
+     * {@link android.content.pm.PackageManager.Property PackageManager.Property}
+     * tag that (when set to false) informs the system the app has opted out of the
+     * full-screen option of the user aspect ratio compatibility override settings. (For
+     * background information about the user aspect ratio compatibility override, see
+     * {@link #PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_OVERRIDE}.)
+     *
+     * <p>When users apply the full-screen compatibility override, the orientation
+     * of the activity is forced to {@link android.content.pm.ActivityInfo#SCREEN_ORIENTATION_USER}.
+     *
+     * <p>The user override is intended to improve the app experience on devices
+     * that have the ignore orientation request display setting enabled by OEMs
+     * (enables compatibility mode for fixed orientation on Android 12 (API
+     * level 31) or higher; see
+     * <a href="https://developer.android.com/guide/topics/large-screens/large-screen-app-compatibility">
+     * Large screen app compatibility</a>
+     * for more details).
+     *
+     * <p>To opt out of the full-screen option of the user aspect ratio compatibility
+     * override, add this property to your app manifest and set the value to {@code false}.
+     * Your app will have full-screen option removed from the list of user aspect ratio
+     * override options in device settings, and users will not be able to apply
+     * full-screen override to your app.
+     *
+     * <p><b>Note:</b> If {@link #PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_OVERRIDE} is
+     * {@code false}, this property has no effect.
+     *
+     * <p>Not setting this property at all, or setting this property to {@code true} has no effect.
+     *
+     * <p><b>Syntax:</b>
+     * <pre>
+     * &lt;application&gt;
+     *   &lt;property
+     *     android:name="android.window.PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_FULLSCREEN_OVERRIDE"
+     *     android:value="false"/&gt;
+     * &lt;/application&gt;
+     * </pre>
+     * @hide
+     */
+    // TODO(b/294227289): Make this public API
+    String PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_FULLSCREEN_OVERRIDE =
+            "android.window.PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_FULLSCREEN_OVERRIDE";
+
+    /**
      * @hide
      */
     public static final String PARCEL_KEY_SHORTCUTS_ARRAY = "shortcuts_array";
@@ -3751,6 +3839,7 @@
          * @see #ROTATION_ANIMATION_ROTATE
          * @see #ROTATION_ANIMATION_CROSSFADE
          * @see #ROTATION_ANIMATION_JUMPCUT
+         * @see #ROTATION_ANIMATION_SEAMLESS
          */
         public int rotationAnimation = ROTATION_ANIMATION_ROTATE;
 
diff --git a/core/java/android/view/accessibility/AccessibilityInteractionClient.java b/core/java/android/view/accessibility/AccessibilityInteractionClient.java
index f14ec37..60f46e6 100644
--- a/core/java/android/view/accessibility/AccessibilityInteractionClient.java
+++ b/core/java/android/view/accessibility/AccessibilityInteractionClient.java
@@ -831,8 +831,17 @@
                     //   A11yService -> App -> SurfaceFlinger -> A11yService
                     ScreenCapture.ScreenCaptureListener listener =
                             new ScreenCapture.ScreenCaptureListener(
-                                    screenshot -> sendWindowScreenshotSuccess(screenshot,
-                                            interactionId));
+                                    (screenshot, status) -> {
+                                        if (status != 0) {
+                                            sendTakeScreenshotOfWindowError(
+                                                    AccessibilityService
+                                                            .ERROR_TAKE_SCREENSHOT_INTERNAL_ERROR,
+                                                    interactionId);
+                                        } else {
+                                            sendWindowScreenshotSuccess(screenshot,
+                                                    interactionId);
+                                        }
+                                    });
                     connection.takeScreenshotOfWindow(accessibilityWindowId, interactionId,
                             listener, this);
                     mMainHandler.postDelayed(() -> {
diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java
index 7f8f611..c877873 100644
--- a/core/java/android/view/inputmethod/InputMethodManager.java
+++ b/core/java/android/view/inputmethod/InputMethodManager.java
@@ -1516,7 +1516,7 @@
      * @see #startStylusHandwriting(View)
      */
     public boolean isStylusHandwritingAvailable() {
-        return isStylusHandwritingAvailableAsUser(UserHandle.myUserId());
+        return isStylusHandwritingAvailableAsUser(UserHandle.of(UserHandle.myUserId()));
     }
 
     /**
@@ -1527,14 +1527,17 @@
      * called and Stylus touch should continue as normal touch input.</p>
      *
      * <p>{@link Manifest.permission#INTERACT_ACROSS_USERS_FULL} is required when and only when
-     * {@code userId} is different from the user id of the current process.</p>
+     * {@code user} is different from the user of the current process.</p>
      *
      * @see #startStylusHandwriting(View)
-     * @param userId user ID to query.
+     * @param user UserHandle to query.
      * @hide
      */
+    @NonNull
     @RequiresPermission(value = Manifest.permission.INTERACT_ACROSS_USERS_FULL, conditional = true)
-    public boolean isStylusHandwritingAvailableAsUser(@UserIdInt int userId) {
+    @TestApi
+    @SuppressLint("UserHandle")
+    public boolean isStylusHandwritingAvailableAsUser(@NonNull UserHandle user) {
         final Context fallbackContext = ActivityThread.currentApplication();
         if (fallbackContext == null) {
             return false;
@@ -1551,7 +1554,7 @@
                     }
                 };
             }
-            isAvailable = mStylusHandwritingAvailableCache.query(userId);
+            isAvailable = mStylusHandwritingAvailableCache.query(user.getIdentifier());
         }
         return isAvailable;
     }
@@ -1643,16 +1646,19 @@
      * Returns the list of enabled input methods for the specified user.
      *
      * <p>{@link Manifest.permission#INTERACT_ACROSS_USERS_FULL} is required when and only when
-     * {@code userId} is different from the user id of the current process.</p>
+     * {@code user} is different from the user of the current process.</p>
      *
-     * @param userId user ID to query
+     * @param user UserHandle to query
      * @return {@link List} of {@link InputMethodInfo}.
-     * @see #getEnabledInputMethodSubtypeListAsUser(String, boolean, int)
+     * @see #getEnabledInputMethodSubtypeListAsUser(String, boolean, UserHandle)
      * @hide
      */
+    @NonNull
     @RequiresPermission(value = Manifest.permission.INTERACT_ACROSS_USERS_FULL, conditional = true)
-    public List<InputMethodInfo> getEnabledInputMethodListAsUser(@UserIdInt int userId) {
-        return IInputMethodManagerGlobalInvoker.getEnabledInputMethodList(userId);
+    @TestApi
+    @SuppressLint("UserHandle")
+    public List<InputMethodInfo> getEnabledInputMethodListAsUser(@NonNull UserHandle user) {
+        return IInputMethodManagerGlobalInvoker.getEnabledInputMethodList(user.getIdentifier());
     }
 
     /**
@@ -1681,7 +1687,7 @@
      *
      * @param imeId IME ID to be queried about.
      * @param allowsImplicitlyEnabledSubtypes {@code true} to include implicitly enabled subtypes.
-     * @param userId user ID to be queried about.
+     * @param user UserHandle to be queried about.
      *               {@link Manifest.permission#INTERACT_ACROSS_USERS_FULL} is required if this is
      *               different from the calling process user ID.
      * @return {@link List} of {@link InputMethodSubtype}.
@@ -1690,10 +1696,14 @@
      */
     @NonNull
     @RequiresPermission(value = Manifest.permission.INTERACT_ACROSS_USERS_FULL, conditional = true)
+    @TestApi
+    @SuppressLint("UserHandle")
     public List<InputMethodSubtype> getEnabledInputMethodSubtypeListAsUser(
-            @NonNull String imeId, boolean allowsImplicitlyEnabledSubtypes, @UserIdInt int userId) {
+            @NonNull String imeId, boolean allowsImplicitlyEnabledSubtypes,
+            @NonNull UserHandle user) {
         return IInputMethodManagerGlobalInvoker.getEnabledInputMethodSubtypeList(
-                Objects.requireNonNull(imeId), allowsImplicitlyEnabledSubtypes, userId);
+                Objects.requireNonNull(imeId), allowsImplicitlyEnabledSubtypes,
+                user.getIdentifier());
     }
 
     /**
@@ -2106,7 +2116,7 @@
         // Re-dispatch if there is a context mismatch.
         final InputMethodManager fallbackImm = getFallbackInputMethodManagerIfNecessary(view);
         if (fallbackImm != null) {
-            return fallbackImm.showSoftInput(view, flags, resultReceiver);
+            return fallbackImm.showSoftInput(view, statsToken, flags, resultReceiver, reason);
         }
 
         checkFocus();
diff --git a/core/java/android/view/inputmethod/RemoteInputConnectionImpl.java b/core/java/android/view/inputmethod/RemoteInputConnectionImpl.java
index 987ac2e..f67a61b 100644
--- a/core/java/android/view/inputmethod/RemoteInputConnectionImpl.java
+++ b/core/java/android/view/inputmethod/RemoteInputConnectionImpl.java
@@ -160,6 +160,8 @@
 
     @NonNull
     private final AtomicReference<InputConnection> mInputConnectionRef;
+    @NonNull
+    private final AtomicBoolean mDeactivateRequested = new AtomicBoolean(false);
 
     @NonNull
     private final Looper mLooper;
@@ -211,10 +213,6 @@
         return mInputConnectionRef.get() == null;
     }
 
-    private boolean isActive() {
-        return mParentInputMethodManager.isActive() && !isFinished();
-    }
-
     private View getServedView() {
         return mServedView.get();
     }
@@ -349,25 +347,15 @@
      */
     @Dispatching(cancellable = false)
     public void deactivate() {
-        if (isFinished()) {
+        if (mDeactivateRequested.getAndSet(true)) {
             // This is a small performance optimization.  Still only the 1st call of
-            // reportFinish() will take effect.
+            // deactivate() will take effect.
             return;
         }
         dispatch(() -> {
-            // Note that we do not need to worry about race condition here, because 1) mFinished is
-            // updated only inside this block, and 2) the code here is running on a Handler hence we
-            // assume multiple closeConnection() tasks will not be handled at the same time.
-            if (isFinished()) {
-                return;
-            }
             Trace.traceBegin(Trace.TRACE_TAG_INPUT, "InputConnection#closeConnection");
             try {
                 InputConnection ic = getInputConnection();
-                // Note we do NOT check isActive() here, because this is safe
-                // for an IME to call at any time, and we need to allow it
-                // through to clean up our state after the IME has switched to
-                // another client.
                 if (ic == null) {
                     return;
                 }
@@ -429,7 +417,7 @@
     public String toString() {
         return "RemoteInputConnectionImpl{"
                 + "connection=" + getInputConnection()
-                + " mParentInputMethodManager.isActive()=" + mParentInputMethodManager.isActive()
+                + " mDeactivateRequested=" + mDeactivateRequested.get()
                 + " mServedView=" + mServedView.get()
                 + "}";
     }
@@ -464,7 +452,7 @@
     public void dispatchReportFullscreenMode(boolean enabled) {
         dispatch(() -> {
             final InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 return;
             }
             ic.reportFullscreenMode(enabled);
@@ -480,7 +468,7 @@
                 return null;  // cancelled
             }
             final InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "getTextAfterCursor on inactive InputConnection");
                 return null;
             }
@@ -502,7 +490,7 @@
                 return null;  // cancelled
             }
             final InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "getTextBeforeCursor on inactive InputConnection");
                 return null;
             }
@@ -524,7 +512,7 @@
                 return null;  // cancelled
             }
             final InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "getSelectedText on inactive InputConnection");
                 return null;
             }
@@ -546,7 +534,7 @@
                 return null;  // cancelled
             }
             final InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "getSurroundingText on inactive InputConnection");
                 return null;
             }
@@ -574,7 +562,7 @@
                 return 0;  // cancelled
             }
             final InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "getCursorCapsMode on inactive InputConnection");
                 return 0;
             }
@@ -591,7 +579,7 @@
                 return null;  // cancelled
             }
             final InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "getExtractedText on inactive InputConnection");
                 return null;
             }
@@ -608,7 +596,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "commitText on inactive InputConnection");
                 return;
             }
@@ -625,7 +613,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "commitText on inactive InputConnection");
                 return;
             }
@@ -641,7 +629,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "commitCompletion on inactive InputConnection");
                 return;
             }
@@ -657,7 +645,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "commitCorrection on inactive InputConnection");
                 return;
             }
@@ -677,7 +665,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "setSelection on inactive InputConnection");
                 return;
             }
@@ -693,7 +681,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "performEditorAction on inactive InputConnection");
                 return;
             }
@@ -709,7 +697,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "performContextMenuAction on inactive InputConnection");
                 return;
             }
@@ -725,7 +713,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "setComposingRegion on inactive InputConnection");
                 return;
             }
@@ -746,7 +734,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "setComposingRegion on inactive InputConnection");
                 return;
             }
@@ -763,7 +751,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "setComposingText on inactive InputConnection");
                 return;
             }
@@ -780,7 +768,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "setComposingText on inactive InputConnection");
                 return;
             }
@@ -809,11 +797,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            // Note we do NOT check isActive() here, because this is safe
-            // for an IME to call at any time, and we need to allow it
-            // through to clean up our state after the IME has switched to
-            // another client.
-            if (ic == null) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "finishComposingTextFromImm on inactive InputConnection");
                 return;
             }
@@ -837,11 +821,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            // Note we do NOT check isActive() here, because this is safe
-            // for an IME to call at any time, and we need to allow it
-            // through to clean up our state after the IME has switched to
-            // another client.
-            if (ic == null) {
+            if (ic == null && mDeactivateRequested.get()) {
                 Log.w(TAG, "finishComposingText on inactive InputConnection");
                 return;
             }
@@ -857,7 +837,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "sendKeyEvent on inactive InputConnection");
                 return;
             }
@@ -873,7 +853,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "clearMetaKeyStates on inactive InputConnection");
                 return;
             }
@@ -890,7 +870,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "deleteSurroundingText on inactive InputConnection");
                 return;
             }
@@ -907,7 +887,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "deleteSurroundingTextInCodePoints on inactive InputConnection");
                 return;
             }
@@ -927,7 +907,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "beginBatchEdit on inactive InputConnection");
                 return;
             }
@@ -943,7 +923,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "endBatchEdit on inactive InputConnection");
                 return;
             }
@@ -959,7 +939,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "performSpellCheck on inactive InputConnection");
                 return;
             }
@@ -976,7 +956,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "performPrivateCommand on inactive InputConnection");
                 return;
             }
@@ -1014,7 +994,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "performHandwritingGesture on inactive InputConnection");
                 if (resultReceiver != null) {
                     resultReceiver.send(
@@ -1054,7 +1034,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "previewHandwritingGesture on inactive InputConnection");
                 return; // cancelled
             }
@@ -1102,7 +1082,7 @@
             @InputConnection.CursorUpdateMode int cursorUpdateMode,
             @InputConnection.CursorUpdateFilter int cursorUpdateFilter, int imeDisplayId) {
         final InputConnection ic = getInputConnection();
-        if (ic == null || !isActive()) {
+        if (ic == null || mDeactivateRequested.get()) {
             Log.w(TAG, "requestCursorUpdates on inactive InputConnection");
             return false;
         }
@@ -1139,7 +1119,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "requestTextBoundsInfo on inactive InputConnection");
                 resultReceiver.send(TextBoundsInfoResult.CODE_CANCELLED, null);
                 return;
@@ -1168,7 +1148,7 @@
                 return false;  // cancelled
             }
             final InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "commitContent on inactive InputConnection");
                 return false;
             }
@@ -1193,7 +1173,7 @@
                 return;  // cancelled
             }
             InputConnection ic = getInputConnection();
-            if (ic == null || !isActive()) {
+            if (ic == null || mDeactivateRequested.get()) {
                 Log.w(TAG, "setImeConsumesInput on inactive InputConnection");
                 return;
             }
@@ -1217,7 +1197,7 @@
                         return; // cancelled
                     }
                     InputConnection ic = getInputConnection();
-                    if (ic == null || !isActive()) {
+                    if (ic == null || mDeactivateRequested.get()) {
                         Log.w(TAG, "replaceText on inactive InputConnection");
                         return;
                     }
@@ -1236,7 +1216,7 @@
                     return;  // cancelled
                 }
                 InputConnection ic = getInputConnection();
-                if (ic == null || !isActive()) {
+                if (ic == null || mDeactivateRequested.get()) {
                     Log.w(TAG, "commitText on inactive InputConnection");
                     return;
                 }
@@ -1256,7 +1236,7 @@
                     return;  // cancelled
                 }
                 InputConnection ic = getInputConnection();
-                if (ic == null || !isActive()) {
+                if (ic == null || mDeactivateRequested.get()) {
                     Log.w(TAG, "setSelection on inactive InputConnection");
                     return;
                 }
@@ -1273,7 +1253,7 @@
                     return null;  // cancelled
                 }
                 final InputConnection ic = getInputConnection();
-                if (ic == null || !isActive()) {
+                if (ic == null || mDeactivateRequested.get()) {
                     Log.w(TAG, "getSurroundingText on inactive InputConnection");
                     return null;
                 }
@@ -1301,7 +1281,7 @@
                     return;  // cancelled
                 }
                 InputConnection ic = getInputConnection();
-                if (ic == null || !isActive()) {
+                if (ic == null || mDeactivateRequested.get()) {
                     Log.w(TAG, "deleteSurroundingText on inactive InputConnection");
                     return;
                 }
@@ -1317,7 +1297,7 @@
                     return;  // cancelled
                 }
                 InputConnection ic = getInputConnection();
-                if (ic == null || !isActive()) {
+                if (ic == null || mDeactivateRequested.get()) {
                     Log.w(TAG, "sendKeyEvent on inactive InputConnection");
                     return;
                 }
@@ -1333,7 +1313,7 @@
                     return;  // cancelled
                 }
                 InputConnection ic = getInputConnection();
-                if (ic == null || !isActive()) {
+                if (ic == null || mDeactivateRequested.get()) {
                     Log.w(TAG, "performEditorAction on inactive InputConnection");
                     return;
                 }
@@ -1349,7 +1329,7 @@
                     return;  // cancelled
                 }
                 InputConnection ic = getInputConnection();
-                if (ic == null || !isActive()) {
+                if (ic == null || mDeactivateRequested.get()) {
                     Log.w(TAG, "performContextMenuAction on inactive InputConnection");
                     return;
                 }
@@ -1366,7 +1346,7 @@
                     return 0;  // cancelled
                 }
                 final InputConnection ic = getInputConnection();
-                if (ic == null || !isActive()) {
+                if (ic == null || mDeactivateRequested.get()) {
                     Log.w(TAG, "getCursorCapsMode on inactive InputConnection");
                     return 0;
                 }
@@ -1382,7 +1362,7 @@
                     return;  // cancelled
                 }
                 InputConnection ic = getInputConnection();
-                if (ic == null || !isActive()) {
+                if (ic == null || mDeactivateRequested.get()) {
                     Log.w(TAG, "clearMetaKeyStates on inactive InputConnection");
                     return;
                 }
diff --git a/core/java/android/view/selectiontoolbar/ISelectionToolbarCallback.aidl b/core/java/android/view/selectiontoolbar/ISelectionToolbarCallback.aidl
deleted file mode 100644
index aaeb120..0000000
--- a/core/java/android/view/selectiontoolbar/ISelectionToolbarCallback.aidl
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.view.selectiontoolbar;
-
-import android.view.selectiontoolbar.ToolbarMenuItem;
-import android.view.selectiontoolbar.WidgetInfo;
-
-/**
- * Binder interface to notify the selection toolbar events from one process to the other.
- * @hide
- */
-oneway interface ISelectionToolbarCallback {
-    void onShown(in WidgetInfo info);
-    void onWidgetUpdated(in WidgetInfo info);
-    void onToolbarShowTimeout();
-    void onMenuItemClicked(in ToolbarMenuItem item);
-    void onError(int errorCode);
-}
diff --git a/core/java/android/view/selectiontoolbar/ISelectionToolbarManager.aidl b/core/java/android/view/selectiontoolbar/ISelectionToolbarManager.aidl
deleted file mode 100644
index 4a647ad..0000000
--- a/core/java/android/view/selectiontoolbar/ISelectionToolbarManager.aidl
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.view.selectiontoolbar;
-
-import android.view.selectiontoolbar.ISelectionToolbarCallback;
-import android.view.selectiontoolbar.ShowInfo;
-
-/**
- * Mediator between apps and selection toolbar service implementation.
- *
- * @hide
- */
-oneway interface ISelectionToolbarManager {
-    void showToolbar(in ShowInfo showInfo, in ISelectionToolbarCallback callback, int userId);
-    void hideToolbar(long widgetToken, int userId);
-    void dismissToolbar(long widgetToken, int userId);
-}
\ No newline at end of file
diff --git a/core/java/android/view/selectiontoolbar/OWNERS b/core/java/android/view/selectiontoolbar/OWNERS
deleted file mode 100644
index 5500b92..0000000
--- a/core/java/android/view/selectiontoolbar/OWNERS
+++ /dev/null
@@ -1,10 +0,0 @@
-# Bug component: 709498
-
-augale@google.com
-joannechung@google.com
-licha@google.com
-lpeter@google.com
-svetoslavganov@google.com
-toki@google.com
-tonymak@google.com
-tymtsai@google.com
\ No newline at end of file
diff --git a/core/java/android/view/selectiontoolbar/SelectionToolbarManager.java b/core/java/android/view/selectiontoolbar/SelectionToolbarManager.java
deleted file mode 100644
index 6de0316..0000000
--- a/core/java/android/view/selectiontoolbar/SelectionToolbarManager.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.view.selectiontoolbar;
-
-import android.annotation.NonNull;
-import android.annotation.SystemService;
-import android.content.Context;
-import android.os.RemoteException;
-import android.provider.DeviceConfig;
-
-import java.util.Objects;
-
-/**
- * The {@link SelectionToolbarManager} class provides ways for apps to control the
- * selection toolbar.
- *
- * @hide
- */
-@SystemService(Context.SELECTION_TOOLBAR_SERVICE)
-public final class SelectionToolbarManager {
-
-    private static final String TAG = "SelectionToolbar";
-
-    /**
-     * The tag which uses for enabling debug log dump. To enable it, we can use command "adb shell
-     * setprop log.tag.UiTranslation DEBUG".
-     */
-    public static final String LOG_TAG = "SelectionToolbar";
-
-    /**
-     * Whether system selection toolbar is enabled.
-     */
-    private static final String REMOTE_SELECTION_TOOLBAR_ENABLED =
-            "remote_selection_toolbar_enabled";
-
-    /**
-     * Used to mark a toolbar that has no toolbar token id.
-     */
-    public static final long NO_TOOLBAR_ID = 0;
-
-    /**
-     * The error code that do not allow to create multiple toolbar.
-     */
-    public static final int ERROR_DO_NOT_ALLOW_MULTIPLE_TOOL_BAR = 1;
-
-    @NonNull
-    private final Context mContext;
-    private final ISelectionToolbarManager mService;
-
-    public SelectionToolbarManager(@NonNull Context context,
-            @NonNull ISelectionToolbarManager service) {
-        mContext = Objects.requireNonNull(context);
-        mService = service;
-    }
-
-    /**
-     * Request to show selection toolbar for a given View.
-     */
-    public void showToolbar(@NonNull ShowInfo showInfo,
-            @NonNull ISelectionToolbarCallback callback) {
-        try {
-            Objects.requireNonNull(showInfo);
-            Objects.requireNonNull(callback);
-            mService.showToolbar(showInfo, callback, mContext.getUserId());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Request to hide selection toolbar.
-     */
-    public void hideToolbar(long widgetToken) {
-        try {
-            mService.hideToolbar(widgetToken, mContext.getUserId());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Dismiss to dismiss selection toolbar.
-     */
-    public void dismissToolbar(long widgetToken) {
-        try {
-            mService.dismissToolbar(widgetToken, mContext.getUserId());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    private boolean isRemoteSelectionToolbarEnabled() {
-        return DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_SELECTION_TOOLBAR,
-                REMOTE_SELECTION_TOOLBAR_ENABLED, false);
-    }
-
-    /**
-     * Returns {@code true} if remote render selection toolbar enabled, otherwise
-     * returns {@code false}.
-     */
-    public static boolean isRemoteSelectionToolbarEnabled(Context context) {
-        SelectionToolbarManager manager = context.getSystemService(SelectionToolbarManager.class);
-        if (manager != null) {
-            return manager.isRemoteSelectionToolbarEnabled();
-        }
-        return false;
-    }
-}
diff --git a/core/java/android/view/selectiontoolbar/ShowInfo.aidl b/core/java/android/view/selectiontoolbar/ShowInfo.aidl
deleted file mode 100644
index dce9c15..0000000
--- a/core/java/android/view/selectiontoolbar/ShowInfo.aidl
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.view.selectiontoolbar;
-
-/**
- * @hide
- */
-parcelable ShowInfo;
diff --git a/core/java/android/view/selectiontoolbar/ShowInfo.java b/core/java/android/view/selectiontoolbar/ShowInfo.java
deleted file mode 100644
index 28b4480..0000000
--- a/core/java/android/view/selectiontoolbar/ShowInfo.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.view.selectiontoolbar;
-
-import android.annotation.NonNull;
-import android.graphics.Rect;
-import android.os.IBinder;
-import android.os.Parcelable;
-
-import com.android.internal.util.DataClass;
-
-import java.util.List;
-
-
-/**
- * The class holds menu information for render service to render the selection toolbar.
- *
- * @hide
- */
-@DataClass(genToString = true, genEqualsHashCode = true)
-public final class ShowInfo implements Parcelable {
-
-    /**
-     * The token that is used to identify the selection toolbar. This is initially set to 0
-     * until a selection toolbar has been created for the showToolbar request.
-     */
-    private final long mWidgetToken;
-
-    /**
-     * If the toolbar menu items need to be re-layout.
-     */
-    private final boolean mLayoutRequired;
-
-    /**
-     * The menu items to be rendered in the selection toolbar.
-     */
-    @NonNull
-    private final List<ToolbarMenuItem> mMenuItems;
-
-    /**
-     * A rect specifying where the selection toolbar on the screen.
-     */
-    @NonNull
-    private final Rect mContentRect;
-
-    /**
-     * A recommended maximum suggested width of the selection toolbar.
-     */
-    private final int mSuggestedWidth;
-
-    /**
-     * The portion of the screen that is available to the selection toolbar.
-     */
-    @NonNull
-    private final Rect mViewPortOnScreen;
-
-    /**
-     * The host application's input token, this allows the remote render service to transfer
-     * the touch focus to the host application.
-     */
-    @NonNull
-    private final IBinder mHostInputToken;
-
-    /**
-     * If the host application uses light theme.
-     */
-    private final boolean mIsLightTheme;
-
-
-
-    // Code below generated by codegen v1.0.23.
-    //
-    // DO NOT MODIFY!
-    // CHECKSTYLE:OFF Generated code
-    //
-    // To regenerate run:
-    // $ codegen $ANDROID_BUILD_TOP/frameworks/base/core/java/android/view/selectiontoolbar/ShowInfo.java
-    //
-    // To exclude the generated code from IntelliJ auto-formatting enable (one-time):
-    //   Settings > Editor > Code Style > Formatter Control
-    //@formatter:off
-
-
-    /**
-     * Creates a new ShowInfo.
-     *
-     * @param widgetToken
-     *   The token that is used to identify the selection toolbar. This is initially set to 0
-     *   until a selection toolbar has been created for the showToolbar request.
-     * @param layoutRequired
-     *   If the toolbar menu items need to be re-layout.
-     * @param menuItems
-     *   The menu items to be rendered in the selection toolbar.
-     * @param contentRect
-     *   A rect specifying where the selection toolbar on the screen.
-     * @param suggestedWidth
-     *   A recommended maximum suggested width of the selection toolbar.
-     * @param viewPortOnScreen
-     *   The portion of the screen that is available to the selection toolbar.
-     * @param hostInputToken
-     *   The host application's input token, this allows the remote render service to transfer
-     *   the touch focus to the host application.
-     * @param isLightTheme
-     *   If the host application uses light theme.
-     */
-    @DataClass.Generated.Member
-    public ShowInfo(
-            long widgetToken,
-            boolean layoutRequired,
-            @NonNull List<ToolbarMenuItem> menuItems,
-            @NonNull Rect contentRect,
-            int suggestedWidth,
-            @NonNull Rect viewPortOnScreen,
-            @NonNull IBinder hostInputToken,
-            boolean isLightTheme) {
-        this.mWidgetToken = widgetToken;
-        this.mLayoutRequired = layoutRequired;
-        this.mMenuItems = menuItems;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mMenuItems);
-        this.mContentRect = contentRect;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mContentRect);
-        this.mSuggestedWidth = suggestedWidth;
-        this.mViewPortOnScreen = viewPortOnScreen;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mViewPortOnScreen);
-        this.mHostInputToken = hostInputToken;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mHostInputToken);
-        this.mIsLightTheme = isLightTheme;
-
-        // onConstructed(); // You can define this method to get a callback
-    }
-
-    /**
-     * The token that is used to identify the selection toolbar. This is initially set to 0
-     * until a selection toolbar has been created for the showToolbar request.
-     */
-    @DataClass.Generated.Member
-    public long getWidgetToken() {
-        return mWidgetToken;
-    }
-
-    /**
-     * If the toolbar menu items need to be re-layout.
-     */
-    @DataClass.Generated.Member
-    public boolean isLayoutRequired() {
-        return mLayoutRequired;
-    }
-
-    /**
-     * The menu items to be rendered in the selection toolbar.
-     */
-    @DataClass.Generated.Member
-    public @NonNull List<ToolbarMenuItem> getMenuItems() {
-        return mMenuItems;
-    }
-
-    /**
-     * A rect specifying where the selection toolbar on the screen.
-     */
-    @DataClass.Generated.Member
-    public @NonNull Rect getContentRect() {
-        return mContentRect;
-    }
-
-    /**
-     * A recommended maximum suggested width of the selection toolbar.
-     */
-    @DataClass.Generated.Member
-    public int getSuggestedWidth() {
-        return mSuggestedWidth;
-    }
-
-    /**
-     * The portion of the screen that is available to the selection toolbar.
-     */
-    @DataClass.Generated.Member
-    public @NonNull Rect getViewPortOnScreen() {
-        return mViewPortOnScreen;
-    }
-
-    /**
-     * The host application's input token, this allows the remote render service to transfer
-     * the touch focus to the host application.
-     */
-    @DataClass.Generated.Member
-    public @NonNull IBinder getHostInputToken() {
-        return mHostInputToken;
-    }
-
-    /**
-     * If the host application uses light theme.
-     */
-    @DataClass.Generated.Member
-    public boolean isIsLightTheme() {
-        return mIsLightTheme;
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public String toString() {
-        // You can override field toString logic by defining methods like:
-        // String fieldNameToString() { ... }
-
-        return "ShowInfo { " +
-                "widgetToken = " + mWidgetToken + ", " +
-                "layoutRequired = " + mLayoutRequired + ", " +
-                "menuItems = " + mMenuItems + ", " +
-                "contentRect = " + mContentRect + ", " +
-                "suggestedWidth = " + mSuggestedWidth + ", " +
-                "viewPortOnScreen = " + mViewPortOnScreen + ", " +
-                "hostInputToken = " + mHostInputToken + ", " +
-                "isLightTheme = " + mIsLightTheme +
-        " }";
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public boolean equals(@android.annotation.Nullable Object o) {
-        // You can override field equality logic by defining either of the methods like:
-        // boolean fieldNameEquals(ShowInfo other) { ... }
-        // boolean fieldNameEquals(FieldType otherValue) { ... }
-
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
-        @SuppressWarnings("unchecked")
-        ShowInfo that = (ShowInfo) o;
-        //noinspection PointlessBooleanExpression
-        return true
-                && mWidgetToken == that.mWidgetToken
-                && mLayoutRequired == that.mLayoutRequired
-                && java.util.Objects.equals(mMenuItems, that.mMenuItems)
-                && java.util.Objects.equals(mContentRect, that.mContentRect)
-                && mSuggestedWidth == that.mSuggestedWidth
-                && java.util.Objects.equals(mViewPortOnScreen, that.mViewPortOnScreen)
-                && java.util.Objects.equals(mHostInputToken, that.mHostInputToken)
-                && mIsLightTheme == that.mIsLightTheme;
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public int hashCode() {
-        // You can override field hashCode logic by defining methods like:
-        // int fieldNameHashCode() { ... }
-
-        int _hash = 1;
-        _hash = 31 * _hash + Long.hashCode(mWidgetToken);
-        _hash = 31 * _hash + Boolean.hashCode(mLayoutRequired);
-        _hash = 31 * _hash + java.util.Objects.hashCode(mMenuItems);
-        _hash = 31 * _hash + java.util.Objects.hashCode(mContentRect);
-        _hash = 31 * _hash + mSuggestedWidth;
-        _hash = 31 * _hash + java.util.Objects.hashCode(mViewPortOnScreen);
-        _hash = 31 * _hash + java.util.Objects.hashCode(mHostInputToken);
-        _hash = 31 * _hash + Boolean.hashCode(mIsLightTheme);
-        return _hash;
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public void writeToParcel(@NonNull android.os.Parcel dest, int flags) {
-        // You can override field parcelling by defining methods like:
-        // void parcelFieldName(Parcel dest, int flags) { ... }
-
-        int flg = 0;
-        if (mLayoutRequired) flg |= 0x2;
-        if (mIsLightTheme) flg |= 0x80;
-        dest.writeInt(flg);
-        dest.writeLong(mWidgetToken);
-        dest.writeParcelableList(mMenuItems, flags);
-        dest.writeTypedObject(mContentRect, flags);
-        dest.writeInt(mSuggestedWidth);
-        dest.writeTypedObject(mViewPortOnScreen, flags);
-        dest.writeStrongBinder(mHostInputToken);
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public int describeContents() { return 0; }
-
-    /** @hide */
-    @SuppressWarnings({"unchecked", "RedundantCast"})
-    @DataClass.Generated.Member
-    /* package-private */ ShowInfo(@NonNull android.os.Parcel in) {
-        // You can override field unparcelling by defining methods like:
-        // static FieldType unparcelFieldName(Parcel in) { ... }
-
-        int flg = in.readInt();
-        boolean layoutRequired = (flg & 0x2) != 0;
-        boolean isLightTheme = (flg & 0x80) != 0;
-        long widgetToken = in.readLong();
-        List<ToolbarMenuItem> menuItems = new java.util.ArrayList<>();
-        in.readParcelableList(menuItems, ToolbarMenuItem.class.getClassLoader(), android.view.selectiontoolbar.ToolbarMenuItem.class);
-        Rect contentRect = (Rect) in.readTypedObject(Rect.CREATOR);
-        int suggestedWidth = in.readInt();
-        Rect viewPortOnScreen = (Rect) in.readTypedObject(Rect.CREATOR);
-        IBinder hostInputToken = (IBinder) in.readStrongBinder();
-
-        this.mWidgetToken = widgetToken;
-        this.mLayoutRequired = layoutRequired;
-        this.mMenuItems = menuItems;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mMenuItems);
-        this.mContentRect = contentRect;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mContentRect);
-        this.mSuggestedWidth = suggestedWidth;
-        this.mViewPortOnScreen = viewPortOnScreen;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mViewPortOnScreen);
-        this.mHostInputToken = hostInputToken;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mHostInputToken);
-        this.mIsLightTheme = isLightTheme;
-
-        // onConstructed(); // You can define this method to get a callback
-    }
-
-    @DataClass.Generated.Member
-    public static final @NonNull Parcelable.Creator<ShowInfo> CREATOR
-            = new Parcelable.Creator<ShowInfo>() {
-        @Override
-        public ShowInfo[] newArray(int size) {
-            return new ShowInfo[size];
-        }
-
-        @Override
-        public ShowInfo createFromParcel(@NonNull android.os.Parcel in) {
-            return new ShowInfo(in);
-        }
-    };
-
-    @DataClass.Generated(
-            time = 1645108384245L,
-            codegenVersion = "1.0.23",
-            sourceFile = "frameworks/base/core/java/android/view/selectiontoolbar/ShowInfo.java",
-            inputSignatures = "private final  long mWidgetToken\nprivate final  boolean mLayoutRequired\nprivate final @android.annotation.NonNull java.util.List<android.view.selectiontoolbar.ToolbarMenuItem> mMenuItems\nprivate final @android.annotation.NonNull android.graphics.Rect mContentRect\nprivate final  int mSuggestedWidth\nprivate final @android.annotation.NonNull android.graphics.Rect mViewPortOnScreen\nprivate final @android.annotation.NonNull android.os.IBinder mHostInputToken\nprivate final  boolean mIsLightTheme\nclass ShowInfo extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genToString=true, genEqualsHashCode=true)")
-    @Deprecated
-    private void __metadata() {}
-
-
-    //@formatter:on
-    // End of generated code
-
-}
diff --git a/core/java/android/view/selectiontoolbar/ToolbarMenuItem.aidl b/core/java/android/view/selectiontoolbar/ToolbarMenuItem.aidl
deleted file mode 100644
index 711a85a..0000000
--- a/core/java/android/view/selectiontoolbar/ToolbarMenuItem.aidl
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.view.selectiontoolbar;
-
-/**
- * @hide
- */
-parcelable ToolbarMenuItem;
diff --git a/core/java/android/view/selectiontoolbar/ToolbarMenuItem.java b/core/java/android/view/selectiontoolbar/ToolbarMenuItem.java
deleted file mode 100644
index 89347c6..0000000
--- a/core/java/android/view/selectiontoolbar/ToolbarMenuItem.java
+++ /dev/null
@@ -1,543 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.view.selectiontoolbar;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.graphics.drawable.Icon;
-import android.os.Parcelable;
-import android.view.MenuItem;
-
-import com.android.internal.util.DataClass;
-
-/**
- * The menu item that is used to show the selection toolbar.
- *
- * @hide
- */
-@DataClass(genBuilder = true, genToString = true, genEqualsHashCode = true)
-public final class ToolbarMenuItem implements Parcelable {
-
-    /**
-     * The priority of menu item is unknown.
-     */
-    public static final int PRIORITY_UNKNOWN = 0;
-
-    /**
-     * The priority of menu item is shown in primary selection toolbar.
-     */
-    public static final int PRIORITY_PRIMARY = 1;
-
-    /**
-     * The priority of menu item is shown in overflow selection toolbar.
-     */
-    public static final int PRIORITY_OVERFLOW = 2;
-
-    /**
-     * The id of the menu item.
-     *
-     * @see MenuItem#getItemId()
-     */
-    private final int mItemId;
-
-    /**
-     * The title of the menu item.
-     *
-     * @see MenuItem#getTitle()
-     */
-    @NonNull
-    private final CharSequence mTitle;
-
-    /**
-     * The content description of the menu item.
-     *
-     * @see MenuItem#getContentDescription()
-     */
-    @Nullable
-    private final CharSequence mContentDescription;
-
-    /**
-     * The group id of the menu item.
-     *
-     * @see MenuItem#getGroupId()
-     */
-    private final int mGroupId;
-
-    /**
-     * The icon id of the menu item.
-     *
-     * @see MenuItem#getIcon()
-     */
-    @Nullable
-    private final Icon mIcon;
-
-    /**
-     * The tooltip text of the menu item.
-     *
-     * @see MenuItem#getTooltipText()
-     */
-    @Nullable
-    private final CharSequence mTooltipText;
-
-    /**
-     * The priority of the menu item used to display the order of the menu item.
-     */
-    private final int mPriority;
-
-    /**
-     * Returns the priority from a given {@link MenuItem}.
-     */
-    public static int getPriorityFromMenuItem(MenuItem menuItem) {
-        if (menuItem.requiresActionButton()) {
-            return PRIORITY_PRIMARY;
-        } else if (menuItem.requiresOverflow()) {
-            return PRIORITY_OVERFLOW;
-        }
-        return PRIORITY_UNKNOWN;
-    }
-
-
-
-
-    // Code below generated by codegen v1.0.23.
-    //
-    // DO NOT MODIFY!
-    // CHECKSTYLE:OFF Generated code
-    //
-    // To regenerate run:
-    // $ codegen $ANDROID_BUILD_TOP/frameworks/base/core/java/android/view/selectiontoolbar/ToolbarMenuItem.java
-    //
-    // To exclude the generated code from IntelliJ auto-formatting enable (one-time):
-    //   Settings > Editor > Code Style > Formatter Control
-    //@formatter:off
-
-
-    @android.annotation.IntDef(prefix = "PRIORITY_", value = {
-        PRIORITY_UNKNOWN,
-        PRIORITY_PRIMARY,
-        PRIORITY_OVERFLOW
-    })
-    @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE)
-    @DataClass.Generated.Member
-    public @interface Priority {}
-
-    @DataClass.Generated.Member
-    public static String priorityToString(@Priority int value) {
-        switch (value) {
-            case PRIORITY_UNKNOWN:
-                    return "PRIORITY_UNKNOWN";
-            case PRIORITY_PRIMARY:
-                    return "PRIORITY_PRIMARY";
-            case PRIORITY_OVERFLOW:
-                    return "PRIORITY_OVERFLOW";
-            default: return Integer.toHexString(value);
-        }
-    }
-
-    @DataClass.Generated.Member
-    /* package-private */ ToolbarMenuItem(
-            int itemId,
-            @NonNull CharSequence title,
-            @Nullable CharSequence contentDescription,
-            int groupId,
-            @Nullable Icon icon,
-            @Nullable CharSequence tooltipText,
-            int priority) {
-        this.mItemId = itemId;
-        this.mTitle = title;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mTitle);
-        this.mContentDescription = contentDescription;
-        this.mGroupId = groupId;
-        this.mIcon = icon;
-        this.mTooltipText = tooltipText;
-        this.mPriority = priority;
-
-        // onConstructed(); // You can define this method to get a callback
-    }
-
-    /**
-     * The id of the menu item.
-     *
-     * @see MenuItem#getItemId()
-     */
-    @DataClass.Generated.Member
-    public int getItemId() {
-        return mItemId;
-    }
-
-    /**
-     * The title of the menu item.
-     *
-     * @see MenuItem#getTitle()
-     */
-    @DataClass.Generated.Member
-    public @NonNull CharSequence getTitle() {
-        return mTitle;
-    }
-
-    /**
-     * The content description of the menu item.
-     *
-     * @see MenuItem#getContentDescription()
-     */
-    @DataClass.Generated.Member
-    public @Nullable CharSequence getContentDescription() {
-        return mContentDescription;
-    }
-
-    /**
-     * The group id of the menu item.
-     *
-     * @see MenuItem#getGroupId()
-     */
-    @DataClass.Generated.Member
-    public int getGroupId() {
-        return mGroupId;
-    }
-
-    /**
-     * The icon id of the menu item.
-     *
-     * @see MenuItem#getIcon()
-     */
-    @DataClass.Generated.Member
-    public @Nullable Icon getIcon() {
-        return mIcon;
-    }
-
-    /**
-     * The tooltip text of the menu item.
-     *
-     * @see MenuItem#getTooltipText()
-     */
-    @DataClass.Generated.Member
-    public @Nullable CharSequence getTooltipText() {
-        return mTooltipText;
-    }
-
-    /**
-     * The priority of the menu item used to display the order of the menu item.
-     */
-    @DataClass.Generated.Member
-    public int getPriority() {
-        return mPriority;
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public String toString() {
-        // You can override field toString logic by defining methods like:
-        // String fieldNameToString() { ... }
-
-        return "ToolbarMenuItem { " +
-                "itemId = " + mItemId + ", " +
-                "title = " + mTitle + ", " +
-                "contentDescription = " + mContentDescription + ", " +
-                "groupId = " + mGroupId + ", " +
-                "icon = " + mIcon + ", " +
-                "tooltipText = " + mTooltipText + ", " +
-                "priority = " + mPriority +
-        " }";
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public boolean equals(@Nullable Object o) {
-        // You can override field equality logic by defining either of the methods like:
-        // boolean fieldNameEquals(ToolbarMenuItem other) { ... }
-        // boolean fieldNameEquals(FieldType otherValue) { ... }
-
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
-        @SuppressWarnings("unchecked")
-        ToolbarMenuItem that = (ToolbarMenuItem) o;
-        //noinspection PointlessBooleanExpression
-        return true
-                && mItemId == that.mItemId
-                && java.util.Objects.equals(mTitle, that.mTitle)
-                && java.util.Objects.equals(mContentDescription, that.mContentDescription)
-                && mGroupId == that.mGroupId
-                && java.util.Objects.equals(mIcon, that.mIcon)
-                && java.util.Objects.equals(mTooltipText, that.mTooltipText)
-                && mPriority == that.mPriority;
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public int hashCode() {
-        // You can override field hashCode logic by defining methods like:
-        // int fieldNameHashCode() { ... }
-
-        int _hash = 1;
-        _hash = 31 * _hash + mItemId;
-        _hash = 31 * _hash + java.util.Objects.hashCode(mTitle);
-        _hash = 31 * _hash + java.util.Objects.hashCode(mContentDescription);
-        _hash = 31 * _hash + mGroupId;
-        _hash = 31 * _hash + java.util.Objects.hashCode(mIcon);
-        _hash = 31 * _hash + java.util.Objects.hashCode(mTooltipText);
-        _hash = 31 * _hash + mPriority;
-        return _hash;
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public void writeToParcel(@NonNull android.os.Parcel dest, int flags) {
-        // You can override field parcelling by defining methods like:
-        // void parcelFieldName(Parcel dest, int flags) { ... }
-
-        byte flg = 0;
-        if (mContentDescription != null) flg |= 0x4;
-        if (mIcon != null) flg |= 0x10;
-        if (mTooltipText != null) flg |= 0x20;
-        dest.writeByte(flg);
-        dest.writeInt(mItemId);
-        dest.writeCharSequence(mTitle);
-        if (mContentDescription != null) dest.writeCharSequence(mContentDescription);
-        dest.writeInt(mGroupId);
-        if (mIcon != null) dest.writeTypedObject(mIcon, flags);
-        if (mTooltipText != null) dest.writeCharSequence(mTooltipText);
-        dest.writeInt(mPriority);
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public int describeContents() { return 0; }
-
-    /** @hide */
-    @SuppressWarnings({"unchecked", "RedundantCast"})
-    @DataClass.Generated.Member
-    /* package-private */ ToolbarMenuItem(@NonNull android.os.Parcel in) {
-        // You can override field unparcelling by defining methods like:
-        // static FieldType unparcelFieldName(Parcel in) { ... }
-
-        byte flg = in.readByte();
-        int itemId = in.readInt();
-        CharSequence title = (CharSequence) in.readCharSequence();
-        CharSequence contentDescription = (flg & 0x4) == 0 ? null : (CharSequence) in.readCharSequence();
-        int groupId = in.readInt();
-        Icon icon = (flg & 0x10) == 0 ? null : (Icon) in.readTypedObject(Icon.CREATOR);
-        CharSequence tooltipText = (flg & 0x20) == 0 ? null : (CharSequence) in.readCharSequence();
-        int priority = in.readInt();
-
-        this.mItemId = itemId;
-        this.mTitle = title;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mTitle);
-        this.mContentDescription = contentDescription;
-        this.mGroupId = groupId;
-        this.mIcon = icon;
-        this.mTooltipText = tooltipText;
-        this.mPriority = priority;
-
-        // onConstructed(); // You can define this method to get a callback
-    }
-
-    @DataClass.Generated.Member
-    public static final @NonNull Parcelable.Creator<ToolbarMenuItem> CREATOR
-            = new Parcelable.Creator<ToolbarMenuItem>() {
-        @Override
-        public ToolbarMenuItem[] newArray(int size) {
-            return new ToolbarMenuItem[size];
-        }
-
-        @Override
-        public ToolbarMenuItem createFromParcel(@NonNull android.os.Parcel in) {
-            return new ToolbarMenuItem(in);
-        }
-    };
-
-    /**
-     * A builder for {@link ToolbarMenuItem}
-     */
-    @SuppressWarnings("WeakerAccess")
-    @DataClass.Generated.Member
-    public static final class Builder {
-
-        private int mItemId;
-        private @NonNull CharSequence mTitle;
-        private @Nullable CharSequence mContentDescription;
-        private int mGroupId;
-        private @Nullable Icon mIcon;
-        private @Nullable CharSequence mTooltipText;
-        private int mPriority;
-
-        private long mBuilderFieldsSet = 0L;
-
-        /**
-         * Creates a new Builder.
-         *
-         * @param itemId
-         *   The id of the menu item.
-         * @param title
-         *   The title of the menu item.
-         * @param contentDescription
-         *   The content description of the menu item.
-         * @param groupId
-         *   The group id of the menu item.
-         * @param icon
-         *   The icon id of the menu item.
-         * @param tooltipText
-         *   The tooltip text of the menu item.
-         * @param priority
-         *   The priority of the menu item used to display the order of the menu item.
-         */
-        public Builder(
-                int itemId,
-                @NonNull CharSequence title,
-                @Nullable CharSequence contentDescription,
-                int groupId,
-                @Nullable Icon icon,
-                @Nullable CharSequence tooltipText,
-                int priority) {
-            mItemId = itemId;
-            mTitle = title;
-            com.android.internal.util.AnnotationValidations.validate(
-                    NonNull.class, null, mTitle);
-            mContentDescription = contentDescription;
-            mGroupId = groupId;
-            mIcon = icon;
-            mTooltipText = tooltipText;
-            mPriority = priority;
-        }
-
-        /**
-         * The id of the menu item.
-         *
-         * @see MenuItem#getItemId()
-         */
-        @DataClass.Generated.Member
-        public @NonNull Builder setItemId(int value) {
-            checkNotUsed();
-            mBuilderFieldsSet |= 0x1;
-            mItemId = value;
-            return this;
-        }
-
-        /**
-         * The title of the menu item.
-         *
-         * @see MenuItem#getTitle()
-         */
-        @DataClass.Generated.Member
-        public @NonNull Builder setTitle(@NonNull CharSequence value) {
-            checkNotUsed();
-            mBuilderFieldsSet |= 0x2;
-            mTitle = value;
-            return this;
-        }
-
-        /**
-         * The content description of the menu item.
-         *
-         * @see MenuItem#getContentDescription()
-         */
-        @DataClass.Generated.Member
-        public @NonNull Builder setContentDescription(@NonNull CharSequence value) {
-            checkNotUsed();
-            mBuilderFieldsSet |= 0x4;
-            mContentDescription = value;
-            return this;
-        }
-
-        /**
-         * The group id of the menu item.
-         *
-         * @see MenuItem#getGroupId()
-         */
-        @DataClass.Generated.Member
-        public @NonNull Builder setGroupId(int value) {
-            checkNotUsed();
-            mBuilderFieldsSet |= 0x8;
-            mGroupId = value;
-            return this;
-        }
-
-        /**
-         * The icon id of the menu item.
-         *
-         * @see MenuItem#getIcon()
-         */
-        @DataClass.Generated.Member
-        public @NonNull Builder setIcon(@NonNull Icon value) {
-            checkNotUsed();
-            mBuilderFieldsSet |= 0x10;
-            mIcon = value;
-            return this;
-        }
-
-        /**
-         * The tooltip text of the menu item.
-         *
-         * @see MenuItem#getTooltipText()
-         */
-        @DataClass.Generated.Member
-        public @NonNull Builder setTooltipText(@NonNull CharSequence value) {
-            checkNotUsed();
-            mBuilderFieldsSet |= 0x20;
-            mTooltipText = value;
-            return this;
-        }
-
-        /**
-         * The priority of the menu item used to display the order of the menu item.
-         */
-        @DataClass.Generated.Member
-        public @NonNull Builder setPriority(int value) {
-            checkNotUsed();
-            mBuilderFieldsSet |= 0x40;
-            mPriority = value;
-            return this;
-        }
-
-        /** Builds the instance. This builder should not be touched after calling this! */
-        public @NonNull ToolbarMenuItem build() {
-            checkNotUsed();
-            mBuilderFieldsSet |= 0x80; // Mark builder used
-
-            ToolbarMenuItem o = new ToolbarMenuItem(
-                    mItemId,
-                    mTitle,
-                    mContentDescription,
-                    mGroupId,
-                    mIcon,
-                    mTooltipText,
-                    mPriority);
-            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 = 1643200806234L,
-            codegenVersion = "1.0.23",
-            sourceFile = "frameworks/base/core/java/android/view/selectiontoolbar/ToolbarMenuItem.java",
-            inputSignatures = "public static final  int PRIORITY_UNKNOWN\npublic static final  int PRIORITY_PRIMARY\npublic static final  int PRIORITY_OVERFLOW\nprivate final  int mItemId\nprivate final @android.annotation.NonNull java.lang.CharSequence mTitle\nprivate final @android.annotation.Nullable java.lang.CharSequence mContentDescription\nprivate final  int mGroupId\nprivate final @android.annotation.Nullable android.graphics.drawable.Icon mIcon\nprivate final @android.annotation.Nullable java.lang.CharSequence mTooltipText\nprivate final  int mPriority\npublic static  int getPriorityFromMenuItem(android.view.MenuItem)\nclass ToolbarMenuItem extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genBuilder=true, genToString=true, genEqualsHashCode=true)")
-    @Deprecated
-    private void __metadata() {}
-
-
-    //@formatter:on
-    // End of generated code
-
-}
diff --git a/core/java/android/view/selectiontoolbar/WidgetInfo.java b/core/java/android/view/selectiontoolbar/WidgetInfo.java
deleted file mode 100644
index 5d0fd47..0000000
--- a/core/java/android/view/selectiontoolbar/WidgetInfo.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.view.selectiontoolbar;
-
-import android.annotation.NonNull;
-import android.graphics.Rect;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.view.SurfaceControlViewHost;
-
-import com.android.internal.util.DataClass;
-
-/**
- * The class holds the rendered content and the related information from the render service to
- * be used to show on the selection toolbar.
- *
- * @hide
- */
-@DataClass(genToString = true, genEqualsHashCode = true)
-public final class WidgetInfo implements Parcelable {
-
-    /**
-     * The token that is used to identify the selection toolbar.
-     */
-    private final long mWidgetToken;
-
-    /**
-     * A Rect that defines the size and positioning of the remote view with respect to
-     * its host window.
-     */
-    @NonNull
-    private final Rect mContentRect;
-
-    /**
-     * The SurfacePackage pointing to the remote view.
-     */
-    @NonNull
-    private final SurfaceControlViewHost.SurfacePackage mSurfacePackage;
-
-
-
-    // Code below generated by codegen v1.0.23.
-    //
-    // DO NOT MODIFY!
-    // CHECKSTYLE:OFF Generated code
-    //
-    // To regenerate run:
-    // $ codegen $ANDROID_BUILD_TOP/frameworks/base/core/java/android/view/selectiontoolbar/WidgetInfo.java
-    //
-    // To exclude the generated code from IntelliJ auto-formatting enable (one-time):
-    //   Settings > Editor > Code Style > Formatter Control
-    //@formatter:off
-
-
-    /**
-     * Creates a new WidgetInfo.
-     *
-     * @param widgetToken
-     *   The token that is used to identify the selection toolbar.
-     * @param contentRect
-     *   A Rect that defines the size and positioning of the remote view with respect to
-     *   its host window.
-     * @param surfacePackage
-     *   The SurfacePackage pointing to the remote view.
-     */
-    @DataClass.Generated.Member
-    public WidgetInfo(
-            long widgetToken,
-            @NonNull Rect contentRect,
-            @NonNull SurfaceControlViewHost.SurfacePackage surfacePackage) {
-        this.mWidgetToken = widgetToken;
-        this.mContentRect = contentRect;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mContentRect);
-        this.mSurfacePackage = surfacePackage;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mSurfacePackage);
-
-        // onConstructed(); // You can define this method to get a callback
-    }
-
-    /**
-     * The token that is used to identify the selection toolbar.
-     */
-    @DataClass.Generated.Member
-    public long getWidgetToken() {
-        return mWidgetToken;
-    }
-
-    /**
-     * A Rect that defines the size and positioning of the remote view with respect to
-     * its host window.
-     */
-    @DataClass.Generated.Member
-    public @NonNull Rect getContentRect() {
-        return mContentRect;
-    }
-
-    /**
-     * The SurfacePackage pointing to the remote view.
-     */
-    @DataClass.Generated.Member
-    public @NonNull SurfaceControlViewHost.SurfacePackage getSurfacePackage() {
-        return mSurfacePackage;
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public String toString() {
-        // You can override field toString logic by defining methods like:
-        // String fieldNameToString() { ... }
-
-        return "WidgetInfo { " +
-                "widgetToken = " + mWidgetToken + ", " +
-                "contentRect = " + mContentRect + ", " +
-                "surfacePackage = " + mSurfacePackage +
-        " }";
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public boolean equals(@android.annotation.Nullable Object o) {
-        // You can override field equality logic by defining either of the methods like:
-        // boolean fieldNameEquals(WidgetInfo other) { ... }
-        // boolean fieldNameEquals(FieldType otherValue) { ... }
-
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
-        @SuppressWarnings("unchecked")
-        WidgetInfo that = (WidgetInfo) o;
-        //noinspection PointlessBooleanExpression
-        return true
-                && mWidgetToken == that.mWidgetToken
-                && java.util.Objects.equals(mContentRect, that.mContentRect)
-                && java.util.Objects.equals(mSurfacePackage, that.mSurfacePackage);
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public int hashCode() {
-        // You can override field hashCode logic by defining methods like:
-        // int fieldNameHashCode() { ... }
-
-        int _hash = 1;
-        _hash = 31 * _hash + Long.hashCode(mWidgetToken);
-        _hash = 31 * _hash + java.util.Objects.hashCode(mContentRect);
-        _hash = 31 * _hash + java.util.Objects.hashCode(mSurfacePackage);
-        return _hash;
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public void writeToParcel(@NonNull Parcel dest, int flags) {
-        // You can override field parcelling by defining methods like:
-        // void parcelFieldName(Parcel dest, int flags) { ... }
-
-        dest.writeLong(mWidgetToken);
-        dest.writeTypedObject(mContentRect, flags);
-        dest.writeTypedObject(mSurfacePackage, flags);
-    }
-
-    @Override
-    @DataClass.Generated.Member
-    public int describeContents() { return 0; }
-
-    /** @hide */
-    @SuppressWarnings({"unchecked", "RedundantCast"})
-    @DataClass.Generated.Member
-    /* package-private */ WidgetInfo(@NonNull Parcel in) {
-        // You can override field unparcelling by defining methods like:
-        // static FieldType unparcelFieldName(Parcel in) { ... }
-
-        long widgetToken = in.readLong();
-        Rect contentRect = (Rect) in.readTypedObject(Rect.CREATOR);
-        SurfaceControlViewHost.SurfacePackage surfacePackage = (SurfaceControlViewHost.SurfacePackage) in.readTypedObject(SurfaceControlViewHost.SurfacePackage.CREATOR);
-
-        this.mWidgetToken = widgetToken;
-        this.mContentRect = contentRect;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mContentRect);
-        this.mSurfacePackage = surfacePackage;
-        com.android.internal.util.AnnotationValidations.validate(
-                NonNull.class, null, mSurfacePackage);
-
-        // onConstructed(); // You can define this method to get a callback
-    }
-
-    @DataClass.Generated.Member
-    public static final @NonNull Parcelable.Creator<WidgetInfo> CREATOR
-            = new Parcelable.Creator<WidgetInfo>() {
-        @Override
-        public WidgetInfo[] newArray(int size) {
-            return new WidgetInfo[size];
-        }
-
-        @Override
-        public WidgetInfo createFromParcel(@NonNull Parcel in) {
-            return new WidgetInfo(in);
-        }
-    };
-
-    @DataClass.Generated(
-            time = 1643281495056L,
-            codegenVersion = "1.0.23",
-            sourceFile = "frameworks/base/core/java/android/view/selectiontoolbar/WidgetInfo.java",
-            inputSignatures = "private final  long mWidgetToken\nprivate final @android.annotation.NonNull android.graphics.Rect mContentRect\nprivate final @android.annotation.NonNull android.view.SurfaceControlViewHost.SurfacePackage mSurfacePackage\nclass WidgetInfo extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genToString=true, genEqualsHashCode=true)")
-    @Deprecated
-    private void __metadata() {}
-
-
-    //@formatter:on
-    // End of generated code
-
-}
diff --git a/core/java/android/widget/HorizontalScrollView.java b/core/java/android/widget/HorizontalScrollView.java
index 1d6778b..55b2251 100644
--- a/core/java/android/widget/HorizontalScrollView.java
+++ b/core/java/android/widget/HorizontalScrollView.java
@@ -1498,6 +1498,11 @@
      * @return The unconsumed delta after the EdgeEffects have had an opportunity to consume.
      */
     private int consumeFlingInStretch(int unconsumed) {
+        int scrollX = getScrollX();
+        if (scrollX < 0 || scrollX > getScrollRange()) {
+            // We've overscrolled, so don't stretch
+            return unconsumed;
+        }
         if (unconsumed > 0 && mEdgeGlowLeft != null && mEdgeGlowLeft.getDistance() != 0f) {
             int size = getWidth();
             float deltaDistance = -unconsumed * FLING_DESTRETCH_FACTOR / size;
diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java
index b0e5f777..e1de05b 100644
--- a/core/java/android/widget/RemoteViews.java
+++ b/core/java/android/widget/RemoteViews.java
@@ -337,7 +337,7 @@
      *
      * @hide
      */
-    private static final int MAX_ADAPTER_CONVERSION_WAITING_TIME_MS = 2000;
+    private static final int MAX_ADAPTER_CONVERSION_WAITING_TIME_MS = 5000;
 
     /**
      * Application that hosts the remote views.
@@ -4823,7 +4823,7 @@
     public static boolean isAdapterConversionEnabled() {
         return AppGlobals.getIntCoreSetting(
                 SystemUiDeviceConfigFlags.REMOTEVIEWS_ADAPTER_CONVERSION,
-                SystemUiDeviceConfigFlags.REMOTEVIEWS_ADAPTER_CONVERSION_DEFAULT ? 1 : 0) == 1;
+                SystemUiDeviceConfigFlags.REMOTEVIEWS_ADAPTER_CONVERSION_DEFAULT ? 1 : 0) != 0;
     }
 
     /**
@@ -6948,6 +6948,7 @@
             // something is going to start.
             opts.setPendingIntentBackgroundActivityStartMode(
                     ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
+            opts.setPendingIntentBackgroundActivityLaunchAllowedByPermission(true);
             return Pair.create(intent, opts);
         }
     }
diff --git a/core/java/android/widget/RemoteViewsService.java b/core/java/android/widget/RemoteViewsService.java
index d4f4d19..a250a86 100644
--- a/core/java/android/widget/RemoteViewsService.java
+++ b/core/java/android/widget/RemoteViewsService.java
@@ -47,7 +47,7 @@
      *
      * @hide
      */
-    private static final int MAX_NUM_ENTRY = 25;
+    private static final int MAX_NUM_ENTRY = 10;
 
     /**
      * An interface for an adapter between a remote collection view (ListView, GridView, etc) and
diff --git a/core/java/android/widget/ScrollView.java b/core/java/android/widget/ScrollView.java
index eeb6b43..d330ebf 100644
--- a/core/java/android/widget/ScrollView.java
+++ b/core/java/android/widget/ScrollView.java
@@ -1566,6 +1566,11 @@
      * @return The unconsumed delta after the EdgeEffects have had an opportunity to consume.
      */
     private int consumeFlingInStretch(int unconsumed) {
+        int scrollY = getScrollY();
+        if (scrollY < 0 || scrollY > getScrollRange()) {
+            // We've overscrolled, so don't stretch
+            return unconsumed;
+        }
         if (unconsumed > 0 && mEdgeGlowTop != null && mEdgeGlowTop.getDistance() != 0f) {
             int size = getHeight();
             float deltaDistance = -unconsumed * FLING_DESTRETCH_FACTOR / size;
diff --git a/core/java/android/widget/TEST_MAPPING b/core/java/android/widget/TEST_MAPPING
index 107cac2..bc71bee 100644
--- a/core/java/android/widget/TEST_MAPPING
+++ b/core/java/android/widget/TEST_MAPPING
@@ -45,6 +45,17 @@
           "exclude-annotation": "android.platform.test.annotations.AppModeFull"
         }
       ]
+    },
+    {
+      "name": "CtsTextTestCases",
+      "options": [
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        },
+        {
+          "exclude-annotation": "androidx.test.filters.LargeTest"
+        }
+      ]
     }
   ]
 }
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 56349d1..afe7559 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -13202,9 +13202,8 @@
         if (mTextOperationUser == null) {
             return super.isStylusHandwritingAvailable();
         }
-        final int userId = mTextOperationUser.getIdentifier();
         final InputMethodManager imm = getInputMethodManager();
-        return imm.isStylusHandwritingAvailableAsUser(userId);
+        return imm.isStylusHandwritingAvailableAsUser(mTextOperationUser);
     }
 
     @Nullable
@@ -14996,7 +14995,9 @@
     }
 
     boolean canShare() {
-        if (!getContext().canStartActivityForResult() || !isDeviceProvisioned()) {
+        if (!getContext().canStartActivityForResult() || !isDeviceProvisioned()
+                || !getContext().getResources().getBoolean(
+                com.android.internal.R.bool.config_textShareSupported)) {
             return false;
         }
         return canCopy();
diff --git a/core/java/android/window/ConfigurationHelper.java b/core/java/android/window/ConfigurationHelper.java
index 269ce08..e32adcf 100644
--- a/core/java/android/window/ConfigurationHelper.java
+++ b/core/java/android/window/ConfigurationHelper.java
@@ -106,7 +106,7 @@
      * @see WindowManager#getCurrentWindowMetrics()
      * @see WindowManager#getMaximumWindowMetrics()
      */
-    public static boolean shouldUpdateWindowMetricsBounds(@NonNull Configuration currentConfig,
+    private static boolean shouldUpdateWindowMetricsBounds(@NonNull Configuration currentConfig,
             @NonNull Configuration newConfig) {
         final Rect currentBounds = currentConfig.windowConfiguration.getBounds();
         final Rect newBounds = newConfig.windowConfiguration.getBounds();
diff --git a/core/java/android/window/IWindowOrganizerController.aidl b/core/java/android/window/IWindowOrganizerController.aidl
index 534c9de..5ba2f6c 100644
--- a/core/java/android/window/IWindowOrganizerController.aidl
+++ b/core/java/android/window/IWindowOrganizerController.aidl
@@ -80,13 +80,8 @@
      * Finishes a transition. This must be called for all created transitions.
      * @param transitionToken Which transition to finish
      * @param t Changes to make before finishing but in the same SF Transaction. Can be null.
-     * @param callback Called when t is finished applying.
-     * @return An ID for the sync operation (see {@link #applySyncTransaction}. This will be
-     *         negative if no sync transaction was attached (null t or callback)
      */
-    int finishTransition(in IBinder transitionToken,
-            in @nullable WindowContainerTransaction t,
-            in IWindowContainerTransactionCallback callback);
+    void finishTransition(in IBinder transitionToken, in @nullable WindowContainerTransaction t);
 
     /** @return An interface enabling the management of task organizers. */
     ITaskOrganizerController getTaskOrganizerController();
diff --git a/core/java/android/window/ScreenCapture.java b/core/java/android/window/ScreenCapture.java
index 0cc9c64..95e9e86 100644
--- a/core/java/android/window/ScreenCapture.java
+++ b/core/java/android/window/ScreenCapture.java
@@ -23,6 +23,7 @@
 import android.graphics.PixelFormat;
 import android.graphics.Rect;
 import android.hardware.HardwareBuffer;
+import android.os.Build;
 import android.os.IBinder;
 import android.os.Parcel;
 import android.os.Parcelable;
@@ -33,7 +34,7 @@
 
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
-import java.util.function.Consumer;
+import java.util.function.ObjIntConsumer;
 
 /**
  * Handles display and layer captures for the system.
@@ -42,14 +43,14 @@
  */
 public class ScreenCapture {
     private static final String TAG = "ScreenCapture";
-    private static final int SCREENSHOT_WAIT_TIME_S = 1;
+    private static final int SCREENSHOT_WAIT_TIME_S = 4 * Build.HW_TIMEOUT_MULTIPLIER;
 
     private static native int nativeCaptureDisplay(DisplayCaptureArgs captureArgs,
             long captureListener);
     private static native int nativeCaptureLayers(LayerCaptureArgs captureArgs,
             long captureListener);
     private static native long nativeCreateScreenCaptureListener(
-            Consumer<ScreenshotHardwareBuffer> consumer);
+            ObjIntConsumer<ScreenshotHardwareBuffer> consumer);
     private static native void nativeWriteListenerToParcel(long nativeObject, Parcel out);
     private static native long nativeReadListenerFromParcel(Parcel in);
     private static native long getNativeListenerFinalizer();
@@ -695,7 +696,7 @@
         /**
          * @param consumer The callback invoked when the screen capture is complete.
          */
-        public ScreenCaptureListener(Consumer<ScreenshotHardwareBuffer> consumer) {
+        public ScreenCaptureListener(ObjIntConsumer<ScreenshotHardwareBuffer> consumer) {
             mNativeObject = nativeCreateScreenCaptureListener(consumer);
             sRegistry.registerNativeAllocation(this, mNativeObject);
         }
@@ -748,8 +749,13 @@
     public static SynchronousScreenCaptureListener createSyncCaptureListener() {
         ScreenshotHardwareBuffer[] bufferRef = new ScreenshotHardwareBuffer[1];
         CountDownLatch latch = new CountDownLatch(1);
-        Consumer<ScreenshotHardwareBuffer> consumer = buffer -> {
-            bufferRef[0] = buffer;
+        ObjIntConsumer<ScreenshotHardwareBuffer> consumer = (buffer, status) -> {
+            if (status != 0) {
+                bufferRef[0] = null;
+                Log.e(TAG, "Failed to generate screen capture. Error code: " + status);
+            } else {
+                bufferRef[0] = buffer;
+            }
             latch.countDown();
         };
 
@@ -758,12 +764,15 @@
             // it references, the underlying JNI listener holds a weak reference to the consumer.
             // This property exists to ensure the consumer stays alive during the listener's
             // lifetime.
-            private Consumer<ScreenshotHardwareBuffer> mConsumer = consumer;
+            private ObjIntConsumer<ScreenshotHardwareBuffer> mConsumer = consumer;
 
             @Override
             public ScreenshotHardwareBuffer getBuffer() {
                 try {
-                    latch.await(SCREENSHOT_WAIT_TIME_S, TimeUnit.SECONDS);
+                    if (!latch.await(SCREENSHOT_WAIT_TIME_S, TimeUnit.SECONDS)) {
+                        Log.e(TAG, "Timed out waiting for screenshot results");
+                        return null;
+                    }
                     return bufferRef[0];
                 } catch (Exception e) {
                     Log.e(TAG, "Failed to wait for screen capture result", e);
@@ -779,7 +788,7 @@
      * {@link #captureDisplay(DisplayCaptureArgs, ScreenCaptureListener)}
      */
     public abstract static class SynchronousScreenCaptureListener extends ScreenCaptureListener {
-        SynchronousScreenCaptureListener(Consumer<ScreenshotHardwareBuffer> consumer) {
+        SynchronousScreenCaptureListener(ObjIntConsumer<ScreenshotHardwareBuffer> consumer) {
             super(consumer);
         }
 
@@ -787,6 +796,7 @@
          * Get the {@link ScreenshotHardwareBuffer} synchronously. This can be null if the
          * screenshot failed or if there was no callback in {@link #SCREENSHOT_WAIT_TIME_S} seconds.
          */
+        @Nullable
         public abstract ScreenshotHardwareBuffer getBuffer();
     }
 }
diff --git a/core/java/android/window/WindowOrganizer.java b/core/java/android/window/WindowOrganizer.java
index 695d01e..2dc2cbc 100644
--- a/core/java/android/window/WindowOrganizer.java
+++ b/core/java/android/window/WindowOrganizer.java
@@ -115,19 +115,15 @@
      * Finishes a running transition.
      * @param transitionToken The transition to finish. Can't be null.
      * @param t A set of window operations to apply before finishing.
-     * @param callback A sync callback (if provided). See {@link #applySyncTransaction}.
-     * @return An ID for the sync operation if performed. See {@link #applySyncTransaction}.
      *
      * @hide
      */
     @SuppressLint("ExecutorRegistration")
     @RequiresPermission(android.Manifest.permission.MANAGE_ACTIVITY_TASKS)
-    public int finishTransition(@NonNull IBinder transitionToken,
-            @Nullable WindowContainerTransaction t,
-            @Nullable WindowContainerTransactionCallback callback) {
+    public void finishTransition(@NonNull IBinder transitionToken,
+            @Nullable WindowContainerTransaction t) {
         try {
-            return getWindowOrganizerController().finishTransition(transitionToken, t,
-                    callback != null ? callback.mInterface : null);
+            getWindowOrganizerController().finishTransition(transitionToken, t);
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
diff --git a/core/java/android/window/WindowTokenClient.java b/core/java/android/window/WindowTokenClient.java
index 6c11797..c1d1b27 100644
--- a/core/java/android/window/WindowTokenClient.java
+++ b/core/java/android/window/WindowTokenClient.java
@@ -23,12 +23,12 @@
 import android.annotation.MainThread;
 import android.annotation.NonNull;
 import android.app.ActivityThread;
-import android.app.IWindowToken;
 import android.app.ResourcesManager;
 import android.content.Context;
 import android.content.res.CompatibilityInfo;
 import android.content.res.Configuration;
 import android.inputmethodservice.AbstractInputMethodService;
+import android.os.Binder;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.Debug;
@@ -37,6 +37,7 @@
 import android.util.Log;
 
 import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.function.pooled.PooledLambda;
 
 import java.lang.ref.WeakReference;
@@ -52,7 +53,7 @@
  *
  * @hide
  */
-public class WindowTokenClient extends IWindowToken.Stub {
+public class WindowTokenClient extends Binder {
     private static final String TAG = WindowTokenClient.class.getSimpleName();
 
     /**
@@ -95,8 +96,8 @@
      * @param newConfig the updated {@link Configuration}
      * @param newDisplayId the updated {@link android.view.Display} ID
      */
+    @VisibleForTesting
     @MainThread
-    @Override
     public void onConfigurationChanged(Configuration newConfig, int newDisplayId) {
         onConfigurationChanged(newConfig, newDisplayId, true /* shouldReportConfigChange */);
     }
@@ -104,6 +105,7 @@
     /**
      * Posts an {@link #onConfigurationChanged} to the main thread.
      */
+    @VisibleForTesting
     public void postOnConfigurationChanged(@NonNull Configuration newConfig, int newDisplayId) {
         mHandler.post(PooledLambda.obtainRunnable(this::onConfigurationChanged, newConfig,
                 newDisplayId, true /* shouldReportConfigChange */).recycleOnUse());
@@ -119,14 +121,13 @@
      * <p>
      * Note that this method must be executed on the main thread if
      * {@code shouldReportConfigChange} is {@code true}, which is usually from
-     * {@link IWindowToken#onConfigurationChanged(Configuration, int)}
+     * {@link #onConfigurationChanged(Configuration, int)}
      * directly, while this method could be run on any thread if it is used to initialize
      * Context's {@code Configuration} via {@link WindowTokenClientController#attachToDisplayArea}
      * or {@link WindowTokenClientController#attachToDisplayContent}.
      *
      * @param shouldReportConfigChange {@code true} to indicate that the {@code Configuration}
      *                                 should be dispatched to listeners.
-     *
      */
     @AnyThread
     public void onConfigurationChanged(Configuration newConfig, int newDisplayId,
@@ -192,8 +193,11 @@
         }
     }
 
+    /**
+     * Called when the attached window is removed from the display.
+     */
+    @VisibleForTesting
     @MainThread
-    @Override
     public void onWindowTokenRemoved() {
         final Context context = mContextRef.get();
         if (context != null) {
diff --git a/core/java/android/window/WindowTokenClientController.java b/core/java/android/window/WindowTokenClientController.java
index 7a84123..10f6d5e 100644
--- a/core/java/android/window/WindowTokenClientController.java
+++ b/core/java/android/window/WindowTokenClientController.java
@@ -160,7 +160,7 @@
     /** Detaches a {@link WindowTokenClient} from associated WindowContainer if there's one. */
     public void detachIfNeeded(@NonNull WindowTokenClient client) {
         synchronized (mLock) {
-            if (mWindowTokenClientMap.remove(client.asBinder()) == null) {
+            if (mWindowTokenClientMap.remove(client) == null) {
                 return;
             }
         }
@@ -174,7 +174,7 @@
     private void onWindowContextTokenAttached(@NonNull WindowTokenClient client,
             @NonNull WindowContextInfo info, boolean shouldReportConfigChange) {
         synchronized (mLock) {
-            mWindowTokenClientMap.put(client.asBinder(), client);
+            mWindowTokenClientMap.put(client, client);
         }
         if (shouldReportConfigChange) {
             // Should trigger an #onConfigurationChanged callback to the WindowContext. Post the
diff --git a/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java b/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java
index f19f6c7..2efe445 100644
--- a/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java
+++ b/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java
@@ -128,7 +128,7 @@
             DialogStatus.SHOWN,
     })
     /** Denotes the user shortcut type. */
-    private @interface DialogStatus {
+    @interface DialogStatus {
         int NOT_SHOWN = 0;
         int SHOWN  = 1;
     }
@@ -333,12 +333,35 @@
         // Avoid non-a11y users accidentally turning shortcut on without reading this carefully.
         // Put "don't turn on" as the primary action.
         final AlertDialog alertDialog = mFrameworkObjectProvider.getAlertDialogBuilder(
-                // Use SystemUI context so we pick up any theme set in a vendor overlay
-                mFrameworkObjectProvider.getSystemUiContext())
+                        // Use SystemUI context so we pick up any theme set in a vendor overlay
+                        mFrameworkObjectProvider.getSystemUiContext())
                 .setTitle(getShortcutWarningTitle(targets))
                 .setMessage(getShortcutWarningMessage(targets))
                 .setCancelable(false)
-                .setNegativeButton(R.string.accessibility_shortcut_on, null)
+                .setNegativeButton(R.string.accessibility_shortcut_on,
+                        (DialogInterface d, int which) -> {
+                            String targetServices = Settings.Secure.getStringForUser(
+                                    mContext.getContentResolver(),
+                                    Settings.Secure.ACCESSIBILITY_SHORTCUT_TARGET_SERVICE, userId);
+                            String defaultService = mContext.getString(
+                                    R.string.config_defaultAccessibilityService);
+                            // If the targetServices is null, means the user enables a
+                            // shortcut for the default service by triggering the volume keys
+                            // shortcut in the SUW instead of intentionally configuring the
+                            // shortcut on UI.
+                            if (targetServices == null && !TextUtils.isEmpty(defaultService)) {
+                                // The defaultService in the string resource could be a shorten
+                                // form like com.google.android.marvin.talkback/.TalkBackService.
+                                // Converts it to the componentName for consistency before saving
+                                // to the Settings.
+                                final ComponentName configDefaultService =
+                                        ComponentName.unflattenFromString(defaultService);
+                                Settings.Secure.putStringForUser(mContext.getContentResolver(),
+                                        Settings.Secure.ACCESSIBILITY_SHORTCUT_TARGET_SERVICE,
+                                        configDefaultService.flattenToString(),
+                                        userId);
+                            }
+                        })
                 .setPositiveButton(R.string.accessibility_shortcut_off,
                         (DialogInterface d, int which) -> {
                             Settings.Secure.putStringForUser(mContext.getContentResolver(),
diff --git a/core/java/com/android/internal/app/AssistUtils.java b/core/java/com/android/internal/app/AssistUtils.java
index 0ea8014..4261a0f 100644
--- a/core/java/com/android/internal/app/AssistUtils.java
+++ b/core/java/com/android/internal/app/AssistUtils.java
@@ -234,6 +234,23 @@
     }
 
     /**
+     * Allows subscription to {@link android.service.voice.VisualQueryDetectionService} service
+     * status.
+     *
+     * @param listener to receive visual service start/stop events.
+     */
+    public void subscribeVisualQueryRecognitionStatus(IVisualQueryRecognitionStatusListener
+            listener) {
+        try {
+            if (mVoiceInteractionManagerService != null) {
+                mVoiceInteractionManagerService.subscribeVisualQueryRecognitionStatus(listener);
+            }
+        } catch (RemoteException e) {
+            Log.w(TAG, "Failed to register visual query detection start listener", e);
+        }
+    }
+
+    /**
      * Enables visual detection service.
      *
      * @param listener to receive visual attention gained/lost events.
diff --git a/core/java/com/android/internal/app/IHotwordRecognitionStatusCallback.aidl b/core/java/com/android/internal/app/IHotwordRecognitionStatusCallback.aidl
index 3801188..ba87caa 100644
--- a/core/java/com/android/internal/app/IHotwordRecognitionStatusCallback.aidl
+++ b/core/java/com/android/internal/app/IHotwordRecognitionStatusCallback.aidl
@@ -22,6 +22,7 @@
 import android.service.voice.HotwordRejectedResult;
 import android.service.voice.SoundTriggerFailure;
 import android.service.voice.VisualQueryDetectionServiceFailure;
+import com.android.internal.infra.AndroidFuture;
 
 /**
  * @hide
@@ -113,4 +114,9 @@
 
     /** Called when the hotword detection process is restarted */
     void onProcessRestarted();
+
+    /**
+     * Called when a file open request is sent.
+     */
+   void onOpenFile(in String filename, in AndroidFuture future);
 }
diff --git a/core/java/com/android/internal/app/IVisualQueryRecognitionStatusListener.aidl b/core/java/com/android/internal/app/IVisualQueryRecognitionStatusListener.aidl
new file mode 100644
index 0000000..cc49a75
--- /dev/null
+++ b/core/java/com/android/internal/app/IVisualQueryRecognitionStatusListener.aidl
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.app;
+
+
+ oneway interface IVisualQueryRecognitionStatusListener {
+    /**
+     * Called when {@link VisualQueryDetectionService#onStartDetection} is scheduled from the system
+     * server via {@link VoiceInteractionManagerService#StartPerceiving}.
+     */
+    void onStartPerceiving();
+
+    /**
+     * Called when {@link VisualQueryDetectionService#onStopDetection} is scheduled from the system
+     * server via {@link VoiceInteractionManagerService#StopPerceiving}.
+     */
+    void onStopPerceiving();
+ }
\ No newline at end of file
diff --git a/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl b/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
index 24d5afc..314ed69 100644
--- a/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
+++ b/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
@@ -40,6 +40,7 @@
 import com.android.internal.app.IVoiceInteractionSoundTriggerSession;
 import com.android.internal.app.IVoiceInteractor;
 import com.android.internal.app.IVisualQueryDetectionAttentionListener;
+import com.android.internal.app.IVisualQueryRecognitionStatusListener;
 
 interface IVoiceInteractionManagerService {
     void showSession(in Bundle sessionArgs, int flags, String attributionTag);
@@ -325,6 +326,9 @@
     void shutdownHotwordDetectionService();
 
     @EnforcePermission("ACCESS_VOICE_INTERACTION_SERVICE")
+    void subscribeVisualQueryRecognitionStatus(in IVisualQueryRecognitionStatusListener listener);
+
+    @EnforcePermission("ACCESS_VOICE_INTERACTION_SERVICE")
     void enableVisualQueryDetection(in IVisualQueryDetectionAttentionListener Listener);
 
     @EnforcePermission("ACCESS_VOICE_INTERACTION_SERVICE")
diff --git a/core/java/com/android/internal/app/LocaleStore.java b/core/java/com/android/internal/app/LocaleStore.java
index 43d263b..b3b0603 100644
--- a/core/java/com/android/internal/app/LocaleStore.java
+++ b/core/java/com/android/internal/app/LocaleStore.java
@@ -390,12 +390,17 @@
     public static Set<LocaleInfo> transformImeLanguageTagToLocaleInfo(
             List<InputMethodSubtype> list) {
         Set<LocaleInfo> imeLocales = new HashSet<>();
+        Set<String> languageTagSet = new HashSet<>();
         for (InputMethodSubtype subtype : list) {
-            Locale locale = Locale.forLanguageTag(subtype.getLanguageTag());
-            LocaleInfo cacheInfo  = getLocaleInfo(locale, sLocaleCache);
-            LocaleInfo localeInfo = new LocaleInfo(cacheInfo);
-            localeInfo.mSuggestionFlags |= LocaleInfo.SUGGESTION_TYPE_IME_LANGUAGE;
-            imeLocales.add(localeInfo);
+            String languageTag = subtype.getLanguageTag();
+            if (!languageTagSet.contains(languageTag)) {
+                languageTagSet.add(languageTag);
+                Locale locale = Locale.forLanguageTag(languageTag);
+                LocaleInfo cacheInfo = getLocaleInfo(locale, sLocaleCache);
+                LocaleInfo localeInfo = new LocaleInfo(cacheInfo);
+                localeInfo.mSuggestionFlags |= LocaleInfo.SUGGESTION_TYPE_IME_LANGUAGE;
+                imeLocales.add(localeInfo);
+            }
         }
         return imeLocales;
     }
diff --git a/core/java/com/android/internal/app/NetInitiatedActivity.java b/core/java/com/android/internal/app/NetInitiatedActivity.java
deleted file mode 100644
index f34aabb..0000000
--- a/core/java/com/android/internal/app/NetInitiatedActivity.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 2007 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.
- */
-
-package com.android.internal.app;
-
-import static android.view.WindowManager.LayoutParams.SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS;
-
-import android.app.AlertDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.location.LocationManagerInternal;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.util.Log;
-
-import com.android.internal.R;
-import com.android.internal.location.GpsNetInitiatedHandler;
-import com.android.server.LocalServices;
-
-/**
- * This activity is shown to the user for them to accept or deny network-initiated
- * requests. It uses the alert dialog style. It will be launched from a notification.
- */
-public class NetInitiatedActivity extends AlertActivity implements DialogInterface.OnClickListener {
-
-    private static final String TAG = "NetInitiatedActivity";
-
-    private static final boolean DEBUG = true;
-
-    private static final int POSITIVE_BUTTON = AlertDialog.BUTTON_POSITIVE;
-    private static final int NEGATIVE_BUTTON = AlertDialog.BUTTON_NEGATIVE;
-
-    private static final int GPS_NO_RESPONSE_TIME_OUT = 1;
-    // Received ID from intent, -1 when no notification is in progress
-    private int notificationId = -1;
-    private int timeout = -1;
-    private int default_response = -1;
-    private int default_response_timeout = 6;
-
-    private final Handler mHandler = new Handler() {
-        public void handleMessage(Message msg) {
-            switch (msg.what) {
-                case GPS_NO_RESPONSE_TIME_OUT: {
-                    if (notificationId != -1) {
-                        sendUserResponse(default_response);
-                    }
-                    finish();
-                }
-                break;
-                default:
-            }
-        }
-    };
-
-    @Override
-    protected void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-
-        getWindow().addSystemFlags(SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS);
-
-        // Set up the "dialog"
-        final Intent intent = getIntent();
-        final AlertController.AlertParams p = mAlertParams;
-        Context context = getApplicationContext();
-        p.mTitle = intent.getStringExtra(GpsNetInitiatedHandler.NI_INTENT_KEY_TITLE);
-        p.mMessage = intent.getStringExtra(GpsNetInitiatedHandler.NI_INTENT_KEY_MESSAGE);
-        p.mPositiveButtonText = String.format(context.getString(R.string.gpsVerifYes));
-        p.mPositiveButtonListener = this;
-        p.mNegativeButtonText = String.format(context.getString(R.string.gpsVerifNo));
-        p.mNegativeButtonListener = this;
-
-        notificationId = intent.getIntExtra(GpsNetInitiatedHandler.NI_INTENT_KEY_NOTIF_ID, -1);
-        timeout = intent.getIntExtra(GpsNetInitiatedHandler.NI_INTENT_KEY_TIMEOUT, default_response_timeout);
-        default_response = intent.getIntExtra(GpsNetInitiatedHandler.NI_INTENT_KEY_DEFAULT_RESPONSE, GpsNetInitiatedHandler.GPS_NI_RESPONSE_ACCEPT);
-        if (DEBUG) Log.d(TAG, "onCreate() : notificationId: " + notificationId + " timeout: " + timeout + " default_response:" + default_response);
-
-        mHandler.sendMessageDelayed(mHandler.obtainMessage(GPS_NO_RESPONSE_TIME_OUT), (timeout * 1000));
-        setupAlert();
-    }
-
-    @Override
-    protected void onResume() {
-        super.onResume();
-        if (DEBUG) Log.d(TAG, "onResume");
-    }
-
-    @Override
-    protected void onPause() {
-        super.onPause();
-        if (DEBUG) Log.d(TAG, "onPause");
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    public void onClick(DialogInterface dialog, int which) {
-        if (which == POSITIVE_BUTTON) {
-            sendUserResponse(GpsNetInitiatedHandler.GPS_NI_RESPONSE_ACCEPT);
-        }
-        if (which == NEGATIVE_BUTTON) {
-            sendUserResponse(GpsNetInitiatedHandler.GPS_NI_RESPONSE_DENY);
-        }
-
-        // No matter what, finish the activity
-        finish();
-        notificationId = -1;
-    }
-
-    // Respond to NI Handler under GnssLocationProvider, 1 = accept, 2 = deny
-    private void sendUserResponse(int response) {
-        if (DEBUG) Log.d(TAG, "sendUserResponse, response: " + response);
-        LocationManagerInternal lm = LocalServices.getService(LocationManagerInternal.class);
-        lm.sendNiResponse(notificationId, response);
-    }
-}
diff --git a/core/java/com/android/internal/app/ResolverActivity.java b/core/java/com/android/internal/app/ResolverActivity.java
index 2445daf..ac15f11 100644
--- a/core/java/com/android/internal/app/ResolverActivity.java
+++ b/core/java/com/android/internal/app/ResolverActivity.java
@@ -40,6 +40,7 @@
 
 import static com.android.internal.annotations.VisibleForTesting.Visibility.PROTECTED;
 
+import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.StringRes;
 import android.annotation.UiThread;
@@ -68,6 +69,7 @@
 import android.content.res.Configuration;
 import android.content.res.TypedArray;
 import android.graphics.Insets;
+import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
 import android.net.Uri;
 import android.os.AsyncTask;
@@ -93,6 +95,7 @@
 import android.view.Window;
 import android.view.WindowInsets;
 import android.view.WindowManager;
+import android.view.accessibility.AccessibilityEvent;
 import android.widget.AbsListView;
 import android.widget.AdapterView;
 import android.widget.Button;
@@ -488,6 +491,14 @@
             rdl.setOnApplyWindowInsetsListener(this::onApplyWindowInsets);
 
             mResolverDrawerLayout = rdl;
+
+            for (int i = 0, size = mMultiProfilePagerAdapter.getCount(); i < size; i++) {
+                View view = mMultiProfilePagerAdapter.getItem(i).rootView.findViewById(
+                        R.id.resolver_list);
+                if (view != null) {
+                    view.setAccessibilityDelegate(new AppListAccessibilityDelegate(rdl));
+                }
+            }
         }
 
         mProfileView = findViewById(R.id.profile_button);
@@ -2607,4 +2618,41 @@
         }
         return resolveInfo.userHandle;
     }
+
+    /**
+     * An a11y delegate that expands resolver drawer when gesture navigation reaches a partially
+     * invisible target in the list.
+     */
+    private static class AppListAccessibilityDelegate extends View.AccessibilityDelegate {
+        private final ResolverDrawerLayout mDrawer;
+        @Nullable
+        private final View mBottomBar;
+        private final Rect mRect = new Rect();
+
+        private AppListAccessibilityDelegate(ResolverDrawerLayout drawer) {
+            mDrawer = drawer;
+            mBottomBar = mDrawer.findViewById(R.id.button_bar_container);
+        }
+
+        @Override
+        public boolean onRequestSendAccessibilityEvent(@androidx.annotation.NonNull ViewGroup host,
+                @NonNull View child,
+                @NonNull AccessibilityEvent event) {
+            boolean result = super.onRequestSendAccessibilityEvent(host, child, event);
+            if (result && event.getEventType() == AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
+                    && mDrawer.isCollapsed()) {
+                child.getBoundsOnScreen(mRect);
+                int childTop = mRect.top;
+                int childBottom = mRect.bottom;
+                mDrawer.getBoundsOnScreen(mRect, true);
+                int bottomBarHeight = mBottomBar == null ? 0 : mBottomBar.getHeight();
+                int drawerTop = mRect.top;
+                int drawerBottom = mRect.bottom - bottomBarHeight;
+                if (drawerTop > childTop || childBottom > drawerBottom) {
+                    mDrawer.setCollapsed(false);
+                }
+            }
+            return result;
+        }
+    }
 }
diff --git a/core/java/com/android/internal/app/SuspendedAppActivity.java b/core/java/com/android/internal/app/SuspendedAppActivity.java
index a5e775a..1e0b2a0 100644
--- a/core/java/com/android/internal/app/SuspendedAppActivity.java
+++ b/core/java/com/android/internal/app/SuspendedAppActivity.java
@@ -297,7 +297,7 @@
                         final IPackageManager ipm = AppGlobals.getPackageManager();
                         try {
                             final String[] errored = ipm.setPackagesSuspendedAsUser(
-                                    new String[]{mSuspendedPackage}, false, null, null, null,
+                                    new String[]{mSuspendedPackage}, false, null, null, null, 0,
                                     mSuspendingPackage, mUserId);
                             if (ArrayUtils.contains(errored, mSuspendedPackage)) {
                                 Slog.e(TAG, "Could not unsuspend " + mSuspendedPackage);
diff --git a/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java b/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java
index a2c4b23..0a69ea8 100644
--- a/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java
+++ b/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java
@@ -534,7 +534,14 @@
     /**
      * (boolean) Whether to enable the adapter conversion in RemoteViews
      */
-    public static final String REMOTEVIEWS_ADAPTER_CONVERSION = "remoteviews_adapter_conversion";
+    public static final String REMOTEVIEWS_ADAPTER_CONVERSION =
+            "CursorControlFeature__remoteviews_adapter_conversion";
+
+    /**
+     * The key name used in app core settings for {@link #REMOTEVIEWS_ADAPTER_CONVERSION}
+     */
+    public static final String KEY_REMOTEVIEWS_ADAPTER_CONVERSION =
+            "systemui__remoteviews_adapter_conversion";
 
     /**
      * Default value for whether the adapter conversion is enabled or not. This is set for
diff --git a/core/java/com/android/internal/config/sysui/SystemUiSystemPropertiesFlags.java b/core/java/com/android/internal/config/sysui/SystemUiSystemPropertiesFlags.java
index 10336bd..9233050 100644
--- a/core/java/com/android/internal/config/sysui/SystemUiSystemPropertiesFlags.java
+++ b/core/java/com/android/internal/config/sysui/SystemUiSystemPropertiesFlags.java
@@ -70,10 +70,6 @@
         public static final Flag OTP_REDACTION =
                 devFlag("persist.sysui.notification.otp_redaction");
 
-        /** Gating the removal of sorting-notifications-by-interruptiveness. */
-        public static final Flag NO_SORT_BY_INTERRUPTIVENESS =
-                releasedFlag("persist.sysui.notification.no_sort_by_interruptiveness");
-
         /** Gating the logging of DND state change events. */
         public static final Flag LOG_DND_STATE_EVENTS =
                 releasedFlag("persist.sysui.notification.log_dnd_state_events");
@@ -86,7 +82,7 @@
         public static final Flag RANKING_UPDATE_ASHMEM = devFlag(
                 "persist.sysui.notification.ranking_update_ashmem");
 
-        public static final Flag PROPAGATE_CHANNEL_UPDATES_TO_CONVERSATIONS = devFlag(
+        public static final Flag PROPAGATE_CHANNEL_UPDATES_TO_CONVERSATIONS = releasedFlag(
                 "persist.sysui.notification.propagate_channel_updates_to_conversations");
     }
 
diff --git a/core/java/com/android/internal/os/BatteryStatsHistory.java b/core/java/com/android/internal/os/BatteryStatsHistory.java
index 0a938ef4..79152b4 100644
--- a/core/java/com/android/internal/os/BatteryStatsHistory.java
+++ b/core/java/com/android/internal/os/BatteryStatsHistory.java
@@ -185,7 +185,7 @@
     private boolean mHaveBatteryLevel;
     private boolean mRecordingHistory;
 
-    private static final int HISTORY_TAG_INDEX_LIMIT = 0x7ffe;
+    static final int HISTORY_TAG_INDEX_LIMIT = 0x7ffe;
     private static final int MAX_HISTORY_TAG_STRING_LENGTH = 1024;
 
     private final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
@@ -1872,6 +1872,7 @@
             }
             return idx | BatteryStatsHistory.TAG_FIRST_OCCURRENCE_FLAG;
         } else {
+            tag.poolIdx = HistoryTag.HISTORY_TAG_POOL_OVERFLOW;
             // Tag pool overflow: include the tag itself in the parcel
             return HISTORY_TAG_INDEX_LIMIT | BatteryStatsHistory.TAG_FIRST_OCCURRENCE_FLAG;
         }
diff --git a/core/java/com/android/internal/os/BatteryStatsHistoryIterator.java b/core/java/com/android/internal/os/BatteryStatsHistoryIterator.java
index ccc3454..4c2b2854 100644
--- a/core/java/com/android/internal/os/BatteryStatsHistoryIterator.java
+++ b/core/java/com/android/internal/os/BatteryStatsHistoryIterator.java
@@ -309,7 +309,11 @@
             BatteryStats.HistoryTag tag = new BatteryStats.HistoryTag();
             tag.readFromParcel(src);
             tag.poolIdx = index & ~BatteryStatsHistory.TAG_FIRST_OCCURRENCE_FLAG;
-            mHistoryTags.put(tag.poolIdx, tag);
+            if (tag.poolIdx < BatteryStatsHistory.HISTORY_TAG_INDEX_LIMIT) {
+                mHistoryTags.put(tag.poolIdx, tag);
+            } else {
+                tag.poolIdx = BatteryStats.HistoryTag.HISTORY_TAG_POOL_OVERFLOW;
+            }
 
             outTag.setTo(tag);
         } else {
diff --git a/core/java/com/android/internal/os/TEST_MAPPING b/core/java/com/android/internal/os/TEST_MAPPING
index 60b160a..d552e0b 100644
--- a/core/java/com/android/internal/os/TEST_MAPPING
+++ b/core/java/com/android/internal/os/TEST_MAPPING
@@ -38,11 +38,18 @@
       ],
       "name": "FrameworksServicesTests",
       "options": [
-        { "include-filter": "com.android.server.am.BatteryStatsServiceTest" },
-        { "include-filter": "com.android.server.power.stats.BatteryStatsTests" }
+        { "include-filter": "com.android.server.am.BatteryStatsServiceTest" }
       ]
     },
     {
+      "file_patterns": [
+        "Battery[^/]*\\.java",
+        "Kernel[^/]*\\.java",
+        "[^/]*Power[^/]*\\.java"
+      ],
+      "name": "PowerStatsTests"
+    },
+    {
       "name": "FrameworksCoreTests",
       "options": [
         {
diff --git a/core/java/com/android/internal/power/TEST_MAPPING b/core/java/com/android/internal/power/TEST_MAPPING
index c6cab18..1946f5c 100644
--- a/core/java/com/android/internal/power/TEST_MAPPING
+++ b/core/java/com/android/internal/power/TEST_MAPPING
@@ -8,11 +8,7 @@
       ]
     },
     {
-      "name": "FrameworksServicesTests",
-      "options": [
-        { "include-filter": "com.android.server.am.BatteryStatsServiceTest" },
-        { "include-filter": "com.android.server.power.stats.BatteryStatsTests" }
-      ]
+      "name": "PowerStatsTests"
     }
   ]
 }
diff --git a/core/java/com/android/internal/util/NotificationMessagingUtil.java b/core/java/com/android/internal/util/NotificationMessagingUtil.java
index d3cc0e7..10856b3 100644
--- a/core/java/com/android/internal/util/NotificationMessagingUtil.java
+++ b/core/java/com/android/internal/util/NotificationMessagingUtil.java
@@ -16,6 +16,7 @@
 
 package com.android.internal.util;
 
+import android.annotation.Nullable;
 import android.app.Notification;
 import android.app.NotificationManager;
 import android.content.Context;
@@ -39,10 +40,12 @@
 
     private static final String DEFAULT_SMS_APP_SETTING = Settings.Secure.SMS_DEFAULT_APPLICATION;
     private final Context mContext;
-    private SparseArray<String> mDefaultSmsApp = new SparseArray<>();
+    private final SparseArray<String> mDefaultSmsApp = new SparseArray<>();
+    private final Object mStateLock;
 
-    public NotificationMessagingUtil(Context context) {
+    public NotificationMessagingUtil(Context context, @Nullable Object stateLock) {
         mContext = context;
+        mStateLock = stateLock != null ? stateLock : new Object();
         mContext.getContentResolver().registerContentObserver(
                 Settings.Secure.getUriFor(DEFAULT_SMS_APP_SETTING), false, mSmsContentObserver);
     }
@@ -63,16 +66,20 @@
     private boolean isDefaultMessagingApp(StatusBarNotification sbn) {
         final int userId = sbn.getUserId();
         if (userId == UserHandle.USER_NULL || userId == UserHandle.USER_ALL) return false;
-        if (mDefaultSmsApp.get(userId) == null) {
-            cacheDefaultSmsApp(userId);
+        synchronized (mStateLock) {
+            if (mDefaultSmsApp.get(userId) == null) {
+                cacheDefaultSmsApp(userId);
+            }
+            return Objects.equals(mDefaultSmsApp.get(userId), sbn.getPackageName());
         }
-        return Objects.equals(mDefaultSmsApp.get(userId), sbn.getPackageName());
     }
 
     private void cacheDefaultSmsApp(int userId) {
-        mDefaultSmsApp.put(userId, Settings.Secure.getStringForUser(
-                mContext.getContentResolver(),
-                Settings.Secure.SMS_DEFAULT_APPLICATION, userId));
+        String smsApp = Settings.Secure.getStringForUser(mContext.getContentResolver(),
+                Settings.Secure.SMS_DEFAULT_APPLICATION, userId);
+        synchronized (mStateLock) {
+            mDefaultSmsApp.put(userId, smsApp);
+        }
     }
 
     private final ContentObserver mSmsContentObserver = new ContentObserver(
diff --git a/core/java/com/android/internal/widget/BigPictureNotificationImageView.java b/core/java/com/android/internal/widget/BigPictureNotificationImageView.java
index 3a7cf74..f95f5db 100644
--- a/core/java/com/android/internal/widget/BigPictureNotificationImageView.java
+++ b/core/java/com/android/internal/widget/BigPictureNotificationImageView.java
@@ -37,13 +37,16 @@
  * Icon.loadDrawable().
  */
 @RemoteViews.RemoteView
-public class BigPictureNotificationImageView extends ImageView {
+public class BigPictureNotificationImageView extends ImageView implements
+        NotificationDrawableConsumer {
 
     private static final String TAG = BigPictureNotificationImageView.class.getSimpleName();
 
     private final int mMaximumDrawableWidth;
     private final int mMaximumDrawableHeight;
 
+    private NotificationIconManager mIconManager;
+
     public BigPictureNotificationImageView(@NonNull Context context) {
         this(context, null, 0, 0);
     }
@@ -69,6 +72,19 @@
                         : R.dimen.notification_big_picture_max_height);
     }
 
+
+    /**
+     * Sets an {@link NotificationIconManager} on this ImageView, which handles the loading of
+     * icons, instead of using the {@link LocalImageResolver} directly.
+     * If set, it overrides the behaviour of {@link #setImageIconAsync} and {@link #setImageIcon},
+     * and it expects that the content of this imageView is only updated calling these two methods.
+     *
+     * @param iconManager to be called, when the icon is updated
+     */
+    public void setIconManager(NotificationIconManager iconManager) {
+        mIconManager = iconManager;
+    }
+
     @Override
     @android.view.RemotableViewMethod(asyncImpl = "setImageURIAsync")
     public void setImageURI(@Nullable Uri uri) {
@@ -84,11 +100,20 @@
     @Override
     @android.view.RemotableViewMethod(asyncImpl = "setImageIconAsync")
     public void setImageIcon(@Nullable Icon icon) {
+        if (mIconManager != null) {
+            mIconManager.updateIcon(this, icon).run();
+            return;
+        }
+        // old code path
         setImageDrawable(loadImage(icon));
     }
 
     /** @hide **/
     public Runnable setImageIconAsync(@Nullable Icon icon) {
+        if (mIconManager != null) {
+            return mIconManager.updateIcon(this, icon);
+        }
+        // old code path
         final Drawable drawable = loadImage(icon);
         return () -> setImageDrawable(drawable);
     }
diff --git a/core/java/com/android/internal/widget/ConversationLayout.java b/core/java/com/android/internal/widget/ConversationLayout.java
index 635adca..5b6b360 100644
--- a/core/java/com/android/internal/widget/ConversationLayout.java
+++ b/core/java/com/android/internal/widget/ConversationLayout.java
@@ -383,7 +383,11 @@
         updateContentEndPaddings();
     }
 
-    @RemotableViewMethod
+    /**
+     * Set conversation data
+     * @param extras Bundle contains conversation data
+     */
+    @RemotableViewMethod(asyncImpl = "setDataAsync")
     public void setData(Bundle extras) {
         Parcelable[] messages = extras.getParcelableArray(Notification.EXTRA_MESSAGES);
         List<Notification.MessagingStyle.Message> newMessages
@@ -393,8 +397,7 @@
                 = Notification.MessagingStyle.Message.getMessagesFromBundleArray(histMessages);
 
         // mUser now set (would be nice to avoid the side effect but WHATEVER)
-        setUser(extras.getParcelable(Notification.EXTRA_MESSAGING_PERSON, android.app.Person.class));
-
+        final Person user = extras.getParcelable(Notification.EXTRA_MESSAGING_PERSON, Person.class);
         // Append remote input history to newMessages (again, side effect is lame but WHATEVS)
         RemoteInputHistoryItem[] history = (RemoteInputHistoryItem[])
                 extras.getParcelableArray(Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS, android.app.RemoteInputHistoryItem.class);
@@ -402,11 +405,32 @@
 
         boolean showSpinner =
                 extras.getBoolean(Notification.EXTRA_SHOW_REMOTE_INPUT_SPINNER, false);
-        // bind it, baby
-        bind(newMessages, newHistoricMessages, showSpinner);
-
         int unreadCount = extras.getInt(Notification.EXTRA_CONVERSATION_UNREAD_MESSAGE_COUNT);
-        setUnreadCount(unreadCount);
+
+        // convert MessagingStyle.Message to MessagingMessage, re-using ones from a previous binding
+        // if they exist
+        final List<MessagingMessage> newMessagingMessages =
+                createMessages(newMessages, /* isHistoric= */false,
+                        /* usePrecomputedText= */false);
+        final List<MessagingMessage> newHistoricMessagingMessages =
+                createMessages(newHistoricMessages, /* isHistoric= */true,
+                        /* usePrecomputedText= */false);
+        // bind it, baby
+        bindViews(user, showSpinner, unreadCount,
+                newMessagingMessages,
+                newHistoricMessagingMessages);
+    }
+
+    /**
+     * RemotableViewMethod's asyncImpl of {@link #setData(Bundle)}.
+     * This should be called on a background thread, and returns a Runnable which is then must be
+     * called on the main thread to complete the operation and set text.
+     * @param extras Bundle contains conversation data
+     * @hide
+     */
+    @NonNull
+    public Runnable setDataAsync(Bundle extras) {
+        return () -> setData(extras);
     }
 
     @Override
@@ -436,15 +460,17 @@
         }
     }
 
-    private void bind(List<Notification.MessagingStyle.Message> newMessages,
-            List<Notification.MessagingStyle.Message> newHistoricMessages,
-            boolean showSpinner) {
-        // convert MessagingStyle.Message to MessagingMessage, re-using ones from a previous binding
-        // if they exist
-        List<MessagingMessage> historicMessages = createMessages(newHistoricMessages,
-                true /* isHistoric */);
-        List<MessagingMessage> messages = createMessages(newMessages, false /* isHistoric */);
 
+    private void bindViews(Person user,
+            boolean showSpinner, int unreadCount, List<MessagingMessage> newMessagingMessages,
+            List<MessagingMessage> newHistoricMessagingMessages) {
+        setUser(user);
+        setUnreadCount(unreadCount);
+        bind(showSpinner, newMessagingMessages, newHistoricMessagingMessages);
+    }
+
+    private void bind(boolean showSpinner, List<MessagingMessage> messages,
+            List<MessagingMessage> historicMessages) {
         // Copy our groups, before they get clobbered
         ArrayList<MessagingGroup> oldGroups = new ArrayList<>(mGroups);
 
@@ -957,15 +983,17 @@
      * @param newMessages the messages to parse.
      */
     private List<MessagingMessage> createMessages(
-            List<Notification.MessagingStyle.Message> newMessages, boolean historic) {
+            List<Notification.MessagingStyle.Message> newMessages, boolean isHistoric,
+            boolean usePrecomputedText) {
         List<MessagingMessage> result = new ArrayList<>();
         for (int i = 0; i < newMessages.size(); i++) {
             Notification.MessagingStyle.Message m = newMessages.get(i);
             MessagingMessage message = findAndRemoveMatchingMessage(m);
             if (message == null) {
-                message = MessagingMessage.createMessage(this, m, mImageResolver);
+                message = MessagingMessage.createMessage(this, m,
+                        mImageResolver, usePrecomputedText);
             }
-            message.setIsHistoric(historic);
+            message.setIsHistoric(isHistoric);
             result.add(message);
         }
         return result;
diff --git a/core/java/com/android/internal/widget/ImageFloatingTextView.java b/core/java/com/android/internal/widget/ImageFloatingTextView.java
index de10bd2..0704cb8 100644
--- a/core/java/com/android/internal/widget/ImageFloatingTextView.java
+++ b/core/java/com/android/internal/widget/ImageFloatingTextView.java
@@ -63,6 +63,8 @@
     public ImageFloatingTextView(Context context, AttributeSet attrs, int defStyleAttr,
             int defStyleRes) {
         super(context, attrs, defStyleAttr, defStyleRes);
+        setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_FULL_FAST);
+        setBreakStrategy(Layout.BREAK_STRATEGY_HIGH_QUALITY);
     }
 
     @Override
@@ -83,8 +85,8 @@
                 .setLineSpacing(getLineSpacingExtra(), getLineSpacingMultiplier())
                 .setIncludePad(getIncludeFontPadding())
                 .setUseLineSpacingFromFallbacks(true)
-                .setBreakStrategy(Layout.BREAK_STRATEGY_HIGH_QUALITY)
-                .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_FULL_FAST);
+                .setBreakStrategy(getBreakStrategy())
+                .setHyphenationFrequency(getHyphenationFrequency());
         int maxLines;
         if (mMaxLinesForHeight > 0) {
             maxLines = mMaxLinesForHeight;
diff --git a/core/java/com/android/internal/widget/MessagingImageMessage.java b/core/java/com/android/internal/widget/MessagingImageMessage.java
index 098bce1..c132d6a 100644
--- a/core/java/com/android/internal/widget/MessagingImageMessage.java
+++ b/core/java/com/android/internal/widget/MessagingImageMessage.java
@@ -93,8 +93,9 @@
     }
 
     @Override
-    public boolean setMessage(Notification.MessagingStyle.Message message) {
-        MessagingMessage.super.setMessage(message);
+    public boolean setMessage(Notification.MessagingStyle.Message message,
+            boolean usePrecomputedText) {
+        MessagingMessage.super.setMessage(message, usePrecomputedText);
         Drawable drawable;
         try {
             Uri uri = message.getDataUri();
@@ -114,32 +115,42 @@
         }
         mDrawable = drawable;
         mAspectRatio = ((float) mDrawable.getIntrinsicWidth()) / intrinsicHeight;
-        setImageDrawable(drawable);
-        setContentDescription(message.getText());
+        if (!usePrecomputedText) {
+            finalizeInflate();
+        }
         return true;
     }
 
     static MessagingMessage createMessage(IMessagingLayout layout,
-            Notification.MessagingStyle.Message m, ImageResolver resolver) {
+            Notification.MessagingStyle.Message m, ImageResolver resolver,
+            boolean usePrecomputedText) {
         MessagingLinearLayout messagingLinearLayout = layout.getMessagingLinearLayout();
         MessagingImageMessage createdMessage = sInstancePool.acquire();
         if (createdMessage == null) {
             createdMessage = (MessagingImageMessage) LayoutInflater.from(
                     layout.getContext()).inflate(
-                            R.layout.notification_template_messaging_image_message,
-                            messagingLinearLayout,
-                            false);
+                    R.layout.notification_template_messaging_image_message,
+                    messagingLinearLayout,
+                    false);
             createdMessage.addOnLayoutChangeListener(MessagingLayout.MESSAGING_PROPERTY_ANIMATOR);
         }
         createdMessage.setImageResolver(resolver);
-        boolean created = createdMessage.setMessage(m);
-        if (!created) {
+        // MessagingImageMessage does not use usePrecomputedText.
+        boolean populated = createdMessage.setMessage(m, /* usePrecomputedText= */false);
+        if (!populated) {
             createdMessage.recycle();
-            return MessagingTextMessage.createMessage(layout, m);
+            return MessagingTextMessage.createMessage(layout, m, usePrecomputedText);
         }
         return createdMessage;
     }
 
+
+    @Override
+    public void finalizeInflate() {
+        setImageDrawable(mDrawable);
+        setContentDescription(getMessage().getText());
+    }
+
     private void setImageResolver(ImageResolver resolver) {
         mImageResolver = resolver;
     }
diff --git a/core/java/com/android/internal/widget/MessagingLayout.java b/core/java/com/android/internal/widget/MessagingLayout.java
index 9d142f6..83557cd 100644
--- a/core/java/com/android/internal/widget/MessagingLayout.java
+++ b/core/java/com/android/internal/widget/MessagingLayout.java
@@ -156,7 +156,11 @@
         mConversationTitle = conversationTitle;
     }
 
-    @RemotableViewMethod
+    /**
+     * Set Messaging data
+     * @param extras Bundle contains messaging data
+     */
+    @RemotableViewMethod(asyncImpl = "setDataAsync")
     public void setData(Bundle extras) {
         Parcelable[] messages = extras.getParcelableArray(Notification.EXTRA_MESSAGES);
         List<Notification.MessagingStyle.Message> newMessages
@@ -168,9 +172,28 @@
         RemoteInputHistoryItem[] history = (RemoteInputHistoryItem[])
                 extras.getParcelableArray(Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS, android.app.RemoteInputHistoryItem.class);
         addRemoteInputHistoryToMessages(newMessages, history);
+
+        final Person user = extras.getParcelable(Notification.EXTRA_MESSAGING_PERSON, Person.class);
         boolean showSpinner =
                 extras.getBoolean(Notification.EXTRA_SHOW_REMOTE_INPUT_SPINNER, false);
-        bind(newMessages, newHistoricMessages, showSpinner);
+
+        final List<MessagingMessage> historicMessagingMessages = createMessages(newHistoricMessages,
+                /* isHistoric= */true, /* usePrecomputedText= */ false);
+        final List<MessagingMessage> newMessagingMessages =
+                createMessages(newMessages, /* isHistoric= */false, /* usePrecomputedText= */false);
+        bindViews(user, showSpinner, historicMessagingMessages, newMessagingMessages);
+    }
+
+    /**
+     * RemotableViewMethod's asyncImpl of {@link #setData(Bundle)}.
+     * This should be called on a background thread, and returns a Runnable which is then must be
+     * called on the main thread to complete the operation and set text.
+     * @param extras Bundle contains messaging data
+     * @hide
+     */
+    @NonNull
+    public Runnable setDataAsync(Bundle extras) {
+        return () -> setData(extras);
     }
 
     @Override
@@ -195,14 +218,15 @@
         }
     }
 
-    private void bind(List<Notification.MessagingStyle.Message> newMessages,
-            List<Notification.MessagingStyle.Message> newHistoricMessages,
-            boolean showSpinner) {
+    private void bindViews(Person user, boolean showSpinner,
+            List<MessagingMessage> historicMessagingMessages,
+            List<MessagingMessage> newMessagingMessages) {
+        setUser(user);
+        bind(showSpinner, historicMessagingMessages, newMessagingMessages);
+    }
 
-        List<MessagingMessage> historicMessages = createMessages(newHistoricMessages,
-                true /* isHistoric */);
-        List<MessagingMessage> messages = createMessages(newMessages, false /* isHistoric */);
-
+    private void bind(boolean showSpinner, List<MessagingMessage> historicMessages,
+            List<MessagingMessage> messages) {
         ArrayList<MessagingGroup> oldGroups = new ArrayList<>(mGroups);
         addMessagesToGroups(historicMessages, messages, showSpinner);
 
@@ -494,15 +518,17 @@
      * @param newMessages the messages to parse.
      */
     private List<MessagingMessage> createMessages(
-            List<Notification.MessagingStyle.Message> newMessages, boolean historic) {
+            List<Notification.MessagingStyle.Message> newMessages, boolean isHistoric,
+            boolean usePrecomputedText) {
         List<MessagingMessage> result = new ArrayList<>();
         for (int i = 0; i < newMessages.size(); i++) {
             Notification.MessagingStyle.Message m = newMessages.get(i);
             MessagingMessage message = findAndRemoveMatchingMessage(m);
             if (message == null) {
-                message = MessagingMessage.createMessage(this, m, mImageResolver);
+                message = MessagingMessage.createMessage(this, m,
+                        mImageResolver, usePrecomputedText);
             }
-            message.setIsHistoric(historic);
+            message.setIsHistoric(isHistoric);
             result.add(message);
         }
         return result;
diff --git a/core/java/com/android/internal/widget/MessagingMessage.java b/core/java/com/android/internal/widget/MessagingMessage.java
index 5ecd3b8..ad90a63 100644
--- a/core/java/com/android/internal/widget/MessagingMessage.java
+++ b/core/java/com/android/internal/widget/MessagingMessage.java
@@ -34,11 +34,12 @@
     String IMAGE_MIME_TYPE_PREFIX = "image/";
 
     static MessagingMessage createMessage(IMessagingLayout layout,
-            Notification.MessagingStyle.Message m, ImageResolver resolver) {
+            Notification.MessagingStyle.Message m, ImageResolver resolver,
+            boolean usePrecomputedText) {
         if (hasImage(m) && !ActivityManager.isLowRamDeviceStatic()) {
-            return MessagingImageMessage.createMessage(layout, m, resolver);
+            return MessagingImageMessage.createMessage(layout, m, resolver, usePrecomputedText);
         } else {
-            return MessagingTextMessage.createMessage(layout, m);
+            return MessagingTextMessage.createMessage(layout, m, usePrecomputedText);
         }
     }
 
@@ -55,9 +56,11 @@
 
     /**
      * Set a message for this view.
+     *
      * @return true if setting the message worked
      */
-    default boolean setMessage(Notification.MessagingStyle.Message message) {
+    default boolean setMessage(Notification.MessagingStyle.Message message,
+            boolean usePrecomputedText) {
         getState().setMessage(message);
         return true;
     }
@@ -151,4 +154,10 @@
     void setVisibility(int visibility);
 
     int getVisibility();
+
+    /**
+     * Finalize inflation of the MessagingMessages, which should be called on Main Thread.
+     * @hide
+     */
+    void finalizeInflate();
 }
diff --git a/core/java/com/android/internal/widget/MessagingTextMessage.java b/core/java/com/android/internal/widget/MessagingTextMessage.java
index 19791db..bd62aad 100644
--- a/core/java/com/android/internal/widget/MessagingTextMessage.java
+++ b/core/java/com/android/internal/widget/MessagingTextMessage.java
@@ -23,7 +23,9 @@
 import android.app.Notification;
 import android.content.Context;
 import android.text.Layout;
+import android.text.PrecomputedText;
 import android.util.AttributeSet;
+import android.util.Log;
 import android.view.LayoutInflater;
 import android.widget.RemoteViews;
 
@@ -35,10 +37,13 @@
 @RemoteViews.RemoteView
 public class MessagingTextMessage extends ImageFloatingTextView implements MessagingMessage {
 
+    private static final String TAG = "MessagingTextMessage";
     private static final MessagingPool<MessagingTextMessage> sInstancePool =
             new MessagingPool<>(20);
     private final MessagingMessageState mState = new MessagingMessageState(this);
 
+    private PrecomputedText mPrecomputedText = null;
+
     public MessagingTextMessage(@NonNull Context context) {
         super(context);
     }
@@ -63,25 +68,32 @@
     }
 
     @Override
-    public boolean setMessage(Notification.MessagingStyle.Message message) {
-        MessagingMessage.super.setMessage(message);
-        setText(message.getText());
+    public boolean setMessage(Notification.MessagingStyle.Message message,
+            boolean usePrecomputedText) {
+        MessagingMessage.super.setMessage(message, usePrecomputedText);
+        if (usePrecomputedText) {
+            mPrecomputedText = PrecomputedText.create(message.getText(), getTextMetricsParams());
+        } else {
+            setText(message.getText());
+            mPrecomputedText = null;
+        }
+
         return true;
     }
 
     static MessagingMessage createMessage(IMessagingLayout layout,
-            Notification.MessagingStyle.Message m) {
+            Notification.MessagingStyle.Message m, boolean usePrecomputedText) {
         MessagingLinearLayout messagingLinearLayout = layout.getMessagingLinearLayout();
         MessagingTextMessage createdMessage = sInstancePool.acquire();
         if (createdMessage == null) {
             createdMessage = (MessagingTextMessage) LayoutInflater.from(
                     layout.getContext()).inflate(
-                            R.layout.notification_template_messaging_text_message,
-                            messagingLinearLayout,
-                            false);
+                    R.layout.notification_template_messaging_text_message,
+                    messagingLinearLayout,
+                    false);
             createdMessage.addOnLayoutChangeListener(MessagingLayout.MESSAGING_PROPERTY_ANIMATOR);
         }
-        createdMessage.setMessage(m);
+        createdMessage.setMessage(m, usePrecomputedText);
         return createdMessage;
     }
 
@@ -135,4 +147,20 @@
     public void setColor(int color) {
         setTextColor(color);
     }
+
+    @Override
+    public void finalizeInflate() {
+        try {
+            setText(mPrecomputedText != null ? mPrecomputedText
+                    : getState().getMessage().getText());
+        } catch (IllegalArgumentException exception) {
+            Log.wtf(
+                    /* tag = */ TAG,
+                    /* msg = */ "PrecomputedText setText failed for TextView:" + this,
+                    /* tr = */ exception
+            );
+            mPrecomputedText = null;
+            setText(getState().getMessage().getText());
+        }
+    }
 }
diff --git a/core/java/com/android/internal/widget/NotificationDrawableConsumer.java b/core/java/com/android/internal/widget/NotificationDrawableConsumer.java
new file mode 100644
index 0000000..7c4d929
--- /dev/null
+++ b/core/java/com/android/internal/widget/NotificationDrawableConsumer.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.widget;
+
+import android.graphics.drawable.Drawable;
+
+import androidx.annotation.Nullable;
+
+/**
+ * An interface for the class, who will use {@link NotificationIconManager} to load icons.
+ */
+public interface NotificationDrawableConsumer {
+
+    /**
+     * Sets a drawable as the content of this consumer.
+     *
+     * @param drawable the {@link Drawable} to set, or {@code null} to clear the content
+     */
+    void setImageDrawable(@Nullable Drawable drawable);
+}
diff --git a/core/java/com/android/internal/widget/NotificationIconManager.java b/core/java/com/android/internal/widget/NotificationIconManager.java
new file mode 100644
index 0000000..221845c
--- /dev/null
+++ b/core/java/com/android/internal/widget/NotificationIconManager.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.widget;
+
+import android.graphics.drawable.Icon;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+/**
+ * An interface used for Notification views to delegate handling the loading of icons.
+ */
+public interface NotificationIconManager {
+
+    /**
+     * Called when a new icon is provided to display.
+     *
+     * @param drawableConsumer a consumer, which can display the loaded drawable.
+     * @param icon             the updated icon to be displayed.
+     *
+     * @return a {@link Runnable} that sets the drawable on the consumer
+     */
+    @NonNull
+    Runnable updateIcon(
+            @NonNull NotificationDrawableConsumer drawableConsumer,
+            @Nullable Icon icon
+    );
+}
diff --git a/core/java/com/android/internal/widget/floatingtoolbar/FloatingToolbarPopup.java b/core/java/com/android/internal/widget/floatingtoolbar/FloatingToolbarPopup.java
index f7af67b..e9449eb 100644
--- a/core/java/com/android/internal/widget/floatingtoolbar/FloatingToolbarPopup.java
+++ b/core/java/com/android/internal/widget/floatingtoolbar/FloatingToolbarPopup.java
@@ -21,7 +21,6 @@
 import android.graphics.Rect;
 import android.view.MenuItem;
 import android.view.View;
-import android.view.selectiontoolbar.SelectionToolbarManager;
 import android.widget.PopupWindow;
 
 import java.util.List;
@@ -89,14 +88,10 @@
             @Nullable PopupWindow.OnDismissListener onDismiss);
 
     /**
-     * Returns {@link RemoteFloatingToolbarPopup} implementation if the system selection toolbar
-     * enabled, otherwise returns {@link LocalFloatingToolbarPopup} implementation.
+     * Returns {@link LocalFloatingToolbarPopup} implementation.
      */
     static FloatingToolbarPopup createInstance(Context context, View parent) {
-        boolean enabled = SelectionToolbarManager.isRemoteSelectionToolbarEnabled(context);
-        return enabled
-                ? new RemoteFloatingToolbarPopup(context, parent)
-                : new LocalFloatingToolbarPopup(context, parent);
+        return new LocalFloatingToolbarPopup(context, parent);
     }
 
 }
diff --git a/core/java/com/android/internal/widget/floatingtoolbar/RemoteFloatingToolbarPopup.java b/core/java/com/android/internal/widget/floatingtoolbar/RemoteFloatingToolbarPopup.java
deleted file mode 100644
index 8787c39..0000000
--- a/core/java/com/android/internal/widget/floatingtoolbar/RemoteFloatingToolbarPopup.java
+++ /dev/null
@@ -1,572 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.widget.floatingtoolbar;
-
-import static android.view.selectiontoolbar.SelectionToolbarManager.NO_TOOLBAR_ID;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.UiThread;
-import android.content.Context;
-import android.content.res.TypedArray;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.PixelFormat;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.ColorDrawable;
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.Icon;
-import android.text.TextUtils;
-import android.util.Log;
-import android.view.Gravity;
-import android.view.MenuItem;
-import android.view.SurfaceView;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.WindowManager;
-import android.view.selectiontoolbar.ISelectionToolbarCallback;
-import android.view.selectiontoolbar.SelectionToolbarManager;
-import android.view.selectiontoolbar.ShowInfo;
-import android.view.selectiontoolbar.ToolbarMenuItem;
-import android.view.selectiontoolbar.WidgetInfo;
-import android.widget.LinearLayout;
-import android.widget.PopupWindow;
-
-import com.android.internal.R;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.ref.WeakReference;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * A popup window used by the floating toolbar to render menu items in the remote system process.
- *
- * It holds 2 panels (i.e. main panel and overflow panel) and an overflow button
- * to transition between panels.
- */
-public final class RemoteFloatingToolbarPopup implements FloatingToolbarPopup {
-
-    private static final boolean DEBUG =
-            Log.isLoggable(FloatingToolbar.FLOATING_TOOLBAR_TAG, Log.VERBOSE);
-
-    private static final int TOOLBAR_STATE_SHOWN = 1;
-    private static final int TOOLBAR_STATE_HIDDEN = 2;
-    private static final int TOOLBAR_STATE_DISMISSED = 3;
-
-    @IntDef(prefix = {"TOOLBAR_STATE_"}, value = {
-            TOOLBAR_STATE_SHOWN,
-            TOOLBAR_STATE_HIDDEN,
-            TOOLBAR_STATE_DISMISSED
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface ToolbarState {
-    }
-
-    @NonNull
-    private final SelectionToolbarManager mSelectionToolbarManager;
-    // Parent for the popup window.
-    @NonNull
-    private final View mParent;
-    // A popup window used for showing menu items rendered by the remote system process
-    @NonNull
-    private final PopupWindow mPopupWindow;
-    // The callback to handle remote rendered selection toolbar.
-    @NonNull
-    private final SelectionToolbarCallbackImpl mSelectionToolbarCallback;
-
-    // tracks this popup state.
-    private @ToolbarState int mState;
-
-    // The token of the current showing floating toolbar.
-    private long mFloatingToolbarToken;
-    private final Rect mPreviousContentRect = new Rect();
-    private List<MenuItem> mMenuItems;
-    private MenuItem.OnMenuItemClickListener mMenuItemClickListener;
-    private int mSuggestedWidth;
-    private final Rect mScreenViewPort = new Rect();
-    private boolean mWidthChanged = true;
-    private final boolean mIsLightTheme;
-
-    private final int[] mCoordsOnScreen = new int[2];
-    private final int[] mCoordsOnWindow = new int[2];
-
-    public RemoteFloatingToolbarPopup(Context context, View parent) {
-        mParent = Objects.requireNonNull(parent);
-        mPopupWindow = createPopupWindow(context);
-        mSelectionToolbarManager = context.getSystemService(SelectionToolbarManager.class);
-        mSelectionToolbarCallback = new SelectionToolbarCallbackImpl(this);
-        mIsLightTheme = isLightTheme(context);
-        mFloatingToolbarToken = NO_TOOLBAR_ID;
-    }
-
-    private boolean isLightTheme(Context context) {
-        TypedArray a = context.obtainStyledAttributes(new int[]{R.attr.isLightTheme});
-        boolean isLightTheme = a.getBoolean(0, true);
-        a.recycle();
-        return isLightTheme;
-    }
-
-    @UiThread
-    @Override
-    public void show(List<MenuItem> menuItems,
-            MenuItem.OnMenuItemClickListener menuItemClickListener, Rect contentRect) {
-        Objects.requireNonNull(menuItems);
-        Objects.requireNonNull(menuItemClickListener);
-        if (isShowing() && Objects.equals(menuItems, mMenuItems)
-                && Objects.equals(contentRect, mPreviousContentRect)) {
-            if (DEBUG) {
-                Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "Ignore duplicate show() for the same content.");
-            }
-            return;
-        }
-
-        boolean isLayoutRequired = mMenuItems == null
-                || !MenuItemRepr.reprEquals(menuItems, mMenuItems)
-                || mWidthChanged;
-        if (isLayoutRequired) {
-            mSelectionToolbarManager.dismissToolbar(mFloatingToolbarToken);
-            doDismissPopupWindow();
-        }
-        mMenuItemClickListener = menuItemClickListener;
-        mMenuItems = menuItems;
-
-        mParent.getWindowVisibleDisplayFrame(mScreenViewPort);
-        final int suggestWidth = mSuggestedWidth > 0
-                ? mSuggestedWidth
-                : mParent.getResources().getDimensionPixelSize(
-                        R.dimen.floating_toolbar_preferred_width);
-        final ShowInfo showInfo = new ShowInfo(
-                mFloatingToolbarToken, isLayoutRequired,
-                getToolbarMenuItems(mMenuItems),
-                contentRect,
-                suggestWidth,
-                mScreenViewPort,
-                mParent.getViewRootImpl().getInputToken(), mIsLightTheme);
-        if (DEBUG) {
-            Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                    "RemoteFloatingToolbarPopup.show() for " + showInfo);
-        }
-        mSelectionToolbarManager.showToolbar(showInfo, mSelectionToolbarCallback);
-        mPreviousContentRect.set(contentRect);
-    }
-
-    @UiThread
-    @Override
-    public void dismiss() {
-        if (mState == TOOLBAR_STATE_DISMISSED) {
-            Log.w(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                    "The floating toolbar already dismissed.");
-            return;
-        }
-        if (DEBUG) {
-            Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                    "RemoteFloatingToolbarPopup.dismiss().");
-        }
-        mSelectionToolbarManager.dismissToolbar(mFloatingToolbarToken);
-        doDismissPopupWindow();
-    }
-
-    @UiThread
-    @Override
-    public void hide() {
-        if (mState == TOOLBAR_STATE_DISMISSED || mState == TOOLBAR_STATE_HIDDEN) {
-            if (DEBUG) {
-                Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "The floating toolbar already dismissed or hidden.");
-            }
-            return;
-        }
-        if (DEBUG) {
-            Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                    "RemoteFloatingToolbarPopup.hide().");
-        }
-        mSelectionToolbarManager.hideToolbar(mFloatingToolbarToken);
-        mState = TOOLBAR_STATE_HIDDEN;
-        mPopupWindow.dismiss();
-    }
-
-    @UiThread
-    @Override
-    public void setSuggestedWidth(int suggestedWidth) {
-        int difference = Math.abs(suggestedWidth - mSuggestedWidth);
-        mWidthChanged = difference > (mSuggestedWidth * 0.2);
-        mSuggestedWidth = suggestedWidth;
-    }
-
-    @Override
-    public void setWidthChanged(boolean widthChanged) {
-        mWidthChanged = widthChanged;
-    }
-
-    @UiThread
-    @Override
-    public boolean isHidden() {
-        return mState == TOOLBAR_STATE_HIDDEN;
-    }
-
-    @UiThread
-    @Override
-    public boolean isShowing() {
-        return mState == TOOLBAR_STATE_SHOWN;
-    }
-
-    @UiThread
-    @Override
-    public boolean setOutsideTouchable(boolean outsideTouchable,
-            @Nullable PopupWindow.OnDismissListener onDismiss) {
-        if (mState == TOOLBAR_STATE_DISMISSED) {
-            return false;
-        }
-        boolean ret = false;
-        if (mPopupWindow.isOutsideTouchable() ^ outsideTouchable) {
-            mPopupWindow.setOutsideTouchable(outsideTouchable);
-            mPopupWindow.setFocusable(!outsideTouchable);
-            mPopupWindow.update();
-            ret = true;
-        }
-        mPopupWindow.setOnDismissListener(onDismiss);
-        return ret;
-    }
-
-    private void updatePopupWindowContent(WidgetInfo widgetInfo) {
-        if (DEBUG) {
-            Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG, "updatePopupWindowContent.");
-        }
-        ViewGroup contentContainer = (ViewGroup) mPopupWindow.getContentView();
-        contentContainer.removeAllViews();
-        SurfaceView surfaceView = new SurfaceView(mParent.getContext());
-        surfaceView.setZOrderOnTop(true);
-        surfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT);
-        surfaceView.setChildSurfacePackage(widgetInfo.getSurfacePackage());
-        contentContainer.addView(surfaceView);
-    }
-
-    private MenuItem getMenuItemByToolbarMenuItem(ToolbarMenuItem toolbarMenuItem) {
-        for (MenuItem item : mMenuItems) {
-            if (toolbarMenuItem.getItemId() == item.getItemId()) {
-                return item;
-            }
-        }
-        return null;
-    }
-
-    private Point getCoordinatesInWindow(int x, int y) {
-        // We later specify the location of PopupWindow relative to the attached window.
-        // The idea here is that 1) we can get the location of a View in both window coordinates
-        // and screen coordinates, where the offset between them should be equal to the window
-        // origin, and 2) we can use an arbitrary for this calculation while calculating the
-        // location of the rootview is supposed to be least expensive.
-        // TODO: Consider to use PopupWindow.setIsLaidOutInScreen(true) so that we can avoid
-        // the following calculation.
-        mParent.getRootView().getLocationOnScreen(mCoordsOnScreen);
-        mParent.getRootView().getLocationInWindow(mCoordsOnWindow);
-        int windowLeftOnScreen = mCoordsOnScreen[0] - mCoordsOnWindow[0];
-        int windowTopOnScreen = mCoordsOnScreen[1] - mCoordsOnWindow[1];
-        return new Point(Math.max(0, x - windowLeftOnScreen), Math.max(0, y - windowTopOnScreen));
-    }
-
-    private static List<ToolbarMenuItem> getToolbarMenuItems(List<MenuItem> menuItems) {
-        final List<ToolbarMenuItem> list = new ArrayList<>(menuItems.size());
-        for (MenuItem menuItem : menuItems) {
-            // TODO: use ToolbarMenuItem.Builder(MenuItem) instead
-            ToolbarMenuItem toolbarMenuItem = new ToolbarMenuItem.Builder(menuItem.getItemId(),
-                    menuItem.getTitle(), menuItem.getContentDescription(), menuItem.getGroupId(),
-                    convertDrawableToIcon(menuItem.getIcon()),
-                    menuItem.getTooltipText(),
-                    ToolbarMenuItem.getPriorityFromMenuItem(menuItem)).build();
-            list.add(toolbarMenuItem);
-        }
-        return list;
-    }
-
-    private static Icon convertDrawableToIcon(Drawable drawable) {
-        if (drawable == null) {
-            return null;
-        }
-        if (drawable instanceof BitmapDrawable) {
-            final BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
-            if (bitmapDrawable.getBitmap() != null) {
-                return Icon.createWithBitmap(bitmapDrawable.getBitmap());
-            }
-        }
-        final Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
-                drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
-        final Canvas canvas = new Canvas(bitmap);
-        drawable.setBounds(0, 0, canvas.getWidth(),  canvas.getHeight());
-        drawable.draw(canvas);
-        return Icon.createWithBitmap(bitmap);
-    }
-
-    private static PopupWindow createPopupWindow(Context content) {
-        ViewGroup popupContentHolder = new LinearLayout(content);
-        PopupWindow popupWindow = new PopupWindow(popupContentHolder);
-        popupWindow.setClippingEnabled(false);
-        popupWindow.setWindowLayoutType(
-                WindowManager.LayoutParams.TYPE_APPLICATION_ABOVE_SUB_PANEL);
-        popupWindow.setAnimationStyle(0);
-        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
-        return popupWindow;
-    }
-
-    private void doDismissPopupWindow() {
-        if (DEBUG) {
-            Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG, "RemoteFloatingToolbarPopup.doDismiss().");
-        }
-        mState = TOOLBAR_STATE_DISMISSED;
-        mMenuItems = null;
-        mMenuItemClickListener = null;
-        mFloatingToolbarToken = 0;
-        mSuggestedWidth = 0;
-        mWidthChanged = true;
-        resetCoords();
-        mPreviousContentRect.setEmpty();
-        mScreenViewPort.setEmpty();
-        mPopupWindow.dismiss();
-    }
-
-    private void resetCoords() {
-        mCoordsOnScreen[0] = 0;
-        mCoordsOnScreen[1] = 0;
-        mCoordsOnWindow[0] = 0;
-        mCoordsOnWindow[1] = 0;
-    }
-
-    private void runOnUiThread(Runnable runnable) {
-        mParent.post(runnable);
-    }
-
-    private void onShow(WidgetInfo info) {
-        runOnUiThread(() -> {
-            mFloatingToolbarToken = info.getWidgetToken();
-            mState = TOOLBAR_STATE_SHOWN;
-            updatePopupWindowContent(info);
-            Rect contentRect = info.getContentRect();
-            mPopupWindow.setWidth(contentRect.width());
-            mPopupWindow.setHeight(contentRect.height());
-            final Point coords = getCoordinatesInWindow(contentRect.left, contentRect.top);
-            mPopupWindow.showAtLocation(mParent, Gravity.NO_GRAVITY, coords.x, coords.y);
-        });
-    }
-
-    private void onWidgetUpdated(WidgetInfo info) {
-        runOnUiThread(() -> {
-            if (!isShowing()) {
-                Log.w(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "onWidgetUpdated(): The widget isn't showing.");
-                return;
-            }
-            updatePopupWindowContent(info);
-            Rect contentRect = info.getContentRect();
-            Point coords = getCoordinatesInWindow(contentRect.left, contentRect.top);
-            if (DEBUG) {
-                Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "PopupWindow x= " + coords.x + " y= " + coords.y + " w="
-                                + contentRect.width() + " h=" + contentRect.height());
-            }
-            mPopupWindow.update(coords.x, coords.y, contentRect.width(), contentRect.height());
-        });
-    }
-
-    private void onToolbarShowTimeout() {
-        runOnUiThread(() -> {
-            if (mState == TOOLBAR_STATE_DISMISSED) {
-                return;
-            }
-            doDismissPopupWindow();
-        });
-    }
-
-    private void onMenuItemClicked(ToolbarMenuItem toolbarMenuItem) {
-        runOnUiThread(() -> {
-            if (mMenuItems == null || mMenuItemClickListener == null) {
-                return;
-            }
-            MenuItem item = getMenuItemByToolbarMenuItem(toolbarMenuItem);
-            if (DEBUG) {
-                Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "SelectionToolbarCallbackImpl onMenuItemClicked. toolbarMenuItem="
-                                + toolbarMenuItem + " item=" + item);
-            }
-            // TODO: handle the menu item like clipboard
-            if (item != null) {
-                mMenuItemClickListener.onMenuItemClick(item);
-            } else {
-                Log.e(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "onMenuItemClicked: cannot find menu item.");
-            }
-        });
-    }
-
-    private static class SelectionToolbarCallbackImpl extends ISelectionToolbarCallback.Stub {
-
-        private final WeakReference<RemoteFloatingToolbarPopup> mRemotePopup;
-
-        SelectionToolbarCallbackImpl(RemoteFloatingToolbarPopup popup) {
-            mRemotePopup = new WeakReference<>(popup);
-        }
-
-        @Override
-        public void onShown(WidgetInfo info) {
-            if (DEBUG) {
-                Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "SelectionToolbarCallbackImpl onShown: " + info);
-            }
-            final RemoteFloatingToolbarPopup remoteFloatingToolbarPopup = mRemotePopup.get();
-            if (remoteFloatingToolbarPopup != null) {
-                remoteFloatingToolbarPopup.onShow(info);
-            } else {
-                Log.w(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "Lost remoteFloatingToolbarPopup reference for onShown.");
-            }
-        }
-
-        @Override
-        public void onWidgetUpdated(WidgetInfo info) {
-            if (DEBUG) {
-                Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "SelectionToolbarCallbackImpl onWidgetUpdated: info = " + info);
-            }
-            final RemoteFloatingToolbarPopup remoteFloatingToolbarPopup = mRemotePopup.get();
-            if (remoteFloatingToolbarPopup != null) {
-                remoteFloatingToolbarPopup.onWidgetUpdated(info);
-            } else {
-                Log.w(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "Lost remoteFloatingToolbarPopup reference for onWidgetUpdated.");
-            }
-        }
-
-        @Override
-        public void onToolbarShowTimeout() {
-            final RemoteFloatingToolbarPopup remoteFloatingToolbarPopup = mRemotePopup.get();
-            if (remoteFloatingToolbarPopup != null) {
-                remoteFloatingToolbarPopup.onToolbarShowTimeout();
-            } else {
-                Log.w(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "Lost remoteFloatingToolbarPopup reference for onToolbarShowTimeout.");
-            }
-        }
-
-        @Override
-        public void onMenuItemClicked(ToolbarMenuItem toolbarMenuItem) {
-            final RemoteFloatingToolbarPopup remoteFloatingToolbarPopup = mRemotePopup.get();
-            if (remoteFloatingToolbarPopup != null) {
-                remoteFloatingToolbarPopup.onMenuItemClicked(toolbarMenuItem);
-            } else {
-                Log.w(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "Lost remoteFloatingToolbarPopup reference for onMenuItemClicked.");
-            }
-        }
-
-        @Override
-        public void onError(int errorCode) {
-            if (DEBUG) {
-                Log.v(FloatingToolbar.FLOATING_TOOLBAR_TAG,
-                        "SelectionToolbarCallbackImpl onError: " + errorCode);
-            }
-        }
-    }
-
-    /**
-     * Represents the identity of a MenuItem that is rendered in a FloatingToolbarPopup.
-     */
-    static final class MenuItemRepr {
-
-        public final int mItemId;
-        public final int mGroupId;
-        @Nullable
-        public final String mTitle;
-        @Nullable private final Drawable mIcon;
-
-        private MenuItemRepr(
-                int itemId, int groupId, @Nullable CharSequence title,
-                @Nullable Drawable icon) {
-            mItemId = itemId;
-            mGroupId = groupId;
-            mTitle = (title == null) ? null : title.toString();
-            mIcon = icon;
-        }
-
-        /**
-         * Creates an instance of MenuItemRepr for the specified menu item.
-         */
-        public static MenuItemRepr of(MenuItem menuItem) {
-            return new MenuItemRepr(
-                    menuItem.getItemId(),
-                    menuItem.getGroupId(),
-                    menuItem.getTitle(),
-                    menuItem.getIcon());
-        }
-
-        /**
-         * Returns this object's hashcode.
-         */
-        @Override
-        public int hashCode() {
-            return Objects.hash(mItemId, mGroupId, mTitle, mIcon);
-        }
-
-        /**
-         * Returns true if this object is the same as the specified object.
-         */
-        @Override
-        public boolean equals(Object o) {
-            if (o == this) {
-                return true;
-            }
-            if (!(o instanceof LocalFloatingToolbarPopup.MenuItemRepr)) {
-                return false;
-            }
-            final MenuItemRepr other = (MenuItemRepr) o;
-            return mItemId == other.mItemId
-                    && mGroupId == other.mGroupId
-                    && TextUtils.equals(mTitle, other.mTitle)
-                    // Many Drawables (icons) do not implement equals(). Using equals() here instead
-                    // of reference comparisons in case a Drawable subclass implements equals().
-                    && Objects.equals(mIcon, other.mIcon);
-        }
-
-        /**
-         * Returns true if the two menu item collections are the same based on MenuItemRepr.
-         */
-        public static boolean reprEquals(
-                Collection<MenuItem> menuItems1, Collection<MenuItem> menuItems2) {
-            if (menuItems1.size() != menuItems2.size()) {
-                return false;
-            }
-
-            final Iterator<MenuItem> menuItems2Iter = menuItems2.iterator();
-            for (MenuItem menuItem1 : menuItems1) {
-                final MenuItem menuItem2 = menuItems2Iter.next();
-                if (!MenuItemRepr.of(menuItem1).equals(
-                        MenuItemRepr.of(menuItem2))) {
-                    return false;
-                }
-            }
-            return true;
-        }
-    }
-}
diff --git a/core/java/com/android/server/backup/CompanionBackupHelper.java b/core/java/com/android/server/backup/CompanionBackupHelper.java
new file mode 100644
index 0000000..ef247c2
--- /dev/null
+++ b/core/java/com/android/server/backup/CompanionBackupHelper.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.UserIdInt;
+import android.app.backup.BlobBackupHelper;
+import android.companion.ICompanionDeviceManager;
+import android.content.Context;
+import android.os.ServiceManager;
+import android.util.Slog;
+
+/**
+ * CDM backup and restore helper.
+ */
+public class CompanionBackupHelper extends BlobBackupHelper {
+
+    private static final String TAG = "CompanionBackupHelper";
+
+    // current schema of the backup state blob
+    private static final int BLOB_VERSION = 1;
+
+    // key under which the CDM data blob is committed to back up
+    private static final String KEY_COMPANION = "companion";
+
+    @UserIdInt
+    private final int mUserId;
+
+    public CompanionBackupHelper(int userId) {
+        super(BLOB_VERSION, KEY_COMPANION);
+
+        mUserId = userId;
+    }
+
+    @Override
+    protected byte[] getBackupPayload(String key) {
+        byte[] payload = null;
+        if (KEY_COMPANION.equals(key)) {
+            try {
+                ICompanionDeviceManager cdm = ICompanionDeviceManager.Stub.asInterface(
+                        ServiceManager.getService(Context.COMPANION_DEVICE_SERVICE));
+                payload = cdm.getBackupPayload(mUserId);
+            } catch (Exception e) {
+                Slog.e(TAG, "Error getting backup from CompanionDeviceManager.", e);
+            }
+        }
+        return payload;
+    }
+
+    @Override
+    protected void applyRestoredPayload(String key, byte[] payload) {
+        Slog.i(TAG, "Got companion backup data.");
+        if (KEY_COMPANION.equals(key)) {
+            try {
+                ICompanionDeviceManager cdm = ICompanionDeviceManager.Stub.asInterface(
+                        ServiceManager.getService(Context.COMPANION_DEVICE_SERVICE));
+                cdm.applyRestoredPayload(payload, mUserId);
+            } catch (Exception e) {
+                Slog.e(TAG, "Error applying restored payload to CompanionDeviceManager.", e);
+            }
+        }
+    }
+}
diff --git a/core/jni/OWNERS b/core/jni/OWNERS
index dd43527..3aca751 100644
--- a/core/jni/OWNERS
+++ b/core/jni/OWNERS
@@ -107,3 +107,6 @@
 
 # SQLite
 per-file android_database_SQLite* = file:/SQLITE_OWNERS
+
+# PerformanceHintManager
+per-file android_os_PerformanceHintManager.cpp = file:/ADPF_OWNERS
diff --git a/core/jni/android_hardware_HardwareBuffer.cpp b/core/jni/android_hardware_HardwareBuffer.cpp
index 5fcc46e..2ea2158d 100644
--- a/core/jni/android_hardware_HardwareBuffer.cpp
+++ b/core/jni/android_hardware_HardwareBuffer.cpp
@@ -203,10 +203,10 @@
     Parcel* parcel = parcelForJavaObject(env, in);
     if (parcel) {
         sp<GraphicBuffer> buffer = new GraphicBuffer();
-        parcel->read(*buffer);
-        return reinterpret_cast<jlong>(new GraphicBufferWrapper(buffer));
+        if (parcel->read(*buffer) == STATUS_OK) {
+            return reinterpret_cast<jlong>(new GraphicBufferWrapper(buffer));
+        }
     }
-
     return NULL;
 }
 
diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp
index 4cf17b7..1998548 100644
--- a/core/jni/android_media_AudioSystem.cpp
+++ b/core/jni/android_media_AudioSystem.cpp
@@ -523,13 +523,14 @@
     }
 
     jclass clazz = env->FindClass(kClassPathName);
-    const char* zechars = regId.string();
-    jstring zestring = env->NewStringUTF(zechars);
+    const char *regIdString = regId.string();
+    jstring regIdJString = env->NewStringUTF(regIdString);
 
     env->CallStaticVoidMethod(clazz, gAudioPolicyEventHandlerMethods.postDynPolicyEventFromNative,
-            event, zestring, val);
+                              event, regIdJString, val);
 
-    env->ReleaseStringUTFChars(zestring, zechars);
+    const char *regIdJChars = env->GetStringUTFChars(regIdJString, NULL);
+    env->ReleaseStringUTFChars(regIdJString, regIdJChars);
     env->DeleteLocalRef(clazz);
 }
 
diff --git a/core/jni/android_os_PerformanceHintManager.cpp b/core/jni/android_os_PerformanceHintManager.cpp
index ffe844d..27c4cd4 100644
--- a/core/jni/android_os_PerformanceHintManager.cpp
+++ b/core/jni/android_os_PerformanceHintManager.cpp
@@ -34,26 +34,28 @@
 struct APerformanceHintSession;
 
 typedef APerformanceHintManager* (*APH_getManager)();
+typedef int64_t (*APH_getPreferredUpdateRateNanos)(APerformanceHintManager* manager);
 typedef APerformanceHintSession* (*APH_createSession)(APerformanceHintManager*, const int32_t*,
                                                       size_t, int64_t);
-typedef int64_t (*APH_getPreferredUpdateRateNanos)(APerformanceHintManager* manager);
 typedef void (*APH_updateTargetWorkDuration)(APerformanceHintSession*, int64_t);
 typedef void (*APH_reportActualWorkDuration)(APerformanceHintSession*, int64_t);
 typedef void (*APH_closeSession)(APerformanceHintSession* session);
 typedef void (*APH_sendHint)(APerformanceHintSession*, int32_t);
 typedef int (*APH_setThreads)(APerformanceHintSession*, const pid_t*, size_t);
 typedef void (*APH_getThreadIds)(APerformanceHintSession*, int32_t* const, size_t* const);
+typedef void (*APH_setPreferPowerEfficiency)(APerformanceHintSession*, bool);
 
 bool gAPerformanceHintBindingInitialized = false;
 APH_getManager gAPH_getManagerFn = nullptr;
-APH_createSession gAPH_createSessionFn = nullptr;
 APH_getPreferredUpdateRateNanos gAPH_getPreferredUpdateRateNanosFn = nullptr;
+APH_createSession gAPH_createSessionFn = nullptr;
 APH_updateTargetWorkDuration gAPH_updateTargetWorkDurationFn = nullptr;
 APH_reportActualWorkDuration gAPH_reportActualWorkDurationFn = nullptr;
 APH_closeSession gAPH_closeSessionFn = nullptr;
 APH_sendHint gAPH_sendHintFn = nullptr;
 APH_setThreads gAPH_setThreadsFn = nullptr;
 APH_getThreadIds gAPH_getThreadIdsFn = nullptr;
+APH_setPreferPowerEfficiency gAPH_setPreferPowerEfficiencyFn = nullptr;
 
 void ensureAPerformanceHintBindingInitialized() {
     if (gAPerformanceHintBindingInitialized) return;
@@ -65,10 +67,6 @@
     LOG_ALWAYS_FATAL_IF(gAPH_getManagerFn == nullptr,
                         "Failed to find required symbol APerformanceHint_getManager!");
 
-    gAPH_createSessionFn = (APH_createSession)dlsym(handle_, "APerformanceHint_createSession");
-    LOG_ALWAYS_FATAL_IF(gAPH_createSessionFn == nullptr,
-                        "Failed to find required symbol APerformanceHint_createSession!");
-
     gAPH_getPreferredUpdateRateNanosFn =
             (APH_getPreferredUpdateRateNanos)dlsym(handle_,
                                                    "APerformanceHint_getPreferredUpdateRateNanos");
@@ -76,6 +74,10 @@
                         "Failed to find required symbol "
                         "APerformanceHint_getPreferredUpdateRateNanos!");
 
+    gAPH_createSessionFn = (APH_createSession)dlsym(handle_, "APerformanceHint_createSession");
+    LOG_ALWAYS_FATAL_IF(gAPH_createSessionFn == nullptr,
+                        "Failed to find required symbol APerformanceHint_createSession!");
+
     gAPH_updateTargetWorkDurationFn =
             (APH_updateTargetWorkDuration)dlsym(handle_,
                                                 "APerformanceHint_updateTargetWorkDuration");
@@ -96,8 +98,7 @@
 
     gAPH_sendHintFn = (APH_sendHint)dlsym(handle_, "APerformanceHint_sendHint");
     LOG_ALWAYS_FATAL_IF(gAPH_sendHintFn == nullptr,
-                        "Failed to find required symbol "
-                        "APerformanceHint_sendHint!");
+                        "Failed to find required symbol APerformanceHint_sendHint!");
 
     gAPH_setThreadsFn = (APH_setThreads)dlsym(handle_, "APerformanceHint_setThreads");
     LOG_ALWAYS_FATAL_IF(gAPH_setThreadsFn == nullptr,
@@ -107,6 +108,13 @@
     LOG_ALWAYS_FATAL_IF(gAPH_getThreadIdsFn == nullptr,
                         "Failed to find required symbol APerformanceHint_getThreadIds!");
 
+    gAPH_setPreferPowerEfficiencyFn =
+            (APH_setPreferPowerEfficiency)dlsym(handle_,
+                                                "APerformanceHint_setPreferPowerEfficiency");
+    LOG_ALWAYS_FATAL_IF(gAPH_setPreferPowerEfficiencyFn == nullptr,
+                        "Failed to find required symbol"
+                        "APerformanceHint_setPreferPowerEfficiency!");
+
     gAPerformanceHintBindingInitialized = true;
 }
 
@@ -223,6 +231,13 @@
     return jintArr;
 }
 
+static void nativeSetPreferPowerEfficiency(JNIEnv* env, jclass clazz, jlong nativeSessionPtr,
+                                           jboolean enabled) {
+    ensureAPerformanceHintBindingInitialized();
+    gAPH_setPreferPowerEfficiencyFn(reinterpret_cast<APerformanceHintSession*>(nativeSessionPtr),
+                                    enabled);
+}
+
 static const JNINativeMethod gPerformanceHintMethods[] = {
         {"nativeAcquireManager", "()J", (void*)nativeAcquireManager},
         {"nativeGetPreferredUpdateRateNanos", "(J)J", (void*)nativeGetPreferredUpdateRateNanos},
@@ -233,6 +248,7 @@
         {"nativeSendHint", "(JI)V", (void*)nativeSendHint},
         {"nativeSetThreads", "(J[I)V", (void*)nativeSetThreads},
         {"nativeGetThreadIds", "(J)[I", (void*)nativeGetThreadIds},
+        {"nativeSetPreferPowerEfficiency", "(JZ)V", (void*)nativeSetPreferPowerEfficiency},
 };
 
 int register_android_os_PerformanceHintManager(JNIEnv* env) {
diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp
index 1afae29..979c9e3 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -347,23 +347,14 @@
 }
 
 static void NativeSetConfiguration(JNIEnv* env, jclass /*clazz*/, jlong ptr, jint mcc, jint mnc,
-                                   jstring default_locale, jobjectArray locales, jint orientation,
-                                   jint touchscreen, jint density, jint keyboard,
-                                   jint keyboard_hidden, jint navigation, jint screen_width,
-                                   jint screen_height, jint smallest_screen_width_dp,
-                                   jint screen_width_dp, jint screen_height_dp, jint screen_layout,
-                                   jint ui_mode, jint color_mode, jint grammatical_gender,
-                                   jint major_version) {
+                                   jstring locale, jint orientation, jint touchscreen, jint density,
+                                   jint keyboard, jint keyboard_hidden, jint navigation,
+                                   jint screen_width, jint screen_height,
+                                   jint smallest_screen_width_dp, jint screen_width_dp,
+                                   jint screen_height_dp, jint screen_layout, jint ui_mode,
+                                   jint color_mode, jint grammatical_gender, jint major_version) {
   ATRACE_NAME("AssetManager::SetConfiguration");
 
-  const jsize locale_count = (locales == NULL) ? 0 : env->GetArrayLength(locales);
-
-  // Constants duplicated from Java class android.content.res.Configuration.
-  static const jint kScreenLayoutRoundMask = 0x300;
-  static const jint kScreenLayoutRoundShift = 8;
-
-  std::vector<ResTable_config> configs;
-
   ResTable_config configuration;
   memset(&configuration, 0, sizeof(configuration));
   configuration.mcc = static_cast<uint16_t>(mcc);
@@ -384,37 +375,25 @@
   configuration.colorMode = static_cast<uint8_t>(color_mode);
   configuration.grammaticalInflection = static_cast<uint8_t>(grammatical_gender);
   configuration.sdkVersion = static_cast<uint16_t>(major_version);
+
+  if (locale != nullptr) {
+    ScopedUtfChars locale_utf8(env, locale);
+    CHECK(locale_utf8.c_str() != nullptr);
+    configuration.setBcp47Locale(locale_utf8.c_str());
+  }
+
+  // Constants duplicated from Java class android.content.res.Configuration.
+  static const jint kScreenLayoutRoundMask = 0x300;
+  static const jint kScreenLayoutRoundShift = 8;
+
   // In Java, we use a 32bit integer for screenLayout, while we only use an 8bit integer
   // in C++. We must extract the round qualifier out of the Java screenLayout and put it
   // into screenLayout2.
   configuration.screenLayout2 =
-          static_cast<uint8_t>((screen_layout & kScreenLayoutRoundMask) >> kScreenLayoutRoundShift);
-
-  if (locale_count > 0) {
-    configs.resize(locale_count, configuration);
-    for (int i = 0; i < locale_count; i++) {
-      jstring locale = (jstring)(env->GetObjectArrayElement(locales, i));
-      ScopedUtfChars locale_utf8(env, locale);
-      CHECK(locale_utf8.c_str() != nullptr);
-      configs[i].setBcp47Locale(locale_utf8.c_str());
-    }
-  } else {
-    configs.push_back(configuration);
-  }
-
-  uint32_t default_locale_int = 0;
-  if (default_locale != nullptr) {
-    ResTable_config config;
-    static_assert(std::is_same_v<decltype(config.locale), decltype(default_locale_int)>);
-    ScopedUtfChars locale_utf8(env, default_locale);
-    CHECK(locale_utf8.c_str() != nullptr);
-    config.setBcp47Locale(locale_utf8.c_str());
-    default_locale_int = config.locale;
-  }
+      static_cast<uint8_t>((screen_layout & kScreenLayoutRoundMask) >> kScreenLayoutRoundShift);
 
   auto assetmanager = LockAndStartAssetManager(ptr);
-  assetmanager->SetConfigurations(configs);
-  assetmanager->SetDefaultLocale(default_locale_int);
+  assetmanager->SetConfiguration(configuration);
 }
 
 static jobject NativeGetAssignedPackageIdentifiers(JNIEnv* env, jclass /*clazz*/, jlong ptr,
@@ -1519,97 +1498,94 @@
 
 // JNI registration.
 static const JNINativeMethod gAssetManagerMethods[] = {
-        // AssetManager setup methods.
-        {"nativeCreate", "()J", (void*)NativeCreate},
-        {"nativeDestroy", "(J)V", (void*)NativeDestroy},
-        {"nativeSetApkAssets", "(J[Landroid/content/res/ApkAssets;Z)V", (void*)NativeSetApkAssets},
-        {"nativeSetConfiguration", "(JIILjava/lang/String;[Ljava/lang/String;IIIIIIIIIIIIIIII)V",
-         (void*)NativeSetConfiguration},
-        {"nativeGetAssignedPackageIdentifiers", "(JZZ)Landroid/util/SparseArray;",
-         (void*)NativeGetAssignedPackageIdentifiers},
+    // AssetManager setup methods.
+    {"nativeCreate", "()J", (void*)NativeCreate},
+    {"nativeDestroy", "(J)V", (void*)NativeDestroy},
+    {"nativeSetApkAssets", "(J[Landroid/content/res/ApkAssets;Z)V", (void*)NativeSetApkAssets},
+    {"nativeSetConfiguration", "(JIILjava/lang/String;IIIIIIIIIIIIIIII)V",
+     (void*)NativeSetConfiguration},
+    {"nativeGetAssignedPackageIdentifiers", "(JZZ)Landroid/util/SparseArray;",
+     (void*)NativeGetAssignedPackageIdentifiers},
 
-        // AssetManager file methods.
-        {"nativeContainsAllocatedTable", "(J)Z", (void*)ContainsAllocatedTable},
-        {"nativeList", "(JLjava/lang/String;)[Ljava/lang/String;", (void*)NativeList},
-        {"nativeOpenAsset", "(JLjava/lang/String;I)J", (void*)NativeOpenAsset},
-        {"nativeOpenAssetFd", "(JLjava/lang/String;[J)Landroid/os/ParcelFileDescriptor;",
-         (void*)NativeOpenAssetFd},
-        {"nativeOpenNonAsset", "(JILjava/lang/String;I)J", (void*)NativeOpenNonAsset},
-        {"nativeOpenNonAssetFd", "(JILjava/lang/String;[J)Landroid/os/ParcelFileDescriptor;",
-         (void*)NativeOpenNonAssetFd},
-        {"nativeOpenXmlAsset", "(JILjava/lang/String;)J", (void*)NativeOpenXmlAsset},
-        {"nativeOpenXmlAssetFd", "(JILjava/io/FileDescriptor;)J", (void*)NativeOpenXmlAssetFd},
+    // AssetManager file methods.
+    {"nativeContainsAllocatedTable", "(J)Z", (void*)ContainsAllocatedTable},
+    {"nativeList", "(JLjava/lang/String;)[Ljava/lang/String;", (void*)NativeList},
+    {"nativeOpenAsset", "(JLjava/lang/String;I)J", (void*)NativeOpenAsset},
+    {"nativeOpenAssetFd", "(JLjava/lang/String;[J)Landroid/os/ParcelFileDescriptor;",
+     (void*)NativeOpenAssetFd},
+    {"nativeOpenNonAsset", "(JILjava/lang/String;I)J", (void*)NativeOpenNonAsset},
+    {"nativeOpenNonAssetFd", "(JILjava/lang/String;[J)Landroid/os/ParcelFileDescriptor;",
+     (void*)NativeOpenNonAssetFd},
+    {"nativeOpenXmlAsset", "(JILjava/lang/String;)J", (void*)NativeOpenXmlAsset},
+    {"nativeOpenXmlAssetFd", "(JILjava/io/FileDescriptor;)J", (void*)NativeOpenXmlAssetFd},
 
-        // AssetManager resource methods.
-        {"nativeGetResourceValue", "(JISLandroid/util/TypedValue;Z)I",
-         (void*)NativeGetResourceValue},
-        {"nativeGetResourceBagValue", "(JIILandroid/util/TypedValue;)I",
-         (void*)NativeGetResourceBagValue},
-        {"nativeGetStyleAttributes", "(JI)[I", (void*)NativeGetStyleAttributes},
-        {"nativeGetResourceStringArray", "(JI)[Ljava/lang/String;",
-         (void*)NativeGetResourceStringArray},
-        {"nativeGetResourceStringArrayInfo", "(JI)[I", (void*)NativeGetResourceStringArrayInfo},
-        {"nativeGetResourceIntArray", "(JI)[I", (void*)NativeGetResourceIntArray},
-        {"nativeGetResourceArraySize", "(JI)I", (void*)NativeGetResourceArraySize},
-        {"nativeGetResourceArray", "(JI[I)I", (void*)NativeGetResourceArray},
-        {"nativeGetParentThemeIdentifier", "(JI)I", (void*)NativeGetParentThemeIdentifier},
+    // AssetManager resource methods.
+    {"nativeGetResourceValue", "(JISLandroid/util/TypedValue;Z)I", (void*)NativeGetResourceValue},
+    {"nativeGetResourceBagValue", "(JIILandroid/util/TypedValue;)I",
+     (void*)NativeGetResourceBagValue},
+    {"nativeGetStyleAttributes", "(JI)[I", (void*)NativeGetStyleAttributes},
+    {"nativeGetResourceStringArray", "(JI)[Ljava/lang/String;",
+     (void*)NativeGetResourceStringArray},
+    {"nativeGetResourceStringArrayInfo", "(JI)[I", (void*)NativeGetResourceStringArrayInfo},
+    {"nativeGetResourceIntArray", "(JI)[I", (void*)NativeGetResourceIntArray},
+    {"nativeGetResourceArraySize", "(JI)I", (void*)NativeGetResourceArraySize},
+    {"nativeGetResourceArray", "(JI[I)I", (void*)NativeGetResourceArray},
+    {"nativeGetParentThemeIdentifier", "(JI)I",
+     (void*)NativeGetParentThemeIdentifier},
 
-        // AssetManager resource name/ID methods.
-        {"nativeGetResourceIdentifier",
-         "(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)I",
-         (void*)NativeGetResourceIdentifier},
-        {"nativeGetResourceName", "(JI)Ljava/lang/String;", (void*)NativeGetResourceName},
-        {"nativeGetResourcePackageName", "(JI)Ljava/lang/String;",
-         (void*)NativeGetResourcePackageName},
-        {"nativeGetResourceTypeName", "(JI)Ljava/lang/String;", (void*)NativeGetResourceTypeName},
-        {"nativeGetResourceEntryName", "(JI)Ljava/lang/String;", (void*)NativeGetResourceEntryName},
-        {"nativeSetResourceResolutionLoggingEnabled", "(JZ)V",
-         (void*)NativeSetResourceResolutionLoggingEnabled},
-        {"nativeGetLastResourceResolution", "(J)Ljava/lang/String;",
-         (void*)NativeGetLastResourceResolution},
-        {"nativeGetLocales", "(JZ)[Ljava/lang/String;", (void*)NativeGetLocales},
-        {"nativeGetSizeConfigurations", "(J)[Landroid/content/res/Configuration;",
-         (void*)NativeGetSizeConfigurations},
-        {"nativeGetSizeAndUiModeConfigurations", "(J)[Landroid/content/res/Configuration;",
-         (void*)NativeGetSizeAndUiModeConfigurations},
+    // AssetManager resource name/ID methods.
+    {"nativeGetResourceIdentifier", "(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)I",
+     (void*)NativeGetResourceIdentifier},
+    {"nativeGetResourceName", "(JI)Ljava/lang/String;", (void*)NativeGetResourceName},
+    {"nativeGetResourcePackageName", "(JI)Ljava/lang/String;", (void*)NativeGetResourcePackageName},
+    {"nativeGetResourceTypeName", "(JI)Ljava/lang/String;", (void*)NativeGetResourceTypeName},
+    {"nativeGetResourceEntryName", "(JI)Ljava/lang/String;", (void*)NativeGetResourceEntryName},
+    {"nativeSetResourceResolutionLoggingEnabled", "(JZ)V",
+     (void*) NativeSetResourceResolutionLoggingEnabled},
+    {"nativeGetLastResourceResolution", "(J)Ljava/lang/String;",
+     (void*) NativeGetLastResourceResolution},
+    {"nativeGetLocales", "(JZ)[Ljava/lang/String;", (void*)NativeGetLocales},
+    {"nativeGetSizeConfigurations", "(J)[Landroid/content/res/Configuration;",
+     (void*)NativeGetSizeConfigurations},
+    {"nativeGetSizeAndUiModeConfigurations", "(J)[Landroid/content/res/Configuration;",
+     (void*)NativeGetSizeAndUiModeConfigurations},
 
-        // Style attribute related methods.
-        {"nativeAttributeResolutionStack", "(JJIII)[I", (void*)NativeAttributeResolutionStack},
-        {"nativeApplyStyle", "(JJIIJ[IJJ)V", (void*)NativeApplyStyle},
-        {"nativeResolveAttrs", "(JJII[I[I[I[I)Z", (void*)NativeResolveAttrs},
-        {"nativeRetrieveAttributes", "(JJ[I[I[I)Z", (void*)NativeRetrieveAttributes},
+    // Style attribute related methods.
+    {"nativeAttributeResolutionStack", "(JJIII)[I", (void*)NativeAttributeResolutionStack},
+    {"nativeApplyStyle", "(JJIIJ[IJJ)V", (void*)NativeApplyStyle},
+    {"nativeResolveAttrs", "(JJII[I[I[I[I)Z", (void*)NativeResolveAttrs},
+    {"nativeRetrieveAttributes", "(JJ[I[I[I)Z", (void*)NativeRetrieveAttributes},
 
-        // Theme related methods.
-        {"nativeThemeCreate", "(J)J", (void*)NativeThemeCreate},
-        {"nativeGetThemeFreeFunction", "()J", (void*)NativeGetThemeFreeFunction},
-        {"nativeThemeApplyStyle", "(JJIZ)V", (void*)NativeThemeApplyStyle},
-        {"nativeThemeRebase", "(JJ[I[ZI)V", (void*)NativeThemeRebase},
+    // Theme related methods.
+    {"nativeThemeCreate", "(J)J", (void*)NativeThemeCreate},
+    {"nativeGetThemeFreeFunction", "()J", (void*)NativeGetThemeFreeFunction},
+    {"nativeThemeApplyStyle", "(JJIZ)V", (void*)NativeThemeApplyStyle},
+    {"nativeThemeRebase", "(JJ[I[ZI)V", (void*)NativeThemeRebase},
 
-        {"nativeThemeCopy", "(JJJJ)V", (void*)NativeThemeCopy},
-        {"nativeThemeGetAttributeValue", "(JJILandroid/util/TypedValue;Z)I",
-         (void*)NativeThemeGetAttributeValue},
-        {"nativeThemeDump", "(JJILjava/lang/String;Ljava/lang/String;)V", (void*)NativeThemeDump},
-        {"nativeThemeGetChangingConfigurations", "(J)I",
-         (void*)NativeThemeGetChangingConfigurations},
+    {"nativeThemeCopy", "(JJJJ)V", (void*)NativeThemeCopy},
+    {"nativeThemeGetAttributeValue", "(JJILandroid/util/TypedValue;Z)I",
+     (void*)NativeThemeGetAttributeValue},
+    {"nativeThemeDump", "(JJILjava/lang/String;Ljava/lang/String;)V", (void*)NativeThemeDump},
+    {"nativeThemeGetChangingConfigurations", "(J)I", (void*)NativeThemeGetChangingConfigurations},
 
-        // AssetInputStream methods.
-        {"nativeAssetDestroy", "(J)V", (void*)NativeAssetDestroy},
-        {"nativeAssetReadChar", "(J)I", (void*)NativeAssetReadChar},
-        {"nativeAssetRead", "(J[BII)I", (void*)NativeAssetRead},
-        {"nativeAssetSeek", "(JJI)J", (void*)NativeAssetSeek},
-        {"nativeAssetGetLength", "(J)J", (void*)NativeAssetGetLength},
-        {"nativeAssetGetRemainingLength", "(J)J", (void*)NativeAssetGetRemainingLength},
+    // AssetInputStream methods.
+    {"nativeAssetDestroy", "(J)V", (void*)NativeAssetDestroy},
+    {"nativeAssetReadChar", "(J)I", (void*)NativeAssetReadChar},
+    {"nativeAssetRead", "(J[BII)I", (void*)NativeAssetRead},
+    {"nativeAssetSeek", "(JJI)J", (void*)NativeAssetSeek},
+    {"nativeAssetGetLength", "(J)J", (void*)NativeAssetGetLength},
+    {"nativeAssetGetRemainingLength", "(J)J", (void*)NativeAssetGetRemainingLength},
 
-        // System/idmap related methods.
-        {"nativeGetOverlayableMap", "(JLjava/lang/String;)Ljava/util/Map;",
-         (void*)NativeGetOverlayableMap},
-        {"nativeGetOverlayablesToString", "(JLjava/lang/String;)Ljava/lang/String;",
-         (void*)NativeGetOverlayablesToString},
+    // System/idmap related methods.
+    {"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},
-        {"getAssetAllocations", "()Ljava/lang/String;", (void*)NativeGetAssetAllocations},
-        {"getGlobalAssetManagerCount", "()I", (void*)NativeGetGlobalAssetManagerCount},
+    // Global management/debug methods.
+    {"getGlobalAssetCount", "()I", (void*)NativeGetGlobalAssetCount},
+    {"getAssetAllocations", "()Ljava/lang/String;", (void*)NativeGetAssetAllocations},
+    {"getGlobalAssetManagerCount", "()I", (void*)NativeGetGlobalAssetManagerCount},
 };
 
 int register_android_content_AssetManager(JNIEnv* env) {
diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp
index 4249253..dbe0338 100644
--- a/core/jni/android_view_SurfaceControl.cpp
+++ b/core/jni/android_view_SurfaceControl.cpp
@@ -257,6 +257,14 @@
     jmethodID onTrustedPresentationChanged;
 } gTrustedPresentationCallbackClassInfo;
 
+static struct {
+    jclass clazz;
+    jmethodID ctor;
+    jfieldID layerName;
+    jfieldID bufferId;
+    jfieldID frameNumber;
+} gStalledTransactionInfoClassInfo;
+
 constexpr ui::Dataspace pickDataspaceFromColorMode(const ui::ColorMode colorMode) {
     switch (colorMode) {
         case ui::ColorMode::DISPLAY_P3:
@@ -2032,6 +2040,29 @@
     return static_cast<jlong>(reinterpret_cast<uintptr_t>(&destroyNativeTpc));
 }
 
+static jobject nativeGetStalledTransactionInfo(JNIEnv* env, jclass clazz, jint pid) {
+    std::optional<gui::StalledTransactionInfo> stalledTransactionInfo =
+            SurfaceComposerClient::getStalledTransactionInfo(pid);
+    if (!stalledTransactionInfo) {
+        return nullptr;
+    }
+
+    jobject jStalledTransactionInfo = env->NewObject(gStalledTransactionInfoClassInfo.clazz,
+                                                     gStalledTransactionInfoClassInfo.ctor);
+    if (!jStalledTransactionInfo) {
+        jniThrowException(env, "java/lang/OutOfMemoryError", nullptr);
+        return nullptr;
+    }
+
+    env->SetObjectField(jStalledTransactionInfo, gStalledTransactionInfoClassInfo.layerName,
+                        env->NewStringUTF(String8{stalledTransactionInfo->layerName}));
+    env->SetLongField(jStalledTransactionInfo, gStalledTransactionInfoClassInfo.bufferId,
+                      static_cast<jlong>(stalledTransactionInfo->bufferId));
+    env->SetLongField(jStalledTransactionInfo, gStalledTransactionInfoClassInfo.frameNumber,
+                      static_cast<jlong>(stalledTransactionInfo->frameNumber));
+    return jStalledTransactionInfo;
+}
+
 // ----------------------------------------------------------------------------
 
 SurfaceControl* android_view_SurfaceControl_getNativeSurfaceControl(JNIEnv* env,
@@ -2281,6 +2312,8 @@
     {"nativeCreateTpc", "(Landroid/view/SurfaceControl$TrustedPresentationCallback;)J",
             (void*)nativeCreateTpc},
     {"getNativeTrustedPresentationCallbackFinalizer", "()J", (void*)getNativeTrustedPresentationCallbackFinalizer },
+    {"nativeGetStalledTransactionInfo", "(I)Landroid/gui/StalledTransactionInfo;",
+            (void*) nativeGetStalledTransactionInfo },
         // clang-format on
 };
 
@@ -2524,6 +2557,18 @@
     gTrustedPresentationCallbackClassInfo.onTrustedPresentationChanged =
             GetMethodIDOrDie(env, trustedPresentationCallbackClazz, "onTrustedPresentationChanged",
                              "(Z)V");
+
+    jclass stalledTransactionInfoClazz = FindClassOrDie(env, "android/gui/StalledTransactionInfo");
+    gStalledTransactionInfoClassInfo.clazz = MakeGlobalRefOrDie(env, stalledTransactionInfoClazz);
+    gStalledTransactionInfoClassInfo.ctor =
+            GetMethodIDOrDie(env, stalledTransactionInfoClazz, "<init>", "()V");
+    gStalledTransactionInfoClassInfo.layerName =
+            GetFieldIDOrDie(env, stalledTransactionInfoClazz, "layerName", "Ljava/lang/String;");
+    gStalledTransactionInfoClassInfo.bufferId =
+            GetFieldIDOrDie(env, stalledTransactionInfoClazz, "bufferId", "J");
+    gStalledTransactionInfoClassInfo.frameNumber =
+            GetFieldIDOrDie(env, stalledTransactionInfoClazz, "frameNumber", "J");
+
     return err;
 }
 
diff --git a/core/jni/android_view_VelocityTracker.cpp b/core/jni/android_view_VelocityTracker.cpp
index 05c9f68..03e9a6a 100644
--- a/core/jni/android_view_VelocityTracker.cpp
+++ b/core/jni/android_view_VelocityTracker.cpp
@@ -16,13 +16,14 @@
 
 #define LOG_TAG "VelocityTracker-JNI"
 
+#include <android-base/logging.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <cutils/properties.h>
 #include <input/Input.h>
 #include <input/VelocityTracker.h>
 #include <nativehelper/JNIHelp.h>
 #include <nativehelper/ScopedUtfChars.h>
-#include <utils/Log.h>
+
 #include "android_view_MotionEvent.h"
 #include "core_jni_helpers.h"
 
@@ -102,7 +103,7 @@
         jobject eventObj) {
     const MotionEvent* event = android_view_MotionEvent_getNativePtr(env, eventObj);
     if (!event) {
-        ALOGW("nativeAddMovement failed because MotionEvent was finalized.");
+        LOG(WARNING) << "nativeAddMovement failed because MotionEvent was finalized.";
         return;
     }
 
diff --git a/core/jni/android_window_ScreenCapture.cpp b/core/jni/android_window_ScreenCapture.cpp
index e729750..bdf7eaa 100644
--- a/core/jni/android_window_ScreenCapture.cpp
+++ b/core/jni/android_window_ScreenCapture.cpp
@@ -102,7 +102,8 @@
         }
 
         if (!captureResults.fenceResult.ok() || captureResults.buffer == nullptr) {
-            env->CallVoidMethod(consumer.get(), gConsumerClassInfo.accept, nullptr);
+            env->CallVoidMethod(consumer.get(), gConsumerClassInfo.accept, nullptr,
+                                fenceStatus(captureResults.fenceResult));
             checkAndClearException(env, "accept");
             return binder::Status::ok();
         }
@@ -117,7 +118,8 @@
                                             captureResults.capturedSecureLayers,
                                             captureResults.capturedHdrLayers);
         checkAndClearException(env, "builder");
-        env->CallVoidMethod(consumer.get(), gConsumerClassInfo.accept, screenshotHardwareBuffer);
+        env->CallVoidMethod(consumer.get(), gConsumerClassInfo.accept, screenshotHardwareBuffer,
+                            fenceStatus(captureResults.fenceResult));
         checkAndClearException(env, "accept");
         env->DeleteLocalRef(jhardwareBuffer);
         env->DeleteLocalRef(screenshotHardwareBuffer);
@@ -285,7 +287,7 @@
             (void*)nativeCaptureDisplay },
     {"nativeCaptureLayers",  "(Landroid/window/ScreenCapture$LayerCaptureArgs;J)I",
             (void*)nativeCaptureLayers },
-    {"nativeCreateScreenCaptureListener", "(Ljava/util/function/Consumer;)J",
+    {"nativeCreateScreenCaptureListener", "(Ljava/util/function/ObjIntConsumer;)J",
             (void*)nativeCreateScreenCaptureListener },
     {"nativeWriteListenerToParcel", "(JLandroid/os/Parcel;)V", (void*)nativeWriteListenerToParcel },
     {"nativeReadListenerFromParcel", "(Landroid/os/Parcel;)J",
@@ -333,8 +335,8 @@
     gLayerCaptureArgsClassInfo.childrenOnly =
             GetFieldIDOrDie(env, layerCaptureArgsClazz, "mChildrenOnly", "Z");
 
-    jclass consumer = FindClassOrDie(env, "java/util/function/Consumer");
-    gConsumerClassInfo.accept = GetMethodIDOrDie(env, consumer, "accept", "(Ljava/lang/Object;)V");
+    jclass consumer = FindClassOrDie(env, "java/util/function/ObjIntConsumer");
+    gConsumerClassInfo.accept = GetMethodIDOrDie(env, consumer, "accept", "(Ljava/lang/Object;I)V");
 
     jclass screenshotGraphicsBufferClazz =
             FindClassOrDie(env, "android/window/ScreenCapture$ScreenshotHardwareBuffer");
diff --git a/core/jni/com_android_internal_content_NativeLibraryHelper.cpp b/core/jni/com_android_internal_content_NativeLibraryHelper.cpp
index da308b2..149e57a 100644
--- a/core/jni/com_android_internal_content_NativeLibraryHelper.cpp
+++ b/core/jni/com_android_internal_content_NativeLibraryHelper.cpp
@@ -130,6 +130,7 @@
 static install_status_t
 copyFileIfChanged(JNIEnv *env, void* arg, ZipFileRO* zipFile, ZipEntryRO zipEntry, const char* fileName)
 {
+    static const size_t kPageSize = getpagesize();
     void** args = reinterpret_cast<void**>(arg);
     jstring* javaNativeLibPath = (jstring*) args[0];
     jboolean extractNativeLibs = *(jboolean*) args[1];
@@ -162,9 +163,9 @@
             return INSTALL_FAILED_INVALID_APK;
         }
 
-        if (offset % PAGE_SIZE != 0) {
-            ALOGE("Library '%s' is not page-aligned - will not be able to open it directly from"
-                " apk.\n", fileName);
+        if (offset % kPageSize != 0) {
+            ALOGE("Library '%s' is not PAGE(%zu)-aligned - will not be able to open it directly "
+                  "from apk.\n", fileName, kPageSize);
             return INSTALL_FAILED_INVALID_APK;
         }
 
diff --git a/core/jni/com_android_internal_content_om_OverlayManagerImpl.cpp b/core/jni/com_android_internal_content_om_OverlayManagerImpl.cpp
index bba1760..d4f6e18 100644
--- a/core/jni/com_android_internal_content_om_OverlayManagerImpl.cpp
+++ b/core/jni/com_android_internal_content_om_OverlayManagerImpl.cpp
@@ -44,6 +44,8 @@
     jfieldID stringData;
     jfieldID binaryData;
     jfieldID configuration;
+    jfieldID binaryDataOffset;
+    jfieldID binaryDataSize;
 } gFabricatedOverlayInternalEntryOffsets;
 
 static struct parcel_file_descriptor_offsets_t {
@@ -281,10 +283,17 @@
         auto binary_data =
                 getNullableFileDescriptor(env, entry,
                                           gFabricatedOverlayInternalEntryOffsets.binaryData);
+
+        const auto data_offset =
+                env->GetLongField(entry, gFabricatedOverlayInternalEntryOffsets.binaryDataOffset);
+        const auto data_size =
+                env->GetLongField(entry, gFabricatedOverlayInternalEntryOffsets.binaryDataSize);
         entries_params.push_back(
                 FabricatedOverlayEntryParameters{resourceName.c_str(), (DataType)dataType,
                                                  (DataValue)data,
                                                  string_data.value_or(std::string()), binary_data,
+                                                 static_cast<off64_t>(data_offset),
+                                                 static_cast<size_t>(data_size),
                                                  configuration.value_or(std::string())});
         ALOGV("resourceName = %s, dataType = 0x%08x, data = 0x%08x, dataString = %s,"
               " binaryData = %d, configuration = %s",
@@ -440,6 +449,12 @@
     gFabricatedOverlayInternalEntryOffsets.configuration =
             GetFieldIDOrDie(env, gFabricatedOverlayInternalEntryOffsets.classObject,
                             "configuration", "Ljava/lang/String;");
+    gFabricatedOverlayInternalEntryOffsets.binaryDataOffset =
+            GetFieldIDOrDie(env, gFabricatedOverlayInternalEntryOffsets.classObject,
+                            "binaryDataOffset", "J");
+    gFabricatedOverlayInternalEntryOffsets.binaryDataSize =
+            GetFieldIDOrDie(env, gFabricatedOverlayInternalEntryOffsets.classObject,
+                            "binaryDataSize", "J");
 
     jclass parcelFileDescriptorClass =
             android::FindClassOrDie(env, "android/os/ParcelFileDescriptor");
diff --git a/core/proto/android/providers/settings/secure.proto b/core/proto/android/providers/settings/secure.proto
index d7969cf..ed0081c 100644
--- a/core/proto/android/providers/settings/secure.proto
+++ b/core/proto/android/providers/settings/secure.proto
@@ -137,6 +137,7 @@
         optional SettingProto gesture_setup_complete = 9 [ (android.privacy).dest = DEST_AUTOMATIC ];
         optional SettingProto touch_gesture_enabled = 10 [ (android.privacy).dest = DEST_AUTOMATIC ];
         optional SettingProto long_press_home_enabled = 11 [ (android.privacy).dest = DEST_AUTOMATIC ];
+        optional SettingProto search_press_hold_nav_handle_enabled = 12 [ (android.privacy).dest = DEST_AUTOMATIC ];
     }
     optional Assist assist = 7;
 
diff --git a/core/proto/android/server/windowmanagertransitiontrace.proto b/core/proto/android/server/windowmanagertransitiontrace.proto
index a950a79..34ccb48 100644
--- a/core/proto/android/server/windowmanagertransitiontrace.proto
+++ b/core/proto/android/server/windowmanagertransitiontrace.proto
@@ -56,6 +56,7 @@
   repeated Target targets = 8;
   optional int32 flags = 9;
   optional int64 abort_time_ns = 10;
+  optional int64 starting_window_remove_time_ns = 11;
 }
 
 message Target {
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 86cf80e..f55501a 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -821,7 +821,6 @@
     <protected-broadcast android:name="android.intent.action.PROFILE_REMOVED" />
     <protected-broadcast android:name="com.android.internal.telephony.cat.SMS_SENT_ACTION" />
     <protected-broadcast android:name="com.android.internal.telephony.cat.SMS_DELIVERY_ACTION" />
-    <protected-broadcast android:name="com.android.internal.telephony.data.ACTION_RETRY" />
     <protected-broadcast android:name="android.companion.virtual.action.VIRTUAL_DEVICE_REMOVED" />
     <protected-broadcast android:name="com.android.internal.intent.action.FLASH_NOTIFICATION_START_PREVIEW" />
     <protected-broadcast android:name="com.android.internal.intent.action.FLASH_NOTIFICATION_STOP_PREVIEW" />
@@ -7791,8 +7790,9 @@
                 android:process=":ui">
         </activity>
         <activity android:name="com.android.internal.app.PlatLogoActivity"
-                android:theme="@style/Theme.Wallpaper.NoTitleBar.Fullscreen"
+                android:theme="@style/Theme.NoTitleBar.Fullscreen"
                 android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"
+                android:enableOnBackInvokedCallback="true"
                 android:icon="@drawable/platlogo"
                 android:process=":ui">
         </activity>
@@ -7864,12 +7864,6 @@
             </intent-filter>
         </activity>
 
-        <activity android:name="com.android.internal.app.NetInitiatedActivity"
-                android:theme="@style/Theme.Dialog.Confirmation"
-                android:excludeFromRecents="true"
-                android:process=":ui">
-        </activity>
-
         <activity android:name="com.android.internal.app.SystemUserHomeActivity"
                   android:enabled="false"
                   android:process=":ui"
diff --git a/core/res/res/drawable/focus_event_rotary_input_background.xml b/core/res/res/drawable/focus_event_rotary_input_background.xml
new file mode 100644
index 0000000..512cd68
--- /dev/null
+++ b/core/res/res/drawable/focus_event_rotary_input_background.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright 2023 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT 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:name="focus_event_rotary_input_background"
+       android:shape="rectangle">
+
+  <!-- View background color -->
+  <solid android:color="#80741b47" />
+
+  <!-- View border color and width -->
+  <stroke android:width="1dp" android:color="#ffff00ff" />
+
+  <!-- The radius makes the corners rounded -->
+  <corners android:radius="4dp" />
+
+</shape>
\ No newline at end of file
diff --git a/core/res/res/raw/default_ringtone_vibration_effect.ahv b/core/res/res/raw/default_ringtone_vibration_effect.ahv
new file mode 100644
index 0000000..c66fc04
--- /dev/null
+++ b/core/res/res/raw/default_ringtone_vibration_effect.ahv
@@ -0,0 +1,47 @@
+<?xml version='1.0' encoding='utf-8' standalone='no' ?>
+
+<!--
+**
+** Copyright 2023, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License")
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+-->
+
+<vibration>
+    <waveform-effect>
+        <waveform-entry amplitude="0" durationMs="0" />
+        <waveform-entry amplitude="255" durationMs="12" />
+        <waveform-entry amplitude="0" durationMs="250" />
+        <waveform-entry amplitude="255" durationMs="12" />
+        <waveform-entry amplitude="0" durationMs="500" />
+        <repeating>
+            <waveform-entry amplitude="77" durationMs="50" />
+            <waveform-entry amplitude="77" durationMs="50" />
+            <waveform-entry amplitude="78" durationMs="50" />
+            <waveform-entry amplitude="79" durationMs="50" />
+            <waveform-entry amplitude="81" durationMs="50" />
+            <waveform-entry amplitude="84" durationMs="50" />
+            <waveform-entry amplitude="87" durationMs="50" />
+            <waveform-entry amplitude="93" durationMs="50" />
+            <waveform-entry amplitude="101" durationMs="50" />
+            <waveform-entry amplitude="114" durationMs="50" />
+            <waveform-entry amplitude="133" durationMs="50" />
+            <waveform-entry amplitude="162" durationMs="50" />
+            <waveform-entry amplitude="205" durationMs="50" />
+            <waveform-entry amplitude="255" durationMs="50" />
+            <waveform-entry amplitude="255" durationMs="300" />
+            <waveform-entry amplitude="0" durationMs="1000" />
+        </repeating>
+    </waveform-effect>
+</vibration>
\ No newline at end of file
diff --git a/core/res/res/values-af/strings.xml b/core/res/res/values-af/strings.xml
index 2d13ab5..7675da5 100644
--- a/core/res/res/values-af/strings.xml
+++ b/core/res/res/values-af/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Gebruik biometrie of skermslot"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verifieer dat dit jy is"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Gebruik jou biometrie om voort te gaan"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Gebruik jou vingerafdruk om voort te gaan"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Gebruik jou gesig om voort te gaan"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Gebruik jou biometriese data of skermslot om voort te gaan"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometriese hardeware is nie beskikbaar nie"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Stawing is gekanselleer"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Vingerafdruk word nie herken nie"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Vingerafdruk word nie herken nie"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Kan nie gesig herken nie. Gebruik eerder vingerafdruk."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Vingerafdruk is gestaaf"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Gesig is gestaaf"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Gesig is gestaaf; druk asseblief bevestig"</string>
@@ -2331,11 +2330,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Laat ’n metgeselapp toe om voorgronddienste van agtergrond af te begin"</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Mikrofoon is beskikbaar"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Mikrofoon is geblokkeer"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dubbelskerm"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dubbelskerm is aan"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen is aan"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> gebruik tans albei skerms om inhoud te wys"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Toestel is te warm"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dubbelskerm is nie beskikbaar nie omdat jou foon tans te warm word"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen is nie beskikbaar nie omdat jou foon tans te warm word"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen is nie beskikbaar nie"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Dual Screen is nie beskikbaar nie omdat Batterybespaarder aan is. Jy kan dit in Instellings afskakel."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Gaan na Instellings"</string>
diff --git a/core/res/res/values-am/strings.xml b/core/res/res/values-am/strings.xml
index 2dd8f3b..8a03761 100644
--- a/core/res/res/values-am/strings.xml
+++ b/core/res/res/values-am/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"ባዮሜትሪክስ ወይም ማያ ገፅ መቆለፊያን ይጠቀሙ"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"እርስዎን መሆንዎን ያረጋግጡ"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"ለመቀጠል ባዮሜትሪክዎን ይጠቀሙ"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"ለመቀጠል የእርስዎን የጣት አሻራ ይጠቀሙ"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"ለመቀጠል የእርስዎን መልክ ይጠቀሙ"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"ለመቀጠል የባዮሜትሪክ ወይም የማያ ገፅ ቁልፍዎን ይጠቀሙ"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"ባዮሜትራዊ ሃርድዌር አይገኝም"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"ማረጋገጥ ተሰርዟል"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"የጣት አሻራ አልታወቀም"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"የጣት አሻራ አልታወቀም"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"መልክን መለየት አልተቻለም። በምትኩ የጣት አሻራ ይጠቀሙ።"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"የጣት አሻራ ትክክለኛነት ተረጋግጧል"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"ፊት ተረጋግጧል"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"ፊት ተረጋግጧል፣ እባክዎ አረጋግጥን ይጫኑ"</string>
diff --git a/core/res/res/values-ar/strings.xml b/core/res/res/values-ar/strings.xml
index 322ae8d..fea0e8f 100644
--- a/core/res/res/values-ar/strings.xml
+++ b/core/res/res/values-ar/strings.xml
@@ -622,8 +622,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"استخدام المقاييس الحيوية أو قفل الشاشة"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"إثبات هويتك"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"استخدام المقاييس الحيوية للمتابعة"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"استخدِم بصمة إصبعك للمتابعة"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"استخدِم وجهك للمتابعة"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"استخدام المقاييس الحيوية أو قفل الشاشة للمتابعة"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"معدّات المقاييس الحيوية غير متاحة."</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"تم إلغاء المصادقة."</string>
@@ -649,6 +647,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"لم يتمّ التعرّف على البصمة."</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"لم يتمّ التعرّف على بصمة الإصبع."</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"يتعذّر التعرّف على الوجه. استخدِم بصمة الإصبع بدلاً من ذلك."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"تم مصادقة بصمة الإصبع"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"تمّت مصادقة الوجه"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"تمّت مصادقة الوجه، يُرجى الضغط على \"تأكيد\"."</string>
@@ -2335,11 +2334,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"يسمح هذا الإذن للتطبيق المصاحب ببدء الخدمات التي تعمل في المقدّمة من الخلفية."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"الميكروفون متاح."</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"تم حظر الميكروفون."</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"استخدام الشاشتين"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"ميزة \"استخدام الشاشتين\" مفعّلة"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"‏ميزة Dual Screen مفعّلة"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"يستخدم \"<xliff:g id="APP_NAME">%1$s</xliff:g>\" كلتا الشاشتين لعرض المحتوى."</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"الجهاز ساخن للغاية"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"ميزة \"استخدام الشاشتين\" غير متاحة لأن هاتفك ساخن للغاية."</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"‏ميزة Dual Screen غير متاحة لأنّ هاتفك ساخن للغاية."</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"‏ميزة Dual Screen غير متاحة"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"‏ميزة Dual Screen غير متاحة لأن ميزة \"توفير شحن البطارية\" مفعّلة. ويمكنك إيقاف هذا الإجراء من خلال \"الإعدادات\"."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"الانتقال إلى الإعدادات"</string>
diff --git a/core/res/res/values-as/strings.xml b/core/res/res/values-as/strings.xml
index 12e0948..24d2932 100644
--- a/core/res/res/values-as/strings.xml
+++ b/core/res/res/values-as/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"বায়\'মেট্ৰিক অথবা স্ক্ৰীন লক ব্যৱহাৰ কৰক"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"এইয়া আপুনিয়েই বুলি সত্যাপন কৰক"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"অব্যাহত ৰাখিবলৈ আপোনাৰ বায়\'মেট্ৰিক ব্যৱহাৰ কৰক"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"অব্যাহত ৰাখিবলৈ আপোনাৰ ফিংগাৰপ্ৰিণ্ট ব্যৱহাৰ কৰক"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"অব্যাহত ৰাখিবলৈ নিজৰ মুখাৱয়ব ব্যৱহাৰ কৰক"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"অব্যাহত ৰাখিবলৈ আপোনাৰ বায়’মেট্ৰিক অথবা স্ক্ৰীন লক ব্যৱহাৰ কৰক"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"বায়োমেট্ৰিক হাৰ্ডৱেৰ উপলব্ধ নহয়"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"বিশ্বাসযোগ্যতাৰ প্ৰমাণীকৰণ বাতিল কৰা হৈছে"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"ফিংগাৰপ্ৰিণ্ট চিনাক্ত কৰিব পৰা নাই"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"ফিংগাৰপ্ৰিণ্ট চিনাক্ত কৰিব পৰা নাই"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"মুখাৱয়ব চিনিব নোৱাৰি। ফিংগাৰপ্ৰিণ্ট ব্যৱহাৰ কৰক।"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"ফিংগাৰপ্ৰিণ্টৰ সত্যাপন কৰা হ’ল"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"মুখমণ্ডলৰ বিশ্বাসযোগ্যতা প্ৰমাণীকৰণ কৰা হ’ল"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"মুখমণ্ডলৰ বিশ্বাসযোগ্যতা প্ৰমাণীকৰণ কৰা হ’ল, অনুগ্ৰহ কৰি ‘নিশ্চিত কৰক’ বুটামটো টিপক"</string>
diff --git a/core/res/res/values-az/strings.xml b/core/res/res/values-az/strings.xml
index ff7436f..4a6d7ff 100644
--- a/core/res/res/values-az/strings.xml
+++ b/core/res/res/values-az/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Biometrik məlumatlardan və ya ekran kilidindən istifadə edin"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Kimliyinizi doğrulayın"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Davam etmək üçün biometrik məlumatlarınızdan istifadə edin"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Barmaq izi ilə davam edin"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Üz ilə davam edin"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Davam etmək üçün biometrik məlumatlar və ya ekran kilidinizdən istifadə edin"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrik proqram əlçatan deyil"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Doğrulama ləğv edildi"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Barmaq izi tanınmır"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Barmaq izi tanınmır"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Tanımaq olmur. Barmaq izini işlədin."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Barmaq izi doğrulandı"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Üz doğrulandı"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Üz təsdiq edildi, təsdiq düyməsinə basın"</string>
diff --git a/core/res/res/values-b+sr+Latn/strings.xml b/core/res/res/values-b+sr+Latn/strings.xml
index c32f95a..7a07cac 100644
--- a/core/res/res/values-b+sr+Latn/strings.xml
+++ b/core/res/res/values-b+sr+Latn/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Koristite biometriju ili zaključavanje ekrana"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Potvrdite svoj identitet"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Koristite biometrijski podatak da biste nastavili"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Nastavite pomoću otiska prsta"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Potvrdite identitet licem da biste nastavili"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Koristite biometrijski podatak ili zaključavanje ekrana da biste nastavili"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrijski hardver nije dostupan"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Potvrda identiteta je otkazana"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Otisak prsta nije prepoznat"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Otisak prsta nije prepoznat"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Lice nije prepoznato. Koristite otisak prsta."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Otisak prsta je potvrđen"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Lice je potvrđeno"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Lice je potvrđeno. Pritisnite Potvrdi"</string>
@@ -2332,11 +2331,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Dozvoljava pratećoj aplikaciji da pokrene usluge u prvom planu iz pozadine."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Mikrofon je dostupan"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Mikrofon je blokiran"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dvojni ekran"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dvojni ekran je uključen"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen je uključen"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> koristi oba ekrana za prikazivanje sadržaja"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Uređaj je previše zagrejan"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dvojni ekran je nedostupan jer je telefon previše zagrejan"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen je nedostupan jer je telefon previše zagrejan"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen nije dostupan"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Dual Screen nije dostupan zato što je Ušteda baterije uključena. To možete da isključite u podešavanjima."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Idi u Podešavanja"</string>
diff --git a/core/res/res/values-be/strings.xml b/core/res/res/values-be/strings.xml
index 3be47fa..2c352f9d 100644
--- a/core/res/res/values-be/strings.xml
+++ b/core/res/res/values-be/strings.xml
@@ -620,8 +620,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Выкарыстоўваць біяметрыю ці блакіроўку экрана"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Спраўдзіце, што гэта вы"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Каб працягнуць, скарыстайце свае біяметрычныя даныя"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Каб працягнуць, скарыстайце адбітак пальца"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Каб працягнуць, скарыстайце распазнаванне твару"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Каб працягнуць, скарыстайце біяметрычныя даныя ці сродак разблакіроўкі экрана"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Біяметрычнае абсталяванне недаступнае"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Аўтэнтыфікацыя скасавана"</string>
@@ -647,6 +645,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Адбітак пальца не распазнаны"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Адбітак пальца не распазнаны"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Твар не распазнаны. Скарыстайце адбітак пальца."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Адбітак пальца распазнаны"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Твар распазнаны"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Твар распазнаны. Націсніце, каб пацвердзіць"</string>
@@ -2333,11 +2332,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Спадарожная праграма зможа запускаць актыўныя сэрвісы з фонавага рэжыму."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Мікрафон даступны"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Мікрафон заблакіраваны"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Двайны экран"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Уключана функцыя \"Двайны экран\""</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Уключана функцыя Dual Screen"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"Праграма \"<xliff:g id="APP_NAME">%1$s</xliff:g>\" выкарыстоўвае абодва экраны для паказу змесціва"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Прылада моцна нагрэлася"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Функцыя \"Двайны экран\" недаступная, бо тэлефон моцна награваецца"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Функцыя Dual Screen недаступная, бо тэлефон моцна награваецца"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Функцыя Dual Screen недаступная"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Функцыя Dual Screen недаступная, бо ўключаны рэжым энергазберажэння. Вы можаце выключыць яго ў Наладах."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Перайсці ў Налады."</string>
diff --git a/core/res/res/values-bg/strings.xml b/core/res/res/values-bg/strings.xml
index 10d747b..078ec85 100644
--- a/core/res/res/values-bg/strings.xml
+++ b/core/res/res/values-bg/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Използване на биометрични данни или опцията за заключване на екрана"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Потвърдете, че сте вие"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Използвайте биометричните си данни, за да продължите"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Използвайте отпечатъка си, за да продължите"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Използвайте лицето си, за да продължите"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Използвайте биометричните си данни или опцията за заключване на екрана, за да продължите"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Биометричният хардуер не е налице"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Удостоверяването бе анулирано"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Отпечатъкът не е разпознат"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Отпечатъкът не е разпознат"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Лицето не е разпознато. Използвайте отпечатък."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Отпечатъкът е удостоверен"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Лицето е удостоверено"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Лицето е удостоверено. Моля, натиснете „Потвърждаване“"</string>
diff --git a/core/res/res/values-bn/strings.xml b/core/res/res/values-bn/strings.xml
index 9d276cb..f451da3 100644
--- a/core/res/res/values-bn/strings.xml
+++ b/core/res/res/values-bn/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"বায়োমেট্রিক্স অথবা স্ক্রিন লক ব্যবহার করুন"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"আপনার পরিচয় যাচাই করুন"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"চালিয়ে যেতে আপনার বায়োমেট্রিক্স ব্যবহার করুন"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"চালিয়ে যেতে ফিঙ্গারপ্রিন্ট ব্যবহার করুন"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"চালিয়ে যেতে আপনার ফেস ব্যবহার করুন"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"চালিয়ে যেতে আপনার বায়োমেট্রিক্স বা স্ক্রিন লক ব্যবহার করুন"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"বায়োমেট্রিক হার্ডওয়্যার পাওয়া যাবে না"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"যাচাইকরণ বাতিল হয়েছে"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"ফিঙ্গারপ্রিন্ট শনাক্ত করা যায়নি"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"ফিঙ্গারপ্রিন্ট শনাক্ত করা যায়নি"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"মুখ শনাক্ত করতে পারছি না। পরিবর্তে আঙ্গুলের ছাপ ব্যবহার করুন।"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"আঙ্গুলের ছাপ যাচাই করা হয়েছে"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"ফেস যাচাই করা হয়েছে"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"ফেস যাচাই করা হয়েছে, \'কনফার্ম করুন\' বোতাম প্রেস করুন"</string>
diff --git a/core/res/res/values-bs/strings.xml b/core/res/res/values-bs/strings.xml
index 33ac0c3..fb02763 100644
--- a/core/res/res/values-bs/strings.xml
+++ b/core/res/res/values-bs/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Koristi biometriju ili zaključavanje ekrana"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Potvrdite identitet"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Koristite biometriju da nastavite"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Potvrdite identitet otiskom prsta da nastavite"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Potvrdite identitet licem da nastavite"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Koristite biometriju ili zaključavanje ekrana da nastavite"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrijski hardver nije dostupan"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autentifikacija je otkazana"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Otisak prsta nije prepoznat"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Otisak prsta nije prepoznat"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Nije moguće prepoznati lice. Koristite otisak prsta."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Otisak prsta je potvrđen"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Lice je provjereno"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Lice je provjereno, pritisnite dugme za potvrdu"</string>
diff --git a/core/res/res/values-ca/strings.xml b/core/res/res/values-ca/strings.xml
index 356576d..edfd9d1 100644
--- a/core/res/res/values-ca/strings.xml
+++ b/core/res/res/values-ca/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Fes servir la biometria o el bloqueig de pantalla"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verifica la teva identitat"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Utilitza la teva biometria per continuar"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Utilitza l\'empremta digital per continuar"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Utilitza la cara per continuar"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Utilitza la biometria o el bloqueig de pantalla per continuar"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Maquinari biomètric no disponible"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"S\'ha cancel·lat l\'autenticació"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"L\'empremta digital no s\'ha reconegut"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"L\'empremta digital no s\'ha reconegut"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"No podem detectar la cara. Usa l\'empremta digital."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"L\'empremta digital s\'ha autenticat"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Cara autenticada"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Cara autenticada; prem el botó per confirmar"</string>
diff --git a/core/res/res/values-cs/strings.xml b/core/res/res/values-cs/strings.xml
index a4e9ab5..d2baa9b 100644
--- a/core/res/res/values-cs/strings.xml
+++ b/core/res/res/values-cs/strings.xml
@@ -620,8 +620,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Použít biometrii nebo zámek obrazovky"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Potvrďte, že jste to vy"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Pokračujte biometrickým ověřením"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Pokračujte přiložením prstu"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Pokračujte ověřením obličeje"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Pokračujte ověřením pomocí biometrických údajů nebo zámku obrazovky"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrický hardware není k dispozici"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Ověření bylo zrušeno"</string>
@@ -647,6 +645,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Otisk prstu nebyl rozpoznán"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Otisk prstu nebyl rozpoznán"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Obličej se nepodařilo rozpoznat. Použijte místo něj otisk prstu."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Otisk byl ověřen"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Obličej byl ověřen"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Obličej byl ověřen, stiskněte tlačítko pro potvrzení"</string>
diff --git a/core/res/res/values-da/strings.xml b/core/res/res/values-da/strings.xml
index b8bd5ba..6de92f9 100644
--- a/core/res/res/values-da/strings.xml
+++ b/core/res/res/values-da/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Brug biometri eller skærmlås"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verificer, at det er dig"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Brug dine biometriske data for at fortsætte"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Brug dit fingeraftryk for at fortsætte"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Brug dit ansigt for at fortsætte"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Brug dine biometriske data eller din skærmlås for at fortsætte"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrisk hardware er ikke tilgængelig"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Godkendelsen blev annulleret"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Fingeraftrykket blev ikke genkendt"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Fingeraftrykket blev ikke genkendt"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Ansigtet kan ikke genkendes. Brug fingeraftryk i stedet."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Fingeraftrykket blev godkendt"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Ansigtet er godkendt"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Ansigtet er godkendt. Tryk på Bekræft."</string>
diff --git a/core/res/res/values-de/strings.xml b/core/res/res/values-de/strings.xml
index 84f2c1f..ec8bb7b 100644
--- a/core/res/res/values-de/strings.xml
+++ b/core/res/res/values-de/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Biometrisches Verfahren oder Displaysperre verwenden"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Deine Identität bestätigen"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Mithilfe eines biometrischen Verfahrens fortfahren"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Fingerabdruck verwenden, um fortzufahren"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Gesichtserkennung verwenden, um fortzufahren"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Verwende deine biometrischen Daten oder deine Display-Entsperrmethode, um fortzufahren"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrische Hardware nicht verfügbar"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Authentifizierung abgebrochen"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Fingerabdruck nicht erkannt"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Fingerabdruck nicht erkannt"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Gesicht wurde nicht erkannt. Verwende stattdessen den Fingerabdruck."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Fingerabdruck wurde authentifiziert"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Gesicht authentifiziert"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Gesicht authentifiziert, bitte bestätigen"</string>
diff --git a/core/res/res/values-el/strings.xml b/core/res/res/values-el/strings.xml
index d603a26..66148a9 100644
--- a/core/res/res/values-el/strings.xml
+++ b/core/res/res/values-el/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Χρήση βιομετρικών ή κλειδώματος οθόνης"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Επαλήθευση ταυτότητας"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Χρησιμοποιήστε βιομετρικά για να συνεχίσετε"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Χρησιμοποιήστε το δακτυλικό σας αποτύπωμα για να συνεχίσετε"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Χρησιμοποιήστε το πρόσωπό σας για να συνεχίσετε"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Χρήση βιομετρικών στοιχείων ή κλειδώματος οθόνης για συνέχεια"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Δεν υπάρχει διαθέσιμος βιομετρικός εξοπλισμός"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Ο έλεγχος ταυτότητας ακυρώθηκε"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Δεν είναι δυνατή η αναγνώριση του δακτυλικού αποτυπώματος"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Δεν είναι δυνατή η αναγνώριση του δακτυλικού αποτυπώματος"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Το πρόσωπο δεν αναγνωρίζεται. Χρησιμ. δακτ. αποτ."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Η ταυτότητα του δακτυλικού αποτυπώματος ελέγχθηκε"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Έγινε έλεγχος ταυτότητας προσώπου"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Έγινε έλεγχος ταυτότητας προσώπου, πατήστε \"Επιβεβαίωση\""</string>
diff --git a/core/res/res/values-en-rAU/strings.xml b/core/res/res/values-en-rAU/strings.xml
index c92f460..906e94c 100644
--- a/core/res/res/values-en-rAU/strings.xml
+++ b/core/res/res/values-en-rAU/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Use biometrics or screen lock"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verify that it’s you"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Use your biometric to continue"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Use your fingerprint to continue"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Use your face to continue"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Use your biometric or screen lock to continue"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometric hardware unavailable"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Authentication cancelled"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Fingerprint not recognised"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Fingerprint not recognised"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Can’t recognise face. Use fingerprint instead."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Fingerprint authenticated"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Face authenticated"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Face authenticated. Please press confirm"</string>
diff --git a/core/res/res/values-en-rCA/strings.xml b/core/res/res/values-en-rCA/strings.xml
index bf94625..2d7ba8d 100644
--- a/core/res/res/values-en-rCA/strings.xml
+++ b/core/res/res/values-en-rCA/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Use biometrics or screen lock"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verify it’s you"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Use your biometric to continue"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Use your fingerprint to continue"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Use your face to continue"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Use your biometric or screen lock to continue"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometric hardware unavailable"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Authentication canceled"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Fingerprint not recognized"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Fingerprint not recognized"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Can’t recognize face. Use fingerprint instead."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Fingerprint authenticated"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Face authenticated"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Face authenticated, please press confirm"</string>
diff --git a/core/res/res/values-en-rGB/strings.xml b/core/res/res/values-en-rGB/strings.xml
index 48a10df..ad9c777 100644
--- a/core/res/res/values-en-rGB/strings.xml
+++ b/core/res/res/values-en-rGB/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Use biometrics or screen lock"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verify that it’s you"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Use your biometric to continue"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Use your fingerprint to continue"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Use your face to continue"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Use your biometric or screen lock to continue"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometric hardware unavailable"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Authentication cancelled"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Fingerprint not recognised"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Fingerprint not recognised"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Can’t recognise face. Use fingerprint instead."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Fingerprint authenticated"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Face authenticated"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Face authenticated. Please press confirm"</string>
diff --git a/core/res/res/values-en-rIN/strings.xml b/core/res/res/values-en-rIN/strings.xml
index a3f2d7d..c9db594 100644
--- a/core/res/res/values-en-rIN/strings.xml
+++ b/core/res/res/values-en-rIN/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Use biometrics or screen lock"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verify that it’s you"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Use your biometric to continue"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Use your fingerprint to continue"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Use your face to continue"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Use your biometric or screen lock to continue"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometric hardware unavailable"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Authentication cancelled"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Fingerprint not recognised"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Fingerprint not recognised"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Can’t recognise face. Use fingerprint instead."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Fingerprint authenticated"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Face authenticated"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Face authenticated. Please press confirm"</string>
diff --git a/core/res/res/values-en-rXC/strings.xml b/core/res/res/values-en-rXC/strings.xml
index 17e3fcb..5888963 100644
--- a/core/res/res/values-en-rXC/strings.xml
+++ b/core/res/res/values-en-rXC/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‏‎‏‎‎‎‏‏‏‎‎‏‏‎‎‎‏‏‏‎‎‎‏‏‏‏‎‎‎‎‏‏‎‏‏‏‎‏‏‎‏‏‎‏‎‎‏‎‏‎‏‎‎‏‎‏‏‎‎‎‎Use biometrics or screen lock‎‏‎‎‏‎"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‎‎‎‏‏‎‎‎‎‏‏‎‏‏‏‏‏‏‎‏‎‎‏‎‏‎‏‎‎‎‏‎‎‎‏‏‏‎‏‏‎‎‎‏‎‎‎‏‎‎‎‏‎‎‏‎‎‏‎‎Verify it’s you‎‏‎‎‏‎"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‎‏‎‏‎‏‎‏‏‏‏‎‎‎‏‎‎‎‎‎‎‎‎‎‎‎‎‏‎‎‎‏‎‏‏‎‏‏‎‏‎‏‏‎‎‏‎‏‎‏‏‎‏‏‎‏‏‎‎‎‎Use your biometric to continue‎‏‎‎‏‎"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‎‎‏‎‏‏‏‏‏‎‎‏‏‎‏‎‎‏‎‏‏‏‏‏‎‏‏‎‎‎‎‎‎‎‏‏‏‎‏‏‏‏‎‎‏‏‏‎‎‎‏‎‎‎‏‎‏‏‏‎‎Use your fingerprint to continue‎‏‎‎‏‎"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‏‎‎‏‎‎‏‎‎‎‎‎‎‏‎‎‎‎‏‎‎‎‎‎‎‏‏‏‎‎‎‏‎‎‏‏‏‏‏‏‏‏‎‏‏‏‎‏‎‏‎‏‏‏‏‎‏‏‎‎‎Use your face to continue‎‏‎‎‏‎"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‎‏‎‏‎‎‎‏‏‎‏‏‎‏‏‎‎‏‏‎‎‎‏‏‏‏‏‏‎‎‎‎‎‎‎‎‎‏‏‏‎‏‎‏‎‏‎‎‏‏‎‏‏‎‎‎‎‏‎‎‏‎Use your biometric or screen lock to continue‎‏‎‎‏‎"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‎‎‏‎‏‎‎‏‏‏‎‎‏‎‏‏‏‏‏‎‎‎‏‎‏‎‎‏‏‏‎‏‎‏‎‏‎‏‏‏‎‏‎‏‏‏‎‎‏‎‏‎‎‎‏‏‎‎‎‎‎Biometric hardware unavailable‎‏‎‎‏‎"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‏‏‎‏‎‏‏‎‏‏‎‏‏‏‏‏‎‎‏‎‏‏‎‎‎‏‎‏‏‏‏‎‎‎‎‏‏‎‎‎‏‏‎‎‎‎‎‏‏‎‎‏‎‎‏‎‎‎‏‎‎Authentication canceled‎‏‎‎‏‎"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‏‏‏‏‏‏‎‏‎‏‎‎‎‏‏‏‏‏‏‏‏‏‏‏‎‏‎‏‏‎‏‏‏‏‏‎‏‎‎‏‎‏‏‏‏‎‎‏‎‎‏‏‏‏‏‏‎‎‎‏‎Fingerprint not recognized‎‏‎‎‏‎"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‎‎‏‎‎‏‎‎‏‏‏‏‎‏‏‏‎‏‎‎‏‏‏‎‏‎‏‎‎‏‎‏‎‎‎‏‏‎‎‎‏‎‏‎‏‏‏‏‏‏‎‎‎‏‎‎‏‎‎‎‎Fingerprint not recognized‎‏‎‎‏‎"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‎‏‏‎‎‏‏‎‎‏‏‏‏‎‎‎‎‏‎‏‏‎‎‏‎‏‎‏‏‏‎‏‎‎‎‎‏‏‏‎‎‎‎‏‏‏‎‏‏‎‎‎‏‏‎‏‏‏‎‏‎Can’t recognize face. Use fingerprint instead.‎‏‎‎‏‎"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‏‎‎‎‎‎‏‏‎‎‏‏‏‎‎‎‎‏‎‎‎‎‎‏‏‎‎‏‎‎‏‏‎‏‎‎‎‎‏‎‏‏‎‎‎‎‏‎‏‎‎‏‏‎‏‏‏‎‎‎Fingerprint authenticated‎‏‎‎‏‎"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‏‎‏‏‎‎‎‏‎‎‎‏‎‎‎‏‎‎‏‎‎‎‏‎‏‎‏‎‏‎‎‎‎‏‎‏‏‏‎‏‎‎‏‏‎‎‎‏‏‎‏‎‎‎‎‎‎‏‏‏‎Face authenticated‎‏‎‎‏‎"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‏‏‏‏‎‏‏‎‎‎‎‎‎‏‏‏‏‏‏‏‎‎‎‎‏‏‏‎‏‎‏‏‎‏‎‎‏‏‎‏‏‏‎‎‏‏‎‎‎‏‎‎‏‎‏‏‏‎‏‏‎Face authenticated, please press confirm‎‏‎‎‏‎"</string>
diff --git a/core/res/res/values-es-rUS/strings.xml b/core/res/res/values-es-rUS/strings.xml
index 347d537..756a198 100644
--- a/core/res/res/values-es-rUS/strings.xml
+++ b/core/res/res/values-es-rUS/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Usar datos biométricos o bloqueo de pantalla"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Comprueba que eres tú"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Usa tus datos biométricos para continuar"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Usa tu huella dactilar para continuar"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Usa el rostro para continuar"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Usa tus datos biométricos o bloqueo de pantalla para continuar"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"No hay hardware biométrico disponible"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Se canceló la autenticación"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"No se reconoció la huella dactilar"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"No se reconoció la huella dactilar"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"No se reconoce el rostro. Usa la huella dactilar."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Se autenticó la huella dactilar"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Se autenticó el rostro"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Se autenticó el rostro; presiona Confirmar"</string>
diff --git a/core/res/res/values-es/strings.xml b/core/res/res/values-es/strings.xml
index 70610d1..57480bd 100644
--- a/core/res/res/values-es/strings.xml
+++ b/core/res/res/values-es/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Usar biometría o bloqueo de pantalla"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verifica que eres tú"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Usa tu biometría para continuar"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Usa la huella digital para continuar"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Usa la cara para continuar"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Usa la biometría o tu bloqueo de pantalla para continuar"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Hardware biométrico no disponible"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autenticación cancelada"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Huella digital no reconocida"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Huella digital no reconocida"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"No se reconoce la cara. Usa la huella digital."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Se ha autenticado la huella digital"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Cara autenticada"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Se ha autenticado la cara, pulsa para confirmar"</string>
@@ -1376,7 +1375,7 @@
     <string name="usb_unsupported_audio_accessory_title" msgid="2335775548086533065">"Se ha detectado un accesorio de audio analógico"</string>
     <string name="usb_unsupported_audio_accessory_message" msgid="1300168007129796621">"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="408390247354560331">"Depuración por USB activa"</string>
-    <string name="adb_active_notification_message" msgid="5617264033476778211">"Toca para desactivar depuración USB"</string>
+    <string name="adb_active_notification_message" msgid="5617264033476778211">"Toca para desactivar la depuración USB"</string>
     <string name="adb_active_notification_message" product="tv" msgid="6624498401272780855">"Seleccionar para inhabilitar la depuración por USB"</string>
     <string name="adbwifi_active_notification_title" msgid="6147343659168302473">"Depuración inalámbrica conectada"</string>
     <string name="adbwifi_active_notification_message" msgid="930987922852867972">"Toca para desactivar la depuración inalámbrica"</string>
diff --git a/core/res/res/values-et/strings.xml b/core/res/res/values-et/strings.xml
index 36ef583..3359447 100644
--- a/core/res/res/values-et/strings.xml
+++ b/core/res/res/values-et/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Biomeetria või ekraaniluku kasutamine"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Kinnitage oma isik"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Jätkamiseks kasutage biomeetriat"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Jätkamiseks kasutage oma sõrmejälge"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Jätkamiseks kasutage oma nägu"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Jätkamiseks kasutage oma biomeetrilisi andmeid või ekraanilukku"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biomeetriline riistvara ei ole saadaval"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autentimine tühistati"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Sõrmejälge ei tuvastatud"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Sõrmejälge ei tuvastatud"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Nägu ei õnnestu tuvastada. Kasutage sõrmejälge."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Sõrmejälg autenditi"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Nägu on autenditud"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Nägu on autenditud, vajutage käsku Kinnita"</string>
diff --git a/core/res/res/values-eu/strings.xml b/core/res/res/values-eu/strings.xml
index bd0a045..c2ef534 100644
--- a/core/res/res/values-eu/strings.xml
+++ b/core/res/res/values-eu/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Erabili sistema biometrikoak edo pantailaren blokeoa"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Egiaztatu zeu zarela"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Aurrera egiteko, erabili sistema biometrikoak"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Aurrera egiteko, erabili hatz-marka"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Aurrera egiteko, erabili aurpegia"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Aurrera egiteko, erabili sistema biometrikoak edo pantailaren blokeoa"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Hardware biometrikoa ez dago erabilgarri"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Utzi da autentifikazioa"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Ez da ezagutu hatz-marka"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Ez da ezagutu hatz-marka"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Ezin da hauteman aurpegia. Erabili hatz-marka."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Autentifikatu da hatz-marka"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Autentifikatu da aurpegia"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Autentifikatu da aurpegia; sakatu Berretsi"</string>
@@ -2331,11 +2330,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Aurreko planoko zerbitzuak atzeko planotik abiarazteko baimena ematen die aplikazio osagarriei."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Erabilgarri dago mikrofonoa"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Blokeatuta dago mikrofonoa"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Bi pantailako modua"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Bi pantailako modua aktibatuta dago"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen aktibatuta dago"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> bi pantailak erabiltzen ari da edukia erakusteko"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Gailua beroegi dago"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Bi pantailako modua ez dago erabilgarri telefonoa berotzen ari delako"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen ez dago erabilgarri telefonoa berotzen ari delako"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen ez dago erabilgarri"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Dual Screen ez dago erabilgarri, bateria-aurreztailea aktibatuta dagoelako. Aukera hori desaktibatzeko, joan ezarpenetara."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Joan Ezarpenak atalera"</string>
diff --git a/core/res/res/values-fa/strings.xml b/core/res/res/values-fa/strings.xml
index 2a5f064..3841eaa 100644
--- a/core/res/res/values-fa/strings.xml
+++ b/core/res/res/values-fa/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"استفاده از زیست‌سنجشی یا قفل صفحه"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"تأیید کنید این شمایید"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"برای ادامه، از زیست‌سنجشی استفاده کنید"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"برای ادامه، از اثر انگشتتان استفاده کنید"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"برای ادامه، از چهره‌تان استفاده کنید"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"برای ادامه، از زیست‌سنجشی یا قفل صفحه استفاده کنید"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"سخت‌افزار زیست‌سنجی دردسترس نیست"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"اصالت‌سنجی لغو شد"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"اثر انگشت تشخیص داده نشد"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"اثر انگشت تشخیص داده نشد"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"چهره شناسایی نشد. درعوض از اثر انگشت استفاده کنید."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"اثر انگشت اصالت‌سنجی شد"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"چهره اصالت‌سنجی شد"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"چهره اصالت‌سنجی شد، لطفاً تأیید را فشار دهید"</string>
diff --git a/core/res/res/values-fi/strings.xml b/core/res/res/values-fi/strings.xml
index 16c864c..5c9f0e4 100644
--- a/core/res/res/values-fi/strings.xml
+++ b/core/res/res/values-fi/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Käytä biometriikkaa tai näytön lukitusta"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Vahvista henkilöllisyytesi"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Jatka käyttämällä biometriikkaa"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Jatka sormenjäljen avulla"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Jatka kasvojen avulla"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Jatka biometriikan tai näytön lukituksen avulla"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrinen laitteisto ei käytettävissä"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Todennus peruutettu"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Sormenjälkeä ei tunnistettu"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Sormenjälkeä ei tunnistettu"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Kasvoja ei voi tunnistaa. Käytä sormenjälkeä."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Sormenjälki tunnistettu"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Kasvot tunnistettu"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Kasvot tunnistettu, valitse Vahvista"</string>
diff --git a/core/res/res/values-fr-rCA/strings.xml b/core/res/res/values-fr-rCA/strings.xml
index 60575ad..9b0c536 100644
--- a/core/res/res/values-fr-rCA/strings.xml
+++ b/core/res/res/values-fr-rCA/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Utiliser les données biométriques ou le verrouillage de l\'écran"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Confirmez que c\'est vous"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Utilisez votre méthode d\'authentification biométrique pour continuer"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Utilisez votre empreinte digitale pour continuer"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Utilisez votre visage pour continuer"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Utilisez vos données biométriques ou le verrouillage de l\'écran pour continuer"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Matériel biométrique indisponible"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Authentification annulée"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Empreinte digitale non reconnue"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Empreinte digitale non reconnue"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Visage non reconnu. Utilisez plutôt l\'empreinte digitale."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Empreinte digitale authentifiée"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Visage authentifié"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Visage authentifié, veuillez appuyer sur le bouton Confirmer"</string>
@@ -2332,11 +2331,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Permet à une application compagnon en arrière-plan de lancer des services d\'avant-plan."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Le microphone est accessible"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Le microphone est bloqué"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Double écran"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Le double écran est activé"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen activé"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> utilise les deux écrans pour afficher le contenu"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"L\'appareil est trop chaud"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Le double écran n\'est pas accessible, car votre téléphone est trop chaud"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen n\'est pas accessible, car votre téléphone est trop chaud"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"La fonctionnalité Dual Screen n\'est pas accessible"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"La fonctionnalité Dual Screen n\'est pas accessible, car l\'économiseur de pile est activé. Vous pouvez désactiver cette option dans les paramètres."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Accéder aux paramètres"</string>
diff --git a/core/res/res/values-fr/strings.xml b/core/res/res/values-fr/strings.xml
index 0edaac5..f5f4316 100644
--- a/core/res/res/values-fr/strings.xml
+++ b/core/res/res/values-fr/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Utiliser la biométrie ou le verrouillage de l\'écran"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Confirmez votre identité"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Utilisez la biométrie pour continuer"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Utilisez votre empreinte digitale pour continuer"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Utilisez la reconnaissance faciale pour continuer"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Utilisez la biométrie ou le verrouillage de l\'écran pour continuer"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Matériel biométrique indisponible"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Authentification annulée"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Empreinte digitale non reconnue"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Empreinte digitale non reconnue"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Visage non reconnu. Utilisez votre empreinte."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Empreinte digitale authentifiée"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Visage authentifié"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Visage authentifié, veuillez appuyer sur \"Confirmer\""</string>
diff --git a/core/res/res/values-gl/strings.xml b/core/res/res/values-gl/strings.xml
index e672b2f..ef6d317 100644
--- a/core/res/res/values-gl/strings.xml
+++ b/core/res/res/values-gl/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Utilizar desbloqueo biométrico ou credencial do dispositivo"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verifica que es ti"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Para continuar, utiliza o desbloqueo biométrico"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Usa a impresión dixital para continuar"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Usa o recoñecemento facial para continuar"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Para continuar, utiliza o desbloqueo biométrico ou o bloqueo de pantalla"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"O hardware biométrico non está dispoñible"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Cancelouse a autenticación"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Non se recoñeceu a impresión dixital"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Non se recoñeceu a impresión dixital"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Non se recoñeceu a cara. Usa a impresión dixital."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Autenticouse a impresión dixital"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Autenticouse a cara"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Autenticouse a cara, preme Confirmar"</string>
diff --git a/core/res/res/values-gu/strings.xml b/core/res/res/values-gu/strings.xml
index 05c839b..1f1bc51 100644
--- a/core/res/res/values-gu/strings.xml
+++ b/core/res/res/values-gu/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"બાયોમેટ્રિક્સ અથવા સ્ક્રીન લૉકનો ઉપયોગ કરો"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"તે તમે જ છો એ ચકાસો"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"આગળ વધવા માટે બાયોમેટ્રિકનો ઉપયોગ કરો"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"ચાલુ રાખવા માટે તમારી ફિંગરપ્રિન્ટનો ઉપયોગ કરો"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"ચાલુ રાખવા માટે તમારા ચહેરાનો ઉપયોગ કરો"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"ચાલુ રાખવા માટે તમારા બાયોમેટ્રિક ડેટા અથવા સ્ક્રીન લૉક સુવિધાનો ઉપયોગ કરો"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"બાયોમેટ્રિક હાર્ડવેર ઉપલબ્ધ નથી"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"પ્રમાણીકરણ રદ કર્યું"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"ફિંગરપ્રિન્ટ ઓળખી શકાઈ નથી"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"ફિંગરપ્રિન્ટ ઓળખી શકાઈ નથી"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"ચહેરો ઓળખી શકતા નથી. તેને બદલે ફિંગરપ્રિન્ટ વાપરો."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"ફિંગરપ્રિન્ટ પ્રમાણિત કરી"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"ચહેરા પ્રમાણિત"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"ચહેરા પ્રમાણિત, કૃપા કરીને કન્ફર્મ કરો"</string>
@@ -2335,9 +2334,9 @@
     <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual screen ચાલુ છે"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"કન્ટેન્ટ બતાવવા માટે <xliff:g id="APP_NAME">%1$s</xliff:g> બન્ને ડિસ્પ્લેનો ઉપયોગ કરી રહી છે"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"ડિવાઇસ ખૂબ જ ગરમ છે"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"ડ્યૂઅલ સ્ક્રીન અનુપલબ્ધ છે કારણ કે તમારો ફોન ખૂબ જ ગરમ થઈ રહ્યો છે"</string>
-    <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"ડ્યૂઅલ સ્ક્રીન અનુપલબ્ધ છે"</string>
-    <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"બૅટરી સેવર ચાલુ હોવાને કારણે ડ્યૂઅલ સ્ક્રીન અનુપલબ્ધ છે. તમે સેટિંગમાં જઈને આને બંધ કરી શકો છો."</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen ઉપલબ્ધ નથી કારણ કે તમારો ફોન ખૂબ જ ગરમ થઈ રહ્યો છે"</string>
+    <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen ઉપલબ્ધ નથી"</string>
+    <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"બૅટરી સેવર ચાલુ હોવાને કારણે Dual Screen ઉપલબ્ધ નથી. તમે સેટિંગમાં જઈને આને બંધ કરી શકો છો."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"સેટિંગ પર જાઓ"</string>
     <string name="device_state_notification_turn_off_button" msgid="6327161707661689232">"બંધ કરો"</string>
     <string name="keyboard_layout_notification_selected_title" msgid="1202560174252421219">"<xliff:g id="DEVICE_NAME">%s</xliff:g>ની ગોઠવણી કરવામાં આવી છે"</string>
diff --git a/core/res/res/values-hi/strings.xml b/core/res/res/values-hi/strings.xml
index 888fc0f..01dec74 100644
--- a/core/res/res/values-hi/strings.xml
+++ b/core/res/res/values-hi/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"बायोमेट्रिक्स या स्क्रीन लॉक का क्रेडेंशियल इस्तेमाल करें"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"अपनी पहचान की पुष्टि करें"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"जारी रखने के लिए, बायोमेट्रिक्स इस्तेमाल करें"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"जारी रखने के लिए, अपने फ़िंगरप्रिंट की मदद से पहचान की पुष्टि करें"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"जारी रखने के लिए, अपने चेहरा की मदद से पहचान की पुष्टि करें"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"जारी रखने के लिए, बायोमेट्रिक या स्क्रीन लॉक क्रेडेंशियल डालकर पुष्टि करें"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"बायोमेट्रिक हार्डवेयर उपलब्ध नहीं है"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"प्रमाणीकरण रद्द किया गया"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"फ़िंगरप्रिंट की पहचान नहीं हो पाई"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"फ़िंगरप्रिंट की पहचान नहीं हो पाई"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"चेहरे की पहचान नहीं हुई. फ़िंगरप्रिंट इस्तेमाल करें."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"फ़िंगरप्रिंट की पुष्टि हो गई"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"चेहरे की पहचान की गई"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"चेहरे की पहचान की गई, कृपया पुष्टि बटन दबाएं"</string>
diff --git a/core/res/res/values-hr/strings.xml b/core/res/res/values-hr/strings.xml
index 2e1b8ad..c1d7a23 100644
--- a/core/res/res/values-hr/strings.xml
+++ b/core/res/res/values-hr/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Upotreba biometrijske autentifikacije ili zaključavanja zaslona"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Potvrdite da ste to vi"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Upotrijebite svoju biometrijsku autentifikaciju da biste nastavili"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Za nastavak upotrijebite otisak prsta"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Za nastavak se identificirajte licem"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Za nastavak se identificirajte biometrijski ili vjerodajnicom zaključavanja zaslona"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrijski hardver nije dostupan"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autentifikacija otkazana"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Otisak prsta nije prepoznat"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Otisak prsta nije prepoznat"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Prepoznavanje lica nije uspjelo. Upotrijebite otisak prsta."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Autentificirano otiskom prsta"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Lice je autentificirano"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Lice je autentificirano, pritisnite Potvrdi"</string>
diff --git a/core/res/res/values-hu/strings.xml b/core/res/res/values-hu/strings.xml
index bdf81a5..75e1ee2 100644
--- a/core/res/res/values-hu/strings.xml
+++ b/core/res/res/values-hu/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"A folytatás biometriai feloldással vagy képernyőzárral lehetséges"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Igazolja, hogy Ön az"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"A folytatás biometriai feloldással lehetséges"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"A folytatáshoz használja ujjlenyomatát"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"A folytatáshoz használja az arcalapú feloldást"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"A folytatás biometriai feloldással vagy a képernyőzár feloldásával lehetséges"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrikus hardver nem áll rendelkezésre"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Hitelesítés megszakítva"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Az ujjlenyomat nem ismerhető fel"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Az ujjlenyomat nem ismerhető fel"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Az arc nem felismerhető. Használjon ujjlenyomatot."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Ujjlenyomat hitelesítve"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Arc hitelesítve"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Arc hitelesítve; nyomja meg a Megerősítés lehetőséget"</string>
diff --git a/core/res/res/values-hy/strings.xml b/core/res/res/values-hy/strings.xml
index 6eec876..b2e1230 100644
--- a/core/res/res/values-hy/strings.xml
+++ b/core/res/res/values-hy/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Օգտագործել կենսաչափական համակարգեր կամ էկրանի կողպում"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Հաստատեք ձեր ինքնությունը"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Շարունակելու համար օգտագործեք կենսաչափական համակարգեր"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Շարունակելու համար օգտագործեք ձեր մատնահետքը"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Շարունակելու համար օգտագործեք դեմքով իսկորոշումը"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Շարունակելու համար օգտագործեք ձեր կենսաչափական տվյալները կամ էկրանի կողպումը"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Կենսաչափական սարքը հասանելի չէ"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Նույնականացումը չեղարկվեց"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Մատնահետքը չի ճանաչվել"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Մատնահետքը չի ճանաչվել"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Դեմքը չի հաջողվում ճանաչել։ Օգտագործեք մատնահետքը։"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Մատնահետքը նույնականացվեց"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Դեմքը ճանաչվեց"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Դեմքը ճանաչվեց: Սեղմեք «Հաստատել»:"</string>
@@ -2331,11 +2330,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Թույլատրում է ուղեկցող հավելվածին ակտիվ ծառայություններ գործարկել ֆոնային ռեժիմից։"</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Խոսափողը հասանելի է"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Խոսափողն արգելափակված է"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Կրկնակի էկրան"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Կրկնակի էկրանը միացված է"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen-ը միացված է"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> հավելվածն օգտագործում է երկու էկրանները"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Սարքը գերտաքացել է"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Կրկնակի էկրանն անհասանելի է, քանի որ ձեր հեռախոսը գերտաքանում է"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen-ն անհասանելի է, քանի որ ձեր հեռախոսը գերտաքանում է"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen-ը հասանելի չէ"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Dual Screen-ն անհասանելի է, քանի որ Մարտկոցի տնտեսումը միացված է։ Դուք կարող եք անջատել այս գործառույթը Կարգավորումներում։"</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Անցնել Կարգավորումներ"</string>
diff --git a/core/res/res/values-in/strings.xml b/core/res/res/values-in/strings.xml
index e65d8e3..f0c8b10 100644
--- a/core/res/res/values-in/strings.xml
+++ b/core/res/res/values-in/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Gunakan biometrik atau kunci layar"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verifikasi bahwa ini memang Anda"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Gunakan biometrik untuk melanjutkan"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Gunakan sidik jari untuk melanjutkan"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Gunakan wajah untuk melanjutkan"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Gunakan biometrik atau kunci layar untuk melanjutkan"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Hardware biometrik tidak tersedia"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autentikasi dibatalkan"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Sidik jari tidak dikenali"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Sidik jari tidak dikenali"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Tidak dapat mengenali wajah. Gunakan sidik jari."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Sidik jari diautentikasi"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Wajah diautentikasi"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Wajah diautentikasi, silakan tekan konfirmasi"</string>
@@ -2331,11 +2330,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Mengizinkan aplikasi pendamping memulai layanan latar depan dari latar belakang."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Mikrofon tersedia"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Mikrofon diblokir"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Layar ganda"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
     <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual screen aktif"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> menggunakan kedua layar untuk menampilkan konten"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Suhu perangkat terlalu panas"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Layar ganda tidak tersedia karena suhu ponsel terlalu panas"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen tidak tersedia karena suhu ponsel terlalu panas"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen tidak tersedia"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Dual Screen tidak tersedia karena Penghemat Baterai aktif. Anda dapat menonaktifkannya di Setelan."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Buka Setelan"</string>
diff --git a/core/res/res/values-is/strings.xml b/core/res/res/values-is/strings.xml
index e904c43..7584d1c 100644
--- a/core/res/res/values-is/strings.xml
+++ b/core/res/res/values-is/strings.xml
@@ -296,9 +296,9 @@
     <string name="foreground_service_multiple_separator" msgid="5002287361849863168">"<xliff:g id="LEFT_SIDE">%1$s</xliff:g>, <xliff:g id="RIGHT_SIDE">%2$s</xliff:g>"</string>
     <string name="safeMode" msgid="8974401416068943888">"Örugg stilling"</string>
     <string name="android_system_label" msgid="5974767339591067210">"Android kerfið"</string>
-    <string name="user_owner_label" msgid="8628726904184471211">"Skipta yfir í eigið snið"</string>
+    <string name="user_owner_label" msgid="8628726904184471211">"Skipta yfir í einkasnið"</string>
     <string name="managed_profile_label" msgid="7316778766973512382">"Skipta yfir í vinnusnið"</string>
-    <string name="user_owner_app_label" msgid="1553595155465750298">"Skipta yfir í eigið snið <xliff:g id="APP_NAME">%1$s</xliff:g>"</string>
+    <string name="user_owner_app_label" msgid="1553595155465750298">"Skipta yfir í einkasnið <xliff:g id="APP_NAME">%1$s</xliff:g>"</string>
     <string name="managed_profile_app_label" msgid="367401088383965725">"Skipta yfir í vinnusnið <xliff:g id="APP_NAME">%1$s</xliff:g>"</string>
     <string name="permgrouplab_contacts" msgid="4254143639307316920">"Tengiliðir"</string>
     <string name="permgroupdesc_contacts" msgid="9163927941244182567">"fá aðgang að tengiliðunum þínum"</string>
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Nota lífkenni eða skjálás"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Staðfestu hver þú ert"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Notaðu lífkenni til að halda áfram"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Notaðu fingrafarið til að halda áfram"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Notaðu andlitið til að halda áfram"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Notaðu lífkenni eða skjálás til að halda áfram"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Lífkennavélbúnaður ekki tiltækur"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Hætt við auðkenningu"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Fingrafar þekkist ekki"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Fingrafar þekkist ekki"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Andlit þekkist ekki. Notaðu fingrafar í staðinn."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Fingrafar staðfest"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Andlit staðfest"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Andlit staðfest, ýttu til að staðfesta"</string>
diff --git a/core/res/res/values-it/strings.xml b/core/res/res/values-it/strings.xml
index 66ee832..ac0c7df 100644
--- a/core/res/res/values-it/strings.xml
+++ b/core/res/res/values-it/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Usa la biometria o il blocco schermo"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verifica la tua identità"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Usa la biometria per continuare"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Utilizza la tua impronta per continuare"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Usa il tuo volto per continuare"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Per continuare devi usare i tuoi dati biometrici o il tuo blocco schermo"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Hardware biometrico non disponibile"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autenticazione annullata"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Impronta non riconosciuta"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Impronta non riconosciuta"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Impossibile riconoscere il volto. Usa l\'impronta."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Impronta autenticata"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Volto autenticato"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Volto autenticato, premi Conferma"</string>
diff --git a/core/res/res/values-iw/strings.xml b/core/res/res/values-iw/strings.xml
index 16b2d17..a17e989 100644
--- a/core/res/res/values-iw/strings.xml
+++ b/core/res/res/values-iw/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"שימוש במידע ביומטרי בנעילת מסך"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"אימות הזהות שלך"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"יש להשתמש במידע ביומטרי כדי להמשיך"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"צריך להשתמש בטביעת האצבע כדי להמשיך"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"צריך להשתמש בזיהוי הפנים כדי להמשיך"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"יש להשתמש במידע הביומטרי או בנעילת המסך כדי להמשיך"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"חומרה ביומטרית לא זמינה"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"האימות בוטל"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"טביעת האצבע לא זוהתה"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"טביעת האצבע לא זוהתה"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"לא ניתן לזהות את הפנים. יש להשתמש בטביעת אצבע במקום."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"טביעת האצבע אומתה"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"זיהוי הפנים בוצע"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"זיהוי הפנים בוצע. יש ללחוץ על אישור"</string>
diff --git a/core/res/res/values-ja/strings.xml b/core/res/res/values-ja/strings.xml
index d606468..3065202 100644
--- a/core/res/res/values-ja/strings.xml
+++ b/core/res/res/values-ja/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"生体認証または画面ロックの使用"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"本人確認"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"続行するには生体認証を使用してください"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"続行するには指紋認証を使用してください"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"続行するには顔認証を使用してください"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"続行するには、生体認証または画面ロックを使用してください"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"生体認証ハードウェアが利用できません"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"認証をキャンセルしました"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"指紋を認識できません"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"指紋を認識できません"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"顔を認識できません。指紋認証を使用してください。"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"指紋認証を完了しました"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"顔を認証しました"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"顔を認証しました。[確認] を押してください"</string>
diff --git a/core/res/res/values-ka/strings.xml b/core/res/res/values-ka/strings.xml
index 2badd0a..dd7aff7 100644
--- a/core/res/res/values-ka/strings.xml
+++ b/core/res/res/values-ka/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"გამოიყენეთ ბიომეტრიული სისტემა ან ეკრანის დაბლოკვა"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"დაადასტურეთ ვინაობა"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"გასაგრძელებლად გამოიყენეთ თქვენი ბიომეტრიული მონაცემები"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"გასაგრძელებლად გამოიყენეთ თქვენი თითის ანაბეჭდი"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"გასაგრძელებლად გამოიყენეთ სახის ამოცნობა"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"გასაგრძელებლად გამოიყენეთ თქვენი ბიომეტრიული მონაცემები ან ეკრანის განბლოკვის ნიმუში"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"ბიომეტრიული აპარატურა მიუწვდომელია"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"ავტორიზაცია გაუქმდა"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"თითის ანაბეჭდის ამოცნობა ვერ მოხერხდა"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"თითის ანაბეჭდის ამოცნობა ვერ მოხერხდა"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"სახის ამოცნობა ვერ ხერხდება. სანაცვლოდ თითის ანაბეჭდი გამოიყენეთ."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"თითის ანაბეჭდი ავტორიზებულია"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"სახე ავტორიზებულია"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"სახე ავტორიზებულია, დააჭირეთ დადასტურებას"</string>
diff --git a/core/res/res/values-kk/strings.xml b/core/res/res/values-kk/strings.xml
index 0bb57f9..8cfc1c0 100644
--- a/core/res/res/values-kk/strings.xml
+++ b/core/res/res/values-kk/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Биометриканы немесе экран құлпын пайдалану"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Бұл сіз екеніңізді растаңыз"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Жалғастыру үшін биометрикаңызды пайдаланыңыз."</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Жалғастыру үшін саусақ ізін пайдаланыңыз."</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Жалғастыру үшін бетті анықтау функциясын пайдаланыңыз."</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Жалғастыру үшін биометриканы немесе экран құлпын пайдаланыңыз."</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Биометрикалық жабдық жоқ"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Аутентификациядан бас тартылды."</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Саусақ ізі танылмады."</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Саусақ ізі танылмады."</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Бет танылмады. Орнына саусақ ізін пайдаланыңыз."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Саусақ ізі аутентификацияланды"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Бет танылды"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Бет танылды, \"Растау\" түймесін басыңыз"</string>
@@ -2331,11 +2330,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Қосымша қолданбаға экрандық режимдегі қызметтерді фоннан іске қосуға рұқсат беріледі."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Микрофон қолжетімді."</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Микрофон блокталған."</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Қос экран"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Қос экран функциясы қосулы"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen функциясы қосулы"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> қолданбасы контентті көрсету үшін екі дисплейді де пайдаланады."</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Құрылғы қатты қызып кетті."</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Қос экран функциясы істемейді, себебі телефон қатты қызып кетеді."</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen функциясы істемейді, себебі телефон қатты қызып кетеді."</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen қолжетімсіз"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Батареяны үнемдеу режимі қосулы болғандықтан, Dual Screen қолжетімсіз. Мұны параметрлерден өшіруге болады."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Параметрлерге өту"</string>
diff --git a/core/res/res/values-km/strings.xml b/core/res/res/values-km/strings.xml
index 8cc3c64..db89e91 100644
--- a/core/res/res/values-km/strings.xml
+++ b/core/res/res/values-km/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"ប្រើជីវមាត្រ ឬ​ការចាក់សោអេក្រង់"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"ផ្ទៀងផ្ទាត់ថាជាអ្នក"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"ប្រើជីវមាត្រ​របស់អ្នក ដើម្បីបន្ត"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"ប្រើ​ស្នាមម្រាមដៃ​របស់អ្នក ដើម្បីបន្ត"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"ប្រើមុខរបស់អ្នក ដើម្បីបន្ត"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"ប្រើការចាក់សោអេក្រង់ ឬជីវមាត្ររបស់អ្នក ដើម្បីបន្ត"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"មិនអាច​ប្រើឧបករណ៍​ស្កេន​ស្នាមម្រាមដៃ​បានទេ"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"បាន​បោះបង់​ការ​ផ្ទៀងផ្ទាត់"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"មិនស្គាល់ស្នាមម្រាមដៃទេ"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"មិនស្គាល់ស្នាមម្រាមដៃទេ"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"មិនអាចសម្គាល់មុខបានទេ។ សូមប្រើស្នាមម្រាមដៃជំនួសវិញ។"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"បាន​ផ្ទៀង​ផ្ទាត់​ស្នាម​ម្រាមដៃ"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"បានផ្ទៀងផ្ទាត់​មុខ"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"បានផ្ទៀងផ្ទាត់​មុខ សូម​ចុច​បញ្ជាក់"</string>
diff --git a/core/res/res/values-kn/strings.xml b/core/res/res/values-kn/strings.xml
index a2a048c..73060eb 100644
--- a/core/res/res/values-kn/strings.xml
+++ b/core/res/res/values-kn/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"ಬಯೋಮೆಟ್ರಿಕ್ಸ್ ಅಥವಾ ಸ್ಕ್ರೀನ್ ಲಾಕ್ ಅನ್ನು ಬಳಸಿ"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"ಇದು ನೀವೇ ಎಂದು ಪರಿಶೀಲಿಸಿ"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"ಮುಂದುವರಿಸಲು ನಿಮ್ಮ ಬಯೋಮೆಟ್ರಿಕ್ ಬಳಸಿ"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"ಮುಂದುವರಿಸಲು ನಿಮ್ಮ ಫಿಂಗರ್ ಪ್ರಿಂಟ್ ಅನ್ನು ಬಳಸಿ"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"ಮುಂದುವರಿಸಲು ನಿಮ್ಮ ಮುಖವನ್ನು ಬಳಸಿ"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"ಮುಂದುವರಿಸಲು ನಿಮ್ಮ ಬಯೋಮೆಟ್ರಿಕ್ ಅಥವಾ ಸ್ಕ್ರೀನ್ ಲಾಕ್ ಅನ್ನು ಬಳಸಿ"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"ಬಯೋಮೆಟ್ರಿಕ್ ಹಾರ್ಡ್‌ವೇರ್‌ ಲಭ್ಯವಿಲ್ಲ"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"ಪ್ರಮಾಣೀಕರಣವನ್ನು ರದ್ದುಗೊಳಿಸಲಾಗಿದೆ"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"ಫಿಂಗರ್‌ಪ್ರಿಂಟ್ ಅನ್ನು ಗುರುತಿಸಲಾಗಿಲ್ಲ"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"ಫಿಂಗರ್‌ಪ್ರಿಂಟ್ ಅನ್ನು ಗುರುತಿಸಲಾಗಿಲ್ಲ"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"ಮುಖ ಗುರುತಿಸಲಾಗುತ್ತಿಲ್ಲ ಬದಲಿಗೆ ಫಿಂಗರ್‌ಪ್ರಿಂಟ್ ಬಳಸಿ."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"ಫಿಂಗರ್‌ಪ್ರಿಂಟ್ ಅನ್ನು ಪ್ರಮಾಣೀಕರಣ ಮಾಡಲಾಗಿದೆ"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"ಮುಖವನ್ನು ದೃಢೀಕರಿಸಲಾಗಿದೆ"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"ಮುಖವನ್ನು ದೃಢೀಕರಿಸಲಾಗಿದೆ, ದೃಢೀಕರಣವನ್ನು ಒತ್ತಿ"</string>
diff --git a/core/res/res/values-ko/strings.xml b/core/res/res/values-ko/strings.xml
index 5b1dfd1..4fe36b6 100644
--- a/core/res/res/values-ko/strings.xml
+++ b/core/res/res/values-ko/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"생체 인식 또는 화면 잠금을 사용"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"본인 확인"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"생체 인식을 사용하여 계속하세요"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"계속하려면 지문을 인증하세요"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"계속하려면 얼굴로 인증하세요"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"계속하려면 생체 인식이나 화면 잠금을 사용하세요"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"생체 인식 하드웨어를 사용할 수 없음"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"인증이 취소되었습니다."</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"지문이 인식되지 않았습니다."</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"지문을 인식할 수 없습니다."</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"얼굴을 인식할 수 없습니다. 대신 지문을 사용하세요."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"지문이 인증됨"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"얼굴이 인증되었습니다"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"얼굴이 인증되었습니다. 확인을 누르세요"</string>
diff --git a/core/res/res/values-ky/strings.xml b/core/res/res/values-ky/strings.xml
index f7852d8..763afb1 100644
--- a/core/res/res/values-ky/strings.xml
+++ b/core/res/res/values-ky/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Биометрикалык жөндөөнү же экрандын кулпусун колдонуу"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Өзүңүздү ырастаңыз"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Улантуу үчүн биометрикалык жөндөөнү колдонуу"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Улантуу үчүн манжаңызды сканерге тийгизиңиз"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Улантуу үчүн жүзүңүздү көрсөтүңүз"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Улантуу үчүн биометрикалык маалыматты же экрандын кулпусун колдонуңуз"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Биометрикалык аппарат жеткиликсиз"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Аныктыгын текшерүү жокко чыгарылды"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Манжа изи таанылган жок"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Манжа изи таанылган жок"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Жүз таанылбай жатат. Манжа изин колдонуңуз."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Манжа изи текшерилди"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Жүздүн аныктыгы текшерилди"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Жүздүн аныктыгы текшерилди, эми \"Ырастоону\" басыңыз"</string>
diff --git a/core/res/res/values-lo/strings.xml b/core/res/res/values-lo/strings.xml
index 68f4acf..c57d386 100644
--- a/core/res/res/values-lo/strings.xml
+++ b/core/res/res/values-lo/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"ໃຊ້ລະບົບຊີວະມິຕິ ຫຼື ການລັອກໜ້າຈໍ"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"ຢັ້ງຢືນວ່າແມ່ນທ່ານ"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"ໃຊ້ລະບົບຊີວະມິຕິຂອງທ່ານເພື່ອດຳເນີນການຕໍ່"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"ໃຊ້ລາຍນິ້ວມືຂອງທ່ານເພື່ອສືບຕໍ່"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"ໃຊ້ໃບໜ້າຂອງທ່ານເພື່ອສືບຕໍ່"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"ໃຊ້ລະບົບຊີວະມິຕິ ຫຼື ການລັອກໜ້າຈໍຂອງທ່ານເພື່ອດຳເນີນການຕໍ່"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"ຮາດແວຊີວະມິຕິບໍ່ສາມາດໃຊ້ໄດ້"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"ຍົກເລີກການຮັບຮອງຄວາມຖືກຕ້ອງແລ້ວ"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"ບໍ່ຮູ້ຈັກລາຍນິ້ວມື"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"ບໍ່ຮູ້ຈັກລາຍນິ້ວມື"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"ບໍ່ສາມາດຈຳແນກໜ້າໄດ້. ກະລຸນາໃຊ້ລາຍນິ້ວມືແທນ."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"ພິສູດຢືນຢັນລາຍນິ້ວມືແລ້ວ"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"ພິສູດຢືນຢັນໃບໜ້າແລ້ວ"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"ພິສູດຢືນຢັນໃບໜ້າແລ້ວ, ກະລຸນາກົດຢືນຢັນ"</string>
diff --git a/core/res/res/values-lt/strings.xml b/core/res/res/values-lt/strings.xml
index fca59f8..ed12059 100644
--- a/core/res/res/values-lt/strings.xml
+++ b/core/res/res/values-lt/strings.xml
@@ -620,8 +620,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Naudoti biometrinius duomenis arba ekrano užraktą"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Patvirtinkite, kad tai jūs"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Norėdami tęsti, naudokite biometrinius duomenis"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Jei norite tęsti, naudokite piršto atspaudą"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Jei norite tęsti, naudokite veido atpažinimo funkciją"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Jei norite tęsti, naudokite biometrinius duomenis arba ekrano užraktą"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrinė aparatinė įranga nepasiekiama"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autentifikavimas atšauktas"</string>
@@ -647,6 +645,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Piršto atspaudas neatpažintas"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Piršto atspaudas neatpažintas"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Veidas neatpažintas. Naudokite kontrolinį kodą."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Piršto antspaudas autentifikuotas"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Veidas autentifikuotas"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Veidas autentifikuotas, paspauskite patvirtinimo mygtuką"</string>
diff --git a/core/res/res/values-lv/strings.xml b/core/res/res/values-lv/strings.xml
index 563d206..a2380d9 100644
--- a/core/res/res/values-lv/strings.xml
+++ b/core/res/res/values-lv/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Biometrijas vai ekrāna bloķēšanas izmantošana"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Apstipriniet, ka tas esat jūs"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Lai turpinātu, izmantojiet biometriju"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Izmantojiet pirksta nospiedumu, lai turpinātu"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Izmantojiet autorizāciju pēc sejas, lai turpinātu"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Izmantojiet biometrijas datus vai ekrāna bloķēšanas opciju, lai turpinātu"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrisko datu aparatūra nav pieejama"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autentifikācija ir atcelta"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Pirksta nospiedums netika atpazīts"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Pirksta nospiedums netika atpazīts"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Nevar atpazīt seju. Lietojiet pirksta nospiedumu."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Pirksta nospiedums tika autentificēts."</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Seja autentificēta"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Seja ir autentificēta. Nospiediet pogu Apstiprināt."</string>
@@ -2332,13 +2331,13 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Ļauj palīglietotnei sākt priekšplāna pakalpojumus no fona."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Mikrofons ir pieejams."</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Mikrofons ir bloķēts."</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Divu ekrānu režīms"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Ieslēgts divu ekrānu režīms"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen režīms"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Ieslēgts Dual Screen režīms"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> satura rādīšanai izmanto abus displejus."</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Ierīce ir pārāk sakarsusi"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Divu ekrānu režīms nav pieejams, jo tālrunis sāk pārāk sakarst."</string>
-    <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Divu ekrānu režīms nav pieejams"</string>
-    <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Divu ekrānu režīms nav pieejams, jo ir ieslēgts akumulatora enerģijas taupīšanas režīms. To var izslēgt iestatījumos."</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen režīms nav pieejams, jo tālrunis sāk pārāk sakarst."</string>
+    <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen režīms nav pieejams"</string>
+    <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Dual Screen režīms nav pieejams, jo ir ieslēgts akumulatora enerģijas taupīšanas režīms. To var izslēgt iestatījumos."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Atvērt iestatījumus"</string>
     <string name="device_state_notification_turn_off_button" msgid="6327161707661689232">"Izslēgt"</string>
     <string name="keyboard_layout_notification_selected_title" msgid="1202560174252421219">"<xliff:g id="DEVICE_NAME">%s</xliff:g> ir konfigurēta"</string>
diff --git a/core/res/res/values-mk/strings.xml b/core/res/res/values-mk/strings.xml
index 678d167..0eb3927 100644
--- a/core/res/res/values-mk/strings.xml
+++ b/core/res/res/values-mk/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Користи биометрика или заклучен екран"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Потврдете дека сте вие"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Користете ја вашата биометрика за да продолжите"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Користете го отпечатокот за да продолжите"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Користете го вашиот лик за да продолжите"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Користете ја вашата биометрика или заклучување екран за да продолжите"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Биометрискиот хардвер е недостапен"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Проверката е откажана"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Отпечатокот не е препознаен"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Отпечатокот не е препознаен"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Не се препознава ликот. Користете отпечаток."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Отпечатокот е проверен"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Лицето е проверено"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Лицето е проверено, притиснете го копчето „Потврди“"</string>
diff --git a/core/res/res/values-ml/strings.xml b/core/res/res/values-ml/strings.xml
index c2bce63c..e550bdd 100644
--- a/core/res/res/values-ml/strings.xml
+++ b/core/res/res/values-ml/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"ബയോമെട്രിക്‌സ് അല്ലെങ്കിൽ സ്‌ക്രീൻ ലോക്ക് ഉപയോഗിക്കുക"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"ഇത് നിങ്ങളാണെന്ന് പരിശോധിച്ചുറപ്പിക്കുക"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"തുടരാൻ ബയോമെട്രിക് ഉപയോഗിക്കുക"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"തുടരാൻ നിങ്ങളുടെ ഫിംഗർപ്രിന്റ് ഉപയോഗിക്കുക"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"തുടരാൻ നിങ്ങളുടെ മുഖം ഉപയോഗിക്കുക"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"തുടരാൻ നിങ്ങളുടെ ബയോമെട്രിക്‌ അല്ലെങ്കിൽ സ്‌ക്രീൻ ലോക്ക് ഉപയോഗിക്കുക"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"ബയോമെട്രിക് ഹാർ‌ഡ്‌വെയർ ലഭ്യമല്ല"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"പരിശോധിച്ചുറപ്പിക്കൽ റദ്ദാക്കി"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"ഫിംഗർപ്രിന്റ് തിരിച്ചറിഞ്ഞില്ല"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"ഫിംഗർപ്രിന്റ് തിരിച്ചറിഞ്ഞില്ല"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"മുഖം തിരിച്ചറിയാനായില്ല. പകരം ഫിംഗർപ്രിന്റ് ഉപയോഗിക്കൂ."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"ഫിംഗർപ്രിന്റ് പരിശോധിച്ചുറപ്പിച്ചു"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"മുഖം പരിശോധിച്ചുറപ്പിച്ചു"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"മുഖം പരിശോധിച്ചുറപ്പിച്ചു, സ്ഥിരീകരിക്കുക അമർത്തുക"</string>
diff --git a/core/res/res/values-mn/strings.xml b/core/res/res/values-mn/strings.xml
index 0ea1b08..5205d1e 100644
--- a/core/res/res/values-mn/strings.xml
+++ b/core/res/res/values-mn/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Биометр эсвэл дэлгэцийн түгжээ ашиглах"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Өөрийгөө мөн гэдгийг баталгаажуулаарай"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Үргэлжлүүлэхийн тулд биометрээ ашиглана уу"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Үргэлжлүүлэхийн тулд хурууныхаа хээг ашиглана уу"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Үргэлжлүүлэхийн тулд царайгаа ашиглана уу"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Үргэлжлүүлэхийн тулд биометр эсвэл дэлгэцийн түгжээгээ ашиглана уу"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Биометрийн техник хангамж боломжгүй байна"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Нотолгоог цуцаллаа"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Хурууны хээг таньсангүй"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Хурууны хээг таньсангүй"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Царай таних боломжгүй. Оронд нь хурууны хээ ашигла"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Хурууны хээг нотолсон"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Царайг баталгаажууллаа"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Царайг баталгаажууллаа. Баталгаажуулах товчлуурыг дарна уу"</string>
diff --git a/core/res/res/values-mr/strings.xml b/core/res/res/values-mr/strings.xml
index ff2e089..c469e36 100644
--- a/core/res/res/values-mr/strings.xml
+++ b/core/res/res/values-mr/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"बायोमेट्रिक किंवा स्क्रीन लॉक वापरा"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"हे तुम्हीच आहात याची पडताळणी करा"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"पुढे सुरू ठेवण्यासाठी तुमचे बायोमेट्रिक वापरा"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"पुढे सुरू ठेवण्‍यासाठी तुमची फिंगरप्रिंट वापरा"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"पुढे सुरू ठेवण्यासाठी तुमचा चेहरा वापरा"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"पुढे सुरू ठेवण्यासाठी तुमचे बायोमेट्रिक किंवा स्क्रीन लॉक वापरा"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"बायोमेट्रिक हार्डवेअर उपलब्ध नाही"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"ऑथेंटिकेशन रद्द केले"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"फिंगरप्रिंट ओळखली नाही"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"फिंगरप्रिंट ओळखली नाही"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"चेहरा ओळखू शकत नाही. त्याऐवजी फिंगरप्रिंट वापरा."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"फिंगरप्रिंट ऑथेंटिकेट केली आहे"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"चेहरा ऑथेंटिकेशन केलेला आहे"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"चेहरा ऑथेंटिकेशन केलेला आहे, कृपया कंफर्म प्रेस करा"</string>
diff --git a/core/res/res/values-ms/strings.xml b/core/res/res/values-ms/strings.xml
index e98caa6..6ee7721 100644
--- a/core/res/res/values-ms/strings.xml
+++ b/core/res/res/values-ms/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Gunakan biometrik atau kunci skrin"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Sahkan itu anda"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Gunakan biometrik anda untuk meneruskan"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Gunakan cap jari anda untuk teruskan"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Gunakan muka anda untuk teruskan"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Gunakan biometrik atau kunci skrin anda untuk meneruskan pengesahan"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Perkakasan biometrik tidak tersedia"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Pengesahan dibatalkan"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Cap jari tidak dikenali"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Cap jari tidak dikenali"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Tidak mengenali wajah. Gunakan cap jari."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Cap jari disahkan"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Wajah disahkan"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Wajah disahkan, sila tekan sahkan"</string>
diff --git a/core/res/res/values-my/strings.xml b/core/res/res/values-my/strings.xml
index d673904..51cf285 100644
--- a/core/res/res/values-my/strings.xml
+++ b/core/res/res/values-my/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"ဇီဝမက်ထရစ်အချက်အလက်များ (သို့) ဖန်သားပြင်လော့ခ်ချခြင်းကို သုံးခြင်း"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"သင်ဖြစ်ကြောင်း အတည်ပြုပါ"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"ရှေ့ဆက်ရန် သင်၏ ဇီဝမက်ထရစ်အချက်အလက်ကို သုံးပါ"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"ရှေ့ဆက်ရန် သင့်လက်ဗွေကို သုံးပါ"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"ရှေ့ဆက်ရန် သင့်မျက်နှာကို သုံးပါ"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"ရှေ့ဆက်ရန် သင်၏ ဇီဝမက်ထရစ်အချက်အလက် (သို့) ဖန်သားပြင်လော့ခ်ကို သုံးပါ"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"ဇီဝအချက်အလက်သုံး ကွန်ပျူတာစက်ပစ္စည်း မရရှိနိုင်ပါ"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"အထောက်အထားစိစစ်ခြင်းကို ပယ်ဖျက်လိုက်သည်"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"လက်ဗွေကို မသိရှိပါ"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"လက်ဗွေကို မသိရှိပါ"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"မျက်နှာကို မမှတ်မိပါ။ လက်ဗွေကို အစားထိုးသုံးပါ။"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"လက်ဗွေကို အထောက်အထား စိစစ်ပြီးပါပြီ"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"မျက်နှာ အထောက်အထားစိစစ်ပြီးပြီ"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"မျက်နှာ အထောက်အထားစိစစ်ပြီးပြီ၊ အတည်ပြုရန်ကို နှိပ်ပါ"</string>
diff --git a/core/res/res/values-nb/strings.xml b/core/res/res/values-nb/strings.xml
index 50bdebf..d48e831e 100644
--- a/core/res/res/values-nb/strings.xml
+++ b/core/res/res/values-nb/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Bruk biometri eller skjermlås"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Bekreft at det er deg"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Bruk biometri for å fortsette"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Bruk fingeravtrykket for å fortsette"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Bruk ansiktet for å fortsette"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Bruk biometri eller skjermlåsen for å fortsette"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrisk maskinvare er utilgjengelig"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autentiseringen er avbrutt"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Gjenkjenner ikke fingeravtrykket"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Gjenkjenner ikke fingeravtrykket"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Ansiktet gjenkjennes ikke. Bruk fingeravtrykk."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Fingeravtrykket er godkjent"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Ansiktet er autentisert"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Ansiktet er autentisert. Trykk på Bekreft"</string>
diff --git a/core/res/res/values-ne/strings.xml b/core/res/res/values-ne/strings.xml
index d95d750..65ea470 100644
--- a/core/res/res/values-ne/strings.xml
+++ b/core/res/res/values-ne/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"बायोमेट्रिक्स वा स्क्रिन लक प्रयोग गर्नुहोस्"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"यो व्यक्ति तपाईं नै हो भन्ने प्रमाणित गर्नुहोस्"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"जारी राख्न आफ्नो बायोमेट्रिक प्रयोग गर्नुहोस्"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"जारी राख्न आफ्नो फिंगरप्रिन्ट प्रयोग गर्नुहोस्"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"जारी राख्न आफ्नो अनुहार प्रयोग गर्नुहोस्"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"जारी राख्न आफ्नो बायोमेट्रिक वा स्क्रिन लक प्रयोग गरी पुष्टि गर्नुहोस्"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"बायोमेट्रिक हार्डवेयर उपलब्ध छैन"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"प्रमाणीकरण रद्द गरियो"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"फिंगरप्रिन्ट पहिचान गर्न सकिएन"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"फिंगरप्रिन्ट पहिचान गर्न सकिएन"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"अनुहार पहिचान गर्न सकिएन। बरु फिंगरप्रिन्ट प्रयोग गर्नुहोस्।"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"फिंगरप्रिन्ट प्रमाणीकरण गरियो"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"अनुहार प्रमाणीकरण गरियो"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"अनुहार प्रमाणीकरण गरियो, कृपया पुष्टि गर्नुहोस् थिच्नुहोस्"</string>
diff --git a/core/res/res/values-nl/strings.xml b/core/res/res/values-nl/strings.xml
index 9b1e982..9a00d68 100644
--- a/core/res/res/values-nl/strings.xml
+++ b/core/res/res/values-nl/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Biometrische gegevens of schermvergrendeling gebruiken"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Je identiteit verifiëren"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Gebruik je biometrische gegevens om door te gaan"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Gebruik je vingerafdruk om door te gaan"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Gebruik je gezicht om door te gaan"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Gebruik je biometrische gegevens of schermvergrendeling om door te gaan"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrische hardware niet beschikbaar"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Verificatie geannuleerd"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Vingerafdruk niet herkend"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Vingerafdruk niet herkend"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Gezicht niet herkend. Gebruik je vingerafdruk."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Vingerafdruk geverifieerd"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Gezicht geverifieerd"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Gezicht geverifieerd. Druk op Bevestigen."</string>
@@ -2331,11 +2330,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Hiermee kan een bijbehorende app services op de voorgrond vanuit de achtergrond starten."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Microfoon is beschikbaar"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Microfoon is geblokkeerd"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dubbel scherm"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dubbel scherm staat aan"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen staat aan"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> gebruikt beide schermen om content te tonen"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Het apparaat is te warm"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dubbel scherm is niet beschikbaar, omdat je telefoon te warm wordt"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen is niet beschikbaar, omdat je telefoon te warm wordt"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen is niet beschikbaar"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Dual Screen is niet beschikbaar omdat Batterijbesparing aanstaat. Je kunt dit uitzetten via Instellingen."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Naar Instellingen"</string>
diff --git a/core/res/res/values-or/strings.xml b/core/res/res/values-or/strings.xml
index 3e8f9d4..5668e25 100644
--- a/core/res/res/values-or/strings.xml
+++ b/core/res/res/values-or/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"ବାୟୋମେଟ୍ରିକ୍ସ ବା ସ୍କ୍ରିନ୍ ଲକ୍ ବ୍ୟବହାର କରନ୍ତୁ"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"ଏହା ଆପଣ ବୋଲି ଯାଞ୍ଚ କରନ୍ତୁ"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"ଜାରି ରଖିବାକୁ ଆପଣଙ୍କ ବାୟୋମେଟ୍ରିକ୍ସ ବ୍ୟବହାର କରନ୍ତୁ"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"ଜାରି ରଖିବାକୁ ଆପଣଙ୍କ ଟିପଚିହ୍ନ ବ୍ୟବହାର କରନ୍ତୁ"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"ଜାରି ରଖିବାକୁ ଆପଣଙ୍କ ଫେସ ବ୍ୟବହାର କରନ୍ତୁ"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"ଜାରି ରଖିବାକୁ ଆପଣଙ୍କ ବାୟୋମେଟ୍ରିକ୍ କିମ୍ବା ସ୍କ୍ରିନ୍ ଲକ୍ ବ୍ୟବହାର କରନ୍ତୁ"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"ବାୟୋମେଟ୍ରିକ୍‌ ହାର୍ଡୱେର୍‌ ଉପଲବ୍ଧ ନାହିଁ"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"ପ୍ରାମାଣିକତାକୁ ବାତିଲ୍ କରାଯାଇଛି"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"ଟିପଚିହ୍ନ ଚିହ୍ନଟ ହେଲା ନାହିଁ"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"ଟିପଚିହ୍ନ ଚିହ୍ନଟ ହେଲା ନାହିଁ"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"ଫେସ୍ ଚିହ୍ନଟ କରିହେବ ନାହିଁ। ଟିପଚିହ୍ନ ବ୍ୟବହାର କରନ୍ତୁ।"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"ଟିପଚିହ୍ନ ପ୍ରମାଣିତ ହେଲା"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"ମୁହଁ ଚିହ୍ନଟ ହୋଇଛି"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"ମୁହଁ ଚିହ୍ନଟ ହୋଇଛି, ଦୟାକରି ସୁନିଶ୍ଚିତ ଦବାନ୍ତୁ"</string>
diff --git a/core/res/res/values-pa/strings.xml b/core/res/res/values-pa/strings.xml
index c287bf6..043c296 100644
--- a/core/res/res/values-pa/strings.xml
+++ b/core/res/res/values-pa/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"ਬਾਇਓਮੈਟ੍ਰਿਕ ਜਾਂ ਸਕ੍ਰੀਨ ਲਾਕ ਦੀ ਵਰਤੋਂ ਕਰੋ"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"ਆਪਣੀ ਪਛਾਣ ਦੀ ਪੁਸ਼ਟੀ ਕਰੋ"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"ਜਾਰੀ ਰੱਖਣ ਲਈ ਆਪਣੇ ਬਾਇਓਮੈਟ੍ਰਿਕ ਦੀ ਵਰਤੋਂ ਕਰੋ"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"ਜਾਰੀ ਰੱਖਣ ਲਈ ਆਪਣੇ ਫਿੰਗਰਪ੍ਰਿੰਟ ਦੀ ਵਰਤੋਂ ਕਰੋ"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"ਜਾਰੀ ਰੱਖਣ ਲਈ ਆਪਣੇ ਚਿਹਰੇ ਦੀ ਵਰਤੋਂ ਕਰੋ"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"ਜਾਰੀ ਰੱਖਣ ਲਈ ਆਪਣਾ ਬਾਇਓਮੈਟ੍ਰਿਕ ਜਾਂ ਸਕ੍ਰੀਨ ਲਾਕ ਵਰਤੋ"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"ਬਾਇਓਮੈਟ੍ਰਿਕ ਹਾਰਡਵੇਅਰ ਉਪਲਬਧ ਨਹੀਂ ਹੈ"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"ਪ੍ਰਮਾਣੀਕਰਨ ਰੱਦ ਕੀਤਾ ਗਿਆ"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"ਫਿੰਗਰਪ੍ਰਿੰਟ ਦੀ ਪਛਾਣ ਨਹੀਂ ਹੋਈ"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"ਫਿੰਗਰਪ੍ਰਿੰਟ ਦੀ ਪਛਾਣ ਨਹੀਂ ਹੋਈ"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"ਚਿਹਰਾ ਨਹੀਂ ਪਛਾਣ ਸਕਦੇ। ਇਸਦੀ ਬਜਾਏ ਫਿੰਗਰਪ੍ਰਿੰਟ ਵਰਤੋ।"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"ਫਿੰਗਰਪ੍ਰਿੰਟ ਪ੍ਰਮਾਣਿਤ ਹੋਇਆ"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"ਚਿਹਰਾ ਪੁਸ਼ਟੀਕਰਨ"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"ਚਿਹਰਾ ਪੁਸ਼ਟੀਕਰਨ, ਕਿਰਪਾ ਕਰਕੇ \'ਪੁਸ਼ਟੀ ਕਰੋ\' ਦਬਾਓ"</string>
@@ -2331,11 +2330,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"ਸੰਬੰਧੀ ਐਪ ਨੂੰ ਬੈਕਗ੍ਰਾਊਂਡ ਤੋਂ ਫੋਰਗ੍ਰਾਊਂਡ ਸੇਵਾਵਾਂ ਸ਼ੁਰੂ ਕਰਨ ਦੀ ਆਗਿਆ ਮਿਲਦੀ ਹੈ।"</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"ਮਾਈਕ੍ਰੋਫ਼ੋਨ ਉਪਲਬਧ ਹੈ"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"ਮਾਈਕ੍ਰੋਫ਼ੋਨ ਬਲਾਕ ਕੀਤਾ ਗਿਆ ਹੈ"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"ਦੋਹਰੀ ਸਕ੍ਰੀਨ"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"ਦੋਹਰੀ ਸਕ੍ਰੀਨ ਚਾਲੂ ਹੈ"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen ਚਾਲੂ ਹੈ"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> ਸਮੱਗਰੀ ਨੂੰ ਦਿਖਾਉਣ ਲਈ ਦੋਵੇਂ ਡਿਸਪਲੇਆਂ ਦੀ ਵਰਤੋਂ ਕਰ ਰਹੀ ਹੈ"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"ਡੀਵਾਈਸ ਬਹੁਤ ਗਰਮ ਹੈ"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"ਦੋਹਰੀ ਸਕ੍ਰੀਨ ਵਿਸ਼ੇਸ਼ਤਾ ਉਪਲਬਧ ਨਹੀਂ ਹੈ ਕਿਉਂਕਿ ਤੁਹਾਡਾ ਫ਼ੋਨ ਬਹੁਤ ਗਰਮ ਹੋ ਰਿਹਾ ਹੈ"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen ਵਿਸ਼ੇਸ਼ਤਾ ਉਪਲਬਧ ਨਹੀਂ ਹੈ ਕਿਉਂਕਿ ਤੁਹਾਡਾ ਫ਼ੋਨ ਬਹੁਤ ਗਰਮ ਹੋ ਰਿਹਾ ਹੈ"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen ਵਿਸ਼ੇਸ਼ਤਾ ਉਪਲਬਧ ਨਹੀਂ ਹੈ"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Dual Screen ਵਿਸ਼ੇਸ਼ਤਾ ਉਪਲਬਧ ਨਹੀਂ ਹੈ ਕਿਉਂਕਿ ਬੈਟਰੀ ਸੇਵਰ ਚਾਲੂ ਹੈ। ਤੁਸੀਂ ਇਸਨੂੰ ਸੈਟਿੰਗਾਂ ਵਿੱਚ ਬੰਦ ਕਰ ਸਕਦੇ ਹੋ।"</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"ਸੈਟਿੰਗਾਂ \'ਤੇ ਜਾਓ"</string>
diff --git a/core/res/res/values-pl/strings.xml b/core/res/res/values-pl/strings.xml
index cf2571b..709b067 100644
--- a/core/res/res/values-pl/strings.xml
+++ b/core/res/res/values-pl/strings.xml
@@ -620,8 +620,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Używaj biometrii lub blokady ekranu"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Potwierdź, że to Ty"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Użyj biometrii, by kontynuować"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Aby kontynuować, użyj odcisku palca"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Aby kontynuować, użyj rozpoznawania twarzy"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Aby kontynuować, użyj biometrii lub blokady ekranu"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Sprzęt biometryczny niedostępny"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Anulowano uwierzytelnianie"</string>
@@ -647,6 +645,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Nie rozpoznano odcisku palca"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Nie rozpoznano odcisku palca"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Nie rozpoznaję twarzy. Użyj odcisku palca."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Uwierzytelniono odciskiem palca"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Twarz rozpoznana"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Twarz rozpoznana, kliknij Potwierdź"</string>
@@ -2337,7 +2336,7 @@
     <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Włączono podwójny ekran"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"Aplikacja <xliff:g id="APP_NAME">%1$s</xliff:g> korzysta z obu wyświetlaczy, aby pokazać treści"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Urządzenie jest za ciepłe"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Podwójny ekran jest niedostępny, ponieważ telefon za bardzo się nagrzewa"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Funkcja Dual Screen jest niedostępna, ponieważ telefon za bardzo się nagrzewa"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Funkcja Dual Screen jest niedostępna"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Funkcja Dual Screen jest niedostępna, ponieważ włączono Oszczędzanie baterii. Możesz to wyłączyć w Ustawieniach."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Otwórz ustawienia"</string>
diff --git a/core/res/res/values-pt-rBR/strings.xml b/core/res/res/values-pt-rBR/strings.xml
index 2ca6ec7..eb6aaeb 100644
--- a/core/res/res/values-pt-rBR/strings.xml
+++ b/core/res/res/values-pt-rBR/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Usar biometria ou bloqueio de tela"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Confirme que é você"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Use seus dados biométricos para continuar"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Use sua impressão digital para continuar"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Use seu rosto para continuar"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Use sua autenticação biométrica ou o bloqueio de tela para continuar"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Hardware biométrico indisponível"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autenticação cancelada"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Impressão digital não reconhecida"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Impressão digital não reconhecida"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Não foi possível reconhecer o rosto Use a impressão digital."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Impressão digital autenticada"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Rosto autenticado"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Rosto autenticado, pressione \"Confirmar\""</string>
diff --git a/core/res/res/values-pt-rPT/strings.xml b/core/res/res/values-pt-rPT/strings.xml
index 83da4b5..25a816c 100644
--- a/core/res/res/values-pt-rPT/strings.xml
+++ b/core/res/res/values-pt-rPT/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Usar a biometria ou o bloqueio de ecrã"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Confirme a sua identidade"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Utilize a biometria para continuar."</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Use a impressão digital para continuar"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Use o rosto para continuar"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Utilize a biometria ou o bloqueio de ecrã para continuar"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Hardware biométrico indisponível."</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autenticação cancelada"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Impressão digital não reconhecida"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Impressão digital não reconhecida"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Impos. reconh. rosto. Utilize a impressão digital."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"A impressão digital foi autenticada."</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Rosto autenticado."</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Rosto autenticado. Prima Confirmar."</string>
@@ -966,7 +965,7 @@
     <string name="keyguard_password_wrong_pin_code" msgid="8583732939138432793">"Código PIN incorreto."</string>
     <string name="keyguard_label_text" msgid="3841953694564168384">"Para desbloquear, prima Menu e, em seguida, 0."</string>
     <string name="emergency_call_dialog_number_for_display" msgid="2978165477085612673">"Número de emergência"</string>
-    <string name="lockscreen_carrier_default" msgid="6192313772955399160">"Sem rede móvel"</string>
+    <string name="lockscreen_carrier_default" msgid="6192313772955399160">"Sem dados"</string>
     <string name="lockscreen_screen_locked" msgid="7364905540516041817">"Ecrã bloqueado."</string>
     <string name="lockscreen_instructions_when_pattern_enabled" msgid="7982445492532123308">"Prima Menu para desbloquear ou efectuar uma chamada de emergência."</string>
     <string name="lockscreen_instructions_when_pattern_disabled" msgid="7434061749374801753">"Prima Menu para desbloquear."</string>
diff --git a/core/res/res/values-pt/strings.xml b/core/res/res/values-pt/strings.xml
index 2ca6ec7..eb6aaeb 100644
--- a/core/res/res/values-pt/strings.xml
+++ b/core/res/res/values-pt/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Usar biometria ou bloqueio de tela"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Confirme que é você"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Use seus dados biométricos para continuar"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Use sua impressão digital para continuar"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Use seu rosto para continuar"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Use sua autenticação biométrica ou o bloqueio de tela para continuar"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Hardware biométrico indisponível"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autenticação cancelada"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Impressão digital não reconhecida"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Impressão digital não reconhecida"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Não foi possível reconhecer o rosto Use a impressão digital."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Impressão digital autenticada"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Rosto autenticado"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Rosto autenticado, pressione \"Confirmar\""</string>
diff --git a/core/res/res/values-ro/strings.xml b/core/res/res/values-ro/strings.xml
index 345f67f..eca2eb3 100644
--- a/core/res/res/values-ro/strings.xml
+++ b/core/res/res/values-ro/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Folosește sistemele biometrice sau blocarea ecranului"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Confirmă-ți identitatea"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Folosește sistemele biometrice pentru a continua"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Folosește amprenta pentru a continua"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Folosește-ți chipul pentru a continua"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Folosește sistemele biometrice sau blocarea ecranului pentru a continua"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Hardware biometric indisponibil"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autentificarea a fost anulată"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Amprenta nu a fost recunoscută"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Amprenta nu a fost recunoscută"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Chipul nu a fost recunoscut. Folosește amprenta."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Amprentă autentificată"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Chip autentificat"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Chip autentificat, apasă pe Confirmă"</string>
diff --git a/core/res/res/values-ru/strings.xml b/core/res/res/values-ru/strings.xml
index efebc8a..8326ba8 100644
--- a/core/res/res/values-ru/strings.xml
+++ b/core/res/res/values-ru/strings.xml
@@ -620,8 +620,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Использовать биометрию или блокировку экрана"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Подтвердите, что это вы"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Чтобы продолжить, используйте биометрические данные."</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Чтобы продолжить, прикоснитесь пальцем к сканеру."</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Чтобы продолжить, используйте фейсконтроль."</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Чтобы продолжить, используйте биометрию или данные для разблокировки экрана."</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Биометрическое оборудование недоступно"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Аутентификация отменена"</string>
@@ -647,6 +645,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Отпечаток не распознан."</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Отпечаток не распознан."</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Не удалось распознать лицо. Используйте отпечаток."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Отпечаток пальца проверен"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Лицо распознано"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Лицо распознано, нажмите кнопку \"Подтвердить\""</string>
@@ -2333,11 +2332,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Сопутствующее приложение сможет запускать активные службы из фонового режима."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Микрофон доступен."</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Микрофон заблокирован."</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Двойной экран"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Двойной экран включен"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Функция Dual Screen включена"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> использует оба экрана."</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Устройство перегрелось"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Двойной экран недоступен из-за перегрева телефона."</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Функция Dual Screen недоступна из-за перегрева телефона."</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Функция Dual Screen недоступна"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Функция Dual Screen недоступна, так как включен режим энергосбережения. Вы можете отключить его в настройках."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Открыть настройки"</string>
diff --git a/core/res/res/values-si/strings.xml b/core/res/res/values-si/strings.xml
index 4a0b715..f81ff63 100644
--- a/core/res/res/values-si/strings.xml
+++ b/core/res/res/values-si/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"ජෛවමිතික හෝ තිර අගුල භාවිත කරන්න"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"එය ඔබ බව තහවුරු කරන්න"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"ඉදිරියට යාමට ඔබගේ ජෛවමිතික භාවිත කරන්න"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"ඉදිරියට යාමට ඔබේ ඇඟිලි සලකුණ භාවිත කරන්න"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"ඉදිරියට යාමට ඔබේ මුහුණ භාවිත කරන්න"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"ඉදිරියට යාමට ඔබගේ ජෛවමිතික හෝ තිර අගුල භාවිත කරන්න"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"ජීවමිතික දෘඪාංග ලබා ගත නොහැකිය"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"සත්‍යාපනය අවලංගු කළා"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"ඇඟිලි සලකුණ හඳුනා නොගන්නා ලදි"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"ඇඟිලි සලකුණ හඳුනා නොගන්නා ලදි"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"මුහුණ හැඳිනිය නොහැක. ඒ වෙනුවට ඇඟිලි සලකුණ භාවිත ක."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"ඇඟිලි සලකුණ සත්‍යාපනය කරන ලදී"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"මුහුණ සත්‍යාපනය කරන ලදී"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"මුහුණ සත්‍යාපනය කරන ලදී, කරුණාකර තහවුරු කරන්න ඔබන්න"</string>
diff --git a/core/res/res/values-sk/strings.xml b/core/res/res/values-sk/strings.xml
index 0a1b1593..7bcf119 100644
--- a/core/res/res/values-sk/strings.xml
+++ b/core/res/res/values-sk/strings.xml
@@ -620,8 +620,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Použiť biometrické údaje alebo zámku obrazovky"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Overenie, že ste to vy"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Ak chcete pokračovať, použite biometrický údaj"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Pokračujte nasnímaním odtlačku prsta"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Pokračujte nasnímaním tváre"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Pokračujte použitím biometrických údajov alebo zámky obrazovky"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrický hardvér nie je k dispozícii"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Overenie bolo zrušené"</string>
@@ -647,6 +645,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Odtlačok prsta nebol rozpoznaný"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Odtlačok prsta nebol rozpoznaný"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Tvár sa nedá rozpoznať. Použite odtlačok prsta."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Odtlačok prsta bol overený"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Tvár bola overená"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Tvár bola overená, stlačte tlačidlo potvrdenia"</string>
diff --git a/core/res/res/values-sl/strings.xml b/core/res/res/values-sl/strings.xml
index 00cf50b..2035979 100644
--- a/core/res/res/values-sl/strings.xml
+++ b/core/res/res/values-sl/strings.xml
@@ -620,8 +620,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Uporaba biometrike ali odklepanja s poverilnico"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Preverite, da ste res vi"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Za nadaljevanje uporabite biometrični podatek."</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Za nadaljevanje uporabite prstni odtis"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Za nadaljevanje uporabite obraz"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Za nadaljevanje uporabite biometrični podatek ali odklepanje s poverilnico."</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Strojna oprema za biometrične podatke ni na voljo"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Preverjanje pristnosti je preklicano"</string>
@@ -647,6 +645,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Prstni odtis ni prepoznan."</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Prstni odtis ni prepoznan."</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Obraza ni mogoče prepoznati. Uporabite prstni odtis."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Pristnost prstnega odtisa je preverjena"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Pristnost obraza je potrjena"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Pristnost obraza je preverjena. Pritisnite gumb »Potrdi«."</string>
diff --git a/core/res/res/values-sq/strings.xml b/core/res/res/values-sq/strings.xml
index 426b255..a2e851a 100644
--- a/core/res/res/values-sq/strings.xml
+++ b/core/res/res/values-sq/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Përdor sistemet biometrike ose kyçjen e ekranit"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verifiko që je ti"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Përdor sistemet e tua biometrike për të vazhduar"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Përdor gjurmën e gishtit për të vazhduar"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Përdor fytyrën tënde për të vazhduar"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Përdor sistemet e tua biometrike ose kyçjen e ekranit për të vazhduar"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Nuk ofrohet harduer biometrik"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Vërtetimi u anulua"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Gjurma e gishtit nuk u njoh"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Gjurma e gishtit nuk u njoh"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Nuk mund ta dallojë fytyrën. Përdor më mirë gjurmën e gishtit."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Gjurma e gishtit u vërtetua"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Fytyra u vërtetua"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Fytyra u vërtetua, shtyp \"Konfirmo\""</string>
diff --git a/core/res/res/values-sr/strings.xml b/core/res/res/values-sr/strings.xml
index a2aee9c..a13d56d 100644
--- a/core/res/res/values-sr/strings.xml
+++ b/core/res/res/values-sr/strings.xml
@@ -619,8 +619,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Користите биометрију или закључавање екрана"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Потврдите свој идентитет"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Користите биометријски податак да бисте наставили"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Наставите помоћу отиска прста"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Потврдите идентитет лицем да бисте наставили"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Користите биометријски податак или закључавање екрана да бисте наставили"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Биометријски хардвер није доступан"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Потврда идентитета је отказана"</string>
@@ -646,6 +644,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Отисак прста није препознат"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Отисак прста није препознат"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Лице није препознато. Користите отисак прста."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Отисак прста је потврђен"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Лице је потврђено"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Лице је потврђено. Притисните Потврди"</string>
@@ -2332,11 +2331,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Дозвољава пратећој апликацији да покрене услуге у првом плану из позадине."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Микрофон је доступан"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Микрофон је блокиран"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Двојни екран"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Двојни екран је укључен"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen је укључен"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> користи оба екрана за приказивање садржаја"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Уређај је превише загрејан"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Двојни екран је недоступан јер је телефон превише загрејан"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen је недоступан јер је телефон превише загрејан"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen није доступан"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Dual Screen није доступан зато што је Уштеда батерије укључена. То можете да искључите у подешавањима."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Иди у Подешавања"</string>
diff --git a/core/res/res/values-sv/strings.xml b/core/res/res/values-sv/strings.xml
index af2e1ea..0a43e46 100644
--- a/core/res/res/values-sv/strings.xml
+++ b/core/res/res/values-sv/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Använd biometrisk data eller skärmlåset"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Verifiera din identitet"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Fortsätt med hjälp av din biometriska data"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Fortsätt med hjälp av ditt fingeravtryck"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Fortsätt med hjälp av ditt ansikte"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Fortsätt med hjälp av din biometriska data eller skärmlåset"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrisk maskinvara är inte tillgänglig"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autentiseringen avbröts"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Fingeravtrycket känns inte igen"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Fingeravtrycket känns inte igen"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Ansiktet kändes inte igen. Använd fingeravtryck."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Fingeravtrycket har autentiserats"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Ansiktet har autentiserats"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Ansiktet har autentiserats. Tryck på Bekräfta"</string>
@@ -2331,11 +2330,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Tillåter att en tillhörande app startar förgrundstjänster i bakgrunden."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Mikrofonen är tillgänglig"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Mikrofonen är blockerad"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dubbel skärm"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dubbel skärm är på"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen är på"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> använder båda skärmarna för att visa innehåll"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Enheten är för varm"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dubbel skärm kan inte användas eftersom telefonen börjar bli för varm"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen kan inte användas eftersom telefonen börjar bli för varm"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen är inte tillgängligt"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Dual Screen kan inte användas eftersom battersparläget är aktiverat. Du kan inaktivera detta i inställningarna."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Öppna inställningarna"</string>
diff --git a/core/res/res/values-sw/strings.xml b/core/res/res/values-sw/strings.xml
index d77385c..466df4f 100644
--- a/core/res/res/values-sw/strings.xml
+++ b/core/res/res/values-sw/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Tumia bayometriki au mbinu ya kufunga skrini"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Thibitisha kuwa ni wewe"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Tumia bayometriki yako ili uendelee"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Tumia alama ya kidole chako ili uendelee"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Tumia uso wako ili uendelee"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Tumia bayometriki au mbinu yako ya kufunga skrini ili uendelee"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Maunzi ya bayometriki hayapatikani"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Imeghairi uthibitishaji"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Alama ya kidole haijatambuliwa"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Alama ya kidole haijatambuliwa"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Imeshindwa kutambua uso. Tumia alama ya kidole."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Imethibitisha alama ya kidole"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Uso umethibitishwa"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Uso umethibitishwa, tafadhali bonyeza thibitisha"</string>
@@ -2332,12 +2331,12 @@
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Maikrofoni inapatikana"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Maikrofoni imezuiwa"</string>
     <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual screen"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Umewasha kipengele cha hali ya skrini mbili"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual screen imewasha"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> inatumia skrini zote kuonyesha maudhui"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Kifaa kina joto sana"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Kipengele cha Hali ya Skrini Mbili hakipatikani kwa sababu simu yako inapata joto sana"</string>
-    <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Kipengele cha Hali ya Skrini Mbili hakipatikani"</string>
-    <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Kipengele cha Hali ya Skrini Mbili hakipatikani kwa sababu kipengele cha Kiokoa Betri kimewashwa. Unaweza kuzima kipengele hiki katika Mipangilio."</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Kipengele cha Dual Screen hakipatikani kwa sababu simu yako inapata joto sana"</string>
+    <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen haipatikani"</string>
+    <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Kipengele cha Dual Screen hakipatikani kwa sababu Kiokoa Betri kimewashwa. Unaweza kukizima katika Mipangilio."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Nenda kwenye Mipangilio"</string>
     <string name="device_state_notification_turn_off_button" msgid="6327161707661689232">"Zima"</string>
     <string name="keyboard_layout_notification_selected_title" msgid="1202560174252421219">"<xliff:g id="DEVICE_NAME">%s</xliff:g> imewekewa mipangilio"</string>
diff --git a/core/res/res/values-ta/strings.xml b/core/res/res/values-ta/strings.xml
index 50d056a..b2551e7 100644
--- a/core/res/res/values-ta/strings.xml
+++ b/core/res/res/values-ta/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"பயோமெட்ரிக்ஸையோ திரைப் பூட்டையோ பயன்படுத்து"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"நீங்கள்தான் என உறுதிசெய்க"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"தொடர உங்கள் பயோமெட்ரிக்கைப் பயன்படுத்துங்கள்"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"தொடர்வதற்கு உங்கள் கைரேகையைப் பயன்படுத்துங்கள்"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"தொடர்வதற்கு உங்கள் முகத்தைப் பயன்படுத்துங்கள்"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"தொடர, உங்கள் பயோமெட்ரிக்கையோ திரைப் பூட்டையோ பயன்படுத்துங்கள்"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"பயோமெட்ரிக் வன்பொருள் இல்லை"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"அங்கீகரிப்பு ரத்தானது"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"கைரேகை அங்கீகரிக்கப்படவில்லை"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"கைரேகை அங்கீகரிக்கப்படவில்லை"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"முகத்தை அடையாளம் காண முடியவில்லை. கைரேகையைப் பயன்படுத்தவும்."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"கைரேகை அங்கீகரிக்கப்பட்டது"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"முகம் அங்கீகரிக்கப்பட்டது"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"முகம் அங்கீகரிக்கப்பட்டது. ’உறுதிப்படுத்துக’ என்பதை அழுத்துக"</string>
diff --git a/core/res/res/values-te/strings.xml b/core/res/res/values-te/strings.xml
index 32ef5bd..a90b2bf3 100644
--- a/core/res/res/values-te/strings.xml
+++ b/core/res/res/values-te/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"బయోమెట్రిక్స్‌ను లేదా స్క్రీన్ లాక్‌ను ఉపయోగించండి"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"ఇది మీరేనని వెరిఫై చేసుకోండి"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"కొనసాగించడానికి, మీ బయోమెట్రిక్‌ను ఉపయోగించండి"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"కొనసాగించడానికి మీ వేలిముద్రను ఉపయోగించండి"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"కొనసాగించడానికి మీ ముఖాన్ని ఉపయోగించండి"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"కొనసాగించడానికి మీ బయోమెట్రిక్ లేదా స్క్రీన్ లాక్‌ను ఉపయోగించండి"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"బయోమెట్రిక్ హార్డ్‌వేర్‌ అందుబాటులో లేదు"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"ప్రమాణీకరణ రద్దు చేయబడింది"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"వేలిముద్ర గుర్తించబడలేదు"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"వేలిముద్ర గుర్తించబడలేదు"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"ముఖం గుర్తించలేము. బదులుగా వేలిముద్ర ఉపయోగించండి."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"వేలిముద్ర ప్రమాణీకరించబడింది"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"ముఖం ప్రమాణీకరించబడింది"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"ముఖం ప్రమాణీకరించబడింది, దయచేసి ధృవీకరించును నొక్కండి"</string>
diff --git a/core/res/res/values-th/strings.xml b/core/res/res/values-th/strings.xml
index 1f65086..74b744f 100644
--- a/core/res/res/values-th/strings.xml
+++ b/core/res/res/values-th/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"ใช้ข้อมูลไบโอเมตริกหรือการล็อกหน้าจอ"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"ยืนยันว่าเป็นตัวคุณ"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"ใช้ข้อมูลไบโอเมตริกเพื่อดำเนินการต่อ"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"ใช้ลายนิ้วมือของคุณเพื่อดำเนินการต่อ"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"ใช้ใบหน้าของคุณเพื่อดำเนินการต่อ"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"ใช้ข้อมูลไบโอเมตริกหรือการล็อกหน้าจอเพื่อดำเนินการต่อ"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"ฮาร์ดแวร์ไบโอเมตริกไม่พร้อมใช้งาน"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"ยกเลิกการตรวจสอบสิทธิ์แล้ว"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"ไม่รู้จักลายนิ้วมือ"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"ไม่รู้จักลายนิ้วมือ"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"ไม่รู้จักใบหน้า ใช้ลายนิ้วมือแทน"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"ตรวจสอบสิทธิ์ลายนิ้วมือแล้ว"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"ตรวจสอบสิทธิ์ใบหน้าแล้ว"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"ตรวจสอบสิทธิ์ใบหน้าแล้ว โปรดกดยืนยัน"</string>
@@ -1404,7 +1403,7 @@
     <string name="select_keyboard_layout_notification_message" msgid="8835158247369158154">"แตะเพื่อเลือกภาษาและรูปแบบ"</string>
     <string name="fast_scroll_alphabet" msgid="8854435958703888376">" กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬอฮ"</string>
     <string name="fast_scroll_numeric_alphabet" msgid="2529539945421557329">" กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬอฮ"</string>
-    <string name="alert_windows_notification_channel_group_name" msgid="6063891141815714246">"แสดงทับแอปอื่นๆ"</string>
+    <string name="alert_windows_notification_channel_group_name" msgid="6063891141815714246">"แสดงทับบนแอปอื่นๆ"</string>
     <string name="alert_windows_notification_channel_name" msgid="3437528564303192620">"<xliff:g id="NAME">%s</xliff:g> แสดงทับแอปอื่นๆ"</string>
     <string name="alert_windows_notification_title" msgid="6331662751095228536">"<xliff:g id="NAME">%s</xliff:g> กำลังแสดงทับแอปอื่นๆ"</string>
     <string name="alert_windows_notification_message" msgid="6538171456970725333">"หากคุณไม่ต้องการให้ <xliff:g id="NAME">%s</xliff:g> ใช้ฟีเจอร์นี้ ให้แตะเพื่อเปิดการตั้งค่าแล้วปิดฟีเจอร์"</string>
@@ -2335,7 +2334,7 @@
     <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen เปิดอยู่"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g> กำลังใช้จอแสดงผลทั้งสองจอเพื่อแสดงเนื้อหา"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"อุปกรณ์ร้อนเกินไป"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"หน้าจอคู่ไม่พร้อมให้ใช้งานเนื่องจากโทรศัพท์ของคุณร้อนเกินไป"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Dual Screen ไม่พร้อมให้ใช้งานเนื่องจากโทรศัพท์ของคุณร้อนเกินไป"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen ใช้งานไม่ได้"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Dual Screen ใช้งานไม่ได้เนื่องจากเปิดโหมดประหยัดแบตเตอรี่อยู่ คุณปิดโหมดนี้ได้ในการตั้งค่า"</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"ไปที่การตั้งค่า"</string>
diff --git a/core/res/res/values-tl/strings.xml b/core/res/res/values-tl/strings.xml
index 567b67e..633282e 100644
--- a/core/res/res/values-tl/strings.xml
+++ b/core/res/res/values-tl/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Gumamit ng biometrics o lock ng screen"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"I-verify na ikaw ito"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Gamitin ang iyong biometric para magpatuloy"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Gamitin ang iyong fingerprint para magpatuloy"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Gamitin ang iyong mukha para magpatuloy"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Gamitin ang iyong biometric o lock ng screen para magpatuloy"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Walang biometric hardware"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Nakansela ang pag-authenticate"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Hindi nakilala ang fingerprint"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Hindi nakilala ang fingerprint"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Hindi makilala ang mukha. Gumamit ng fingerprint."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Na-authenticate ang fingerprint"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Na-authenticate ang mukha"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Na-authenticate ang mukha, pakipindot ang kumpirmahin"</string>
diff --git a/core/res/res/values-tr/strings.xml b/core/res/res/values-tr/strings.xml
index 3bf35a5..17db4f4 100644
--- a/core/res/res/values-tr/strings.xml
+++ b/core/res/res/values-tr/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Biyometri veya ekran kilidi kullan"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Siz olduğunuzu doğrulayın"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Devam etmek için biyometri kullanın"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Devam etmek için parmak izinizi kullanın"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Devam etmek için yüzünüzü kullanın"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Devam etmek için biyometrik kimlik bilginizi veya ekran kilidinizi kullanın"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biyometrik donanım kullanılamıyor"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Kimlik doğrulama iptal edildi"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Parmak izi tanınmadı"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Parmak izi tanınmadı"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Yüz tanınamadı. Bunun yerine parmak izi kullanın."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Parmak izi kimlik doğrulaması yapıldı"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Yüz kimliği doğrulandı"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Yüz kimliği doğrulandı, lütfen onayla\'ya basın"</string>
@@ -2331,11 +2330,11 @@
     <string name="permdesc_startForegroundServicesFromBackground" msgid="4071826571656001537">"Tamamlayıcı uygulamanın arka plandan ön plan hizmetlerini başlatmasına izin verir."</string>
     <string name="mic_access_on_toast" msgid="2666925317663845156">"Mikrofon kullanılabilir"</string>
     <string name="mic_access_off_toast" msgid="8111040892954242437">"Mikrofon engellenmiş"</string>
-    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Çift ekran"</string>
-    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Çift ekran açık"</string>
+    <string name="concurrent_display_notification_name" msgid="1526911253558311131">"Dual Screen"</string>
+    <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen açık"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"<xliff:g id="APP_NAME">%1$s</xliff:g>, içeriği göstermek için her iki ekranı da kullanıyor"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Cihaz çok ısındı"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Telefonunuz çok ısındığı için Çift Ekran kullanılamıyor"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Telefonunuz çok ısındığı için Dual Screen kullanılamıyor"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Dual Screen kullanılamıyor"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Pil Tasarrufu açık olduğundan Dual Screen kullanılamıyor. Bu özelliği Ayarlar\'dan kapatabilirsiniz."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Ayarlar\'a git"</string>
diff --git a/core/res/res/values-uk/strings.xml b/core/res/res/values-uk/strings.xml
index 47e529c..0606c7a 100644
--- a/core/res/res/values-uk/strings.xml
+++ b/core/res/res/values-uk/strings.xml
@@ -620,8 +620,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Використовувати біометрію або дані для розблокування екрана"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Підтвердьте, що це ви"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Щоб продовжити, скористайтеся біометрією"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Щоб продовжити, скористайтеся відбитком пальця"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Щоб продовжити, скористайтеся фейс-контролем"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Щоб продовжити, скористайтеся біометрією або даними для розблокування екрана"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Біометричне апаратне забезпечення недоступне"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Автентифікацію скасовано"</string>
@@ -647,6 +645,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Відбиток пальця не розпізнано"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Відбиток пальця не розпізнано"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Обличчя не розпізнано. Скористайтеся відбитком пальця."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Відбиток пальця автентифіковано"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Обличчя автентифіковано"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Обличчя автентифіковано. Натисніть \"Підтвердити\""</string>
@@ -2337,7 +2336,7 @@
     <string name="concurrent_display_notification_active_title" msgid="4892473462327943673">"Dual Screen увімкнено"</string>
     <string name="concurrent_display_notification_active_content" msgid="5889355473710601270">"Додаток <xliff:g id="APP_NAME">%1$s</xliff:g> використовує обидва екрани для показу контенту"</string>
     <string name="concurrent_display_notification_thermal_title" msgid="5921609404644739229">"Пристрій сильно нагрівається"</string>
-    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Подвійний екран недоступний, оскільки телефон сильно нагрівається"</string>
+    <string name="concurrent_display_notification_thermal_content" msgid="2075484836527609319">"Функція Dual Screen недоступна, оскільки телефон сильно нагрівається"</string>
     <string name="concurrent_display_notification_power_save_title" msgid="1794569070730736281">"Функція Dual Screen недоступна"</string>
     <string name="concurrent_display_notification_power_save_content" msgid="2198116070583851493">"Функція Dual Screen недоступна, оскільки ввімкнено режим енергозбереження. Її можна вимкнути в налаштуваннях."</string>
     <string name="device_state_notification_settings_button" msgid="691937505741872749">"Перейти до налаштувань"</string>
diff --git a/core/res/res/values-ur/strings.xml b/core/res/res/values-ur/strings.xml
index 907ebd9..dc4ea46 100644
--- a/core/res/res/values-ur/strings.xml
+++ b/core/res/res/values-ur/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"بایو میٹرکس یا اسکرین لاک استعمال کریں"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"توثیق کریں کہ یہ آپ ہیں"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"جاری رکھنے کیلئے اپنا بایو میٹرک استعمال کریں"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"جاری رکھنے کے لیے اپنا فنگر پرنٹ استعمال کریں"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"جاری رکھنے کے لیے اپنے چہرے کا استعمال کریں"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"جاری رکھنے کے لیے اپنے بایو میٹرک اور اسکرین لاک کا استعمال کریں"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"بایومیٹرک ہارڈ ویئر دستیاب نہیں ہے"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"تصدیق کا عمل منسوخ ہو گیا"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"فنگر پرنٹ کی شناخت نہیں ہو سکی"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"فنگر پرنٹ کی شناخت نہیں ہو سکی"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"چہرے کی شناخت نہیں ہو سکی۔ اس کے بجائے فنگر پرنٹ استعمال کریں۔"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"فنگر پرنٹ کی تصدیق ہو گئی"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"چہرے کی تصدیق ہو گئی"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"چہرے کی تصدیق ہو گئی، براہ کرم \'تصدیق کریں\' کو دبائيں"</string>
diff --git a/core/res/res/values-uz/strings.xml b/core/res/res/values-uz/strings.xml
index a65b478..979c578 100644
--- a/core/res/res/values-uz/strings.xml
+++ b/core/res/res/values-uz/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Biometrika yoki ekran qulfi"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Oʻzingizni taniting"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Davom etish uchun biometrik tasdiqlang"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Davom etish uchun barmoq izingizdan foydalaning"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Yuz tekshiruvi bilan davom eting"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Davom etish uchun biometrika yoki ekran qulfidan foydalaning"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Biometrik sensor ishlamayapti"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Autentifikatsiya bekor qilindi"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Barmoq izi aniqlanmadi"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Barmoq izi aniqlanmadi"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Bu yuz notanish. Barmoq izi orqali urining."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Barmoq izi tekshirildi"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Yuzingiz aniqlandi"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Yuzingiz aniqlandi, tasdiqlash uchun bosing"</string>
diff --git a/core/res/res/values-vi/strings.xml b/core/res/res/values-vi/strings.xml
index 9c77299..58cec01 100644
--- a/core/res/res/values-vi/strings.xml
+++ b/core/res/res/values-vi/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Dùng dữ liệu sinh trắc học hoặc phương thức khóa màn hình"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Xác minh danh tính của bạn"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Dùng dữ liệu sinh trắc học của bạn để tiếp tục"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Hãy dùng vân tay để tiếp tục"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Hãy dùng khuôn mặt để tiếp tục"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Dùng dữ liệu sinh trắc học của bạn hoặc phương thức khóa màn hình để tiếp tục"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"Không có phần cứng sinh trắc học"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Đã hủy xác thực"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Không nhận dạng được vân tay"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Không nhận dạng được vân tay"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Không thể nhận dạng khuôn mặt. Hãy dùng vân tay."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Đã xác thực vân tay"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Đã xác thực khuôn mặt"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Đã xác thực khuôn mặt, vui lòng nhấn để xác nhận"</string>
diff --git a/core/res/res/values-zh-rCN/strings.xml b/core/res/res/values-zh-rCN/strings.xml
index 955cbe7..e5535af 100644
--- a/core/res/res/values-zh-rCN/strings.xml
+++ b/core/res/res/values-zh-rCN/strings.xml
@@ -274,7 +274,7 @@
     <string name="notification_channel_physical_keyboard" msgid="5417306456125988096">"实体键盘"</string>
     <string name="notification_channel_security" msgid="8516754650348238057">"安全性"</string>
     <string name="notification_channel_car_mode" msgid="2123919247040988436">"车载模式"</string>
-    <string name="notification_channel_account" msgid="6436294521740148173">"帐号状态"</string>
+    <string name="notification_channel_account" msgid="6436294521740148173">"账号状态"</string>
     <string name="notification_channel_developer" msgid="1691059964407549150">"开发者消息"</string>
     <string name="notification_channel_developer_important" msgid="7197281908918789589">"重要开发者消息"</string>
     <string name="notification_channel_updates" msgid="7907863984825495278">"更新"</string>
@@ -448,9 +448,9 @@
     <string name="permdesc_broadcastSticky" product="tv" msgid="2338185920171000650">"允许应用发送置顶广播,这类广播在广播结束后仍会继续存在。过度使用这项功能可能会导致 Android TV 设备使用过多内存,从而降低其运行速度或稳定性。"</string>
     <string name="permdesc_broadcastSticky" product="default" msgid="134529339678913453">"允许该应用发送持久广播消息,此类消息在广播结束后仍会保留。过度使用可能会导致手机使用过多内存,从而降低其速度或稳定性。"</string>
     <string name="permlab_readContacts" msgid="8776395111787429099">"读取联系人"</string>
-    <string name="permdesc_readContacts" product="tablet" msgid="6430093481659992692">"允许该应用读取您的平板电脑上存储的联系人相关数据。应用还将有权访问您的平板电脑上已创建联系人的帐号,其中可能包括您已安装的应用所创建的帐号。此权限允许应用保存您的联系人数据,而恶意应用可能会在您不知情的情况下分享联系人数据。"</string>
-    <string name="permdesc_readContacts" product="tv" msgid="8400138591135554789">"允许该应用读取您的 Android TV 设备上存储的联系人相关数据。应用还将有权访问您的 Android TV 设备上已创建联系人的帐号,其中可能包括您已安装的应用所创建的帐号。此权限允许应用保存您的联系人数据,而恶意应用可能会在您不知情的情况下分享联系人数据。"</string>
-    <string name="permdesc_readContacts" product="default" msgid="4911989776203207644">"允许该应用读取您手机上存储的联系人相关数据。应用还将有权访问您的手机上已创建联系人的帐号,其中可能包括您已安装的应用所创建的帐号。此权限允许应用保存您的联系人数据,而恶意应用可能会在您不知情的情况下分享联系人数据。"</string>
+    <string name="permdesc_readContacts" product="tablet" msgid="6430093481659992692">"允许该应用读取您的平板电脑上存储的联系人相关数据。应用还将有权访问您的平板电脑上已创建联系人的账号,其中可能包括您已安装的应用所创建的账号。此权限允许应用保存您的联系人数据,而恶意应用可能会在您不知情的情况下分享联系人数据。"</string>
+    <string name="permdesc_readContacts" product="tv" msgid="8400138591135554789">"允许该应用读取您的 Android TV 设备上存储的联系人相关数据。应用还将有权访问您的 Android TV 设备上已创建联系人的账号,其中可能包括您已安装的应用所创建的账号。此权限允许应用保存您的联系人数据,而恶意应用可能会在您不知情的情况下分享联系人数据。"</string>
+    <string name="permdesc_readContacts" product="default" msgid="4911989776203207644">"允许该应用读取您手机上存储的联系人相关数据。应用还将有权访问您的手机上已创建联系人的账号,其中可能包括您已安装的应用所创建的账号。此权限允许应用保存您的联系人数据,而恶意应用可能会在您不知情的情况下分享联系人数据。"</string>
     <string name="permlab_writeContacts" msgid="8919430536404830430">"修改您的通讯录"</string>
     <string name="permdesc_writeContacts" product="tablet" msgid="6422419281427826181">"允许该应用修改您平板电脑上存储的联系人相关数据。此权限允许应用删除联系人数据。"</string>
     <string name="permdesc_writeContacts" product="tv" msgid="6488872735379978935">"允许该应用修改您的 Android TV 设备上存储的联系人相关数据。此权限允许应用删除联系人数据。"</string>
@@ -542,10 +542,10 @@
     <string name="permdesc_setTimeZone" product="tablet" msgid="1788868809638682503">"允许应用更改平板电脑的时区。"</string>
     <string name="permdesc_setTimeZone" product="tv" msgid="9069045914174455938">"允许应用更改 Android TV 设备的时区。"</string>
     <string name="permdesc_setTimeZone" product="default" msgid="4611828585759488256">"允许应用更改手机的时区。"</string>
-    <string name="permlab_getAccounts" msgid="5304317160463582791">"查找设备上的帐号"</string>
-    <string name="permdesc_getAccounts" product="tablet" msgid="1784452755887604512">"允许该应用获取平板电脑已知的帐号列表,其中可能包括由已安装的应用创建的所有帐号。"</string>
-    <string name="permdesc_getAccounts" product="tv" msgid="437604680436540822">"允许应用获取 Android TV 设备已知的帐号列表,其中可能包括您已安装的应用所创建的任何帐号。"</string>
-    <string name="permdesc_getAccounts" product="default" msgid="2491273043569751867">"允许该应用获取手机已知的帐号列表,其中可能包括由已安装的应用创建的所有帐号。"</string>
+    <string name="permlab_getAccounts" msgid="5304317160463582791">"查找设备上的账号"</string>
+    <string name="permdesc_getAccounts" product="tablet" msgid="1784452755887604512">"允许该应用获取平板电脑已知的账号列表,其中可能包括由已安装的应用创建的所有账号。"</string>
+    <string name="permdesc_getAccounts" product="tv" msgid="437604680436540822">"允许应用获取 Android TV 设备已知的账号列表,其中可能包括您已安装的应用所创建的任何账号。"</string>
+    <string name="permdesc_getAccounts" product="default" msgid="2491273043569751867">"允许该应用获取手机已知的账号列表,其中可能包括由已安装的应用创建的所有账号。"</string>
     <string name="permlab_accessNetworkState" msgid="2349126720783633918">"查看网络连接"</string>
     <string name="permdesc_accessNetworkState" msgid="4394564702881662849">"允许该应用查看网络连接的相关信息,例如存在和连接的网络。"</string>
     <string name="permlab_createNetworkSockets" msgid="3224420491603590541">"拥有完全的网络访问权限"</string>
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"使用生物识别或屏幕锁定凭据"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"验证是您本人在操作"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"使用生物识别验证身份才能继续"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"如需继续操作,请使用指纹验证身份"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"如需继续操作,请刷脸验证身份"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"使用生物识别或屏幕锁定凭据验证身份,才能继续操作"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"生物识别硬件无法使用"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"身份验证已取消"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"未能识别指纹"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"未能识别指纹"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"无法识别人脸。请改用指纹。"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"已验证指纹"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"面孔已验证"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"面孔已验证,请按确认按钮"</string>
@@ -732,11 +731,11 @@
     <string name="face_error_vendor_unknown" msgid="7387005932083302070">"出了点问题,请重试。"</string>
     <string name="face_icon_content_description" msgid="465030547475916280">"面孔图标"</string>
     <string name="permlab_readSyncSettings" msgid="6250532864893156277">"读取同步设置"</string>
-    <string name="permdesc_readSyncSettings" msgid="1325658466358779298">"允许该应用读取某个帐号的同步设置。例如,此权限可确定“联系人”应用是否与某个帐号同步。"</string>
+    <string name="permdesc_readSyncSettings" msgid="1325658466358779298">"允许该应用读取某个账号的同步设置。例如,此权限可确定“联系人”应用是否与某个账号同步。"</string>
     <string name="permlab_writeSyncSettings" msgid="6583154300780427399">"启用和停用同步"</string>
-    <string name="permdesc_writeSyncSettings" msgid="6029151549667182687">"允许该应用修改某个帐号的同步设置。例如,此权限可用于在“联系人”应用与某个帐号之间启用同步。"</string>
+    <string name="permdesc_writeSyncSettings" msgid="6029151549667182687">"允许该应用修改某个账号的同步设置。例如,此权限可用于在“联系人”应用与某个账号之间启用同步。"</string>
     <string name="permlab_readSyncStats" msgid="3747407238320105332">"读取同步统计信息"</string>
-    <string name="permdesc_readSyncStats" msgid="3867809926567379434">"允许该应用读取某个帐号的同步统计信息,包括同步活动历史记录和同步数据量。"</string>
+    <string name="permdesc_readSyncStats" msgid="3867809926567379434">"允许该应用读取某个账号的同步统计信息,包括同步活动历史记录和同步数据量。"</string>
     <string name="permlab_sdcardRead" msgid="5791467020950064920">"读取您共享存储空间中的内容"</string>
     <string name="permdesc_sdcardRead" msgid="6872973242228240382">"允许该应用读取您共享存储空间中的内容。"</string>
     <string name="permlab_readMediaAudio" msgid="8723513075731763810">"从共享存储空间读取音频文件"</string>
@@ -1002,7 +1001,7 @@
     <string name="lockscreen_too_many_failed_password_attempts_dialog_message" msgid="3118353451602377380">"您已连续 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次输错密码。\n\n请在 <xliff:g id="NUMBER_1">%2$d</xliff:g> 秒后重试。"</string>
     <string name="lockscreen_too_many_failed_pin_attempts_dialog_message" msgid="2874278239714821984">"您已经<xliff:g id="NUMBER_0">%1$d</xliff:g>次输错了PIN码。\n\n请在<xliff:g id="NUMBER_1">%2$d</xliff:g>秒后重试。"</string>
     <string name="lockscreen_failed_attempts_almost_glogin" product="tablet" msgid="3069635524964070596">"您已连续 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次画错解锁图案。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用自己的 Google 登录信息解锁平板电脑。\n\n请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
-    <string name="lockscreen_failed_attempts_almost_glogin" product="tv" msgid="6399092175942158529">"您已画错解锁图案 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您登录 Google 帐号来解锁 Android TV 设备。\n\n 请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
+    <string name="lockscreen_failed_attempts_almost_glogin" product="tv" msgid="6399092175942158529">"您已画错解锁图案 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您登录 Google 账号来解锁 Android TV 设备。\n\n 请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
     <string name="lockscreen_failed_attempts_almost_glogin" product="default" msgid="5691623136957148335">"您已连续 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次画错解锁图案。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用自己的 Google 登录信息解锁手机。\n\n请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
     <string name="lockscreen_failed_attempts_almost_at_wipe" product="tablet" msgid="7914445759242151426">"您已经 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次错误地尝试解锁平板电脑。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,平板电脑将恢复为出厂默认设置,所有用户数据都会丢失。"</string>
     <string name="lockscreen_failed_attempts_almost_at_wipe" product="tv" msgid="4275591249631864248">"您尝试解锁 Android TV 设备失败的次数已达 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,您的 Android TV 设备就会恢复出厂设置,而且所有用户数据都会丢失。"</string>
@@ -1012,9 +1011,9 @@
     <string name="lockscreen_failed_attempts_now_wiping" product="default" msgid="2203704707679895487">"您已经<xliff:g id="NUMBER">%d</xliff:g>次错误地尝试解锁手机。手机现在将恢复为出厂默认设置。"</string>
     <string name="lockscreen_too_many_failed_attempts_countdown" msgid="6807200118164539589">"<xliff:g id="NUMBER">%d</xliff:g>秒后重试。"</string>
     <string name="lockscreen_forgot_pattern_button_text" msgid="8362442730606839031">"忘记了图案?"</string>
-    <string name="lockscreen_glogin_forgot_pattern" msgid="9218940117797602518">"帐号解锁"</string>
+    <string name="lockscreen_glogin_forgot_pattern" msgid="9218940117797602518">"账号解锁"</string>
     <string name="lockscreen_glogin_too_many_attempts" msgid="3775904917743034195">"图案尝试次数过多"</string>
-    <string name="lockscreen_glogin_instructions" msgid="4695162942525531700">"要解除锁定,请使用您的 Google 帐号登录。"</string>
+    <string name="lockscreen_glogin_instructions" msgid="4695162942525531700">"要解除锁定,请使用您的 Google 账号登录。"</string>
     <string name="lockscreen_glogin_username_hint" msgid="6916101478673157045">"用户名(电子邮件)"</string>
     <string name="lockscreen_glogin_password_hint" msgid="3031027901286812848">"密码"</string>
     <string name="lockscreen_glogin_submit_button" msgid="3590556636347843733">"登录"</string>
@@ -1482,14 +1481,14 @@
     <string name="ime_action_default" msgid="8265027027659800121">"执行"</string>
     <string name="dial_number_using" msgid="6060769078933953531">"拨打电话\n<xliff:g id="NUMBER">%s</xliff:g>"</string>
     <string name="create_contact_using" msgid="6200708808003692594">"创建电话号码为\n<xliff:g id="NUMBER">%s</xliff:g> 的联系人"</string>
-    <string name="grant_credentials_permission_message_header" msgid="5365733888842570481">"以下一个或多个应用请求获得相应权限,以便在当前和以后访问您的帐号。"</string>
+    <string name="grant_credentials_permission_message_header" msgid="5365733888842570481">"以下一个或多个应用请求获得相应权限,以便在当前和以后访问您的账号。"</string>
     <string name="grant_credentials_permission_message_footer" msgid="1886710210516246461">"您是否同意此请求?"</string>
     <string name="grant_permissions_header_text" msgid="3420736827804657201">"访问权限请求"</string>
     <string name="allow" msgid="6195617008611933762">"允许"</string>
     <string name="deny" msgid="6632259981847676572">"拒绝"</string>
     <string name="permission_request_notification_title" msgid="1810025922441048273">"权限请求"</string>
-    <string name="permission_request_notification_with_subtitle" msgid="3743417870360129298">"应用对帐号 <xliff:g id="ACCOUNT">%s</xliff:g>\n 提出权限请求。"</string>
-    <string name="permission_request_notification_for_app_with_subtitle" msgid="1298704005732851350">"“<xliff:g id="APP">%1$s</xliff:g>”请求获得以下帐号的访问权限:\n<xliff:g id="ACCOUNT">%2$s</xliff:g>。"</string>
+    <string name="permission_request_notification_with_subtitle" msgid="3743417870360129298">"应用对账号 <xliff:g id="ACCOUNT">%s</xliff:g>\n 提出权限请求。"</string>
+    <string name="permission_request_notification_for_app_with_subtitle" msgid="1298704005732851350">"“<xliff:g id="APP">%1$s</xliff:g>”请求获得以下账号的访问权限:\n<xliff:g id="ACCOUNT">%2$s</xliff:g>。"</string>
     <string name="forward_intent_to_owner" msgid="4620359037192871015">"您目前是在工作资料之外使用此应用"</string>
     <string name="forward_intent_to_work" msgid="3620262405636021151">"您目前是在工作资料内使用此应用"</string>
     <string name="input_method_binding_label" msgid="1166731601721983656">"输入法"</string>
@@ -1535,13 +1534,13 @@
     <string name="gpsVerifYes" msgid="3719843080744112940">"是"</string>
     <string name="gpsVerifNo" msgid="1671201856091564741">"否"</string>
     <string name="sync_too_many_deletes" msgid="6999440774578705300">"超出删除限制"</string>
-    <string name="sync_too_many_deletes_desc" msgid="7409327940303504440">"帐号 <xliff:g id="ACCOUNT_NAME">%3$s</xliff:g> 在进行“<xliff:g id="TYPE_OF_SYNC">%2$s</xliff:g>”同步时删除了 <xliff:g id="NUMBER_OF_DELETED_ITEMS">%1$d</xliff:g> 项内容。您要如何处理这些删除的内容?"</string>
+    <string name="sync_too_many_deletes_desc" msgid="7409327940303504440">"账号 <xliff:g id="ACCOUNT_NAME">%3$s</xliff:g> 在进行“<xliff:g id="TYPE_OF_SYNC">%2$s</xliff:g>”同步时删除了 <xliff:g id="NUMBER_OF_DELETED_ITEMS">%1$d</xliff:g> 项内容。您要如何处理这些删除的内容?"</string>
     <string name="sync_really_delete" msgid="5657871730315579051">"删除这些内容"</string>
     <string name="sync_undo_deletes" msgid="5786033331266418896">"撤消删除"</string>
     <string name="sync_do_nothing" msgid="4528734662446469646">"目前不进行任何操作"</string>
-    <string name="choose_account_label" msgid="5557833752759831548">"选择帐号"</string>
-    <string name="add_account_label" msgid="4067610644298737417">"添加帐号"</string>
-    <string name="add_account_button_label" msgid="322390749416414097">"添加帐号"</string>
+    <string name="choose_account_label" msgid="5557833752759831548">"选择账号"</string>
+    <string name="add_account_label" msgid="4067610644298737417">"添加账号"</string>
+    <string name="add_account_button_label" msgid="322390749416414097">"添加账号"</string>
     <string name="number_picker_increment_button" msgid="7621013714795186298">"增大"</string>
     <string name="number_picker_decrement_button" msgid="5116948444762708204">"减小"</string>
     <string name="number_picker_increment_scroll_mode" msgid="8403893549806805985">"<xliff:g id="VALUE">%s</xliff:g> 触摸并按住。"</string>
@@ -1665,13 +1664,13 @@
     <string name="kg_invalid_puk" msgid="4809502818518963344">"请重新输入正确的PUK码。如果尝试错误次数过多,SIM卡将永久停用。"</string>
     <string name="kg_invalid_confirm_pin_hint" product="default" msgid="4705368340409816254">"PIN 码不匹配"</string>
     <string name="kg_login_too_many_attempts" msgid="699292728290654121">"图案尝试次数过多"</string>
-    <string name="kg_login_instructions" msgid="3619844310339066827">"要解锁,请登录您的 Google 帐号。"</string>
+    <string name="kg_login_instructions" msgid="3619844310339066827">"要解锁,请登录您的 Google 账号。"</string>
     <string name="kg_login_username_hint" msgid="1765453775467133251">"用户名(电子邮件地址)"</string>
     <string name="kg_login_password_hint" msgid="3330530727273164402">"密码"</string>
     <string name="kg_login_submit_button" msgid="893611277617096870">"登录"</string>
     <string name="kg_login_invalid_input" msgid="8292367491901220210">"用户名或密码无效。"</string>
     <string name="kg_login_account_recovery_hint" msgid="4892466171043541248">"忘记了用户名或密码?\n请访问 "<b>"google.com/accounts/recovery"</b>"。"</string>
-    <string name="kg_login_checking_password" msgid="4676010303243317253">"正在检查帐号…"</string>
+    <string name="kg_login_checking_password" msgid="4676010303243317253">"正在检查账号…"</string>
     <string name="kg_too_many_failed_pin_attempts_dialog_message" msgid="23741434207544038">"您已经<xliff:g id="NUMBER_0">%1$d</xliff:g>次输错了PIN码。\n\n请在<xliff:g id="NUMBER_1">%2$d</xliff:g>秒后重试。"</string>
     <string name="kg_too_many_failed_password_attempts_dialog_message" msgid="3328686432962224215">"您已连续 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次输错密码。\n\n请在 <xliff:g id="NUMBER_1">%2$d</xliff:g> 秒后重试。"</string>
     <string name="kg_too_many_failed_pattern_attempts_dialog_message" msgid="7357404233979139075">"您已连续 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次画错解锁图案。\n\n请在 <xliff:g id="NUMBER_1">%2$d</xliff:g> 秒后重试。"</string>
@@ -1681,9 +1680,9 @@
     <string name="kg_failed_attempts_now_wiping" product="tablet" msgid="2299099385175083308">"您已经<xliff:g id="NUMBER">%d</xliff:g>次错误地尝试解锁平板电脑。平板电脑现在将恢复为出厂默认设置。"</string>
     <string name="kg_failed_attempts_now_wiping" product="tv" msgid="5045460916106267585">"您尝试解锁 Android TV 设备失败的次数已达 <xliff:g id="NUMBER">%d</xliff:g> 次。您的 Android TV 设备现在将恢复出厂设置。"</string>
     <string name="kg_failed_attempts_now_wiping" product="default" msgid="5043730590446071189">"您已经<xliff:g id="NUMBER">%d</xliff:g>次错误地尝试解锁手机。手机现在将恢复为出厂默认设置。"</string>
-    <string name="kg_failed_attempts_almost_at_login" product="tablet" msgid="7086799295109717623">"您已连续 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次画错解锁图案。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用自己的电子邮件帐号解锁平板电脑。\n\n请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
-    <string name="kg_failed_attempts_almost_at_login" product="tv" msgid="4670840383567106114">"您已画错解锁图案 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用电子邮件帐号解锁 Android TV 设备。\n\n 请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
-    <string name="kg_failed_attempts_almost_at_login" product="default" msgid="5270861875006378092">"您已连续 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次画错解锁图案。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用自己的电子邮件帐号解锁手机。\n\n请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
+    <string name="kg_failed_attempts_almost_at_login" product="tablet" msgid="7086799295109717623">"您已连续 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次画错解锁图案。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用自己的电子邮件账号解锁平板电脑。\n\n请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
+    <string name="kg_failed_attempts_almost_at_login" product="tv" msgid="4670840383567106114">"您已画错解锁图案 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用电子邮件账号解锁 Android TV 设备。\n\n 请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
+    <string name="kg_failed_attempts_almost_at_login" product="default" msgid="5270861875006378092">"您已连续 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次画错解锁图案。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用自己的电子邮件账号解锁手机。\n\n请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
     <string name="kg_text_message_separator" product="default" msgid="4503708889934976866">" — "</string>
     <string name="kg_reordering_delete_drop_target_text" msgid="2034358143731750914">"删除"</string>
     <string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"要将音量调高到建议的音量以上吗?\n\n长时间保持高音量可能会损伤听力。"</string>
@@ -1733,7 +1732,7 @@
     <string name="accessibility_magnification_chooser_text" msgid="1502075582164931596">"放大功能"</string>
     <string name="user_switched" msgid="7249833311585228097">"当前用户是<xliff:g id="NAME">%1$s</xliff:g>。"</string>
     <string name="user_switching_message" msgid="1912993630661332336">"正在切换为<xliff:g id="NAME">%1$s</xliff:g>…"</string>
-    <string name="user_logging_out_message" msgid="7216437629179710359">"正在将<xliff:g id="NAME">%1$s</xliff:g>退出帐号…"</string>
+    <string name="user_logging_out_message" msgid="7216437629179710359">"正在将<xliff:g id="NAME">%1$s</xliff:g>退出账号…"</string>
     <string name="owner_name" msgid="8713560351570795743">"机主"</string>
     <string name="guest_name" msgid="8502103277839834324">"访客"</string>
     <string name="error_message_title" msgid="4082495589294631966">"错误"</string>
@@ -1938,7 +1937,7 @@
     <string name="importance_from_user" msgid="2782756722448800447">"这些通知的重要程度由您来设置。"</string>
     <string name="importance_from_person" msgid="4235804979664465383">"这条通知涉及特定的人,因此被归为重要通知。"</string>
     <string name="notification_history_title_placeholder" msgid="7748630986182249599">"自定义应用通知"</string>
-    <string name="user_creation_account_exists" msgid="2239146360099708035">"允许<xliff:g id="APP">%1$s</xliff:g>使用 <xliff:g id="ACCOUNT">%2$s</xliff:g>(目前已有用户使用此帐号)创建新用户吗?"</string>
+    <string name="user_creation_account_exists" msgid="2239146360099708035">"允许<xliff:g id="APP">%1$s</xliff:g>使用 <xliff:g id="ACCOUNT">%2$s</xliff:g>(目前已有用户使用此账号)创建新用户吗?"</string>
     <string name="user_creation_adding" msgid="7305185499667958364">"允许<xliff:g id="APP">%1$s</xliff:g>使用 <xliff:g id="ACCOUNT">%2$s</xliff:g> 创建新用户吗?"</string>
     <string name="supervised_user_creation_label" msgid="6884904353827427515">"添加受监管用户"</string>
     <string name="language_selection_title" msgid="52674936078683285">"添加语言"</string>
diff --git a/core/res/res/values-zh-rHK/strings.xml b/core/res/res/values-zh-rHK/strings.xml
index 899c314..935e757 100644
--- a/core/res/res/values-zh-rHK/strings.xml
+++ b/core/res/res/values-zh-rHK/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"使用生物識別或螢幕鎖定"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"驗證是你本人"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"如要繼續操作,請使用使用生物識別驗證身分"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"如要繼續操作,請使用你的指紋驗證身分"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"如要繼續操作,請使用你的面孔驗證身分"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"請使用生物識別或螢幕鎖定功能驗證身分,才能繼續操作"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"無法使用生物識別硬件"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"已取消驗證"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"無法辨識指紋"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"無法辨識指紋"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"無法辨識面孔,請改用指紋完成驗證。"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"驗證咗指紋"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"面孔已經驗證"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"面孔已經驗證,請㩒一下 [確認]"</string>
diff --git a/core/res/res/values-zh-rTW/strings.xml b/core/res/res/values-zh-rTW/strings.xml
index 717e046..3f93ecd 100644
--- a/core/res/res/values-zh-rTW/strings.xml
+++ b/core/res/res/values-zh-rTW/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"使用生物特徵辨識或螢幕鎖定功能"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"驗證你的身分"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"如要繼續操作,請使用生物特徵辨識功能驗證身分"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"如要繼續操作,請使用指紋驗證身分"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"如要繼續操作,請使用臉孔驗證身分"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"請使用生物特徵辨識或螢幕鎖定功能驗證身分,才能繼續操作"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"無法使用生物特徵辨識硬體"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"已取消驗證"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"指紋辨識失敗"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"指紋辨識失敗"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"無法辨識臉孔,請改用指紋完成驗證。"</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"指紋驗證成功"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"臉孔驗證成功"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"臉孔驗證成功,請按下 [確認] 按鈕"</string>
diff --git a/core/res/res/values-zu/strings.xml b/core/res/res/values-zu/strings.xml
index 88a3547..929af23 100644
--- a/core/res/res/values-zu/strings.xml
+++ b/core/res/res/values-zu/strings.xml
@@ -618,8 +618,6 @@
     <string name="biometric_or_screen_lock_app_setting_name" msgid="5348462421758257752">"Sebenzisa i-biometrics noma ukukhiya isikrini"</string>
     <string name="biometric_dialog_default_title" msgid="55026799173208210">"Qinisekisa ukuthi nguwe"</string>
     <string name="biometric_dialog_default_subtitle" msgid="8457232339298571992">"Sebenzisa i-biometric yakho ukuze uqhubeke"</string>
-    <string name="biometric_dialog_fingerprint_subtitle" msgid="2520227942533751342">"Sebenzisa isigxivizo sakho somunwe ukuze uqhubeke"</string>
-    <string name="biometric_dialog_face_subtitle" msgid="5269284162191087084">"Sebenzisa ubuso bakho ukuze uqhubeke"</string>
     <string name="biometric_or_screen_lock_dialog_default_subtitle" msgid="159539678371552009">"Sebenzisa i-biometric noma ukukhiya isikrini ukuze uqhubeke"</string>
     <string name="biometric_error_hw_unavailable" msgid="2494077380540615216">"I-Biometric hardware ayitholakali"</string>
     <string name="biometric_error_user_canceled" msgid="6732303949695293730">"Ukufakazela ubuqiniso kukhanseliwe"</string>
@@ -645,6 +643,7 @@
   </string-array>
     <string name="fingerprint_error_not_match" msgid="4599441812893438961">"Isigxivizo somunwe asaziwa"</string>
     <string name="fingerprint_udfps_error_not_match" msgid="8236930793223158856">"Isigxivizo somunwe asaziwa"</string>
+    <string name="fingerprint_dialog_use_fingerprint_instead" msgid="6226091888364083421">"Ayibazi ubuso. Sebenzisa izigxivizo zeminwe kunalokho."</string>
     <string name="fingerprint_authenticated" msgid="2024862866860283100">"Izigxivizo zeminwe zigunyaziwe"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="8867889115112348167">"Ubuso bufakazelwe ubuqiniso"</string>
     <string name="face_authenticated_confirmation_required" msgid="6872632732508013755">"Ukuqinisekiswa kobuso, sicela ucindezele okuthi qinisekisa"</string>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index d80cfa3..f45499a 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -2465,7 +2465,7 @@
                duration of the vector animation automatically. -->
         <attr name="windowSplashScreenAnimationDuration" format="integer"/>
 
-        <!-- Place an drawable image in the bottom of the starting window, it can be used to
+        <!-- Place a drawable image in the bottom of the starting window. The image can be used to
              represent the branding of the application. -->
         <attr name="windowSplashScreenBrandingImage" format="reference"/>
         <!-- Set a background behind the splash screen icon. This is useful if there is not enough
@@ -3245,7 +3245,7 @@
 
         <!-- Specifies the id of a view for which this view serves as a label for
              accessibility purposes. For example, a TextView before an EditText in
-             the UI usually specifies what infomation is contained in the EditText.
+             the UI usually specifies what information is contained in the EditText.
              Hence, the TextView is a label for the EditText. -->
         <attr name="labelFor" format="reference" />
 
@@ -6787,7 +6787,7 @@
              edges of a bitmap when rotated. Default value is false. -->
         <attr name="antialias" format="boolean" />
         <!-- Enables or disables bitmap filtering. Filtering is used when the bitmap is
-             shrunk or stretched to smooth its apperance. Default value is true. -->
+             shrunk or stretched to smooth its appearance. Default value is true. -->
         <attr name="filter" format="boolean" />
         <!-- Enables or disables dithering of the bitmap if the bitmap does not have the
              same pixel configuration as the screen (for instance: a ARGB 8888 bitmap with
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index b7d088b..95f1493 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -634,7 +634,7 @@
          able to return to it. -->
     <attr name="noHistory" format="boolean" />
 
-    <!-- Specify whether an acitivty's task state should always be maintained
+    <!-- Specify whether an activity's task state should always be maintained
          by the system, or if it is allowed to reset the task to its initial
          state in certain situations.
 
@@ -731,15 +731,17 @@
          This is equivalent to calling {@link android.app.Activity#setVrModeEnabled} with the
          the given component name within the Activity that this attribute is set for.
          Declaring this will prevent the system from leaving VR mode during an Activity
-         transtion from one VR activity to another. -->
+         transition from one VR activity to another. -->
     <attr name="enableVrMode" format="string" />
 
-    <!-- Flag allowing the activity to specify which screen rotation animation
-         it desires.  Valid values are "rotate", "crossfade", and "jumpcut"
-         as described in {@link android.view.WindowManager.LayoutParams#rotationAnimation}.
-         Specifying your Rotation animation in the WindowManager.LayoutParams
-         may be racy with app startup and updattransitions occuring during application startup and thusly
-         the manifest attribute is preferred.
+    <!-- Flag that specifies the activity's preferred screen rotation animation.
+         Valid values are "rotate", "crossfade", "jumpcut", and "seamless" as
+         described in
+         {@link android.view.WindowManager.LayoutParams#rotationAnimation}.
+         Specifying your rotation animation in
+         <code>WindowManager.LayoutParams</code> may be racy with app startup
+         and update transitions that occur during application startup; and so,
+         specify the animation in the manifest attribute.
     -->
     <attr name="rotationAnimation">
       <flag name="rotate" value= "0" />
@@ -830,7 +832,7 @@
         <enum name="singleInstance" value="3" />
         <!-- The activity can only be running as the root activity of the task, the first activity
             that created the task, and therefore there will only be one instance of this activity
-            in a task. In constrast to the {@code singleTask} launch mode, this activity can be
+            in a task. In contrast to the {@code singleTask} launch mode, this activity can be
             started in multiple instances in different tasks if the
             {@code FLAG_ACTIVITY_MULTIPLE_TASK} or {@code FLAG_ACTIVITY_NEW_DOCUMENT} is set.-->
         <enum name="singleInstancePerTask" value="4" />
@@ -1328,7 +1330,7 @@
          <p>Such a document is any kind of item for which an application may want to
          maintain multiple simultaneous instances. Examples might be text files, web
          pages, spreadsheets, or emails. Each such document will be in a separate
-         task in the recent taskss list.
+         task in the recent tasks list.
 
          <p>This attribute is equivalent to adding the flag {@link
          android.content.Intent#FLAG_ACTIVITY_NEW_DOCUMENT} to every Intent used to launch
@@ -1771,7 +1773,7 @@
     </attr>
 
     <!-- Enable hardware memory tagging (ARM MTE) in this process.
-         When enabled, heap memory bugs like use-after-free and buffer overlow
+         When enabled, heap memory bugs like use-after-free and buffer overflow
          are detected and result in an immediate ("sync" mode) or delayed ("async"
          mode) crash instead of a silent memory corruption. Sync mode, while slower,
          provides enhanced bug reports including stack traces at the time of allocation
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 71630cb..2f0b390 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -45,9 +45,7 @@
         <item><xliff:g id="id">@string/status_bar_phone_signal</xliff:g></item>
         <item><xliff:g id="id">@string/status_bar_secure</xliff:g></item>
         <item><xliff:g id="id">@string/status_bar_managed_profile</xliff:g></item>
-        <item><xliff:g id="id">@string/status_bar_cast</xliff:g></item>
         <item><xliff:g id="id">@string/status_bar_connected_display</xliff:g></item>
-        <item><xliff:g id="id">@string/status_bar_screen_record</xliff:g></item>
         <item><xliff:g id="id">@string/status_bar_vpn</xliff:g></item>
         <item><xliff:g id="id">@string/status_bar_bluetooth</xliff:g></item>
         <item><xliff:g id="id">@string/status_bar_camera</xliff:g></item>
@@ -56,6 +54,8 @@
         <item><xliff:g id="id">@string/status_bar_mute</xliff:g></item>
         <item><xliff:g id="id">@string/status_bar_volume</xliff:g></item>
         <item><xliff:g id="id">@string/status_bar_zen</xliff:g></item>
+        <item><xliff:g id="id">@string/status_bar_screen_record</xliff:g></item>
+        <item><xliff:g id="id">@string/status_bar_cast</xliff:g></item>
         <item><xliff:g id="id">@string/status_bar_ethernet</xliff:g></item>
         <item><xliff:g id="id">@string/status_bar_wifi</xliff:g></item>
         <item><xliff:g id="id">@string/status_bar_hotspot</xliff:g></item>
@@ -3036,14 +3036,15 @@
          on the headphone/microphone jack. When false use the older uevent framework. -->
     <bool name="config_useDevInputEventForAudioJack">false</bool>
 
-    <!-- Whether safe headphone volume is enabled or not (country specific). -->
+    <!-- Whether safe headphone hearing is enforced by any regulation (e.g.
+         EN50332-3, EN50332-2) or not (country specific). -->
     <bool name="config_safe_media_volume_enabled">true</bool>
 
-    <!-- Whether safe headphone sound dosage warning is enabled or not
-         (country specific). This value should only be overlaid to true
-         when a vendor supports offload and has the HAL sound dose
-         interfaces implemented. Otherwise, this can lead to a compliance
-         issue with the safe hearing standards EN50332-3 and IEC62368-1.
+    <!-- Whether safe headphone sound dosage warning is enabled or not.
+         This value should only be overlaid to true when a vendor supports
+         offload and has the HAL sound dose interfaces implemented.
+         Otherwise, this can lead to a compliance issue with the safe
+         hearing standards EN50332-3 and IEC62368-1.
     -->
     <bool name="config_safe_sound_dosage_enabled">false</bool>
 
@@ -4288,6 +4289,9 @@
     <!-- Colon separated list of package names that should be granted DND access -->
     <string name="config_defaultDndAccessPackages" translatable="false">com.android.camera2</string>
 
+    <!-- Colon separated list of package names that should be removed from DND access packages -->
+    <string name="config_defaultDndDeniedPackages" translatable="false"></string>
+
     <!-- User restrictions set on the SYSTEM user when it is first created.
          Note: Also update appropriate overlay files. -->
     <string-array translatable="false" name="config_defaultFirstUserRestrictions">
@@ -5037,6 +5041,21 @@
     </array>
 
     <!-- See DisplayWhiteBalanceController.
+         A float array containing a list of ambient brightnesses, in Lux. This array,
+         together with config_displayWhiteBalanceLowLightAmbientBiasesStrong, is used to generate a
+         lookup table used in DisplayWhiteBalanceController. This lookup table is used to map
+         ambient brightness readings to a bias, where the bias is used to linearly interpolate
+         between ambient color temperature and
+         config_displayWhiteBalanceLowLightAmbientColorTemperatureIdle.
+         This table is optional. If used, this array must,
+         1) Contain at least two entries
+         2) Be the same length as config_displayWhiteBalanceLowLightAmbientBiasesStrong. -->
+    <array name ="config_displayWhiteBalanceLowLightAmbientBrightnessesStrong">
+        <item>10.0</item>
+        <item>10.0</item>
+    </array>
+
+    <!-- See DisplayWhiteBalanceController.
          An array containing a list of biases. See
          config_displayWhiteBalanceLowLightAmbientBrightnesses for additional details.
          This array must be in the range of [0.0, 1.0]. -->
@@ -5046,12 +5065,28 @@
     </array>
 
     <!-- See DisplayWhiteBalanceController.
+         An array containing a list of biases. See
+         config_displayWhiteBalanceLowLightAmbientBrightnessesStrong for additional details.
+         This array must be in the range of [0.0, 1.0]. -->
+    <array name ="config_displayWhiteBalanceLowLightAmbientBiasesStrong">
+        <item>0.0</item>
+        <item>1.0</item>
+    </array>
+
+    <!-- See DisplayWhiteBalanceController.
          The ambient color temperature (in cct) to which we interpolate towards using the
          the look up table generated by config_displayWhiteBalanceLowLightAmbientBrightnesses
          and config_displayWhiteBalanceLowLightAmbientBiases. -->
     <item name="config_displayWhiteBalanceLowLightAmbientColorTemperature" format="float" type="dimen">6500.0</item>
 
     <!-- See DisplayWhiteBalanceController.
+         The ambient color temperature (in cct) to which we interpolate towards using the
+         the look up table generated by config_displayWhiteBalanceLowLightAmbientBrightnessesStrong
+         and config_displayWhiteBalanceLowLightAmbientBiasesStrong. Used when device is in Idle Screen
+         Brightness mode. -->
+    <item name="config_displayWhiteBalanceLowLightAmbientColorTemperatureStrong" format="float" type="dimen">6500.0</item>
+
+    <!-- See DisplayWhiteBalanceController.
          A float array containing a list of ambient brightnesses, in Lux. This array,
          together with config_displayWhiteBalanceHighLightAmbientBiases, is used to generate a
          lookup table used in DisplayWhiteBalanceController. This lookup table is used to map
@@ -5065,6 +5100,19 @@
     </array>
 
     <!-- See DisplayWhiteBalanceController.
+         A float array containing a list of ambient brightnesses, in Lux. This array,
+         together with config_displayWhiteBalanceHighLightAmbientBiasesStrong, is used to generate a
+         lookup table used in DisplayWhiteBalanceController. This lookup table is used to map
+         ambient brightness readings to a bias, where the bias is used to linearly interpolate
+         between ambient color temperature and
+         config_displayWhiteBalanceHighLightAmbientColorTemperatureStrong.
+         This table is optional. If used, this array must,
+         1) Contain at least two entries
+         2) Be the same length as config_displayWhiteBalanceHighLightAmbientBiasesStrong. -->
+    <array name ="config_displayWhiteBalanceHighLightAmbientBrightnessesStrong">
+    </array>
+
+    <!-- See DisplayWhiteBalanceController.
          An array containing a list of biases. See
          config_displayWhiteBalanceHighLightAmbientBrightnesses for additional details.
          This array must be in the range of [0.0, 1.0]. -->
@@ -5072,12 +5120,26 @@
     </array>
 
     <!-- See DisplayWhiteBalanceController.
+         An array containing a list of biases. See
+         config_displayWhiteBalanceHighLightAmbientBrightnessesStrong for additional details.
+         This array must be in the range of [0.0, 1.0]. -->
+    <array name ="config_displayWhiteBalanceHighLightAmbientBiasesStrong">
+    </array>
+
+    <!-- See DisplayWhiteBalanceController.
          The ambient color temperature (in cct) to which we interpolate towards using the
          the look up table generated by config_displayWhiteBalanceHighLightAmbientBrightnesses
          and config_displayWhiteBalanceHighLightAmbientBiases. -->
     <item name="config_displayWhiteBalanceHighLightAmbientColorTemperature" format="float" type="dimen">8000.0</item>
 
     <!-- See DisplayWhiteBalanceController.
+         The ambient color temperature (in cct) to which we interpolate towards using the
+         the look up table generated by config_displayWhiteBalanceHighLightAmbientBrightnessesStrong
+         and config_displayWhiteBalanceHighLightAmbientBiasesStrong. Used when device is in Idle
+         Screen Brightness mode. -->
+    <item name="config_displayWhiteBalanceHighLightAmbientColorTemperatureStrong" format="float" type="dimen">8000.0</item>
+
+    <!-- See DisplayWhiteBalanceController.
          A float array containing a list of ambient color temperatures, in Kelvin. This array,
          together with config_displayWhiteBalanceDisplayColorTemperatures, is used to generate a
          lookup table used in DisplayWhiteBalanceController. This lookup table is used to map
@@ -5369,6 +5431,12 @@
     <!-- Default value for performant auth feature. -->
     <bool name="config_performantAuthDefault">false</bool>
 
+    <!-- Threshold for false rejection rate (FRR) of biometric authentication. Applies for both
+         fingerprint and face. If a dual-modality device only enrolled a single biometric and
+         experiences high FRR (above threshold), system notification will be sent to encourage user
+         to enroll the other eligible biometric. -->
+    <fraction name="config_biometricNotificationFrrThreshold">30%</fraction>
+
     <!-- The component name for the default profile supervisor, which can be set as a profile owner
     even after user setup is complete. The defined component should be used for supervision purposes
     only. The component must be part of a system app. -->
@@ -6104,6 +6172,9 @@
     <!-- Default value for Settings.ASSIST_TOUCH_GESTURE_ENABLED -->
     <bool name="config_assistTouchGestureEnabledDefault">true</bool>
 
+    <!-- Default value for Settings.SEARCH_PRESS_HOLD_NAV_HANDLE_ENABLED -->
+    <bool name="config_searchPressHoldNavHandleEnabledDefault">true</bool>
+
     <!-- The maximum byte size of the information contained in the bundle of
     HotwordDetectedResult. -->
     <integer translatable="false" name="config_hotwordDetectedResultMaxBundleSize">0</integer>
@@ -6589,6 +6660,10 @@
          for the non-customized ones. -->
     <string name="config_hapticFeedbackCustomizationFile" />
 
+    <!-- Enables or disables the "Share" action item shown in the context menu that appears upon
+        long-pressing on selected text. Enabled by default. -->
+    <bool name="config_textShareSupported">true</bool>
+
     <!-- Whether or not ActivityManager PSS profiling is disabled. -->
     <bool name="config_am_disablePssProfiling">false</bool>
 </resources>
diff --git a/core/res/res/values/config_battery_saver.xml b/core/res/res/values/config_battery_saver.xml
index eb396df..e1b0ef4 100644
--- a/core/res/res/values/config_battery_saver.xml
+++ b/core/res/res/values/config_battery_saver.xml
@@ -26,6 +26,10 @@
 <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
     <string translatable="false" name="config_batterySaverDeviceSpecificConfig"></string>
 
+    <!-- Whether or not the device supports battery saver. If false, battery saver will be
+     disabled. -->
+    <bool name="config_batterySaverSupported">true</bool>
+
     <!-- Whether or not battery saver should be "sticky" when manually enabled. -->
     <bool name="config_batterySaverStickyBehaviourDisabled">false</bool>
 
diff --git a/core/res/res/values/config_device_idle.xml b/core/res/res/values/config_device_idle.xml
index 764dbbe..98a5ff9 100644
--- a/core/res/res/values/config_device_idle.xml
+++ b/core/res/res/values/config_device_idle.xml
@@ -120,7 +120,7 @@
     <!-- Default for DeviceIdleController.Constants.USE_WINDOW_ALARMS -->
     <bool name="device_idle_use_window_alarms">true</bool>
 
-    <!-- Default for DeviceIdleController.Constants.USE_BODY_SENSOR -->
-    <bool name="device_idle_use_body_sensor">false</bool>
+    <!-- Default for DeviceIdleController.Constants.USE_MODE_MANAGER -->
+    <bool name="device_idle_use_mode_manager">false</bool>
 </resources>
 
diff --git a/core/res/res/values/config_telephony.xml b/core/res/res/values/config_telephony.xml
index 18abe70..bda194a 100644
--- a/core/res/res/values/config_telephony.xml
+++ b/core/res/res/values/config_telephony.xml
@@ -160,6 +160,7 @@
             3 = {@link android.telephony.NetworkRegistrationInfo#SERVICE_TYPE_SMS}
             4 = {@link android.telephony.NetworkRegistrationInfo#SERVICE_TYPE_VIDEO}
             5 = {@link android.telephony.NetworkRegistrationInfo#SERVICE_TYPE_EMERGENCY}
+            6 = {@link android.telephony.NetworkRegistrationInfo#SERVICE_TYPE_MMS}
          Example of a config string: "10011:2,3"
 
          The PLMNs not configured in this array will be ignored and will not be used for satellite
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index a11eaa9..0dd6c74 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -1786,10 +1786,6 @@
     <string name="biometric_dialog_default_title">Verify it\u2019s you</string>
     <!-- Subtitle shown on the system-provided biometric dialog, asking the user to authenticate with a biometric (e.g. fingerprint or face). [CHAR LIMIT=70] -->
     <string name="biometric_dialog_default_subtitle">Use your biometric to continue</string>
-    <!-- Subtitle shown on the system-provided biometric dialog, asking the user to authenticate with fingerprint. [CHAR LIMIT=70] -->
-    <string name="biometric_dialog_fingerprint_subtitle">Use your fingerprint to continue</string>
-    <!-- Subtitle shown on the system-provided biometric dialog, asking the user to authenticate with face. [CHAR LIMIT=70] -->
-    <string name="biometric_dialog_face_subtitle">Use your face to continue</string>
     <!-- Subtitle shown on the system-provided biometric dialog, asking the user to authenticate with a biometric (e.g. fingerprint or face) or their screen lock credential (i.e. PIN, pattern, or password). [CHAR LIMIT=90] -->
     <string name="biometric_or_screen_lock_dialog_default_subtitle">Use your biometric or screen lock to continue</string>
 
@@ -1841,6 +1837,8 @@
     <string name="fingerprint_error_not_match">Fingerprint not recognized</string>
     <!-- Message shown when UDFPS fails to match -->
     <string name="fingerprint_udfps_error_not_match">Fingerprint not recognized</string>
+    <!-- Message shown to inform the user a face cannot be recognized and fingerprint should instead be used.[CHAR LIMIT=50] -->
+    <string name="fingerprint_dialog_use_fingerprint_instead">Can\u2019t recognize face. Use fingerprint instead.</string>
 
     <!-- Accessibility message announced when a fingerprint has been authenticated [CHAR LIMIT=NONE] -->
     <string name="fingerprint_authenticated">Fingerprint authenticated</string>
@@ -1897,22 +1895,22 @@
     <!-- Content description which should be used for the fingerprint icon. -->
     <string name="fingerprint_icon_content_description">Fingerprint icon</string>
 
+    <!-- Notification name shown when the system requires the user to set up device unlock. [CHAR LIMIT=NONE] -->
+    <string name="device_unlock_notification_name">Device unlock</string>
+    <!-- Notification title shown when the system suggests the user to set up another way to unlock. [CHAR LIMIT=NONE] -->
+    <string name="alternative_unlock_setup_notification_title">Try another way to unlock</string>
+    <!-- Notification content shown when the system suggests the user to enroll their face. [CHAR LIMIT=NONE] -->
+    <string name="alternative_face_setup_notification_content">Use Face Unlock when your fingerprint isn\'t recognized, like when your fingers are wet</string>
+    <!-- Notification content shown when the system suggests the user to enroll their fingerprint. [CHAR LIMIT=NONE] -->
+    <string name="alternative_fp_setup_notification_content">Use Fingerprint Unlock when your face isn\'t recognized, like when there\'s not enough light</string>
     <!-- Notification name shown when the system requires the user to re-enroll their face. [CHAR LIMIT=NONE] -->
     <string name="face_recalibrate_notification_name">Face Unlock</string>
     <!-- Notification title shown when the system requires the user to re-enroll their face. [CHAR LIMIT=NONE] -->
     <string name="face_recalibrate_notification_title">Issue with Face Unlock</string>
     <!-- Notification content shown when the system requires the user to re-enroll their face. [CHAR LIMIT=NONE] -->
     <string name="face_recalibrate_notification_content">Tap to delete your face model, then add your face again</string>
-    <!-- Title of a notification that directs the user to set up Face Unlock by enrolling their face. [CHAR LIMIT=NONE] -->
-    <string name="face_setup_notification_title">Set up Face Unlock</string>
-    <!-- Contents of a notification that directs the user to set up face unlock by enrolling their face. [CHAR LIMIT=NONE] -->
-    <string name="face_setup_notification_content">Unlock your phone by looking at it</string>
     <!-- Error message indicating that the camera privacy sensor has been turned on [CHAR LIMIT=NONE] -->
     <string name="face_sensor_privacy_enabled">To use Face Unlock, turn on <b>Camera access</b> in Settings > Privacy</string>
-    <!-- Title of a notification that directs the user to enroll a fingerprint. [CHAR LIMIT=NONE] -->
-    <string name="fingerprint_setup_notification_title">Set up more ways to unlock</string>
-    <!-- Contents of a notification that directs the user to enroll a fingerprint. [CHAR LIMIT=NONE] -->
-    <string name="fingerprint_setup_notification_content">Tap to add a fingerprint</string>
 
     <!-- Notification name shown when the system requires the user to re-calibrate their fingerprint. [CHAR LIMIT=NONE] -->
     <string name="fingerprint_recalibrate_notification_name">Fingerprint Unlock</string>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 5806e93..f1a78a6 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2585,8 +2585,6 @@
   <java-symbol type="string" name="biometric_or_screen_lock_app_setting_name" />
   <java-symbol type="string" name="biometric_dialog_default_title" />
   <java-symbol type="string" name="biometric_dialog_default_subtitle" />
-  <java-symbol type="string" name="biometric_dialog_face_subtitle" />
-  <java-symbol type="string" name="biometric_dialog_fingerprint_subtitle" />
   <java-symbol type="string" name="biometric_or_screen_lock_dialog_default_subtitle" />
   <java-symbol type="string" name="biometric_error_hw_unavailable" />
   <java-symbol type="string" name="biometric_error_user_canceled" />
@@ -2596,6 +2594,15 @@
   <java-symbol type="string" name="biometric_error_device_not_secured" />
   <java-symbol type="string" name="biometric_error_generic" />
 
+  <!-- Biometric FRR config -->
+  <java-symbol type="fraction" name="config_biometricNotificationFrrThreshold" />
+
+  <!-- Biometric FRR notification messages -->
+  <java-symbol type="string" name="device_unlock_notification_name" />
+  <java-symbol type="string" name="alternative_unlock_setup_notification_title" />
+  <java-symbol type="string" name="alternative_face_setup_notification_content" />
+  <java-symbol type="string" name="alternative_fp_setup_notification_content" />
+
   <!-- Device credential strings for BiometricManager -->
   <java-symbol type="string" name="screen_lock_app_setting_name" />
   <java-symbol type="string" name="screen_lock_dialog_default_subtitle" />
@@ -2609,6 +2616,7 @@
   <java-symbol type="string" name="fingerprint_error_vendor_unknown" />
   <java-symbol type="string" name="fingerprint_error_not_match" />
   <java-symbol type="string" name="fingerprint_udfps_error_not_match" />
+  <java-symbol type="string" name="fingerprint_dialog_use_fingerprint_instead" />
   <java-symbol type="string" name="fingerprint_acquired_partial" />
   <java-symbol type="string" name="fingerprint_acquired_insufficient" />
   <java-symbol type="string" name="fingerprint_acquired_imager_dirty" />
@@ -3051,6 +3059,7 @@
   <java-symbol type="id" name="addToDictionaryButton" />
   <java-symbol type="id" name="deleteButton" />
   <!-- TextView -->
+  <java-symbol type="bool" name="config_textShareSupported" />
   <java-symbol type="string" name="failed_to_copy_to_clipboard" />
 
   <java-symbol type="id" name="notification_material_reply_container" />
@@ -3383,6 +3392,8 @@
 
   <!-- Colon separated list of package names that should be granted DND access -->
   <java-symbol type="string" name="config_defaultDndAccessPackages" />
+  <!-- Colon separated list of package names that should be removed from DND access packages -->
+  <java-symbol type="string" name="config_defaultDndDeniedPackages" />
 
   <!-- For NetworkPolicyManagerService -->
   <java-symbol type="string" name="config_networkOverLimitComponent" />
@@ -4014,6 +4025,7 @@
 
   <!-- Battery saver config -->
   <java-symbol type="integer" name="config_lowBatteryAutoTriggerDefaultLevel" />
+  <java-symbol type="bool" name="config_batterySaverSupported" />
   <java-symbol type="string" name="config_batterySaverDeviceSpecificConfig" />
   <java-symbol type="bool" name="config_batterySaverStickyBehaviourDisabled" />
   <java-symbol type="integer" name="config_dynamicPowerSavingsDefaultDisableThreshold" />
@@ -4161,11 +4173,17 @@
   <java-symbol type="array" name="config_displayWhiteBalanceIncreaseThresholds" />
   <java-symbol type="array" name="config_displayWhiteBalanceDecreaseThresholds" />
   <java-symbol type="array" name="config_displayWhiteBalanceLowLightAmbientBrightnesses" />
+  <java-symbol type="array" name="config_displayWhiteBalanceLowLightAmbientBrightnessesStrong" />
   <java-symbol type="array" name="config_displayWhiteBalanceLowLightAmbientBiases" />
+  <java-symbol type="array" name="config_displayWhiteBalanceLowLightAmbientBiasesStrong" />
   <java-symbol type="dimen" name="config_displayWhiteBalanceLowLightAmbientColorTemperature" />
+  <java-symbol type="dimen" name="config_displayWhiteBalanceLowLightAmbientColorTemperatureStrong" />
   <java-symbol type="array" name="config_displayWhiteBalanceHighLightAmbientBrightnesses" />
+  <java-symbol type="array" name="config_displayWhiteBalanceHighLightAmbientBrightnessesStrong" />
   <java-symbol type="array" name="config_displayWhiteBalanceHighLightAmbientBiases" />
+  <java-symbol type="array" name="config_displayWhiteBalanceHighLightAmbientBiasesStrong" />
   <java-symbol type="dimen" name="config_displayWhiteBalanceHighLightAmbientColorTemperature" />
+  <java-symbol type="dimen" name="config_displayWhiteBalanceHighLightAmbientColorTemperatureStrong" />
   <java-symbol type="array" name="config_displayWhiteBalanceAmbientColorTemperatures" />
   <java-symbol type="array" name="config_displayWhiteBalanceDisplayColorTemperatures" />
   <java-symbol type="array" name="config_displayWhiteBalanceStrongAmbientColorTemperatures" />
@@ -4522,7 +4540,7 @@
   <java-symbol type="integer" name="device_idle_notification_allowlist_duration_ms" />
   <java-symbol type="bool" name="device_idle_wait_for_unlock" />
   <java-symbol type="bool" name="device_idle_use_window_alarms" />
-  <java-symbol type="bool" name="device_idle_use_body_sensor" />
+  <java-symbol type="bool" name="device_idle_use_mode_manager" />
 
   <!-- Binder heavy hitter watcher configs -->
   <java-symbol type="bool" name="config_defaultBinderHeavyHitterWatcherEnabled" />
@@ -4889,6 +4907,8 @@
   <java-symbol type="bool" name="config_assistLongPressHomeEnabledDefault" />
   <java-symbol type="bool" name="config_assistTouchGestureEnabledDefault" />
 
+  <java-symbol type="bool" name="config_searchPressHoldNavHandleEnabledDefault" />
+
   <java-symbol type="integer" name="config_hotwordDetectedResultMaxBundleSize" />
 
   <java-symbol type="dimen" name="config_wallpaperDimAmount" />
@@ -5179,6 +5199,7 @@
   <java-symbol type="style" name="ThemeOverlay.DeviceDefault.Dark.ActionBar.Accent" />
 
   <java-symbol type="drawable" name="focus_event_pressed_key_background" />
+  <java-symbol type="drawable" name="focus_event_rotary_input_background" />
   <java-symbol type="string" name="config_defaultShutdownVibrationFile" />
   <java-symbol type="string" name="lockscreen_too_many_failed_attempts_countdown" />
 
@@ -5188,4 +5209,6 @@
 
   <!-- For ActivityManager PSS profiling configurability -->
   <java-symbol type="bool" name="config_am_disablePssProfiling" />
+
+  <java-symbol type="raw" name="default_ringtone_vibration_effect" />
 </resources>
diff --git a/core/tests/coretests/Android.bp b/core/tests/coretests/Android.bp
index c7aaeb0..7f56eb7 100644
--- a/core/tests/coretests/Android.bp
+++ b/core/tests/coretests/Android.bp
@@ -88,10 +88,9 @@
 
     resource_dirs: ["res"],
     resource_zips: [":FrameworksCoreTests_apks_as_resources"],
-    java_resources: [":ApkVerityTestCertDer"],
+    java_resources: [":FrameworksCoreTests_unit_test_cert_der"],
 
     data: [
-        ":BstatsTestApp",
         ":BinderDeathRecipientHelperApp1",
         ":BinderDeathRecipientHelperApp2",
         ":com.android.cts.helpers.aosp",
diff --git a/core/tests/coretests/AndroidManifest.xml b/core/tests/coretests/AndroidManifest.xml
index 129de64..a358c4f 100644
--- a/core/tests/coretests/AndroidManifest.xml
+++ b/core/tests/coretests/AndroidManifest.xml
@@ -231,6 +231,28 @@
             </intent-filter>
         </activity>
 
+        <activity android:name="android.widget.HorizontalScrollViewActivity"
+                android:label="HorizontalScrollViewActivity"
+                android:screenOrientation="portrait"
+                android:exported="true"
+                android:theme="@android:style/Theme.Material.Light">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+            </intent-filter>
+        </activity>
+
+        <activity android:name="android.widget.ScrollViewActivity"
+                android:label="ScrollViewActivity"
+                android:screenOrientation="portrait"
+                android:exported="true"
+                android:theme="@android:style/Theme.Material.Light">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+            </intent-filter>
+        </activity>
+
         <activity android:name="android.widget.DatePickerActivity"
                 android:label="DatePickerActivity"
                 android:screenOrientation="portrait"
@@ -1727,6 +1749,15 @@
                 <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
             </intent-filter>
         </activity>
+
+        <activity android:name="android.view.ViewGroupTestActivity"
+                  android:label="ViewGroup Test"
+                  android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+            </intent-filter>
+        </activity>
     </application>
 
     <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
diff --git a/core/tests/coretests/AndroidTest.xml b/core/tests/coretests/AndroidTest.xml
index 3e4c47b..05b309b 100644
--- a/core/tests/coretests/AndroidTest.xml
+++ b/core/tests/coretests/AndroidTest.xml
@@ -20,7 +20,6 @@
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="FrameworksCoreTests.apk" />
-        <option name="test-file-name" value="BstatsTestApp.apk" />
         <option name="test-file-name" value="BinderDeathRecipientHelperApp1.apk" />
         <option name="test-file-name" value="BinderDeathRecipientHelperApp2.apk" />
     </target_preparer>
diff --git a/core/tests/coretests/BstatsTestApp/OWNERS b/core/tests/coretests/BstatsTestApp/OWNERS
deleted file mode 100644
index 4068e2b..0000000
--- a/core/tests/coretests/BstatsTestApp/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-include /BATTERY_STATS_OWNERS
diff --git a/core/tests/coretests/certs/Android.bp b/core/tests/coretests/certs/Android.bp
index 8d4ecf4..cefdc4d 100644
--- a/core/tests/coretests/certs/Android.bp
+++ b/core/tests/coretests/certs/Android.bp
@@ -13,3 +13,8 @@
     name: "FrameworksCoreTests_unit_test_cert",
     certificate: "unit_test",
 }
+
+filegroup {
+    name: "FrameworksCoreTests_unit_test_cert_der",
+    srcs: ["unit_test.der"],
+}
diff --git a/core/tests/coretests/certs/README b/core/tests/coretests/certs/README
index 00917a1..b5c096e 100644
--- a/core/tests/coretests/certs/README
+++ b/core/tests/coretests/certs/README
@@ -2,3 +2,5 @@
 
 development/tools/make_key unit_test         '/CN=unit_test'
 development/tools/make_key unit_test_diff    '/CN=unit_test_diff'
+
+openssl x509 -in unit_test.x509.pem -out unit_test.der -outform der
diff --git a/core/tests/coretests/certs/unit_test.der b/core/tests/coretests/certs/unit_test.der
new file mode 100644
index 0000000..4dbbc49
--- /dev/null
+++ b/core/tests/coretests/certs/unit_test.der
Binary files differ
diff --git a/core/tests/coretests/res/layout/activity_horizontal_scroll_view.xml b/core/tests/coretests/res/layout/activity_horizontal_scroll_view.xml
new file mode 100644
index 0000000..866e1a9
--- /dev/null
+++ b/core/tests/coretests/res/layout/activity_horizontal_scroll_view.xml
@@ -0,0 +1,118 @@
+<?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
+  -->
+
+<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:id="@+id/horizontal_scroll_view">
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal">
+
+        <View
+            android:background="#F00"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#880"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#0F0"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#088"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#00F"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#808"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#F00"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#880"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#0F0"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#088"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#00F"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#808"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#F00"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#880"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#0F0"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#088"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#00F"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#808"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+    </LinearLayout>
+</HorizontalScrollView>
diff --git a/core/tests/coretests/res/layout/activity_scroll_view.xml b/core/tests/coretests/res/layout/activity_scroll_view.xml
new file mode 100644
index 0000000..61fabf8
--- /dev/null
+++ b/core/tests/coretests/res/layout/activity_scroll_view.xml
@@ -0,0 +1,118 @@
+<?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
+  -->
+
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:id="@+id/scroll_view">
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="vertical">
+
+        <View
+            android:background="#F00"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#880"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#0F0"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#088"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#00F"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#808"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#F00"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#880"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#0F0"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#088"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#00F"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#808"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#F00"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#880"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#0F0"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#088"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#00F"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+        <View
+            android:background="#808"
+            android:layout_width="100dp"
+            android:layout_height="100dp" />
+
+    </LinearLayout>
+</ScrollView>
diff --git a/core/tests/coretests/res/layout/viewgroup_test.xml b/core/tests/coretests/res/layout/viewgroup_test.xml
new file mode 100644
index 0000000..04f4f52
--- /dev/null
+++ b/core/tests/coretests/res/layout/viewgroup_test.xml
@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2023 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<!-- Demonstrates adding/removing views from ViewGroup. See corresponding Java code. -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:id="@+id/linear_layout"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
+              android:orientation="vertical">
+    <EditText
+        android:id="@+id/view"
+        android:layout_width="20dp"
+        android:layout_height="10dp"
+        android:text="Hello World!"
+        android:background="#2F00FF00" />
+    <EditText
+        android:id="@+id/view_scale"
+        android:layout_width="20dp"
+        android:layout_height="10dp"
+        android:scaleX="0.5"
+        android:scaleY="2"
+        android:transformPivotX="0dp"
+        android:transformPivotY="0dp"
+        android:text="Hello World!"
+        android:background="#2F00FF00" />
+    <EditText
+        android:id="@+id/view_translate"
+        android:layout_width="20dp"
+        android:layout_height="10dp"
+        android:translationX="10dp"
+        android:translationY="20dp"
+        android:text="Hello World!"
+        android:background="#2F00FF00" />
+    <FrameLayout
+        android:layout_width="20dp"
+        android:layout_height="10dp">
+        <EditText
+            android:id="@+id/view_overlap_bottom"
+            android:layout_width="20dp"
+            android:layout_height="10dp"
+            android:text="Hello World!"/>
+        <Button
+            android:id="@+id/view_overlap_top"
+            android:layout_width="10dp"
+            android:layout_height="10dp"/>
+    </FrameLayout>
+
+    <FrameLayout
+        android:layout_width="20dp"
+        android:layout_height="10dp">
+        <EditText
+            android:id="@+id/view_cover_bottom"
+            android:layout_width="10dp"
+            android:layout_height="10dp"
+            android:text="Hello World!"/>
+        <Button
+            android:id="@+id/view_cover_top"
+            android:layout_width="10dp"
+            android:layout_height="10dp"/>
+    </FrameLayout>
+
+</LinearLayout>
diff --git a/core/tests/coretests/res/raw/fsverity_sig b/core/tests/coretests/res/raw/fsverity_sig
index b2f335d..2c28f0b 100644
--- a/core/tests/coretests/res/raw/fsverity_sig
+++ b/core/tests/coretests/res/raw/fsverity_sig
Binary files differ
diff --git a/core/tests/coretests/src/android/app/NotificationChannelTest.java b/core/tests/coretests/src/android/app/NotificationChannelTest.java
index 647bfe8..d8305f0 100644
--- a/core/tests/coretests/src/android/app/NotificationChannelTest.java
+++ b/core/tests/coretests/src/android/app/NotificationChannelTest.java
@@ -16,19 +16,52 @@
 
 package android.app;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import static junit.framework.TestCase.assertEquals;
 
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import android.content.AttributionSource;
+import android.content.ContentProvider;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.IContentProvider;
+import android.content.pm.ApplicationInfo;
+import android.database.MatrixCursor;
+import android.media.AudioAttributes;
 import android.net.Uri;
+import android.os.AsyncTask;
+import android.os.Bundle;
 import android.os.Parcel;
+import android.os.RemoteCallback;
+import android.os.RemoteException;
+import android.provider.MediaStore.Audio.AudioColumns;
+import android.test.mock.MockContentResolver;
+import android.util.Xml;
 
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
 
+import com.android.modules.utils.TypedXmlPullParser;
+import com.android.modules.utils.TypedXmlSerializer;
+
 import com.google.common.base.Strings;
 
+import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 import java.lang.reflect.Field;
 
 @RunWith(AndroidJUnit4.class)
@@ -36,6 +69,88 @@
 public class NotificationChannelTest {
     private final String CLASS = "android.app.NotificationChannel";
 
+    Context mContext;
+    ContentProvider mContentProvider;
+    IContentProvider mIContentProvider;
+
+    @Before
+    public void setUp() throws Exception {
+        mContext = mock(Context.class);
+        when(mContext.getApplicationInfo()).thenReturn(new ApplicationInfo());
+        MockContentResolver mContentResolver = new MockContentResolver(mContext);
+        when(mContext.getContentResolver()).thenReturn(mContentResolver);
+        mContentProvider = mock(ContentProvider.class);
+        mIContentProvider = mock(IContentProvider.class);
+        when(mContentProvider.getIContentProvider()).thenReturn(mIContentProvider);
+        doAnswer(
+                invocation -> {
+                        AttributionSource attributionSource = invocation.getArgument(0);
+                        Uri uri = invocation.getArgument(1);
+                        RemoteCallback cb = invocation.getArgument(2);
+                        IContentProvider mock = (IContentProvider) (invocation.getMock());
+                        AsyncTask.SERIAL_EXECUTOR.execute(
+                                () -> {
+                                final Bundle bundle = new Bundle();
+                                try {
+                                        bundle.putParcelable(
+                                                ContentResolver.REMOTE_CALLBACK_RESULT,
+                                                mock.canonicalize(attributionSource, uri));
+                                } catch (RemoteException e) {
+                                        /* consume */
+                                }
+                                cb.sendResult(bundle);
+                                });
+                        return null;
+                })
+            .when(mIContentProvider)
+            .canonicalizeAsync(any(), any(), any());
+        doAnswer(
+                invocation -> {
+                        AttributionSource attributionSource = invocation.getArgument(0);
+                        Uri uri = invocation.getArgument(1);
+                        RemoteCallback cb = invocation.getArgument(2);
+                        IContentProvider mock = (IContentProvider) (invocation.getMock());
+                        AsyncTask.SERIAL_EXECUTOR.execute(
+                                () -> {
+                                final Bundle bundle = new Bundle();
+                                try {
+                                        bundle.putParcelable(
+                                                ContentResolver.REMOTE_CALLBACK_RESULT,
+                                                mock.uncanonicalize(attributionSource, uri));
+                                } catch (RemoteException e) {
+                                        /* consume */
+                                }
+                                cb.sendResult(bundle);
+                                });
+                        return null;
+                })
+            .when(mIContentProvider)
+            .uncanonicalizeAsync(any(), any(), any());
+        doAnswer(
+                invocation -> {
+                        Uri uri = invocation.getArgument(0);
+                        RemoteCallback cb = invocation.getArgument(1);
+                        IContentProvider mock = (IContentProvider) (invocation.getMock());
+                        AsyncTask.SERIAL_EXECUTOR.execute(
+                                () -> {
+                                final Bundle bundle = new Bundle();
+                                try {
+                                        bundle.putString(
+                                                ContentResolver.REMOTE_CALLBACK_RESULT,
+                                                mock.getType(uri));
+                                } catch (RemoteException e) {
+                                        /* consume */
+                                }
+                                cb.sendResult(bundle);
+                                });
+                        return null;
+                })
+            .when(mIContentProvider)
+            .getTypeAsync(any(), any());
+
+        mContentResolver.addProvider("media", mContentProvider);
+    }
+
     @Test
     public void testLongStringFields() {
         NotificationChannel channel = new NotificationChannel("id", "name", 3);
@@ -103,4 +218,139 @@
         assertEquals(NotificationChannel.MAX_TEXT_LENGTH,
                 fromParcel.getSound().toString().length());
     }
+
+    @Test
+    public void testRestoreSoundUri_customLookup() throws Exception {
+        Uri uriToBeRestoredUncanonicalized = Uri.parse("content://media/1");
+        Uri uriToBeRestoredCanonicalized = Uri.parse("content://media/1?title=Song&canonical=1");
+        Uri uriAfterRestoredUncanonicalized = Uri.parse("content://media/100");
+        Uri uriAfterRestoredCanonicalized = Uri.parse("content://media/100?title=Song&canonical=1");
+
+        NotificationChannel channel = new NotificationChannel("id", "name", 3);
+
+        MatrixCursor cursor = new MatrixCursor(new String[] {"_id"});
+        cursor.addRow(new Object[] {100L});
+
+        when(mIContentProvider.canonicalize(any(), eq(uriToBeRestoredUncanonicalized)))
+                .thenReturn(uriToBeRestoredCanonicalized);
+
+        // Mock the failure of regular uncanonicalize.
+        when(mIContentProvider.uncanonicalize(any(), eq(uriToBeRestoredCanonicalized)))
+                .thenReturn(null);
+
+        // Mock the custom lookup in RingtoneManager.getRingtoneUriForRestore.
+        when(mIContentProvider.query(any(), any(), any(), any(), any())).thenReturn(cursor);
+
+        // Mock the canonicalize in RingtoneManager.getRingtoneUriForRestore.
+        when(mIContentProvider.canonicalize(any(), eq(uriAfterRestoredUncanonicalized)))
+                .thenReturn(uriAfterRestoredCanonicalized);
+
+        assertThat(
+                        channel.restoreSoundUri(
+                                mContext,
+                                uriToBeRestoredUncanonicalized,
+                                true,
+                                AudioAttributes.USAGE_NOTIFICATION))
+                .isEqualTo(uriAfterRestoredCanonicalized);
+    }
+
+    @Test
+    public void testWriteXmlForBackup_customLookup_notificationUsage() throws Exception {
+        testWriteXmlForBackup_customLookup(
+                AudioAttributes.USAGE_NOTIFICATION, AudioColumns.IS_NOTIFICATION);
+    }
+
+    @Test
+    public void testWriteXmlForBackup_customLookup_alarmUsage() throws Exception {
+        testWriteXmlForBackup_customLookup(AudioAttributes.USAGE_ALARM, AudioColumns.IS_ALARM);
+    }
+
+    @Test
+    public void testWriteXmlForBackup_customLookup_ringtoneUsage() throws Exception {
+        testWriteXmlForBackup_customLookup(
+                AudioAttributes.USAGE_NOTIFICATION_RINGTONE, AudioColumns.IS_RINGTONE);
+    }
+
+    @Test
+    public void testWriteXmlForBackup_customLookup_unknownUsage() throws Exception {
+        testWriteXmlForBackup_customLookup(
+                AudioAttributes.USAGE_UNKNOWN, AudioColumns.IS_NOTIFICATION);
+    }
+
+    private void testWriteXmlForBackup_customLookup(int usage, String customQuerySelection)
+            throws Exception {
+        Uri uriToBeRestoredUncanonicalized = Uri.parse("content://media/1");
+        Uri uriToBeRestoredCanonicalized = Uri.parse("content://media/1?title=Song&canonical=1");
+        Uri uriAfterRestoredUncanonicalized = Uri.parse("content://media/100");
+        Uri uriAfterRestoredCanonicalized = Uri.parse("content://media/100?title=Song&canonical=1");
+
+        AudioAttributes mAudioAttributes =
+                new AudioAttributes.Builder()
+                        .setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
+                        .setUsage(usage)
+                        .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
+                        .build();
+
+        NotificationChannel channel = new NotificationChannel("id", "name", 3);
+        channel.setSound(uriToBeRestoredCanonicalized, mAudioAttributes);
+
+        TypedXmlSerializer serializer = Xml.newFastSerializer();
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        serializer.setOutput(new BufferedOutputStream(baos), "utf-8");
+        serializer.startDocument(null, true);
+
+        // mock the canonicalize in writeXmlForBackup -> getSoundForBackup
+        when(mIContentProvider.canonicalize(any(), eq(uriToBeRestoredUncanonicalized)))
+                .thenReturn(uriToBeRestoredCanonicalized);
+        when(mIContentProvider.canonicalize(any(), eq(uriToBeRestoredCanonicalized)))
+                .thenReturn(uriToBeRestoredCanonicalized);
+
+        channel.writeXmlForBackup(serializer, mContext);
+        serializer.endDocument();
+        serializer.flush();
+
+        TypedXmlPullParser parser = Xml.newFastPullParser();
+        byte[] byteArray = baos.toByteArray();
+        parser.setInput(new BufferedInputStream(new ByteArrayInputStream(byteArray)), null);
+        parser.nextTag();
+
+        NotificationChannel targetChannel = new NotificationChannel("id", "name", 3);
+
+        MatrixCursor cursor = new MatrixCursor(new String[] {"_id"});
+        cursor.addRow(new Object[] {100L});
+
+        when(mIContentProvider.canonicalize(any(), eq(uriToBeRestoredCanonicalized)))
+                .thenReturn(uriToBeRestoredCanonicalized);
+
+        // Mock the failure of regular uncanonicalize.
+        when(mIContentProvider.uncanonicalize(any(), eq(uriToBeRestoredCanonicalized)))
+                .thenReturn(null);
+
+        Bundle expectedBundle =
+                ContentResolver.createSqlQueryBundle(
+                        customQuerySelection + "=1 AND title=?", new String[] {"Song"}, null);
+
+        // Mock the custom lookup in RingtoneManager.getRingtoneUriForRestore.
+        when(mIContentProvider.query(
+                        any(),
+                        any(),
+                        any(),
+                        // any(),
+                        argThat(
+                                queryBundle -> {
+                                    return queryBundle != null
+                                            && expectedBundle
+                                                    .toString()
+                                                    .equals(queryBundle.toString());
+                                }),
+                        any()))
+                .thenReturn(cursor);
+
+        // Mock the canonicalize in RingtoneManager.getRingtoneUriForRestore.
+        when(mIContentProvider.canonicalize(any(), eq(uriAfterRestoredUncanonicalized)))
+                .thenReturn(uriAfterRestoredCanonicalized);
+
+        targetChannel.populateFromXmlForRestore(parser, true, mContext);
+        assertThat(targetChannel.getSound()).isEqualTo(uriAfterRestoredCanonicalized);
+    }
 }
diff --git a/core/tests/coretests/src/android/app/NotificationTest.java b/core/tests/coretests/src/android/app/NotificationTest.java
index a936cea..f9377fc 100644
--- a/core/tests/coretests/src/android/app/NotificationTest.java
+++ b/core/tests/coretests/src/android/app/NotificationTest.java
@@ -19,6 +19,8 @@
 import static android.app.Notification.CarExtender.UnreadConversation.KEY_ON_READ;
 import static android.app.Notification.CarExtender.UnreadConversation.KEY_ON_REPLY;
 import static android.app.Notification.CarExtender.UnreadConversation.KEY_REMOTE_INPUT;
+import static android.app.Notification.DEFAULT_SOUND;
+import static android.app.Notification.DEFAULT_VIBRATE;
 import static android.app.Notification.EXTRA_ANSWER_INTENT;
 import static android.app.Notification.EXTRA_BUILDER_APPLICATION_INFO;
 import static android.app.Notification.EXTRA_CALL_PERSON;
@@ -35,6 +37,9 @@
 import static android.app.Notification.EXTRA_PICTURE_ICON;
 import static android.app.Notification.EXTRA_SUMMARY_TEXT;
 import static android.app.Notification.EXTRA_TITLE;
+import static android.app.Notification.GROUP_ALERT_CHILDREN;
+import static android.app.Notification.GROUP_ALERT_SUMMARY;
+import static android.app.Notification.GROUP_KEY_SILENT;
 import static android.app.Notification.MessagingStyle.Message.KEY_DATA_URI;
 import static android.app.Notification.MessagingStyle.Message.KEY_SENDER_PERSON;
 import static android.app.Notification.MessagingStyle.Message.KEY_TEXT;
@@ -511,6 +516,75 @@
     }
 
     @Test
+    public void testBuilder_setSilent_summaryBehavior_groupAlertChildren() {
+        Notification summaryNotif = new Notification.Builder(mContext, "channelId")
+                .setGroupSummary(true)
+                .setGroup("groupKey")
+                .setSilent(true)
+                .build();
+        assertEquals(GROUP_ALERT_CHILDREN, summaryNotif.getGroupAlertBehavior());
+    }
+
+    @Test
+    public void testBuilder_setSilent_childBehavior_groupAlertSummary() {
+        Notification childNotif = new Notification.Builder(mContext, "channelId")
+                .setGroupSummary(false)
+                .setGroup("groupKey")
+                .setSilent(true)
+                .build();
+        assertEquals(GROUP_ALERT_SUMMARY, childNotif.getGroupAlertBehavior());
+    }
+
+    @Test
+    public void testBuilder_setSilent_emptyGroupKey_groupKeySilent() {
+        Notification emptyGroupKeyNotif = new Notification.Builder(mContext, "channelId")
+                .setGroup("")
+                .setSilent(true)
+                .build();
+        assertEquals(GROUP_KEY_SILENT, emptyGroupKeyNotif.getGroup());
+    }
+
+    @Test
+    public void testBuilder_setSilent_vibrateNull() {
+        Notification silentNotif = new Notification.Builder(mContext, "channelId")
+                .setGroup("")
+                .setSilent(true)
+                .build();
+
+        assertNull(silentNotif.vibrate);
+    }
+
+    @Test
+    public void testBuilder_setSilent_soundNull() {
+        Notification silentNotif = new Notification.Builder(mContext, "channelId")
+                .setGroup("")
+                .setSilent(true)
+                .build();
+
+        assertNull(silentNotif.sound);
+    }
+
+    @Test
+    public void testBuilder_setSilent_noDefaultSound() {
+        Notification silentNotif = new Notification.Builder(mContext, "channelId")
+                .setGroup("")
+                .setSilent(true)
+                .build();
+
+        assertEquals(0, (silentNotif.defaults & DEFAULT_SOUND));
+    }
+
+    @Test
+    public void testBuilder_setSilent_noDefaultVibrate() {
+        Notification silentNotif = new Notification.Builder(mContext, "channelId")
+                .setGroup("")
+                .setSilent(true)
+                .build();
+
+        assertEquals(0, (silentNotif.defaults & DEFAULT_VIBRATE));
+    }
+
+    @Test
     public void testCallStyle_getSystemActions_forIncomingCall() {
         PendingIntent answerIntent = createPendingIntent("answer");
         PendingIntent declineIntent = createPendingIntent("decline");
diff --git a/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java b/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
index c904d96..91c4dde 100644
--- a/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
+++ b/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
@@ -472,8 +472,10 @@
         final Rect bounds = activity.getWindowManager().getCurrentWindowMetrics().getBounds();
         assertEquals(activityConfigPortrait.windowConfiguration.getBounds(), bounds);
 
-        // Ensure changes in window configuration bounds are reported
-        assertEquals(numOfConfig + 1, activity.mNumOfConfigChanges);
+        // Ensure that Activity#onConfigurationChanged() not be called because the changes in
+        // WindowConfiguration shouldn't be reported, and we only apply the latest Configuration
+        // update in transaction.
+        assertEquals(numOfConfig, activity.mNumOfConfigChanges);
     }
 
     @Test
diff --git a/core/tests/coretests/src/android/database/sqlite/SQLiteDatabaseTest.java b/core/tests/coretests/src/android/database/sqlite/SQLiteDatabaseTest.java
index fc72f61..4ee987b 100644
--- a/core/tests/coretests/src/android/database/sqlite/SQLiteDatabaseTest.java
+++ b/core/tests/coretests/src/android/database/sqlite/SQLiteDatabaseTest.java
@@ -180,8 +180,8 @@
                     assertFalse(r);
                     s.reset();
                     assertEquals(i + 1, mDatabase.getLastInsertRowId());
-                    assertEquals(1, mDatabase.getLastChangedRowsCount());
-                    assertEquals(i + 2, mDatabase.getTotalChangedRowsCount());
+                    assertEquals(1, mDatabase.getLastChangedRowCount());
+                    assertEquals(i + 2, mDatabase.getTotalChangedRowCount());
                 }
             }
             mDatabase.setTransactionSuccessful();
@@ -205,8 +205,8 @@
                     assertFalse(r);
                     s.reset();
                     assertEquals(size + i + 1, mDatabase.getLastInsertRowId());
-                    assertEquals(1, mDatabase.getLastChangedRowsCount());
-                    assertEquals(size + i + 2, mDatabase.getTotalChangedRowsCount());
+                    assertEquals(1, mDatabase.getLastChangedRowCount());
+                    assertEquals(size + i + 2, mDatabase.getTotalChangedRowCount());
                 }
             }
             mDatabase.setTransactionSuccessful();
@@ -214,4 +214,21 @@
             mDatabase.endTransaction();
         }
     }
+
+    @Test
+    public void testAutomaticCountersOutsideTransactions() {
+        try {
+            mDatabase.getLastChangedRowCount();
+            fail("getLastChangedRowCount() succeeded outside a transaction");
+        } catch (IllegalStateException e) {
+            // This exception is expected.
+        }
+
+        try {
+            mDatabase.getTotalChangedRowCount();
+            fail("getTotalChangedRowCount() succeeded outside a transaction");
+        } catch (IllegalStateException e) {
+            // This exception is expected.
+        }
+    }
 }
diff --git a/core/tests/coretests/src/android/os/OWNERS b/core/tests/coretests/src/android/os/OWNERS
index f2d6ff8..8b333f3 100644
--- a/core/tests/coretests/src/android/os/OWNERS
+++ b/core/tests/coretests/src/android/os/OWNERS
@@ -5,4 +5,7 @@
 per-file *Vibrat*.java = file:/services/core/java/com/android/server/vibrator/OWNERS
 
 # Power
-per-file PowerManager*.java = michaelwr@google.com, santoscordon@google.com
\ No newline at end of file
+per-file PowerManager*.java = michaelwr@google.com, santoscordon@google.com
+
+# PerformanceHintManager
+per-file PerformanceHintManagerTest.java = file:/ADPF_OWNERS
diff --git a/core/tests/coretests/src/android/os/PerformanceHintManagerTest.java b/core/tests/coretests/src/android/os/PerformanceHintManagerTest.java
index 2c03fdc..20ba427 100644
--- a/core/tests/coretests/src/android/os/PerformanceHintManagerTest.java
+++ b/core/tests/coretests/src/android/os/PerformanceHintManagerTest.java
@@ -69,6 +69,24 @@
     }
 
     @Test
+    public void testCreateHintSession_noTids() {
+        assertThrows(NullPointerException.class, () -> {
+            mPerformanceHintManager.createHintSession(
+                    null, DEFAULT_TARGET_NS);
+        });
+        assertThrows(IllegalArgumentException.class, () -> {
+            mPerformanceHintManager.createHintSession(
+                    new int[]{}, DEFAULT_TARGET_NS);
+        });
+    }
+
+    @Test
+    public void testCreateHintSession_invalidTids() {
+        assertNull(mPerformanceHintManager.createHintSession(
+                new int[]{-1}, DEFAULT_TARGET_NS));
+    }
+
+    @Test
     public void testGetPreferredUpdateRateNanos() {
         if (createSession() != null) {
             assertTrue(mPerformanceHintManager.getPreferredUpdateRateNanos() > 0);
@@ -155,4 +173,13 @@
             session.setThreads(new int[]{-1});
         });
     }
+
+    @Test
+    public void testSetPreferPowerEfficiency() {
+        Session s = createSession();
+        assumeNotNull(s);
+        s.setPreferPowerEfficiency(false);
+        s.setPreferPowerEfficiency(true);
+        s.setPreferPowerEfficiency(true);
+    }
 }
diff --git a/core/tests/coretests/src/android/os/health/SystemHealthManagerTest.java b/core/tests/coretests/src/android/os/health/SystemHealthManagerTest.java
index 2232e3a..e1f9523 100644
--- a/core/tests/coretests/src/android/os/health/SystemHealthManagerTest.java
+++ b/core/tests/coretests/src/android/os/health/SystemHealthManagerTest.java
@@ -20,6 +20,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import android.os.ConditionVariable;
 import android.os.PowerMonitor;
 import android.os.PowerMonitorReadings;
 
@@ -29,13 +30,16 @@
 import java.util.List;
 
 public class SystemHealthManagerTest {
+    private List<PowerMonitor> mPowerMonitorInfo;
+    private PowerMonitorReadings mReadings;
+    private RuntimeException mException;
 
     @Test
     public void getPowerMonitors() {
         SystemHealthManager shm = getContext().getSystemService(SystemHealthManager.class);
-        PowerMonitor[] powerMonitorInfo = shm.getSupportedPowerMonitors();
+        List<PowerMonitor> powerMonitorInfo = shm.getSupportedPowerMonitors();
         assertThat(powerMonitorInfo).isNotNull();
-        if (powerMonitorInfo.length == 0) {
+        if (powerMonitorInfo.isEmpty()) {
             // This device does not support PowerStats HAL
             return;
         }
@@ -50,20 +54,73 @@
             }
         }
 
-        List<PowerMonitor> pmis = new ArrayList<>();
+        List<PowerMonitor> selectedMonitors = new ArrayList<>();
         if (consumerMonitor != null) {
-            pmis.add(consumerMonitor);
+            selectedMonitors.add(consumerMonitor);
         }
         if (measurementMonitor != null) {
-            pmis.add(measurementMonitor);
+            selectedMonitors.add(measurementMonitor);
         }
 
-        PowerMonitor[] selectedMonitors = pmis.toArray(new PowerMonitor[0]);
         PowerMonitorReadings readings = shm.getPowerMonitorReadings(selectedMonitors);
 
         for (PowerMonitor monitor : selectedMonitors) {
             assertThat(readings.getConsumedEnergyUws(monitor)).isAtLeast(0);
-            assertThat(readings.getTimestampMs(monitor)).isGreaterThan(0);
+            assertThat(readings.getTimestamp(monitor)).isGreaterThan(0);
+        }
+    }
+
+    @Test
+    public void getPowerMonitorsAsync() {
+        SystemHealthManager shm = getContext().getSystemService(SystemHealthManager.class);
+        ConditionVariable done = new ConditionVariable();
+        shm.getSupportedPowerMonitors(null, pms -> {
+            mPowerMonitorInfo = pms;
+            done.open();
+        });
+        done.block();
+        assertThat(mPowerMonitorInfo).isNotNull();
+        if (mPowerMonitorInfo.isEmpty()) {
+            // This device does not support PowerStats HAL
+            return;
+        }
+
+        PowerMonitor consumerMonitor = null;
+        PowerMonitor measurementMonitor = null;
+        for (PowerMonitor pmi : mPowerMonitorInfo) {
+            if (pmi.type == PowerMonitor.POWER_MONITOR_TYPE_MEASUREMENT) {
+                measurementMonitor = pmi;
+            } else {
+                consumerMonitor = pmi;
+            }
+        }
+
+        List<PowerMonitor> selectedMonitors = new ArrayList<>();
+        if (consumerMonitor != null) {
+            selectedMonitors.add(consumerMonitor);
+        }
+        if (measurementMonitor != null) {
+            selectedMonitors.add(measurementMonitor);
+        }
+
+        done.close();
+        shm.getPowerMonitorReadings(selectedMonitors, null,
+                readings -> {
+                    mReadings = readings;
+                    done.open();
+                },
+                exception -> {
+                    mException = exception;
+                    done.open();
+                }
+        );
+        done.block();
+
+        assertThat(mException).isNull();
+
+        for (PowerMonitor monitor : selectedMonitors) {
+            assertThat(mReadings.getConsumedEnergyUws(monitor)).isAtLeast(0);
+            assertThat(mReadings.getTimestamp(monitor)).isGreaterThan(0);
         }
     }
 }
diff --git a/core/tests/coretests/src/android/security/keystore/OWNERS b/core/tests/coretests/src/android/security/keystore/OWNERS
new file mode 100644
index 0000000..d9e0116
--- /dev/null
+++ b/core/tests/coretests/src/android/security/keystore/OWNERS
@@ -0,0 +1 @@
+include /keystore/OWNERS
diff --git a/core/tests/coretests/src/android/service/controls/ControlProviderServiceTest.java b/core/tests/coretests/src/android/service/controls/ControlProviderServiceTest.java
index 5fe17ee..4d446901 100644
--- a/core/tests/coretests/src/android/service/controls/ControlProviderServiceTest.java
+++ b/core/tests/coretests/src/android/service/controls/ControlProviderServiceTest.java
@@ -21,6 +21,7 @@
 import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -36,6 +37,7 @@
 import android.graphics.drawable.Icon;
 import android.os.Binder;
 import android.os.Bundle;
+import android.os.DeadObjectException;
 import android.os.IBinder;
 import android.os.RemoteException;
 import android.service.controls.actions.CommandAction;
@@ -53,6 +55,7 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
+import org.mockito.ArgumentMatchers;
 import org.mockito.Captor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
@@ -307,6 +310,18 @@
                 intent.getParcelableExtra(ControlsProviderService.EXTRA_CONTROL)));
     }
 
+    @Test
+    public void testOnNextDoesntRethrowDeadObjectException() throws RemoteException {
+        doAnswer(invocation -> {
+            throw new DeadObjectException();
+        }).when(mSubscriber).onNext(ArgumentMatchers.any(), ArgumentMatchers.any());
+        Control control = new Control.StatelessBuilder("TEST_ID", mPendingIntent).build();
+
+        sendControlGetControl(control);
+
+        assertTrue(mControlsProviderService.mSubscription.mIsCancelled);
+    }
+
     /**
      * Sends the control through the publisher in {@code mControlsProviderService}, returning
      * the control obtained by the subscriber
@@ -359,6 +374,7 @@
         }
 
         private List<Control> mControls;
+        private FakeSubscription mSubscription;
 
         public void setControls(List<Control> controls) {
             mControls = controls;
@@ -398,17 +414,35 @@
         }
 
         private Subscription createSubscription(Subscriber s, List<Control> controls) {
-            return new Subscription() {
-                public void request(long n) {
-                    int i = 0;
-                    for (Control c : mControls) {
-                        if (i++ < n) s.onNext(c);
-                        else break;
-                    }
-                    s.onComplete();
-                }
-                public void cancel() {}
-            };
+            FakeSubscription subscription = new FakeSubscription(s, controls);
+            mSubscription = subscription;
+            return subscription;
+        }
+    }
+
+    private static final class FakeSubscription implements Subscription {
+
+        private final Subscriber mSubscriber;
+        private final List<Control> mControls;
+
+        private boolean mIsCancelled = false;
+
+        FakeSubscription(Subscriber s, List<Control> controls) {
+            mSubscriber = s;
+            mControls = controls;
+        }
+
+        public void request(long n) {
+            int i = 0;
+            for (Control c : mControls) {
+                if (i++ < n) mSubscriber.onNext(c);
+                else break;
+            }
+            mSubscriber.onComplete();
+        }
+
+        public void cancel() {
+            mIsCancelled = true;
         }
     }
 }
diff --git a/core/tests/coretests/src/android/view/ViewGroupGetChildLocalHitRegionTest.java b/core/tests/coretests/src/android/view/ViewGroupGetChildLocalHitRegionTest.java
new file mode 100644
index 0000000..60a0a2a
--- /dev/null
+++ b/core/tests/coretests/src/android/view/ViewGroupGetChildLocalHitRegionTest.java
@@ -0,0 +1,216 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view;
+
+import static com.google.common.truth.Truth.assertThat;
+
+
+import android.graphics.Matrix;
+import android.graphics.Region;
+import android.platform.test.annotations.Presubmit;
+import android.widget.LinearLayout;
+
+import androidx.test.ext.junit.rules.ActivityScenarioRule;
+import androidx.test.filters.SmallTest;
+
+import com.android.frameworks.coretests.R;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+/**
+ * Test basic functions of ViewGroup.
+ *
+ * Build/Install/Run:
+ *     atest FrameworksCoreTests:ViewGroupTest
+ */
+@Presubmit
+@SmallTest
+public class ViewGroupGetChildLocalHitRegionTest {
+    @Rule
+    public ActivityScenarioRule<ViewGroupTestActivity> mScenarioRule =
+            new ActivityScenarioRule<>(ViewGroupTestActivity.class);
+
+    private LinearLayout mRoot;
+    private final int[] mRootLocation = new int[2];
+
+    @Before
+    public void setup() {
+        mScenarioRule.getScenario().onActivity(activity -> {
+            mRoot = activity.findViewById(R.id.linear_layout);
+            mRoot.getLocationInWindow(mRootLocation);
+        });
+    }
+
+    @Test
+    public void testGetChildLocalHitRegion() {
+        assertGetChildLocalHitRegion(R.id.view);
+    }
+
+    @Test
+    public void testGetChildLocalHitRegion_withScale() {
+        assertGetChildLocalHitRegion(R.id.view_scale);
+    }
+
+    @Test
+    public void testGetChildLocalHitRegion_withTranslate() {
+        assertGetChildLocalHitRegion(R.id.view_translate);
+    }
+
+    @Test
+    public void testGetChildLocalHitRegion_overlap_noMotionEvent() {
+        assertGetChildLocalHitRegion(R.id.view_overlap_bottom);
+    }
+    @Test
+    public void testGetChildLocalHitRegion_overlap_withMotionEvent() {
+        // In this case, view_cover_bottom is partially covered by the view_cover_top.
+        // The returned region is the bounds of the bottom view subtract the bounds of the top view.
+        assertGetChildLocalHitRegion(R.id.view_overlap_top, R.id.view_overlap_bottom);
+    }
+
+    @Test
+    public void testGetChildLocalHitRegion_cover_withMotionEvent() {
+        // In this case, view_cover_bottom is completely covered by the view_cover_top.
+        // The returned region is expected to be empty.
+        assertGetChildLocalHitRegionEmpty(R.id.view_cover_top, R.id.view_cover_bottom);
+    }
+
+    private void injectMotionEvent(View view, boolean isHover) {
+        int[] location = new int[2];
+        view.getLocationInWindow(location);
+
+        float x = location[0] + view.getWidth() / 2f;
+        float y = location[1] + view.getHeight() / 2f;
+
+        int action = isHover ? MotionEvent.ACTION_HOVER_ENTER : MotionEvent.ACTION_DOWN;
+        MotionEvent motionEvent = MotionEvent.obtain(/* downtime= */ 0, /* eventTime= */ 0, action,
+                x, y, /* pressure= */ 0, /* size= */ 0, /* metaState= */ 0,
+                /* xPrecision= */ 1, /* yPrecision= */ 1, /* deviceId= */0, /* edgeFlags= */0);
+
+        View rootView = view.getRootView();
+        rootView.dispatchPointerEvent(motionEvent);
+    }
+
+    private void assertGetChildLocalHitRegion(int viewId) {
+        assertGetChildLocalHitRegion(viewId, /* isHover= */ true);
+        assertGetChildLocalHitRegion(viewId, /* isHover= */ false);
+    }
+
+    /**
+     * Assert ViewParent#getChildLocalHitRegion for a single view.
+     * @param viewId the viewId of the tested view.
+     * @param isHover if true, check the hit region of the hover events. Otherwise, check the hit
+     *                region of the touch events.
+     */
+    private void assertGetChildLocalHitRegion(int viewId, boolean isHover) {
+        mScenarioRule.getScenario().onActivity(activity -> {
+            View view = activity.findViewById(viewId);
+
+            Matrix actualMatrix = new Matrix();
+            Region actualRegion = new Region(0, 0, view.getWidth(), view.getHeight());
+            boolean actualNotEmpty = view.getParent()
+                    .getChildLocalHitRegion(view, actualRegion, actualMatrix, isHover);
+
+            int[] windowLocation = new int[2];
+            view.getLocationInWindow(windowLocation);
+            Matrix expectMatrix = new Matrix();
+            expectMatrix.preScale(1 / view.getScaleX(), 1 / view.getScaleY());
+            expectMatrix.preTranslate(-windowLocation[0], -windowLocation[1]);
+
+            Region expectRegion = new Region(0, 0, view.getWidth(), view.getHeight());
+
+            assertThat(actualNotEmpty).isTrue();
+            assertThat(actualMatrix).isEqualTo(expectMatrix);
+            assertThat(actualRegion).isEqualTo(expectRegion);
+        });
+    }
+
+    private void assertGetChildLocalHitRegion(int viewIdTop, int viewIdBottom) {
+        assertGetChildLocalHitRegion(viewIdTop, viewIdBottom, /* isHover= */ true);
+        assertGetChildLocalHitRegion(viewIdTop, viewIdBottom, /* isHover= */ false);
+    }
+
+    /**
+     * Assert ViewParent#getChildLocalHitRegion of a view that is covered by another view. It will
+     * inject {@link MotionEvent}s to the view on top first and then get the hit region of the
+     * bottom view.
+     *
+     * @param viewIdTop the view id of the test view on top.
+     * @param viewIdBottom the view id of the test view at the bottom.
+     * @param isHover if true, check the hit region of the hover events. Otherwise, check the hit
+     *                region of the touch events.
+     */
+    private void assertGetChildLocalHitRegion(int viewIdTop, int viewIdBottom, boolean isHover) {
+        mScenarioRule.getScenario().onActivity(activity -> {
+            View viewTop = activity.findViewById(viewIdTop);
+            View viewBottom = activity.findViewById(viewIdBottom);
+
+            injectMotionEvent(viewTop, isHover);
+
+            Matrix actualMatrix = new Matrix();
+            Region actualRegion = new Region(0, 0, viewBottom.getWidth(), viewBottom.getHeight());
+            boolean actualNotEmpty = viewBottom.getParent()
+                    .getChildLocalHitRegion(viewBottom, actualRegion, actualMatrix, isHover);
+
+            int[] windowLocation = new int[2];
+            viewBottom.getLocationInWindow(windowLocation);
+            Matrix expectMatrix = new Matrix();
+            expectMatrix.preTranslate(-windowLocation[0], -windowLocation[1]);
+
+            Region expectRegion = new Region(0, 0, viewBottom.getWidth(), viewBottom.getHeight());
+            expectRegion.op(0, 0, viewTop.getWidth(), viewTop.getHeight(), Region.Op.DIFFERENCE);
+
+            assertThat(actualNotEmpty).isTrue();
+            assertThat(actualMatrix).isEqualTo(expectMatrix);
+            assertThat(actualRegion).isEqualTo(expectRegion);
+        });
+    }
+
+    private void assertGetChildLocalHitRegionEmpty(int viewIdTop, int viewIdBottom) {
+        assertGetChildLocalHitRegionEmpty(viewIdTop, viewIdBottom, /* isHover= */ true);
+        assertGetChildLocalHitRegionEmpty(viewIdTop, viewIdBottom, /* isHover= */ false);
+    }
+
+    /**
+     * Assert ViewParent#getChildLocalHitRegion returns an empty region for a view that is
+     * completely covered by another view. It will inject {@link MotionEvent}s to the view on top
+     * first and then get the hit region of the
+     * bottom view.
+     *
+     * @param viewIdTop the view id of the test view on top.
+     * @param viewIdBottom the view id of the test view at the bottom.
+     * @param isHover if true, check the hit region of the hover events. Otherwise, check the hit
+     *                region of the touch events.
+     */
+    private void assertGetChildLocalHitRegionEmpty(int viewIdTop, int viewIdBottom,
+            boolean isHover) {
+        mScenarioRule.getScenario().onActivity(activity -> {
+            View viewTop = activity.findViewById(viewIdTop);
+            View viewBottom = activity.findViewById(viewIdBottom);
+
+            injectMotionEvent(viewTop, isHover);
+
+            Region actualRegion = new Region(0, 0, viewBottom.getWidth(), viewBottom.getHeight());
+            boolean actualNotEmpty = viewBottom.getParent()
+                    .getChildLocalHitRegion(viewBottom, actualRegion, new Matrix(), isHover);
+
+            assertThat(actualNotEmpty).isFalse();
+            assertThat(actualRegion.isEmpty()).isTrue();
+        });
+    }
+}
diff --git a/core/tests/coretests/src/android/view/ViewGroupTestActivity.java b/core/tests/coretests/src/android/view/ViewGroupTestActivity.java
new file mode 100644
index 0000000..b94bda5
--- /dev/null
+++ b/core/tests/coretests/src/android/view/ViewGroupTestActivity.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view;
+
+import android.annotation.Nullable;
+import android.app.Activity;
+import android.os.Bundle;
+
+import com.android.frameworks.coretests.R;
+
+public class ViewGroupTestActivity extends Activity {
+    @Override
+    protected void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.viewgroup_test);
+    }
+}
diff --git a/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java b/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java
index 8028b14..f1eef75 100644
--- a/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java
+++ b/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java
@@ -221,8 +221,10 @@
 
     @Test
     public void onTouchEvent_startHandwriting_inputConnectionBuilt_stylusMoveInExtendedHWArea() {
+        // The stylus down point is between mTestView1 and  mTestView2, but it is within the
+        // extended handwriting area of both views. It is closer to mTestView1.
         final int x1 = sHwArea1.right + HW_BOUNDS_OFFSETS_RIGHT_PX / 2;
-        final int y1 = sHwArea1.bottom + HW_BOUNDS_OFFSETS_BOTTOM_PX / 2;
+        final int y1 = sHwArea1.bottom + (sHwArea2.top - sHwArea1.bottom) / 3;
         MotionEvent stylusEvent1 = createStylusEvent(ACTION_DOWN, x1, y1, 0);
         mHandwritingInitiator.onTouchEvent(stylusEvent1);
 
@@ -231,10 +233,14 @@
         MotionEvent stylusEvent2 = createStylusEvent(ACTION_MOVE, x2, y2, 0);
         mHandwritingInitiator.onTouchEvent(stylusEvent2);
 
-        // InputConnection is created after stylus movement.
-        mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+        // First create InputConnection for mTestView2 and verify that handwriting is not started.
+        mHandwritingInitiator.onInputConnectionCreated(mTestView2);
+        verify(mHandwritingInitiator, never()).startHandwriting(mTestView2);
 
-        verify(mHandwritingInitiator, times(1)).startHandwriting(mTestView1);
+        // Next create InputConnection for mTextView1. Handwriting is started for this view since
+        // the stylus down point is closest to this view.
+        mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+        verify(mHandwritingInitiator).startHandwriting(mTestView1);
     }
 
     @Test
diff --git a/core/tests/coretests/src/android/view/stylus/HandwritingTestUtil.java b/core/tests/coretests/src/android/view/stylus/HandwritingTestUtil.java
index 388a996..b4c72ca 100644
--- a/core/tests/coretests/src/android/view/stylus/HandwritingTestUtil.java
+++ b/core/tests/coretests/src/android/view/stylus/HandwritingTestUtil.java
@@ -21,7 +21,9 @@
 
 import android.app.Instrumentation;
 import android.content.Context;
+import android.graphics.Matrix;
 import android.graphics.Rect;
+import android.graphics.Region;
 import android.view.View;
 import android.view.ViewGroup;
 
@@ -45,7 +47,7 @@
             float handwritingBoundsOffsetRight, float handwritingBoundsOffsetBottom) {
         final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
         final Context context = instrumentation.getTargetContext();
-        // mock a parent so that HandwritingInitiator can get
+        // mock a parent so that HandwritingInitiator can get visible rect and hit region.
         final ViewGroup parent = new ViewGroup(context) {
             @Override
             protected void onLayout(boolean changed, int l, int t, int r, int b) {
@@ -56,6 +58,14 @@
                 r.set(handwritingArea);
                 return true;
             }
+
+            @Override
+            public boolean getChildLocalHitRegion(View child, Region region, Matrix matrix,
+                    boolean isHover) {
+                matrix.reset();
+                region.set(handwritingArea);
+                return true;
+            }
         };
 
         View view = spy(new View(context));
diff --git a/core/tests/coretests/src/android/widget/HorizontalScrollViewActivity.java b/core/tests/coretests/src/android/widget/HorizontalScrollViewActivity.java
new file mode 100644
index 0000000..2101354
--- /dev/null
+++ b/core/tests/coretests/src/android/widget/HorizontalScrollViewActivity.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.widget;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+import com.android.frameworks.coretests.R;
+
+/**
+ * An activity for testing the TextView widget.
+ */
+public class HorizontalScrollViewActivity extends Activity {
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_horizontal_scroll_view);
+    }
+}
diff --git a/core/tests/coretests/src/android/widget/HorizontalScrollViewFunctionalTest.java b/core/tests/coretests/src/android/widget/HorizontalScrollViewFunctionalTest.java
new file mode 100644
index 0000000..86f26e5
--- /dev/null
+++ b/core/tests/coretests/src/android/widget/HorizontalScrollViewFunctionalTest.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.widget;
+
+import static org.junit.Assert.assertEquals;
+
+import android.platform.test.annotations.Presubmit;
+import android.util.PollingCheck;
+
+import androidx.test.filters.MediumTest;
+import androidx.test.rule.ActivityTestRule;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.frameworks.coretests.R;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+@MediumTest
+@Presubmit
+public class HorizontalScrollViewFunctionalTest {
+    private HorizontalScrollViewActivity mActivity;
+    private HorizontalScrollView mHorizontalScrollView;
+    @Rule
+    public ActivityTestRule<HorizontalScrollViewActivity> mActivityRule = new ActivityTestRule<>(
+            HorizontalScrollViewActivity.class);
+
+    @Before
+    public void setUp() throws Exception {
+        mActivity = mActivityRule.getActivity();
+        mHorizontalScrollView = mActivity.findViewById(R.id.horizontal_scroll_view);
+    }
+
+    @Test
+    public void testScrollAfterFlingTop() {
+        mHorizontalScrollView.scrollTo(100, 0);
+        mHorizontalScrollView.fling(-10000);
+        PollingCheck.waitFor(() -> mHorizontalScrollView.mEdgeGlowLeft.getDistance() > 0);
+        PollingCheck.waitFor(() -> mHorizontalScrollView.mEdgeGlowLeft.getDistance() == 0f);
+        assertEquals(0, mHorizontalScrollView.getScrollX());
+    }
+
+    @Test
+    public void testScrollAfterFlingBottom() {
+        int childWidth = mHorizontalScrollView.getChildAt(0).getWidth();
+        int maxScroll = childWidth - mHorizontalScrollView.getWidth();
+        mHorizontalScrollView.scrollTo(maxScroll - 100, 0);
+        mHorizontalScrollView.fling(10000);
+        PollingCheck.waitFor(() -> mHorizontalScrollView.mEdgeGlowRight.getDistance() > 0);
+        PollingCheck.waitFor(() -> mHorizontalScrollView.mEdgeGlowRight.getDistance() == 0f);
+        assertEquals(maxScroll, mHorizontalScrollView.getScrollX());
+    }
+}
+
diff --git a/core/tests/coretests/src/android/widget/ScrollViewActivity.java b/core/tests/coretests/src/android/widget/ScrollViewActivity.java
new file mode 100644
index 0000000..899d631
--- /dev/null
+++ b/core/tests/coretests/src/android/widget/ScrollViewActivity.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.widget;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+import com.android.frameworks.coretests.R;
+
+/**
+ * An activity for testing the TextView widget.
+ */
+public class ScrollViewActivity extends Activity {
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_scroll_view);
+    }
+}
diff --git a/core/tests/coretests/src/android/widget/ScrollViewFunctionalTest.java b/core/tests/coretests/src/android/widget/ScrollViewFunctionalTest.java
new file mode 100644
index 0000000..a49bb6a
--- /dev/null
+++ b/core/tests/coretests/src/android/widget/ScrollViewFunctionalTest.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.widget;
+
+import static org.junit.Assert.assertEquals;
+
+import android.platform.test.annotations.Presubmit;
+import android.util.PollingCheck;
+
+import androidx.test.filters.MediumTest;
+import androidx.test.rule.ActivityTestRule;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.frameworks.coretests.R;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+@MediumTest
+@Presubmit
+public class ScrollViewFunctionalTest {
+    private ScrollViewActivity mActivity;
+    private ScrollView mScrollView;
+    @Rule
+    public ActivityTestRule<ScrollViewActivity> mActivityRule = new ActivityTestRule<>(
+            ScrollViewActivity.class);
+
+    @Before
+    public void setUp() throws Exception {
+        mActivity = mActivityRule.getActivity();
+        mScrollView = mActivity.findViewById(R.id.scroll_view);
+    }
+
+    @Test
+    public void testScrollAfterFlingTop() {
+        mScrollView.scrollTo(0, 100);
+        mScrollView.fling(-10000);
+        PollingCheck.waitFor(() -> mScrollView.mEdgeGlowTop.getDistance() > 0);
+        PollingCheck.waitFor(() -> mScrollView.mEdgeGlowTop.getDistance() == 0f);
+        assertEquals(0, mScrollView.getScrollY());
+    }
+
+    @Test
+    public void testScrollAfterFlingBottom() {
+        int childHeight = mScrollView.getChildAt(0).getHeight();
+        int maxScroll = childHeight - mScrollView.getHeight();
+        mScrollView.scrollTo(0, maxScroll - 100);
+        mScrollView.fling(10000);
+        PollingCheck.waitFor(() -> mScrollView.mEdgeGlowBottom.getDistance() > 0);
+        PollingCheck.waitFor(() -> mScrollView.mEdgeGlowBottom.getDistance() == 0f);
+        assertEquals(maxScroll, mScrollView.getScrollY());
+    }
+}
+
diff --git a/core/tests/coretests/src/android/window/WindowTokenClientControllerTest.java b/core/tests/coretests/src/android/window/WindowTokenClientControllerTest.java
index 7bd6f05..a21c917 100644
--- a/core/tests/coretests/src/android/window/WindowTokenClientControllerTest.java
+++ b/core/tests/coretests/src/android/window/WindowTokenClientControllerTest.java
@@ -58,8 +58,6 @@
     @Mock
     private WindowTokenClient mWindowTokenClient;
     @Mock
-    private IBinder mClientToken;
-    @Mock
     private IBinder mWindowToken;
     // Can't mock final class.
     private final Configuration mConfiguration = new Configuration();
@@ -70,7 +68,6 @@
     @Before
     public void setup() {
         MockitoAnnotations.initMocks(this);
-        doReturn(mClientToken).when(mWindowTokenClient).asBinder();
         mController = spy(WindowTokenClientController.createInstanceForTesting());
         doReturn(mWindowManagerService).when(mController).getWindowManagerService();
         mWindowContextInfo = new WindowContextInfo(mConfiguration, DEFAULT_DISPLAY);
@@ -205,7 +202,7 @@
                 .attachWindowContextToWindowToken(any(), any(), any());
 
         // No invoke if not attached.
-        mController.onWindowContextInfoChanged(mClientToken, mWindowContextInfo);
+        mController.onWindowContextInfoChanged(mWindowTokenClient, mWindowContextInfo);
 
         verify(mWindowTokenClient, never()).onConfigurationChanged(any(), anyInt());
 
@@ -216,7 +213,7 @@
 
         // Invoke onConfigurationChanged when onWindowContextInfoChanged
         mController.onWindowContextInfoChanged(
-                mClientToken, new WindowContextInfo(mConfiguration, DEFAULT_DISPLAY + 1));
+                mWindowTokenClient, new WindowContextInfo(mConfiguration, DEFAULT_DISPLAY + 1));
 
         verify(mWindowTokenClient).onConfigurationChanged(mConfiguration, DEFAULT_DISPLAY + 1);
     }
@@ -227,7 +224,7 @@
                 .attachWindowContextToWindowToken(any(), any(), any());
 
         // No invoke if not attached.
-        mController.onWindowContextWindowRemoved(mClientToken);
+        mController.onWindowContextWindowRemoved(mWindowTokenClient);
 
         verify(mWindowTokenClient, never()).onWindowTokenRemoved();
 
@@ -237,7 +234,7 @@
         verify(mWindowTokenClient, never()).onWindowTokenRemoved();
 
         // Invoke onWindowTokenRemoved when onWindowContextWindowRemoved
-        mController.onWindowContextWindowRemoved(mClientToken);
+        mController.onWindowContextWindowRemoved(mWindowTokenClient);
 
         verify(mWindowTokenClient).onWindowTokenRemoved();
     }
diff --git a/core/tests/coretests/src/com/android/internal/accessibility/AccessibilityShortcutControllerTest.java b/core/tests/coretests/src/com/android/internal/accessibility/AccessibilityShortcutControllerTest.java
index 2de1230..cd5ec85 100644
--- a/core/tests/coretests/src/com/android/internal/accessibility/AccessibilityShortcutControllerTest.java
+++ b/core/tests/coretests/src/com/android/internal/accessibility/AccessibilityShortcutControllerTest.java
@@ -27,9 +27,7 @@
 import static com.android.internal.accessibility.AccessibilityShortcutController.ONE_HANDED_COMPONENT_NAME;
 import static com.android.internal.accessibility.AccessibilityShortcutController.REDUCE_BRIGHT_COLORS_COMPONENT_NAME;
 
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
 
 import static org.junit.Assert.fail;
 import static org.mockito.AdditionalMatchers.aryEq;
@@ -68,7 +66,6 @@
 import android.speech.tts.TextToSpeech;
 import android.speech.tts.Voice;
 import android.test.mock.MockContentResolver;
-import android.text.TextUtils;
 import android.view.Window;
 import android.view.WindowManager;
 import android.view.accessibility.AccessibilityManager;
@@ -76,7 +73,7 @@
 import android.widget.Toast;
 
 import androidx.test.InstrumentationRegistry;
-import androidx.test.runner.AndroidJUnit4;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
 
 import com.android.internal.R;
 import com.android.internal.accessibility.AccessibilityShortcutController.FrameworkObjectProvider;
@@ -232,7 +229,7 @@
             throws Exception {
         configureNoShortcutService();
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
-        assertFalse(getController().isAccessibilityShortcutAvailable(false));
+        assertThat(getController().isAccessibilityShortcutAvailable(false)).isFalse();
     }
 
     @Test
@@ -240,7 +237,7 @@
             throws Exception {
         configureValidShortcutService();
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
-        assertTrue(getController().isAccessibilityShortcutAvailable(false));
+        assertThat(getController().isAccessibilityShortcutAvailable(false)).isTrue();
     }
 
     @Test
@@ -248,7 +245,7 @@
             throws Exception {
         configureValidShortcutService();
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
-        assertFalse(getController().isAccessibilityShortcutAvailable(true));
+        assertThat(getController().isAccessibilityShortcutAvailable(true)).isFalse();
     }
 
     @Test
@@ -256,7 +253,7 @@
             throws Exception {
         configureValidShortcutService();
         configureShortcutEnabled(ENABLED_INCLUDING_LOCK_SCREEN);
-        assertTrue(getController().isAccessibilityShortcutAvailable(true));
+        assertThat(getController().isAccessibilityShortcutAvailable(true)).isTrue();
     }
 
     @Test
@@ -267,10 +264,14 @@
         configureShortcutEnabled(ENABLED_INCLUDING_LOCK_SCREEN);
         Settings.Secure.putString(
                 mContentResolver, ACCESSIBILITY_SHORTCUT_ON_LOCK_SCREEN, null);
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 0);
-        assertFalse(getController().isAccessibilityShortcutAvailable(true));
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 1);
-        assertTrue(getController().isAccessibilityShortcutAvailable(true));
+        Settings.Secure.putInt(
+                mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
+        assertThat(getController().isAccessibilityShortcutAvailable(true)).isFalse();
+        Settings.Secure.putInt(
+                mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.SHOWN);
+        assertThat(getController().isAccessibilityShortcutAvailable(true)).isTrue();
     }
 
     @Test
@@ -281,7 +282,9 @@
         AccessibilityShortcutController accessibilityShortcutController = getController();
         configureNoShortcutService();
         accessibilityShortcutController.onSettingsChanged();
-        assertFalse(accessibilityShortcutController.isAccessibilityShortcutAvailable(false));
+        assertThat(
+                accessibilityShortcutController.isAccessibilityShortcutAvailable(false)
+        ).isFalse();
     }
 
     @Test
@@ -292,7 +295,9 @@
         AccessibilityShortcutController accessibilityShortcutController = getController();
         configureValidShortcutService();
         accessibilityShortcutController.onSettingsChanged();
-        assertTrue(accessibilityShortcutController.isAccessibilityShortcutAvailable(false));
+        assertThat(
+                accessibilityShortcutController.isAccessibilityShortcutAvailable(false)
+        ).isTrue();
     }
 
     @Test
@@ -302,7 +307,9 @@
         AccessibilityShortcutController accessibilityShortcutController = getController();
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
         accessibilityShortcutController.onSettingsChanged();
-        assertTrue(accessibilityShortcutController.isAccessibilityShortcutAvailable(false));
+        assertThat(
+                accessibilityShortcutController.isAccessibilityShortcutAvailable(false)
+        ).isTrue();
     }
 
     @Test
@@ -313,7 +320,9 @@
         AccessibilityShortcutController accessibilityShortcutController = getController();
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
         accessibilityShortcutController.onSettingsChanged();
-        assertFalse(accessibilityShortcutController.isAccessibilityShortcutAvailable(true));
+        assertThat(
+                accessibilityShortcutController.isAccessibilityShortcutAvailable(true)
+        ).isFalse();
     }
 
     @Test
@@ -324,7 +333,9 @@
         AccessibilityShortcutController accessibilityShortcutController = getController();
         configureShortcutEnabled(ENABLED_INCLUDING_LOCK_SCREEN);
         accessibilityShortcutController.onSettingsChanged();
-        assertTrue(accessibilityShortcutController.isAccessibilityShortcutAvailable(true));
+        assertThat(
+                accessibilityShortcutController.isAccessibilityShortcutAvailable(true)
+        ).isTrue();
     }
 
     @Test
@@ -341,11 +352,15 @@
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
         configureValidShortcutService();
         AccessibilityShortcutController accessibilityShortcutController = getController();
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 0);
+        Settings.Secure.putInt(
+                mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
         accessibilityShortcutController.performAccessibilityShortcut();
 
-        assertEquals(1, Settings.Secure.getInt(
-                mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 0));
+        assertThat(Settings.Secure.getInt(
+                mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN)).isEqualTo(
+                AccessibilityShortcutController.DialogStatus.SHOWN);
         verify(mResources).getString(
                 R.string.accessibility_shortcut_single_service_warning_title, PACKAGE_NAME_STRING);
         verify(mAlertDialog).show();
@@ -357,11 +372,12 @@
 
     @Test
     public void testOnAccessibilityShortcut_withDialogShowing_callsServer()
-        throws Exception {
+            throws Exception {
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
         configureValidShortcutService();
         AccessibilityShortcutController accessibilityShortcutController = getController();
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 0);
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
         accessibilityShortcutController.performAccessibilityShortcut();
         accessibilityShortcutController.performAccessibilityShortcut();
         verify(mToast).show();
@@ -374,11 +390,12 @@
 
     @Test
     public void testOnAccessibilityShortcut_ifCanceledFirstTime_showsWarningDialog()
-        throws Exception {
+            throws Exception {
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
         configureValidShortcutService();
         AccessibilityShortcutController accessibilityShortcutController = getController();
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 0);
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
         accessibilityShortcutController.performAccessibilityShortcut();
         ArgumentCaptor<AlertDialog.OnCancelListener> cancelListenerCaptor =
                 ArgumentCaptor.forClass(AlertDialog.OnCancelListener.class);
@@ -394,49 +411,98 @@
     public void testClickingDisableButtonInDialog_shouldClearShortcutId() throws Exception {
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
         configureValidShortcutService();
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 0);
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
         getController().performAccessibilityShortcut();
 
         ArgumentCaptor<DialogInterface.OnClickListener> captor =
                 ArgumentCaptor.forClass(DialogInterface.OnClickListener.class);
         verify(mAlertDialogBuilder).setPositiveButton(eq(R.string.accessibility_shortcut_off),
                 captor.capture());
-        // Call the button callback, if one exists
-        if (captor.getValue() != null) {
-            captor.getValue().onClick(null, 0);
-        }
-        assertTrue(TextUtils.isEmpty(
-                Settings.Secure.getString(mContentResolver, ACCESSIBILITY_SHORTCUT_TARGET_SERVICE)));
-        assertEquals(0, Settings.Secure.getInt(
-                mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN));
+        captor.getValue().onClick(null, DialogInterface.BUTTON_POSITIVE);
+
+        assertThat(
+                Settings.Secure.getString(mContentResolver, ACCESSIBILITY_SHORTCUT_TARGET_SERVICE)
+        ).isEmpty();
+        assertThat(Settings.Secure.getInt(
+                mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN)).isEqualTo(
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
     }
 
     @Test
     public void testClickingTurnOnButtonInDialog_shouldLeaveShortcutReady() throws Exception {
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
         configureValidShortcutService();
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 0);
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
         getController().performAccessibilityShortcut();
 
         ArgumentCaptor<DialogInterface.OnClickListener> captor =
-            ArgumentCaptor.forClass(DialogInterface.OnClickListener.class);
+                ArgumentCaptor.forClass(DialogInterface.OnClickListener.class);
         verify(mAlertDialogBuilder).setNegativeButton(eq(R.string.accessibility_shortcut_on),
                 captor.capture());
-        // Call the button callback, if one exists
-        if (captor.getValue() != null) {
-            captor.getValue().onClick(null, 0);
-        }
-        assertEquals(SERVICE_NAME_STRING,
-                Settings.Secure.getString(mContentResolver, ACCESSIBILITY_SHORTCUT_TARGET_SERVICE));
-        assertEquals(1, Settings.Secure.getInt(
-                mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN));
+        captor.getValue().onClick(null, DialogInterface.BUTTON_NEGATIVE);
+
+        assertThat(
+                Settings.Secure.getString(mContentResolver, ACCESSIBILITY_SHORTCUT_TARGET_SERVICE)
+        ).isEqualTo(SERVICE_NAME_STRING);
+        assertThat(Settings.Secure.getInt(
+                mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN)).isEqualTo(
+                AccessibilityShortcutController.DialogStatus.SHOWN);
+    }
+
+    @Test
+    public void testTurnOnDefaultA11yServiceInDialog_defaultServiceShortcutTurnsOn()
+            throws Exception {
+        configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
+        configureDefaultAccessibilityService();
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
+        getController().performAccessibilityShortcut();
+
+        ArgumentCaptor<DialogInterface.OnClickListener> captor =
+                ArgumentCaptor.forClass(DialogInterface.OnClickListener.class);
+        verify(mAlertDialogBuilder).setNegativeButton(eq(R.string.accessibility_shortcut_on),
+                captor.capture());
+        captor.getValue().onClick(null, DialogInterface.BUTTON_NEGATIVE);
+
+        assertThat(
+                Settings.Secure.getString(mContentResolver,
+                        ACCESSIBILITY_SHORTCUT_TARGET_SERVICE)).isEqualTo(SERVICE_NAME_STRING);
+        assertThat(Settings.Secure.getInt(
+                mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN)).isEqualTo(
+                AccessibilityShortcutController.DialogStatus.SHOWN);
+    }
+
+    @Test
+    public void testTurnOffDefaultA11yServiceInDialog_defaultServiceShortcutTurnsOff()
+            throws Exception {
+        configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
+        configureDefaultAccessibilityService();
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
+        getController().performAccessibilityShortcut();
+
+        ArgumentCaptor<DialogInterface.OnClickListener> captor =
+                ArgumentCaptor.forClass(DialogInterface.OnClickListener.class);
+        verify(mAlertDialogBuilder).setPositiveButton(eq(R.string.accessibility_shortcut_off),
+                captor.capture());
+        captor.getValue().onClick(null, DialogInterface.BUTTON_POSITIVE);
+
+        assertThat(
+                Settings.Secure.getString(mContentResolver,
+                        ACCESSIBILITY_SHORTCUT_TARGET_SERVICE)).isEmpty();
+        assertThat(Settings.Secure.getInt(
+                mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN)).isEqualTo(
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
     }
 
     @Test
     public void testOnAccessibilityShortcut_afterDialogShown_shouldCallServer() throws Exception {
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
         configureValidShortcutService();
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 1);
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.SHOWN);
         getController().performAccessibilityShortcut();
 
         verifyZeroInteractions(mAlertDialogBuilder, mAlertDialog);
@@ -464,10 +530,10 @@
                 frameworkFeatureMap =
                 AccessibilityShortcutController.getFrameworkShortcutFeaturesMap();
 
-        assertTrue(frameworkFeatureMap.containsKey(COLOR_INVERSION_COMPONENT_NAME));
-        assertTrue(frameworkFeatureMap.containsKey(DALTONIZER_COMPONENT_NAME));
-        assertTrue(frameworkFeatureMap.containsKey(REDUCE_BRIGHT_COLORS_COMPONENT_NAME));
-        assertTrue(frameworkFeatureMap.containsKey(ACCESSIBILITY_HEARING_AIDS_COMPONENT_NAME));
+        assertThat(frameworkFeatureMap).containsKey(COLOR_INVERSION_COMPONENT_NAME);
+        assertThat(frameworkFeatureMap).containsKey(DALTONIZER_COMPONENT_NAME);
+        assertThat(frameworkFeatureMap).containsKey(REDUCE_BRIGHT_COLORS_COMPONENT_NAME);
+        assertThat(frameworkFeatureMap).containsKey(ACCESSIBILITY_HEARING_AIDS_COMPONENT_NAME);
     }
 
     @Test
@@ -478,7 +544,7 @@
                 frameworkFeatureMap =
                 AccessibilityShortcutController.getFrameworkShortcutFeaturesMap();
 
-        assertTrue(frameworkFeatureMap.containsKey(ONE_HANDED_COMPONENT_NAME));
+        assertThat(frameworkFeatureMap).containsKey(ONE_HANDED_COMPONENT_NAME);
     }
 
     @Test
@@ -489,7 +555,7 @@
                 frameworkFeatureMap =
                 AccessibilityShortcutController.getFrameworkShortcutFeaturesMap();
 
-        assertFalse(frameworkFeatureMap.containsKey(ONE_HANDED_COMPONENT_NAME));
+        assertThat(frameworkFeatureMap).doesNotContainKey(ONE_HANDED_COMPONENT_NAME);
     }
 
     @Test
@@ -498,7 +564,8 @@
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
         configureValidShortcutService();
         when(mServiceInfo.loadSummary(any())).thenReturn(null);
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 1);
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.SHOWN);
         getController().performAccessibilityShortcut();
         verify(mAccessibilityManagerService).performAccessibilityShortcut(null);
     }
@@ -508,7 +575,8 @@
             throws Exception {
         configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
         configureFirstFrameworkFeature();
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 1);
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.SHOWN);
         getController().performAccessibilityShortcut();
 
         verifyZeroInteractions(mToast);
@@ -523,7 +591,8 @@
         configureApplicationTargetSdkVersion(Build.VERSION_CODES.R);
         configureRequestAccessibilityButton();
         configureEnabledService();
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 1);
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.SHOWN);
         getController().performAccessibilityShortcut();
 
         verifyZeroInteractions(mToast);
@@ -538,7 +607,8 @@
         configureTtsSpokenPromptEnabled();
         configureHandlerCallbackInvocation();
         AccessibilityShortcutController accessibilityShortcutController = getController();
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 0);
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
         accessibilityShortcutController.performAccessibilityShortcut();
 
         verify(mAlertDialog).show();
@@ -563,7 +633,8 @@
         configureTtsSpokenPromptEnabled();
         configureHandlerCallbackInvocation();
         AccessibilityShortcutController accessibilityShortcutController = getController();
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 0);
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
         accessibilityShortcutController.performAccessibilityShortcut();
 
         verify(mAlertDialog).show();
@@ -583,7 +654,8 @@
         configureTtsSpokenPromptEnabled();
         configureHandlerCallbackInvocation();
         AccessibilityShortcutController accessibilityShortcutController = getController();
-        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 0);
+        Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN,
+                AccessibilityShortcutController.DialogStatus.NOT_SHOWN);
         Set<String> features = new HashSet<>();
         features.add(TextToSpeech.Engine.KEY_FEATURE_NOT_INSTALLED);
         doReturn(features, Collections.emptySet()).when(mVoice).getFeatures();
@@ -682,4 +754,13 @@
         accessibilityShortcutController.mFrameworkObjectProvider = mFrameworkObjectProvider;
         return accessibilityShortcutController;
     }
+
+    private void configureDefaultAccessibilityService() throws Exception {
+        when(mAccessibilityManagerService
+                .getAccessibilityShortcutTargets(ACCESSIBILITY_SHORTCUT_KEY))
+                .thenReturn(Collections.singletonList(SERVICE_NAME_STRING));
+
+        when(mResources.getString(R.string.config_defaultAccessibilityService)).thenReturn(
+                SERVICE_NAME_STRING);
+    }
 }
diff --git a/core/tests/coretests/src/com/android/internal/security/VerityUtilsTest.java b/core/tests/coretests/src/com/android/internal/security/VerityUtilsTest.java
index 1513654..a978e3b 100644
--- a/core/tests/coretests/src/com/android/internal/security/VerityUtilsTest.java
+++ b/core/tests/coretests/src/com/android/internal/security/VerityUtilsTest.java
@@ -229,11 +229,12 @@
     @Test
     public void testSignatureGeneratedExternally() throws Exception {
         var context = InstrumentationRegistry.getInstrumentation().getContext();
-        byte[] cert = getClass().getClassLoader().getResourceAsStream("ApkVerityTestCert.der")
+        byte[] cert = getClass().getClassLoader().getResourceAsStream("unit_test.der")
                 .readAllBytes();
         // The signature is generated by:
-        //   fsverity sign <(echo -n fs-verity) fsverity_sig --key=ApkVerityTestKey.pem \
-        //   --cert=ApkVerityTestCert.pem
+        //   openssl pkcs8 -topk8 -nocrypt -in certs/unit_test.pk8 -out certs/unit_test.key.pem
+        //   fsverity sign <(echo -n fs-verity) fsverity_sig --key=certs/unit_test.key.pem \
+        //   --cert=certs/unit_test.x509.pem
         byte[] sig = context.getResources().openRawResource(R.raw.fsverity_sig).readAllBytes();
         // The fs-verity digest is generated by:
         //   fsverity digest --compact <(echo -n fs-verity)
diff --git a/core/tests/packagemonitortests/Android.bp b/core/tests/packagemonitortests/Android.bp
index 453b476..7b5d7df 100644
--- a/core/tests/packagemonitortests/Android.bp
+++ b/core/tests/packagemonitortests/Android.bp
@@ -24,6 +24,9 @@
 android_test {
     name: "FrameworksCorePackageMonitorTests",
     srcs: ["src/**/*.java"],
+    exclude_srcs: [
+        "src/com/android/internal/content/withoutpermission/PackageMonitorPermissionTest.java",
+    ],
     static_libs: [
         "androidx.test.runner",
         "compatibility-device-util-axt",
@@ -39,3 +42,19 @@
         ":TestVisibilityApp",
     ],
 }
+
+android_test {
+    name: "FrameworksCorePackageMonitorWithoutPermissionTests",
+    srcs: ["src/com/android/internal/content/withoutpermission/PackageMonitorPermissionTest.java"],
+    manifest: "AndroidManifestNoPermission.xml",
+    static_libs: [
+        "androidx.test.runner",
+        "compatibility-device-util-axt",
+        "frameworks-base-testutils",
+    ],
+    libs: ["android.test.runner"],
+    platform_apis: true,
+    certificate: "platform",
+    test_suites: ["device-tests"],
+    test_config: "AndroidTestWithoutPermission.xml",
+}
diff --git a/core/tests/packagemonitortests/AndroidManifestNoPermission.xml b/core/tests/packagemonitortests/AndroidManifestNoPermission.xml
new file mode 100644
index 0000000..5d6308a
--- /dev/null
+++ b/core/tests/packagemonitortests/AndroidManifestNoPermission.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2023 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT 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.frameworks.packagemonitor.withoutpermission">
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation
+            android:name="androidx.test.runner.AndroidJUnitRunner"
+            android:targetPackage="com.android.frameworks.packagemonitor.withoutpermission"
+            android:label="Frameworks PackageMonitor Core without Permission Tests" />
+</manifest>
diff --git a/core/tests/packagemonitortests/AndroidTestWithoutPermission.xml b/core/tests/packagemonitortests/AndroidTestWithoutPermission.xml
new file mode 100644
index 0000000..37a6a2f
--- /dev/null
+++ b/core/tests/packagemonitortests/AndroidTestWithoutPermission.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2023 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT 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 Frameworks Core Tests.">
+    <option name="test-suite-tag" value="apct" />
+    <option name="test-suite-tag" value="apct-instrumentation" />
+
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="FrameworksCorePackageMonitorWithoutPermissionTests.apk" />
+    </target_preparer>
+
+    <option name="test-tag" value="FrameworksCorePackageMonitorWithoutPermissionTests" />
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="com.android.frameworks.packagemonitor.withoutpermission" />
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
+        <option name="hidden-api-checks" value="false"/>
+    </test>
+</configuration>
diff --git a/core/tests/packagemonitortests/src/com/android/internal/content/PackageMonitorVisibilityTest.java b/core/tests/packagemonitortests/src/com/android/internal/content/PackageMonitorVisibilityTest.java
index a310edc..da8e4cc 100644
--- a/core/tests/packagemonitortests/src/com/android/internal/content/PackageMonitorVisibilityTest.java
+++ b/core/tests/packagemonitortests/src/com/android/internal/content/PackageMonitorVisibilityTest.java
@@ -20,9 +20,12 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.junit.Assert.assertThrows;
+
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.os.Handler;
+import android.os.IRemoteCallback;
 import android.os.Looper;
 import android.os.UserHandle;
 
@@ -45,6 +48,25 @@
             TEST_DATA_PATH + "TestVisibilityApp.apk";
     private static final String TEAT_APK_PACKAGE_NAME = "com.example.android.testvisibilityapp";
     private static final int WAIT_CALLBACK_CALLED_IN_SECONDS = 1;
+
+    @Test
+    public void testPackageMonitorCallbackMultipleRegisterThrowsException() throws Exception {
+        Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        final IRemoteCallback callback = new IRemoteCallback.Stub() {
+            @Override
+            public void sendResult(android.os.Bundle bundle) {
+                // do-nothing
+            }
+        };
+        try {
+            context.getPackageManager().registerPackageMonitorCallback(callback, 0);
+            assertThrows(IllegalStateException.class,
+                    () -> context.getPackageManager().registerPackageMonitorCallback(callback, 0));
+        } finally {
+            context.getPackageManager().unregisterPackageMonitorCallback(callback);
+        }
+    }
+
     @Test
     public void testPackageMonitorPackageVisible() throws Exception {
         TestVisibilityPackageMonitor testPackageMonitor = new TestVisibilityPackageMonitor();
diff --git a/core/tests/packagemonitortests/src/com/android/internal/content/withoutpermission/PackageMonitorPermissionTest.java b/core/tests/packagemonitortests/src/com/android/internal/content/withoutpermission/PackageMonitorPermissionTest.java
new file mode 100644
index 0000000..659c0c2
--- /dev/null
+++ b/core/tests/packagemonitortests/src/com/android/internal/content/withoutpermission/PackageMonitorPermissionTest.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.content.withoutpermission;
+
+import static org.junit.Assert.assertThrows;
+
+import android.content.Context;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.UserHandle;
+
+import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.internal.content.PackageMonitor;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * A test to verify PackageMonitor implementation without INTERACT_ACROSS_USERS_FULL permission.
+ */
+@RunWith(AndroidJUnit4.class)
+public class PackageMonitorPermissionTest {
+
+    @Test
+    public void testPackageMonitorNoCrossUserPermission() throws Exception {
+        TestVisibilityPackageMonitor testPackageMonitor = new TestVisibilityPackageMonitor();
+
+        Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        assertThrows(SecurityException.class,
+                () -> testPackageMonitor.register(context, UserHandle.ALL,
+                        new Handler(Looper.getMainLooper())));
+    }
+
+    private static class TestVisibilityPackageMonitor extends PackageMonitor {
+    }
+}
diff --git a/core/tests/vibrator/src/android/os/VibrationEffectTest.java b/core/tests/vibrator/src/android/os/VibrationEffectTest.java
index 8be489e..e875875 100644
--- a/core/tests/vibrator/src/android/os/VibrationEffectTest.java
+++ b/core/tests/vibrator/src/android/os/VibrationEffectTest.java
@@ -41,8 +41,6 @@
 import android.os.vibrator.PrimitiveSegment;
 import android.os.vibrator.StepSegment;
 
-import androidx.test.InstrumentationRegistry;
-
 import com.android.internal.R;
 
 import org.jetbrains.annotations.NotNull;
@@ -838,31 +836,29 @@
 
     @Test
     public void testAreVibrationFeaturesSupported_allSegmentsSupported() {
-        Vibrator vibrator =
-                createVibratorWithCustomInfo(new VibratorInfo.Builder(/* id= */ 1)
-                        .setCapabilities(IVibrator.CAP_AMPLITUDE_CONTROL)
-                        .build());
+        VibratorInfo info = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_AMPLITUDE_CONTROL)
+                .build();
 
         assertTrue(VibrationEffect.createWaveform(
                         /* timings= */ new long[] {1, 2, 3}, /* repeatIndex= */ -1)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(VibrationEffect.createWaveform(
                         /* timings= */ new long[] {1, 2, 3},
                         /* amplitudes= */ new int[] {10, 20, 40},
                         /* repeatIndex= */ 2)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(
                 VibrationEffect.startComposition()
                         .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK))
                         .repeatEffectIndefinitely(TEST_ONE_SHOT)
                         .compose()
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testAreVibrationFeaturesSupported_withUnsupportedSegments() {
-        Vibrator vibrator =
-                createVibratorWithCustomInfo(new VibratorInfo.Builder(/* id= */ 1).build());
+        VibratorInfo info = new VibratorInfo.Builder(/* id= */ 1).build();
 
         assertFalse(
                 VibrationEffect.startComposition()
@@ -872,7 +868,7 @@
                                 /* amplitudes= */ new int[] {10, 20, 40},
                                 /* repeatIndex= */ -1))
                         .compose()
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
     }
 
     @Test
@@ -996,13 +992,4 @@
 
         return context;
     }
-
-    private Vibrator createVibratorWithCustomInfo(VibratorInfo info) {
-        return new SystemVibrator(InstrumentationRegistry.getContext()) {
-            @Override
-            public VibratorInfo getInfo() {
-                return info;
-            }
-        };
-    }
 }
diff --git a/core/tests/vibrator/src/android/os/VibratorInfoTest.java b/core/tests/vibrator/src/android/os/VibratorInfoTest.java
index ff917aa..808c4ec 100644
--- a/core/tests/vibrator/src/android/os/VibratorInfoTest.java
+++ b/core/tests/vibrator/src/android/os/VibratorInfoTest.java
@@ -57,6 +57,17 @@
     }
 
     @Test
+    public void testHasFrequencyControl() {
+        VibratorInfo noCapabilities = new VibratorInfo.Builder(TEST_VIBRATOR_ID).build();
+        assertFalse(noCapabilities.hasFrequencyControl());
+        VibratorInfo composeAndFrequencyControl = new VibratorInfo.Builder(TEST_VIBRATOR_ID)
+                .setCapabilities(
+                        IVibrator.CAP_FREQUENCY_CONTROL | IVibrator.CAP_COMPOSE_PWLE_EFFECTS)
+                .build();
+        assertTrue(composeAndFrequencyControl.hasFrequencyControl());
+    }
+
+    @Test
     public void testHasCapabilities() {
         VibratorInfo info = new VibratorInfo.Builder(TEST_VIBRATOR_ID)
                 .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
@@ -335,4 +346,186 @@
         assertEquals(original, restored);
         assertEquals(original.hashCode(), restored.hashCode());
     }
+
+    @Test
+    public void areVibrationFeaturesSupported_noAmplitudeControl_fractionalAmplitudeUnsupported() {
+        VibratorInfo info = new VibratorInfo.Builder(/* id= */ 1).build();
+
+        // Have at least one fractional amplitude (amplitude not min (0) or max (255) or DEFAULT).
+        assertFalse(info.areVibrationFeaturesSupported(waveformWithAmplitudes(10, 30)));
+        assertFalse(info.areVibrationFeaturesSupported(waveformWithAmplitudes(10, 255)));
+        assertFalse(info.areVibrationFeaturesSupported(
+                VibrationEffect.createOneShot(20, /* amplitude= */ 40)));
+    }
+
+    @Test
+    public void areVibrationFeaturesSupported_noAmplitudeControl_nonFractionalAmplitudeSupported() {
+        VibratorInfo info = new VibratorInfo.Builder(/* id= */ 1).build();
+
+        // All amplitudes are min, max, or default. Requires no amplitude control.
+        assertTrue(info.areVibrationFeaturesSupported(
+                waveformWithAmplitudes(255, 0, VibrationEffect.DEFAULT_AMPLITUDE, 255)));
+        assertTrue(info.areVibrationFeaturesSupported(
+                VibrationEffect.createWaveform(
+                        /* timings= */ new long[] {1, 2, 3}, /* repeatIndex= */ -1)));
+        assertTrue(info.areVibrationFeaturesSupported(
+                VibrationEffect.createOneShot(20, VibrationEffect.DEFAULT_AMPLITUDE)));
+        assertTrue(info.areVibrationFeaturesSupported(
+                VibrationEffect.createOneShot(20, /* amplitude= */ 255)));
+    }
+
+    @Test
+    public void areVibrationFeaturesSupported_withAmplitudeControl_allWaveformsSupported() {
+        VibratorInfo info = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_AMPLITUDE_CONTROL)
+                .build();
+
+        // All forms of amplitudes are valid when amplitude control is available.
+        assertTrue(info.areVibrationFeaturesSupported(
+                waveformWithAmplitudes(255, 0, VibrationEffect.DEFAULT_AMPLITUDE, 255)));
+        assertTrue(info.areVibrationFeaturesSupported(
+                VibrationEffect.createWaveform(
+                        /* timings= */ new long[] {1, 2, 3}, /* repeatIndex= */ -1)));
+        assertTrue(info.areVibrationFeaturesSupported(waveformWithAmplitudes(10, 30, 50)));
+        assertTrue(info.areVibrationFeaturesSupported(
+                waveformWithAmplitudes(7, 255, 0, 0, 60)));
+        assertTrue(info.areVibrationFeaturesSupported(
+                VibrationEffect.createOneShot(20, VibrationEffect.DEFAULT_AMPLITUDE)));
+        assertTrue(info.areVibrationFeaturesSupported(
+                VibrationEffect.createOneShot(20, /* amplitude= */ 255)));
+        assertTrue(info.areVibrationFeaturesSupported(
+                VibrationEffect.createOneShot(20, /* amplitude= */ 40)));
+    }
+
+    @Test
+    public void areVibrationFeaturesSupported_compositionsWithSupportedPrimitivesSupported() {
+        VibratorInfo info = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
+                .build();
+
+        assertTrue(info.areVibrationFeaturesSupported(
+                VibrationEffect.startComposition()
+                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK)
+                        .compose()));
+        assertTrue(info.areVibrationFeaturesSupported(
+                VibrationEffect.startComposition()
+                        .addPrimitive(
+                                VibrationEffect.Composition.PRIMITIVE_CLICK,
+                                /* scale= */ 0.2f,
+                                /* delay= */ 200)
+                        .compose()));
+    }
+
+    @Test
+    public void areVibrationFeaturesSupported_compositionsWithUnupportedPrimitivesUnsupported() {
+        VibratorInfo info = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
+                .build();
+
+        assertFalse(info.areVibrationFeaturesSupported(
+                VibrationEffect.startComposition()
+                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK)
+                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD)
+                        .compose()));
+        assertFalse(info.areVibrationFeaturesSupported(
+                VibrationEffect.startComposition()
+                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_LOW_TICK)
+                        .compose()));
+    }
+
+    @Test
+    public void areVibrationFeaturesSupported_composedEffects_allComponentsSupported() {
+        VibratorInfo info = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS | IVibrator.CAP_AMPLITUDE_CONTROL)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
+                .setSupportedEffects(VibrationEffect.EFFECT_TICK, VibrationEffect.EFFECT_POP)
+                .build();
+
+        assertTrue(info.areVibrationFeaturesSupported(
+                VibrationEffect.startComposition()
+                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK)
+                        .addEffect(VibrationEffect.createWaveform(
+                                /* timings= */ new long[] {1, 2, 3},
+                                /* amplitudes= */ new int[] {10, 20, 255},
+                                /* repeatIndex= */ -1))
+                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK))
+                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_POP))
+                        .compose()));
+
+        info = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD, 10)
+                .setSupportedEffects(VibrationEffect.EFFECT_POP, VibrationEffect.EFFECT_CLICK)
+                .build();
+
+        assertTrue(info.areVibrationFeaturesSupported(
+                VibrationEffect.startComposition()
+                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD)
+                        .addEffect(VibrationEffect.createWaveform(
+                                // These timings are given either 0 or default amplitudes, which
+                                // do not require vibrator's amplitude control.
+                                /* timings= */ new long[] {1, 2, 3},
+                                /* repeatIndex= */ -1))
+                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_POP))
+                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK))
+                        .compose()));
+    }
+
+    @Test
+    public void areVibrationFeaturesSupported_composedEffects_someComponentsUnupported() {
+        VibratorInfo info = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS | IVibrator.CAP_AMPLITUDE_CONTROL)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
+                .setSupportedEffects(VibrationEffect.EFFECT_TICK, VibrationEffect.EFFECT_POP)
+                .build();
+
+        // Not supported due to the TICK primitive, which the vibrator has no support for.
+        assertFalse(info.areVibrationFeaturesSupported(
+                VibrationEffect.startComposition()
+                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK)
+                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_TICK)
+                        .addEffect(VibrationEffect.createWaveform(
+                                /* timings= */ new long[] {1, 2, 3},
+                                /* amplitudes= */ new int[] {10, 20, 255},
+                                /* repeatIndex= */ -1))
+                        .compose()));
+        // Not supported due to the THUD effect, which the vibrator has no support for.
+        assertFalse(info.areVibrationFeaturesSupported(
+                VibrationEffect.startComposition()
+                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK)
+                        .addEffect(VibrationEffect.createWaveform(
+                                /* timings= */ new long[] {1, 2, 3},
+                                /* amplitudes= */ new int[] {10, 20, 255},
+                                /* repeatIndex= */ -1))
+                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_THUD))
+                        .compose()));
+
+        info = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD, 10)
+                .setSupportedEffects(VibrationEffect.EFFECT_POP)
+                .build();
+
+        // Not supported due to fractional amplitudes (amplitudes not min (0) or max (255) or
+        // DEFAULT), because the vibrator has no amplitude control.
+        assertFalse(info.areVibrationFeaturesSupported(
+                VibrationEffect.startComposition()
+                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD)
+                        .addEffect(VibrationEffect.createWaveform(
+                                /* timings= */ new long[] {1, 2, 3},
+                                /* amplitudes= */ new int[] {10, 20, 255},
+                                /* repeatIndex= */ -1))
+                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_POP))
+                        .compose()));
+    }
+
+    private static VibrationEffect waveformWithAmplitudes(int...amplitudes) {
+        long[] timings = new long[amplitudes.length];
+        for (int i = 0; i < timings.length; i++) {
+            timings[i] = i * 2; // Arbitrary timings.
+        }
+        return VibrationEffect.createWaveform(timings, amplitudes, /* repeatIndex= */ -1);
+    }
 }
diff --git a/core/tests/vibrator/src/android/os/VibratorTest.java b/core/tests/vibrator/src/android/os/VibratorTest.java
index c559e34..8141ca4 100644
--- a/core/tests/vibrator/src/android/os/VibratorTest.java
+++ b/core/tests/vibrator/src/android/os/VibratorTest.java
@@ -578,189 +578,6 @@
         assertEquals(new VibrationAttributes.Builder().build(), vibrationAttributes);
     }
 
-    @Test
-    public void areVibrationFeaturesSupported_noAmplitudeControl_fractionalAmplitudes() {
-        Vibrator vibrator =
-                createVibratorWithCustomInfo(new VibratorInfo.Builder(/* id= */ 1)
-                        .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                        .setSupportedEffects(VibrationEffect.EFFECT_THUD)
-                        .build());
-
-        // Have at least one fractional amplitude (amplitude not min (0) or max (255) or DEFAULT).
-        assertFalse(vibrator.areVibrationFeaturesSupported(waveformWithAmplitudes(10, 30)));
-        assertFalse(vibrator.areVibrationFeaturesSupported(waveformWithAmplitudes(10, 255)));
-        assertFalse(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.createOneShot(20, /* amplitude= */ 40)));
-    }
-
-    @Test
-    public void areVibrationFeaturesSupported_noAmplitudeControl_nonFractionalAmplitudes() {
-        Vibrator vibrator =
-                createVibratorWithCustomInfo(new VibratorInfo.Builder(/* id= */ 1)
-                        .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                        .setSupportedEffects(VibrationEffect.EFFECT_THUD)
-                        .build());
-
-        // All amplitudes are min, max, or default. Requires no amplitude control.
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                waveformWithAmplitudes(255, 0, VibrationEffect.DEFAULT_AMPLITUDE, 255)));
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.createWaveform(
-                        /* timings= */ new long[] {1, 2, 3}, /* repeatIndex= */ -1)));
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.createOneShot(20, VibrationEffect.DEFAULT_AMPLITUDE)));
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.createOneShot(20, /* amplitude= */ 255)));
-    }
-
-    @Test
-    public void areVibrationFeaturesSupported_withAmplitudeControl() {
-        Vibrator vibrator =
-                createVibratorWithCustomInfo(new VibratorInfo.Builder(/* id= */ 1)
-                        .setCapabilities(IVibrator.CAP_AMPLITUDE_CONTROL)
-                        .build());
-
-        // All forms of amplitudes are valid when amplitude control is available.
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                waveformWithAmplitudes(255, 0, VibrationEffect.DEFAULT_AMPLITUDE, 255)));
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.createWaveform(
-                        /* timings= */ new long[] {1, 2, 3}, /* repeatIndex= */ -1)));
-        assertTrue(vibrator.areVibrationFeaturesSupported(waveformWithAmplitudes(10, 30, 50)));
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                waveformWithAmplitudes(7, 255, 0, 0, 60)));
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.createOneShot(20, VibrationEffect.DEFAULT_AMPLITUDE)));
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.createOneShot(20, /* amplitude= */ 255)));
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.createOneShot(20, /* amplitude= */ 40)));
-    }
-
-    @Test
-    public void areVibrationFeaturesSupported_primitiveCompositionsWithSupportedPrimitives() {
-        Vibrator vibrator = createVibratorWithCustomInfo(new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
-                .build());
-
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.startComposition()
-                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK)
-                        .compose()));
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.startComposition()
-                        .addPrimitive(
-                                VibrationEffect.Composition.PRIMITIVE_CLICK,
-                                /* scale= */ 0.2f,
-                                /* delay= */ 200)
-                        .compose()));
-    }
-
-    @Test
-    public void areVibrationFeaturesSupported_primitiveCompositionsWithUnupportedPrimitives() {
-        Vibrator vibrator = createVibratorWithCustomInfo(new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
-                .build());
-
-        assertFalse(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.startComposition()
-                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK)
-                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD)
-                        .compose()));
-        assertFalse(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.startComposition()
-                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_LOW_TICK)
-                        .compose()));
-    }
-
-    @Test
-    public void areVibrationFeaturesSupported_composedEffects_allComponentsSupported() {
-        Vibrator vibrator = createVibratorWithCustomInfo(new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS | IVibrator.CAP_AMPLITUDE_CONTROL)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
-                .setSupportedEffects(VibrationEffect.EFFECT_TICK, VibrationEffect.EFFECT_POP)
-                .build());
-
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.startComposition()
-                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK)
-                        .addEffect(VibrationEffect.createWaveform(
-                                /* timings= */ new long[] {1, 2, 3},
-                                /* amplitudes= */ new int[] {10, 20, 255},
-                                /* repeatIndex= */ -1))
-                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK))
-                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_POP))
-                        .compose()));
-
-        vibrator = createVibratorWithCustomInfo(new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD, 10)
-                .setSupportedEffects(VibrationEffect.EFFECT_POP, VibrationEffect.EFFECT_CLICK)
-                .build());
-
-        assertTrue(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.startComposition()
-                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD)
-                        .addEffect(VibrationEffect.createWaveform(
-                                // These timings are given either 0 or default amplitudes, which
-                                // do not require vibrator's amplitude control.
-                                /* timings= */ new long[] {1, 2, 3},
-                                /* repeatIndex= */ -1))
-                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_POP))
-                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK))
-                        .compose()));
-    }
-
-    @Test
-    public void areVibrationFeaturesSupported_composedEffects_someComponentsUnupported() {
-        Vibrator vibrator = createVibratorWithCustomInfo(new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS | IVibrator.CAP_AMPLITUDE_CONTROL)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
-                .setSupportedEffects(VibrationEffect.EFFECT_TICK, VibrationEffect.EFFECT_POP)
-                .build());
-
-        // Not supported due to the TICK primitive, which the vibrator has no support for.
-        assertFalse(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.startComposition()
-                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK)
-                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_TICK)
-                        .addEffect(VibrationEffect.createWaveform(
-                                /* timings= */ new long[] {1, 2, 3},
-                                /* amplitudes= */ new int[] {10, 20, 255},
-                                /* repeatIndex= */ -1))
-                        .compose()));
-        // Not supported due to the THUD effect, which the vibrator has no support for.
-        assertFalse(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.startComposition()
-                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK)
-                        .addEffect(VibrationEffect.createWaveform(
-                                /* timings= */ new long[] {1, 2, 3},
-                                /* amplitudes= */ new int[] {10, 20, 255},
-                                /* repeatIndex= */ -1))
-                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_THUD))
-                        .compose()));
-
-        vibrator = createVibratorWithCustomInfo(new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD, 10)
-                .setSupportedEffects(VibrationEffect.EFFECT_POP)
-                .build());
-
-        // Not supported due to fractional amplitudes (amplitudes not min (0) or max (255) or
-        // DEFAULT), because the vibrator has no amplitude control.
-        assertFalse(vibrator.areVibrationFeaturesSupported(
-                VibrationEffect.startComposition()
-                        .addPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD)
-                        .addEffect(VibrationEffect.createWaveform(
-                                /* timings= */ new long[] {1, 2, 3},
-                                /* amplitudes= */ new int[] {10, 20, 255},
-                                /* repeatIndex= */ -1))
-                        .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_POP))
-                        .compose()));
-    }
-
     /**
      * Asserts that the frequency profile is empty, and therefore frequency control isn't supported.
      */
@@ -768,21 +585,4 @@
         assertTrue(info.getFrequencyProfile().isEmpty());
         assertEquals(false, info.hasCapability(IVibrator.CAP_FREQUENCY_CONTROL));
     }
-
-    private Vibrator createVibratorWithCustomInfo(VibratorInfo info) {
-        return new SystemVibrator(mContextSpy) {
-            @Override
-            public VibratorInfo getInfo() {
-                return info;
-            }
-        };
-    }
-
-    private static VibrationEffect waveformWithAmplitudes(int...amplitudes) {
-        long[] timings = new long[amplitudes.length];
-        for (int i = 0; i < timings.length; i++) {
-            timings[i] = i * 2; // Arbitrary timings.
-        }
-        return VibrationEffect.createWaveform(timings, amplitudes, /* repeatIndex= */ -1);
-    }
 }
diff --git a/core/tests/vibrator/src/android/os/vibrator/PrebakedSegmentTest.java b/core/tests/vibrator/src/android/os/vibrator/PrebakedSegmentTest.java
index 8268077..4f5f3c0 100644
--- a/core/tests/vibrator/src/android/os/vibrator/PrebakedSegmentTest.java
+++ b/core/tests/vibrator/src/android/os/vibrator/PrebakedSegmentTest.java
@@ -25,18 +25,14 @@
 import static org.testng.Assert.assertThrows;
 
 import android.os.Parcel;
-import android.os.SystemVibrator;
 import android.os.VibrationEffect;
-import android.os.Vibrator;
 import android.os.VibratorInfo;
 
-import androidx.test.InstrumentationRegistry;
-
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.runners.JUnit4;
 
-@RunWith(MockitoJUnitRunner.class)
+@RunWith(JUnit4.class)
 public class PrebakedSegmentTest {
 
     @Test
@@ -149,121 +145,121 @@
 
     @Test
     public void testVibrationFeaturesSupport_idsWithFallback_fallbackEnabled_vibratorSupport() {
-        Vibrator vibrator = createVibratorWithSupportedEffects(
+        VibratorInfo info = createVibratorInfoWithSupportedEffects(
                 VibrationEffect.EFFECT_TICK,
                 VibrationEffect.EFFECT_CLICK,
                 VibrationEffect.EFFECT_DOUBLE_CLICK,
                 VibrationEffect.EFFECT_HEAVY_CLICK);
 
         assertTrue(createSegmentWithFallback(VibrationEffect.EFFECT_TICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithFallback(VibrationEffect.EFFECT_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithFallback(VibrationEffect.EFFECT_DOUBLE_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithFallback(VibrationEffect.EFFECT_HEAVY_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
 
     }
 
     @Test
     public void testVibrationFeaturesSupport_idsWithFallback_fallbackEnabled_noVibratorSupport() {
-        Vibrator vibrator = createVibratorWithSupportedEffects(new int[0]);
+        VibratorInfo info = createVibratorInfoWithSupportedEffects(new int[0]);
 
         assertTrue(createSegmentWithFallback(VibrationEffect.EFFECT_TICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithFallback(VibrationEffect.EFFECT_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithFallback(VibrationEffect.EFFECT_DOUBLE_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithFallback(VibrationEffect.EFFECT_HEAVY_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_idsWithFallback_fallbackDisabled_vibratorSupport() {
-        Vibrator vibrator = createVibratorWithSupportedEffects(
+        VibratorInfo info = createVibratorInfoWithSupportedEffects(
                 VibrationEffect.EFFECT_TICK,
                 VibrationEffect.EFFECT_CLICK,
                 VibrationEffect.EFFECT_DOUBLE_CLICK,
                 VibrationEffect.EFFECT_HEAVY_CLICK);
 
         assertTrue(createSegmentWithoutFallback(VibrationEffect.EFFECT_TICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithoutFallback(VibrationEffect.EFFECT_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithoutFallback(VibrationEffect.EFFECT_DOUBLE_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithoutFallback(VibrationEffect.EFFECT_HEAVY_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_idsWithFallback_fallbackDisabled_noVibratorSupport() {
-        Vibrator vibrator = createVibratorWithSupportedEffects(new int[0]);
+        VibratorInfo info = createVibratorInfoWithSupportedEffects(new int[0]);
 
         assertFalse(createSegmentWithoutFallback(VibrationEffect.EFFECT_TICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertFalse(createSegmentWithoutFallback(VibrationEffect.EFFECT_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertFalse(createSegmentWithoutFallback(VibrationEffect.EFFECT_DOUBLE_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertFalse(createSegmentWithoutFallback(VibrationEffect.EFFECT_HEAVY_CLICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_idsWithNoFallback_fallbackEnabled_vibratorSupport() {
-        Vibrator vibrator = createVibratorWithSupportedEffects(
+        VibratorInfo info = createVibratorInfoWithSupportedEffects(
                 VibrationEffect.EFFECT_THUD,
                 VibrationEffect.EFFECT_POP,
                 VibrationEffect.EFFECT_TEXTURE_TICK);
 
         assertTrue(createSegmentWithFallback(VibrationEffect.EFFECT_THUD)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithFallback(VibrationEffect.EFFECT_POP)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithFallback(VibrationEffect.EFFECT_TEXTURE_TICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_idsWithNoFallback_fallbackEnabled_noVibratorSupport() {
-        Vibrator vibrator = createVibratorWithSupportedEffects(new int[0]);
+        VibratorInfo info = createVibratorInfoWithSupportedEffects(new int[0]);
 
         assertFalse(createSegmentWithFallback(VibrationEffect.EFFECT_THUD)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertFalse(createSegmentWithFallback(VibrationEffect.EFFECT_POP)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertFalse(createSegmentWithFallback(VibrationEffect.EFFECT_TEXTURE_TICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_idsWithNoFallback_fallbackDisabled_vibratorSupport() {
-        Vibrator vibrator = createVibratorWithSupportedEffects(
+        VibratorInfo info = createVibratorInfoWithSupportedEffects(
                 VibrationEffect.EFFECT_THUD,
                 VibrationEffect.EFFECT_POP,
                 VibrationEffect.EFFECT_TEXTURE_TICK);
 
         assertTrue(createSegmentWithoutFallback(VibrationEffect.EFFECT_THUD)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithoutFallback(VibrationEffect.EFFECT_POP)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertTrue(createSegmentWithoutFallback(VibrationEffect.EFFECT_TEXTURE_TICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_idsWithNoFallback_fallbackDisabled_noVibSupport() {
-        Vibrator vibrator = createVibratorWithSupportedEffects(new int[0]);
+        VibratorInfo info = createVibratorInfoWithSupportedEffects(new int[0]);
 
         assertFalse(createSegmentWithoutFallback(VibrationEffect.EFFECT_THUD)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertFalse(createSegmentWithoutFallback(VibrationEffect.EFFECT_POP)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
         assertFalse(createSegmentWithoutFallback(VibrationEffect.EFFECT_TEXTURE_TICK)
-                .areVibrationFeaturesSupported(vibrator));
+                .areVibrationFeaturesSupported(info));
     }
 
     @Test
@@ -283,14 +279,9 @@
         return new PrebakedSegment(effectId, false, VibrationEffect.EFFECT_STRENGTH_MEDIUM);
     }
 
-    private static Vibrator createVibratorWithSupportedEffects(int... supportedEffects) {
-        return new SystemVibrator(InstrumentationRegistry.getContext()) {
-            @Override
-            public VibratorInfo getInfo() {
-                return new VibratorInfo.Builder(/* id= */ 1)
-                        .setSupportedEffects(supportedEffects)
-                        .build();
-            }
-        };
+    private static VibratorInfo createVibratorInfoWithSupportedEffects(int... supportedEffects) {
+        return new VibratorInfo.Builder(/* id= */ 1)
+                .setSupportedEffects(supportedEffects)
+                .build();
     }
 }
diff --git a/core/tests/vibrator/src/android/os/vibrator/PrimitiveSegmentTest.java b/core/tests/vibrator/src/android/os/vibrator/PrimitiveSegmentTest.java
index 6f5adcd..ec5a084 100644
--- a/core/tests/vibrator/src/android/os/vibrator/PrimitiveSegmentTest.java
+++ b/core/tests/vibrator/src/android/os/vibrator/PrimitiveSegmentTest.java
@@ -25,18 +25,14 @@
 
 import android.hardware.vibrator.IVibrator;
 import android.os.Parcel;
-import android.os.SystemVibrator;
 import android.os.VibrationEffect;
-import android.os.Vibrator;
 import android.os.VibratorInfo;
 
-import androidx.test.InstrumentationRegistry;
-
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.runners.JUnit4;
 
-@RunWith(MockitoJUnitRunner.class)
+@RunWith(JUnit4.class)
 public class PrimitiveSegmentTest {
     private static final float TOLERANCE = 1e-2f;
 
@@ -146,15 +142,15 @@
     public void testVibrationFeaturesSupport_primitiveSupportedByVibrator() {
         assertTrue(createSegment(VibrationEffect.Composition.PRIMITIVE_CLICK)
                 .areVibrationFeaturesSupported(
-                        createVibratorWithSupportedPrimitive(
+                        createVibratorInfoWithSupportedPrimitive(
                                 VibrationEffect.Composition.PRIMITIVE_CLICK)));
         assertTrue(createSegment(VibrationEffect.Composition.PRIMITIVE_THUD)
                 .areVibrationFeaturesSupported(
-                        createVibratorWithSupportedPrimitive(
+                        createVibratorInfoWithSupportedPrimitive(
                                 VibrationEffect.Composition.PRIMITIVE_THUD)));
         assertTrue(createSegment(VibrationEffect.Composition.PRIMITIVE_QUICK_RISE)
                 .areVibrationFeaturesSupported(
-                        createVibratorWithSupportedPrimitive(
+                        createVibratorInfoWithSupportedPrimitive(
                                 VibrationEffect.Composition.PRIMITIVE_QUICK_RISE)));
     }
 
@@ -162,15 +158,15 @@
     public void testVibrationFeaturesSupport_primitiveNotSupportedByVibrator() {
         assertFalse(createSegment(VibrationEffect.Composition.PRIMITIVE_CLICK)
                 .areVibrationFeaturesSupported(
-                        createVibratorWithSupportedPrimitive(
+                        createVibratorInfoWithSupportedPrimitive(
                                 VibrationEffect.Composition.PRIMITIVE_THUD)));
         assertFalse(createSegment(VibrationEffect.Composition.PRIMITIVE_THUD)
                 .areVibrationFeaturesSupported(
-                        createVibratorWithSupportedPrimitive(
+                        createVibratorInfoWithSupportedPrimitive(
                                 VibrationEffect.Composition.PRIMITIVE_CLICK)));
         assertFalse(createSegment(VibrationEffect.Composition.PRIMITIVE_THUD)
                 .areVibrationFeaturesSupported(
-                        createVibratorWithSupportedPrimitive(
+                        createVibratorInfoWithSupportedPrimitive(
                                 VibrationEffect.Composition.PRIMITIVE_QUICK_RISE)));
     }
 
@@ -193,15 +189,10 @@
         return new PrimitiveSegment(primitiveId, 0.2f, 10);
     }
 
-    private static Vibrator createVibratorWithSupportedPrimitive(int primitiveId) {
-        return new SystemVibrator(InstrumentationRegistry.getContext()) {
-            @Override
-            public VibratorInfo getInfo() {
-                return new VibratorInfo.Builder(/* id= */ 1)
-                        .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                        .setSupportedPrimitive(primitiveId, 10)
-                        .build();
-                }
-        };
+    private static VibratorInfo createVibratorInfoWithSupportedPrimitive(int primitiveId) {
+        return new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(primitiveId, 10)
+                .build();
     }
 }
diff --git a/core/tests/vibrator/src/android/os/vibrator/RampSegmentTest.java b/core/tests/vibrator/src/android/os/vibrator/RampSegmentTest.java
index 68870e5..5caa86b 100644
--- a/core/tests/vibrator/src/android/os/vibrator/RampSegmentTest.java
+++ b/core/tests/vibrator/src/android/os/vibrator/RampSegmentTest.java
@@ -23,31 +23,21 @@
 import static junit.framework.Assert.assertSame;
 import static junit.framework.Assert.assertTrue;
 
-import static org.mockito.Mockito.when;
 import static org.testng.Assert.assertThrows;
 
+import android.hardware.vibrator.IVibrator;
 import android.os.Parcel;
 import android.os.VibrationEffect;
-import android.os.Vibrator;
+import android.os.VibratorInfo;
 
-import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnit;
-import org.mockito.junit.MockitoJUnitRunner;
-import org.mockito.junit.MockitoRule;
+import org.junit.runners.JUnit4;
 
-@RunWith(MockitoJUnitRunner.class)
+@RunWith(JUnit4.class)
 public class RampSegmentTest {
     private static final float TOLERANCE = 1e-2f;
 
-    @Rule
-    public MockitoRule mMockitoRule = MockitoJUnit.rule();
-
-    @Mock
-    private Vibrator mVibrator;
-
     @Test
     public void testCreation() {
         RampSegment ramp = new RampSegment(/* startAmplitude= */ 1, /* endAmplitude= */ 0,
@@ -147,71 +137,71 @@
 
     @Test
     public void testVibrationFeaturesSupport_amplitudeAndFrequencyControls_supported() {
-        when(mVibrator.hasAmplitudeControl()).thenReturn(true);
-        when(mVibrator.hasFrequencyControl()).thenReturn(true);
+        VibratorInfo info =
+                createVibInfo(/* hasAmplitudeControl= */ true, /* hasFrequencyControl= */ true);
 
         // Increasing amplitude
-        assertTrue(new RampSegment(0.5f, 1, 0, 0, 10).areVibrationFeaturesSupported(mVibrator));
+        assertTrue(new RampSegment(0.5f, 1, 0, 0, 10).areVibrationFeaturesSupported(info));
         // Increasing frequency
-        assertTrue(new RampSegment(0.5f, 0.5f, 0, 1, 10).areVibrationFeaturesSupported(mVibrator));
+        assertTrue(new RampSegment(0.5f, 0.5f, 0, 1, 10).areVibrationFeaturesSupported(info));
         // Decreasing amplitude
-        assertTrue(new RampSegment(1, 0.5f, 0, 0, 10).areVibrationFeaturesSupported(mVibrator));
+        assertTrue(new RampSegment(1, 0.5f, 0, 0, 10).areVibrationFeaturesSupported(info));
         // Decreasing frequency
-        assertTrue(new RampSegment(0.5f, 0.5f, 1, 0, 10).areVibrationFeaturesSupported(mVibrator));
+        assertTrue(new RampSegment(0.5f, 0.5f, 1, 0, 10).areVibrationFeaturesSupported(info));
         // Zero duration
-        assertTrue(new RampSegment(0.5f, 0.5f, 1, 0, 0).areVibrationFeaturesSupported(mVibrator));
+        assertTrue(new RampSegment(0.5f, 0.5f, 1, 0, 0).areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_noAmplitudeControl_unsupportedForChangingAmplitude() {
-        when(mVibrator.hasAmplitudeControl()).thenReturn(false);
-        when(mVibrator.hasFrequencyControl()).thenReturn(true);
+        VibratorInfo info =
+                createVibInfo(/* hasAmplitudeControl= */ false, /* hasFrequencyControl= */ true);
 
         // Test with increasing/decreasing amplitudes.
-        assertFalse(new RampSegment(0.5f, 1, 0, 0, 10).areVibrationFeaturesSupported(mVibrator));
-        assertFalse(new RampSegment(1, 0.5f, 0, 0, 10).areVibrationFeaturesSupported(mVibrator));
+        assertFalse(new RampSegment(0.5f, 1, 0, 0, 10).areVibrationFeaturesSupported(info));
+        assertFalse(new RampSegment(1, 0.5f, 0, 0, 10).areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_noAmplitudeControl_fractionalAmplitudeUnsupported() {
-        when(mVibrator.hasAmplitudeControl()).thenReturn(false);
-        when(mVibrator.hasFrequencyControl()).thenReturn(true);
+        VibratorInfo info =
+                createVibInfo(/* hasAmplitudeControl= */ false, /* hasFrequencyControl= */ true);
 
-        assertFalse(new RampSegment(0.2f, 0.2f, 0, 0, 10).areVibrationFeaturesSupported(mVibrator));
-        assertFalse(new RampSegment(0, 0.2f, 0, 0, 10).areVibrationFeaturesSupported(mVibrator));
-        assertFalse(new RampSegment(0.2f, 0, 0, 0, 10).areVibrationFeaturesSupported(mVibrator));
+        assertFalse(new RampSegment(0.2f, 0.2f, 0, 0, 10).areVibrationFeaturesSupported(info));
+        assertFalse(new RampSegment(0, 0.2f, 0, 0, 10).areVibrationFeaturesSupported(info));
+        assertFalse(new RampSegment(0.2f, 0, 0, 0, 10).areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_unchangingZeroAmplitude_supported() {
         RampSegment amplitudeZeroWithIncreasingFrequency = new RampSegment(1, 1, 0.5f, 0.8f, 10);
         RampSegment amplitudeZeroWithDecreasingFrequency = new RampSegment(1, 1, 0.8f, 0.5f, 10);
-        when(mVibrator.hasFrequencyControl()).thenReturn(true);
-        when(mVibrator.hasAmplitudeControl()).thenReturn(false);
+        VibratorInfo info =
+                createVibInfo(/* hasAmplitudeControl= */ false, /* hasFrequencyControl= */ true);
 
-        assertTrue(amplitudeZeroWithIncreasingFrequency.areVibrationFeaturesSupported(mVibrator));
-        assertTrue(amplitudeZeroWithDecreasingFrequency.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(amplitudeZeroWithIncreasingFrequency.areVibrationFeaturesSupported(info));
+        assertTrue(amplitudeZeroWithDecreasingFrequency.areVibrationFeaturesSupported(info));
 
-        when(mVibrator.hasAmplitudeControl()).thenReturn(true);
+        info = createVibInfo(/* hasAmplitudeControl= */ true, /* hasFrequencyControl= */ true);
 
-        assertTrue(amplitudeZeroWithIncreasingFrequency.areVibrationFeaturesSupported(mVibrator));
-        assertTrue(amplitudeZeroWithDecreasingFrequency.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(amplitudeZeroWithIncreasingFrequency.areVibrationFeaturesSupported(info));
+        assertTrue(amplitudeZeroWithDecreasingFrequency.areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_unchangingOneAmplitude_supported() {
         RampSegment amplitudeOneWithIncreasingFrequency = new RampSegment(1, 1, 0.5f, 0.8f, 10);
         RampSegment amplitudeOneWithDecreasingFrequency = new RampSegment(1, 1, 0.8f, 0.5f, 10);
-        when(mVibrator.hasFrequencyControl()).thenReturn(true);
-        when(mVibrator.hasAmplitudeControl()).thenReturn(false);
+        VibratorInfo info =
+                createVibInfo(/* hasAmplitudeControl= */ false, /* hasFrequencyControl= */ true);
 
-        assertTrue(amplitudeOneWithIncreasingFrequency.areVibrationFeaturesSupported(mVibrator));
-        assertTrue(amplitudeOneWithDecreasingFrequency.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(amplitudeOneWithIncreasingFrequency.areVibrationFeaturesSupported(info));
+        assertTrue(amplitudeOneWithDecreasingFrequency.areVibrationFeaturesSupported(info));
 
-        when(mVibrator.hasAmplitudeControl()).thenReturn(true);
+        info = createVibInfo(/* hasAmplitudeControl= */ true, /* hasFrequencyControl= */ true);
 
-        assertTrue(amplitudeOneWithIncreasingFrequency.areVibrationFeaturesSupported(mVibrator));
-        assertTrue(amplitudeOneWithDecreasingFrequency.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(amplitudeOneWithIncreasingFrequency.areVibrationFeaturesSupported(info));
+        assertTrue(amplitudeOneWithDecreasingFrequency.areVibrationFeaturesSupported(info));
     }
 
     @Test
@@ -220,52 +210,52 @@
                 new RampSegment(DEFAULT_AMPLITUDE, DEFAULT_AMPLITUDE, 0.5f, 0.8f, 10);
         RampSegment defaultAmplitudeDecreasingFrequency =
                 new RampSegment(DEFAULT_AMPLITUDE, DEFAULT_AMPLITUDE, 0.8f, 0.5f, 10);
-        when(mVibrator.hasFrequencyControl()).thenReturn(true);
-        when(mVibrator.hasAmplitudeControl()).thenReturn(false);
+        VibratorInfo info =
+                createVibInfo(/* hasAmplitudeControl= */ false, /* hasFrequencyControl= */ true);
 
-        assertTrue(defaultAmplitudeIncreasingFrequency.areVibrationFeaturesSupported(mVibrator));
-        assertTrue(defaultAmplitudeDecreasingFrequency.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(defaultAmplitudeIncreasingFrequency.areVibrationFeaturesSupported(info));
+        assertTrue(defaultAmplitudeDecreasingFrequency.areVibrationFeaturesSupported(info));
 
-        when(mVibrator.hasAmplitudeControl()).thenReturn(true);
+        info = createVibInfo(/* hasAmplitudeControl= */ true, /* hasFrequencyControl= */ true);
 
-        assertTrue(defaultAmplitudeIncreasingFrequency.areVibrationFeaturesSupported(mVibrator));
-        assertTrue(defaultAmplitudeDecreasingFrequency.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(defaultAmplitudeIncreasingFrequency.areVibrationFeaturesSupported(info));
+        assertTrue(defaultAmplitudeDecreasingFrequency.areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_noFrequencyControl_unsupportedForChangingFrequency() {
-        when(mVibrator.hasAmplitudeControl()).thenReturn(true);
-        when(mVibrator.hasFrequencyControl()).thenReturn(false);
+        VibratorInfo info =
+                createVibInfo(/* hasAmplitudeControl= */ true, /* hasFrequencyControl= */ false);
 
         // Test with increasing/decreasing frequencies.
-        assertFalse(new RampSegment(0, 0, 0.2f, 0.4f, 10).areVibrationFeaturesSupported(mVibrator));
-        assertFalse(new RampSegment(0, 0, 0.4f, 0.2f, 10).areVibrationFeaturesSupported(mVibrator));
+        assertFalse(new RampSegment(0, 0, 0.2f, 0.4f, 10).areVibrationFeaturesSupported(info));
+        assertFalse(new RampSegment(0, 0, 0.4f, 0.2f, 10).areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_noFrequencyControl_fractionalFrequencyUnsupported() {
-        when(mVibrator.hasAmplitudeControl()).thenReturn(true);
-        when(mVibrator.hasFrequencyControl()).thenReturn(false);
+        VibratorInfo info =
+                createVibInfo(/* hasAmplitudeControl= */ true, /* hasFrequencyControl= */ false);
 
-        assertFalse(new RampSegment(0, 0, 0.2f, 0.2f, 10).areVibrationFeaturesSupported(mVibrator));
-        assertFalse(new RampSegment(0, 0, 0.2f, 0, 10).areVibrationFeaturesSupported(mVibrator));
-        assertFalse(new RampSegment(0, 0, 0, 0.2f, 10).areVibrationFeaturesSupported(mVibrator));
+        assertFalse(new RampSegment(0, 0, 0.2f, 0.2f, 10).areVibrationFeaturesSupported(info));
+        assertFalse(new RampSegment(0, 0, 0.2f, 0, 10).areVibrationFeaturesSupported(info));
+        assertFalse(new RampSegment(0, 0, 0, 0.2f, 10).areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_unchangingZeroFrequency_supported() {
         RampSegment frequencyZeroWithIncreasingAmplitude = new RampSegment(0.1f, 1, 0, 0, 10);
         RampSegment frequencyZeroWithDecreasingAmplitude = new RampSegment(1, 0.1f, 0, 0, 10);
-        when(mVibrator.hasAmplitudeControl()).thenReturn(true);
-        when(mVibrator.hasFrequencyControl()).thenReturn(false);
+        VibratorInfo info =
+                createVibInfo(/* hasAmplitudeControl= */ true, /* hasFrequencyControl= */ false);
 
-        assertTrue(frequencyZeroWithIncreasingAmplitude.areVibrationFeaturesSupported(mVibrator));
-        assertTrue(frequencyZeroWithDecreasingAmplitude.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(frequencyZeroWithIncreasingAmplitude.areVibrationFeaturesSupported(info));
+        assertTrue(frequencyZeroWithDecreasingAmplitude.areVibrationFeaturesSupported(info));
 
-        when(mVibrator.hasFrequencyControl()).thenReturn(true);
+        info = createVibInfo(/* hasAmplitudeControl= */ true, /* hasFrequencyControl= */ true);
 
-        assertTrue(frequencyZeroWithIncreasingAmplitude.areVibrationFeaturesSupported(mVibrator));
-        assertTrue(frequencyZeroWithDecreasingAmplitude.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(frequencyZeroWithIncreasingAmplitude.areVibrationFeaturesSupported(info));
+        assertTrue(frequencyZeroWithDecreasingAmplitude.areVibrationFeaturesSupported(info));
     }
 
     @Test
@@ -274,4 +264,17 @@
         // duration checked in VibrationEffect implementations.
         assertTrue(new RampSegment(0.5f, 1, 0, 0, 5_000).isHapticFeedbackCandidate());
     }
+
+    private static VibratorInfo createVibInfo(
+            boolean hasAmplitudeControl, boolean hasFrequencyControl) {
+        VibratorInfo.Builder builder = new VibratorInfo.Builder(/* id= */ 1);
+        long capabilities = 0;
+        if (hasAmplitudeControl) {
+            capabilities |= IVibrator.CAP_AMPLITUDE_CONTROL;
+        }
+        if (hasFrequencyControl) {
+            capabilities |= (IVibrator.CAP_FREQUENCY_CONTROL | IVibrator.CAP_COMPOSE_PWLE_EFFECTS);
+        }
+        return builder.setCapabilities(capabilities).build();
+    }
 }
diff --git a/core/tests/vibrator/src/android/os/vibrator/StepSegmentTest.java b/core/tests/vibrator/src/android/os/vibrator/StepSegmentTest.java
index 34bb892..44db306 100644
--- a/core/tests/vibrator/src/android/os/vibrator/StepSegmentTest.java
+++ b/core/tests/vibrator/src/android/os/vibrator/StepSegmentTest.java
@@ -21,31 +21,20 @@
 import static junit.framework.Assert.assertSame;
 import static junit.framework.Assert.assertTrue;
 
-import static org.mockito.Mockito.when;
 import static org.testng.Assert.assertThrows;
 
+import android.hardware.vibrator.IVibrator;
 import android.os.Parcel;
 import android.os.VibrationEffect;
-import android.os.Vibrator;
+import android.os.VibratorInfo;
 
-import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnit;
-import org.mockito.junit.MockitoJUnitRunner;
-import org.mockito.junit.MockitoRule;
+import org.junit.runners.JUnit4;
 
-@RunWith(MockitoJUnitRunner.class)
+@RunWith(JUnit4.class)
 public class StepSegmentTest {
     private static final float TOLERANCE = 1e-2f;
-
-    @Rule
-    public MockitoRule mMockitoRule = MockitoJUnit.rule();
-
-    @Mock
-    private Vibrator mVibrator;
-
     @Test
     public void testCreation() {
         StepSegment step = new StepSegment(/* amplitude= */ 1f, /* frequencyHz= */ 1f,
@@ -160,26 +149,26 @@
     public void testVibrationFeaturesSupport_zeroAmplitude_supported() {
         StepSegment segment =
                 new StepSegment(/* amplitude= */ 0, /* frequencyHz= */ 0, /* duration= */ 0);
-        when(mVibrator.hasAmplitudeControl()).thenReturn(true);
+        VibratorInfo info = createVibInfoForAmplitude(/* hasAmplitudeControl= */ true);
 
-        assertTrue(segment.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(segment.areVibrationFeaturesSupported(info));
 
-        when(mVibrator.hasAmplitudeControl()).thenReturn(false);
+        info = createVibInfoForAmplitude(/* hasAmplitudeControl= */ false);
 
-        assertTrue(segment.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(segment.areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_maxAmplitude_supported() {
         StepSegment segment =
                 new StepSegment(/* amplitude= */ 1, /* frequencyHz= */ 0, /* duration= */ 0);
-        when(mVibrator.hasAmplitudeControl()).thenReturn(true);
+        VibratorInfo info = createVibInfoForAmplitude(/* hasAmplitudeControl= */ true);
 
-        assertTrue(segment.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(segment.areVibrationFeaturesSupported(info));
 
-        when(mVibrator.hasAmplitudeControl()).thenReturn(false);
+        info = createVibInfoForAmplitude(/* hasAmplitudeControl= */ false);
 
-        assertTrue(segment.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(segment.areVibrationFeaturesSupported(info));
     }
 
     @Test
@@ -189,60 +178,60 @@
                         /* amplitude= */ VibrationEffect.DEFAULT_AMPLITUDE,
                         /* frequencyHz= */ 0,
                         /* duration= */ 0);
-        when(mVibrator.hasAmplitudeControl()).thenReturn(true);
+        VibratorInfo info = createVibInfoForAmplitude(/* hasAmplitudeControl= */ true);
 
-        assertTrue(segment.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(segment.areVibrationFeaturesSupported(info));
 
-        when(mVibrator.hasAmplitudeControl()).thenReturn(false);
+        info = createVibInfoForAmplitude(/* hasAmplitudeControl= */ false);
 
-        assertTrue(segment.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(segment.areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_fractionalAmplitude_hasAmplitudeCtrl_supported() {
-        when(mVibrator.hasAmplitudeControl()).thenReturn(true);
+        VibratorInfo info = createVibInfoForAmplitude(/* hasAmplitudeControl= */ true);
 
         assertTrue(new StepSegment(/* amplitude= */ 0.2f, /* frequencyHz= */ 0, /* duration= */ 0)
-                .areVibrationFeaturesSupported(mVibrator));
+                .areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_fractionalAmplitude_hasNoAmplitudeCtrl_notSupported() {
-        when(mVibrator.hasAmplitudeControl()).thenReturn(false);
+        VibratorInfo info = createVibInfoForAmplitude(/* hasAmplitudeControl= */ false);
 
         assertFalse(new StepSegment(/* amplitude= */ 0.2f, /* frequencyHz= */ 0, /* duration= */ 0)
-                .areVibrationFeaturesSupported(mVibrator));
+                .areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_zeroFrequency_supported() {
         StepSegment segment =
                 new StepSegment(/* amplitude= */ 0f, /* frequencyHz= */ 0, /* duration= */ 0);
-        when(mVibrator.hasFrequencyControl()).thenReturn(false);
+        VibratorInfo info = createVibInfoForFrequency(/* hasFrequencyControl= */ false);
 
-        assertTrue(segment.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(segment.areVibrationFeaturesSupported(info));
 
-        when(mVibrator.hasFrequencyControl()).thenReturn(true);
+        info = createVibInfoForFrequency(/* hasFrequencyControl= */ true);
 
-        assertTrue(segment.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(segment.areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_nonZeroFrequency_hasFrequencyCtrl_supported() {
         StepSegment segment =
                 new StepSegment(/* amplitude= */ 0f, /* frequencyHz= */ 0.2f, /* duration= */ 0);
-        when(mVibrator.hasFrequencyControl()).thenReturn(true);
+        VibratorInfo info = createVibInfoForFrequency(/* hasFrequencyControl= */ true);
 
-        assertTrue(segment.areVibrationFeaturesSupported(mVibrator));
+        assertTrue(segment.areVibrationFeaturesSupported(info));
     }
 
     @Test
     public void testVibrationFeaturesSupport_nonZeroFrequency_hasNoFrequencyCtrl_notSupported() {
         StepSegment segment =
                 new StepSegment(/* amplitude= */ 0f, /* frequencyHz= */ 0.2f, /* duration= */ 0);
-        when(mVibrator.hasFrequencyControl()).thenReturn(false);
+        VibratorInfo info = createVibInfoForFrequency(/* hasFrequencyControl= */ false);
 
-        assertFalse(segment.areVibrationFeaturesSupported(mVibrator));
+        assertFalse(segment.areVibrationFeaturesSupported(info));
     }
 
     @Test
@@ -251,4 +240,21 @@
         // duration checked in VibrationEffect implementations.
         assertTrue(new StepSegment(0, 0, 5_000).isHapticFeedbackCandidate());
     }
+
+    private static VibratorInfo createVibInfoForAmplitude(boolean hasAmplitudeControl) {
+        VibratorInfo.Builder builder = new VibratorInfo.Builder(/* id= */ 1);
+        if (hasAmplitudeControl) {
+            builder.setCapabilities(IVibrator.CAP_AMPLITUDE_CONTROL);
+        }
+        return builder.build();
+    }
+
+    private static VibratorInfo createVibInfoForFrequency(boolean hasFrequencyControl) {
+        VibratorInfo.Builder builder = new VibratorInfo.Builder(/* id= */ 1);
+        if (hasFrequencyControl) {
+            builder.setCapabilities(
+                    IVibrator.CAP_FREQUENCY_CONTROL | IVibrator.CAP_COMPOSE_PWLE_EFFECTS);
+        }
+        return builder.build();
+    }
 }
diff --git a/data/etc/com.android.settings.xml b/data/etc/com.android.settings.xml
index e278c52..dcc9686 100644
--- a/data/etc/com.android.settings.xml
+++ b/data/etc/com.android.settings.xml
@@ -37,6 +37,7 @@
         <permission name="android.permission.MANAGE_USER_OEM_UNLOCK_STATE" />
         <permission name="android.permission.MASTER_CLEAR"/>
         <permission name="android.permission.MEDIA_CONTENT_CONTROL"/>
+        <permission name="android.permission.MODIFY_AUDIO_SETTINGS_PRIVILEGED" />
         <permission name="android.permission.MODIFY_PHONE_STATE"/>
         <permission name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
         <permission name="android.permission.MOVE_PACKAGE"/>
diff --git a/data/etc/services.core.protolog.json b/data/etc/services.core.protolog.json
index 87e6b18..6057852 100644
--- a/data/etc/services.core.protolog.json
+++ b/data/etc/services.core.protolog.json
@@ -691,6 +691,12 @@
       "group": "WM_DEBUG_WINDOW_TRANSITIONS",
       "at": "com\/android\/server\/wm\/Transition.java"
     },
+    "-1449515133": {
+      "message": "Content Recording: stopping active projection for display %d",
+      "level": "ERROR",
+      "group": "WM_DEBUG_CONTENT_RECORDING",
+      "at": "com\/android\/server\/wm\/ContentRecorder.java"
+    },
     "-1443029505": {
       "message": "SAFE MODE ENABLED (menu=%d s=%d dpad=%d trackball=%d)",
       "level": "INFO",
@@ -1285,6 +1291,12 @@
       "group": "WM_DEBUG_STATES",
       "at": "com\/android\/server\/wm\/ActivityRecord.java"
     },
+    "-921346089": {
+      "message": "Content Recording: Unable to tell MediaProjectionManagerService to stop the active projection for display %d: %s",
+      "level": "ERROR",
+      "group": "WM_DEBUG_CONTENT_RECORDING",
+      "at": "com\/android\/server\/wm\/ContentRecorder.java"
+    },
     "-917215012": {
       "message": "%s: caller %d is using old GET_TASKS but privileged; allowing",
       "level": "WARN",
@@ -2233,12 +2245,6 @@
       "group": "WM_DEBUG_CONFIGURATION",
       "at": "com\/android\/server\/wm\/ActivityRecord.java"
     },
-    "-88873335": {
-      "message": "Content Recording: Unable to tell MediaProjectionManagerService to stop the active projection: %s",
-      "level": "ERROR",
-      "group": "WM_DEBUG_CONTENT_RECORDING",
-      "at": "com\/android\/server\/wm\/ContentRecorder.java"
-    },
     "-87705714": {
       "message": "findFocusedWindow: focusedApp=null using new focus @ %s",
       "level": "VERBOSE",
diff --git a/graphics/TEST_MAPPING b/graphics/TEST_MAPPING
index abeaf19..8afc30d 100644
--- a/graphics/TEST_MAPPING
+++ b/graphics/TEST_MAPPING
@@ -7,6 +7,18 @@
           "exclude-annotation": "androidx.test.filters.FlakyTest"
         }
       ]
+    },
+    {
+      "name": "CtsTextTestCases",
+      "options": [
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        },
+        {
+          "exclude-annotation": "androidx.test.filters.LargeTest"
+        }
+      ],
+      "file_patterns": ["(/|^)Typeface\\.java", "(/|^)Paint\\.java"]
     }
   ]
 }
diff --git a/graphics/java/android/graphics/ColorSpace.java b/graphics/java/android/graphics/ColorSpace.java
index 99bebb8..a2319a5 100644
--- a/graphics/java/android/graphics/ColorSpace.java
+++ b/graphics/java/android/graphics/ColorSpace.java
@@ -199,6 +199,8 @@
 
     private static final float[] SRGB_PRIMARIES = { 0.640f, 0.330f, 0.300f, 0.600f, 0.150f, 0.060f };
     private static final float[] NTSC_1953_PRIMARIES = { 0.67f, 0.33f, 0.21f, 0.71f, 0.14f, 0.08f };
+    private static final float[] DCI_P3_PRIMARIES =
+            { 0.680f, 0.320f, 0.265f, 0.690f, 0.150f, 0.060f };
     private static final float[] BT2020_PRIMARIES =
             { 0.708f, 0.292f, 0.170f, 0.797f, 0.131f, 0.046f };
     /**
@@ -211,6 +213,9 @@
     private static final Rgb.TransferParameters SRGB_TRANSFER_PARAMETERS =
             new Rgb.TransferParameters(1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045, 2.4);
 
+    private static final Rgb.TransferParameters SMPTE_170M_TRANSFER_PARAMETERS =
+            new Rgb.TransferParameters(1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081, 1 / 0.45);
+
     // HLG transfer with an SDR whitepoint of 203 nits
     private static final Rgb.TransferParameters BT2020_HLG_TRANSFER_PARAMETERS =
             new Rgb.TransferParameters(2.0, 2.0, 1 / 0.17883277, 0.28466892, 0.55991073,
@@ -1559,10 +1564,10 @@
                 DataSpace.DATASPACE_SCRGB_LINEAR, Named.LINEAR_EXTENDED_SRGB.ordinal());
         sNamedColorSpaces[Named.BT709.ordinal()] = new ColorSpace.Rgb(
                 "Rec. ITU-R BT.709-5",
-                new float[] { 0.640f, 0.330f, 0.300f, 0.600f, 0.150f, 0.060f },
+                SRGB_PRIMARIES,
                 ILLUMINANT_D65,
                 null,
-                new Rgb.TransferParameters(1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081, 1 / 0.45),
+                SMPTE_170M_TRANSFER_PARAMETERS,
                 Named.BT709.ordinal()
         );
         sDataToColorSpaces.put(DataSpace.DATASPACE_BT709, Named.BT709.ordinal());
@@ -1577,7 +1582,7 @@
         sDataToColorSpaces.put(DataSpace.DATASPACE_BT2020, Named.BT2020.ordinal());
         sNamedColorSpaces[Named.DCI_P3.ordinal()] = new ColorSpace.Rgb(
                 "SMPTE RP 431-2-2007 DCI (P3)",
-                new float[] { 0.680f, 0.320f, 0.265f, 0.690f, 0.150f, 0.060f },
+                DCI_P3_PRIMARIES,
                 new float[] { 0.314f, 0.351f },
                 2.6,
                 0.0f, 1.0f,
@@ -1586,7 +1591,7 @@
         sDataToColorSpaces.put(DataSpace.DATASPACE_DCI_P3, Named.DCI_P3.ordinal());
         sNamedColorSpaces[Named.DISPLAY_P3.ordinal()] = new ColorSpace.Rgb(
                 "Display P3",
-                new float[] { 0.680f, 0.320f, 0.265f, 0.690f, 0.150f, 0.060f },
+                DCI_P3_PRIMARIES,
                 ILLUMINANT_D65,
                 null,
                 SRGB_TRANSFER_PARAMETERS,
@@ -1598,7 +1603,7 @@
                 NTSC_1953_PRIMARIES,
                 ILLUMINANT_C,
                 null,
-                new Rgb.TransferParameters(1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081, 1 / 0.45),
+                SMPTE_170M_TRANSFER_PARAMETERS,
                 Named.NTSC_1953.ordinal()
         );
         sNamedColorSpaces[Named.SMPTE_C.ordinal()] = new ColorSpace.Rgb(
@@ -1606,7 +1611,7 @@
                 new float[] { 0.630f, 0.340f, 0.310f, 0.595f, 0.155f, 0.070f },
                 ILLUMINANT_D65,
                 null,
-                new Rgb.TransferParameters(1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081, 1 / 0.45),
+                SMPTE_170M_TRANSFER_PARAMETERS,
                 Named.SMPTE_C.ordinal()
         );
         sNamedColorSpaces[Named.ADOBE_RGB.ordinal()] = new ColorSpace.Rgb(
@@ -3057,7 +3062,7 @@
          * primaries for such a ColorSpace does not make sense, so we use a special
          * set of primaries that are all 1s.</p>
          *
-         * @return A new non-null array of 2 floats
+         * @return A new non-null array of 6 floats
          *
          * @see #getPrimaries(float[])
          */
diff --git a/graphics/java/android/graphics/Gainmap.java b/graphics/java/android/graphics/Gainmap.java
index f639521..b5fb13d 100644
--- a/graphics/java/android/graphics/Gainmap.java
+++ b/graphics/java/android/graphics/Gainmap.java
@@ -124,8 +124,6 @@
     /**
      * Creates a new gainmap using the provided gainmap as the metadata source and the provided
      * bitmap as the replacement for the gainmapContents
-     * TODO: Make public, it's useful
-     * @hide
      */
     public Gainmap(@NonNull Gainmap gainmap, @NonNull Bitmap gainmapContents) {
         this(gainmapContents, nCreateCopy(gainmap.mNativePtr));
diff --git a/graphics/java/android/graphics/TEST_MAPPING b/graphics/java/android/graphics/TEST_MAPPING
new file mode 100644
index 0000000..df91222
--- /dev/null
+++ b/graphics/java/android/graphics/TEST_MAPPING
@@ -0,0 +1,21 @@
+{
+  "presubmit": [
+    {
+      "name": "CtsTextTestCases",
+      "options": [
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        },
+        {
+          "exclude-annotation": "androidx.test.filters.LargeTest"
+        }
+      ],
+      "file_patterns": [
+        "Typeface\\.java",
+        "Paint\\.java",
+        "[^/]*Canvas\\.java",
+        "[^/]*Font[^/]*\\.java"
+      ]
+    }
+  ]
+}
diff --git a/graphics/java/android/graphics/fonts/SystemFonts.java b/graphics/java/android/graphics/fonts/SystemFonts.java
index 98629a2..36bfb98 100644
--- a/graphics/java/android/graphics/fonts/SystemFonts.java
+++ b/graphics/java/android/graphics/fonts/SystemFonts.java
@@ -235,6 +235,22 @@
     }
 
     /**
+     * Get the updated FontConfig.
+     *
+     * @param updatableFontMap a font mapping of updated font files.
+     * @hide
+     */
+    public static @NonNull FontConfig getSystemFontConfigForTesting(
+            @NonNull String fontsXml,
+            @Nullable Map<String, File> updatableFontMap,
+            long lastModifiedDate,
+            int configVersion
+    ) {
+        return getSystemFontConfigInternal(fontsXml, SYSTEM_FONT_DIR, OEM_XML, OEM_FONT_DIR,
+                updatableFontMap, lastModifiedDate, configVersion);
+    }
+
+    /**
      * Get the system preinstalled FontConfig.
      * @hide
      */
diff --git a/graphics/java/android/graphics/fonts/TEST_MAPPING b/graphics/java/android/graphics/fonts/TEST_MAPPING
new file mode 100644
index 0000000..99cbfe7
--- /dev/null
+++ b/graphics/java/android/graphics/fonts/TEST_MAPPING
@@ -0,0 +1,15 @@
+{
+  "presubmit": [
+    {
+      "name": "CtsTextTestCases",
+      "options": [
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        },
+        {
+          "exclude-annotation": "androidx.test.filters.LargeTest"
+        }
+      ]
+    }
+  ]
+}
diff --git a/graphics/java/android/graphics/text/TEST_MAPPING b/graphics/java/android/graphics/text/TEST_MAPPING
new file mode 100644
index 0000000..99cbfe7
--- /dev/null
+++ b/graphics/java/android/graphics/text/TEST_MAPPING
@@ -0,0 +1,15 @@
+{
+  "presubmit": [
+    {
+      "name": "CtsTextTestCases",
+      "options": [
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        },
+        {
+          "exclude-annotation": "androidx.test.filters.LargeTest"
+        }
+      ]
+    }
+  ]
+}
diff --git a/keystore/OWNERS b/keystore/OWNERS
index 7ab9d76..913f655 100644
--- a/keystore/OWNERS
+++ b/keystore/OWNERS
@@ -1,4 +1,4 @@
+# Bug component: 189335
 eranm@google.com
 jbires@google.com
-jdanis@google.com
 swillden@google.com
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java
index 25f5dec..b4d8def 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java
@@ -36,6 +36,7 @@
 import android.security.keystore.SecureKeyImportUnavailableException;
 import android.security.keystore.WrappedKeyEntry;
 import android.system.keystore2.AuthenticatorSpec;
+import android.system.keystore2.Authorization;
 import android.system.keystore2.Domain;
 import android.system.keystore2.IKeystoreSecurityLevel;
 import android.system.keystore2.KeyDescriptor;
@@ -966,6 +967,32 @@
             authenticatorSpecs.add(authSpec);
         }
 
+        if (parts.length > 2) {
+            @KeyProperties.EncryptionPaddingEnum int padding =
+                    KeyProperties.EncryptionPadding.toKeymaster(parts[2]);
+            if (padding == KeymasterDefs.KM_PAD_RSA_OAEP
+                    && response.metadata != null
+                    && response.metadata.authorizations != null) {
+                Authorization[] keyCharacteristics = response.metadata.authorizations;
+
+                for (Authorization authorization : keyCharacteristics) {
+                    // Add default MGF1 digest SHA-1
+                    // when wrapping key has KM_TAG_RSA_OAEP_MGF_DIGEST tag
+                    if (authorization.keyParameter.tag
+                            == KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST) {
+                        // Default MGF1 digest is SHA-1
+                        // and KeyMint only supports default MGF1 digest crypto operations
+                        // for importWrappedKey.
+                        args.add(KeyStore2ParameterUtils.makeEnum(
+                                KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST,
+                                KeyProperties.Digest.toKeymaster(DEFAULT_MGF1_DIGEST)
+                        ));
+                        break;
+                    }
+                }
+            }
+        }
+
         try {
             securityLevel.importWrappedKey(
                     wrappedKey, wrappingkey,
diff --git a/keystore/java/android/security/keystore2/KeyStore2ParameterUtils.java b/keystore/java/android/security/keystore2/KeyStore2ParameterUtils.java
index 54955c6..1394bd4 100644
--- a/keystore/java/android/security/keystore2/KeyStore2ParameterUtils.java
+++ b/keystore/java/android/security/keystore2/KeyStore2ParameterUtils.java
@@ -325,32 +325,25 @@
             args.add(KeyStore2ParameterUtils.makeBool(
                     KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED));
         } else {
-            if (spec.getUserAuthenticationValidityDurationSeconds() == 0) {
-                // Every use of this key needs to be authorized by the user.
-                addSids(args, spec);
-                args.add(KeyStore2ParameterUtils.makeEnum(
-                        KeymasterDefs.KM_TAG_USER_AUTH_TYPE, spec.getUserAuthenticationType()
-                ));
-
-                if (spec.isUserAuthenticationValidWhileOnBody()) {
-                    throw new ProviderException(
-                            "Key validity extension while device is on-body is not "
-                                    + "supported for keys requiring fingerprint authentication");
-                }
-            } else {
-                addSids(args, spec);
-                args.add(KeyStore2ParameterUtils.makeEnum(
-                        KeymasterDefs.KM_TAG_USER_AUTH_TYPE, spec.getUserAuthenticationType()
-                ));
+            addSids(args, spec);
+            args.add(KeyStore2ParameterUtils.makeEnum(
+                    KeymasterDefs.KM_TAG_USER_AUTH_TYPE, spec.getUserAuthenticationType()
+            ));
+            if (spec.getUserAuthenticationValidityDurationSeconds() != 0) {
                 args.add(KeyStore2ParameterUtils.makeInt(
                         KeymasterDefs.KM_TAG_AUTH_TIMEOUT,
                         spec.getUserAuthenticationValidityDurationSeconds()
                 ));
-                if (spec.isUserAuthenticationValidWhileOnBody()) {
-                    args.add(KeyStore2ParameterUtils.makeBool(
-                            KeymasterDefs.KM_TAG_ALLOW_WHILE_ON_BODY
-                    ));
+            }
+            if (spec.isUserAuthenticationValidWhileOnBody()) {
+                if (spec.getUserAuthenticationValidityDurationSeconds() == 0) {
+                    throw new ProviderException(
+                            "Key validity extension while device is on-body is not "
+                                    + "supported for keys requiring fingerprint authentication");
                 }
+                args.add(KeyStore2ParameterUtils.makeBool(
+                        KeymasterDefs.KM_TAG_ALLOW_WHILE_ON_BODY
+                ));
             }
         }
     }
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitContainer.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitContainer.java
index 381e9d4..08b7bb8 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitContainer.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitContainer.java
@@ -25,6 +25,7 @@
 import android.window.WindowContainerTransaction;
 
 import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
 import androidx.window.extensions.core.util.function.Function;
 
 /**
@@ -186,10 +187,21 @@
         return (mSplitRule instanceof SplitPlaceholderRule);
     }
 
-    @NonNull
-    SplitInfo toSplitInfo() {
-        return new SplitInfo(mPrimaryContainer.toActivityStack(),
-                mSecondaryContainer.toActivityStack(), mCurrentSplitAttributes, mToken);
+    /**
+     * Returns the SplitInfo representing this container.
+     *
+     * @return the SplitInfo representing this container if the underlying TaskFragmentContainers
+     * are stable, or {@code null} if any TaskFragmentContainer is in an intermediate state.
+     */
+    @Nullable
+    SplitInfo toSplitInfoIfStable() {
+        final ActivityStack primaryActivityStack = mPrimaryContainer.toActivityStackIfStable();
+        final ActivityStack secondaryActivityStack = mSecondaryContainer.toActivityStackIfStable();
+        if (primaryActivityStack == null || secondaryActivityStack == null) {
+            return null;
+        }
+        return new SplitInfo(primaryActivityStack, secondaryActivityStack,
+                mCurrentSplitAttributes, mToken);
     }
 
     static boolean shouldFinishPrimaryWithSecondary(@NonNull SplitRule splitRule) {
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java
index f95f3ff..81384ca 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java
@@ -242,9 +242,20 @@
                 return false;
             }
 
+            // Abort if no space to split.
+            final SplitAttributes calculatedSplitAttributes = mPresenter.computeSplitAttributes(
+                    task.getTaskProperties(), splitPinRule,
+                    splitPinRule.getDefaultSplitAttributes(),
+                    getActivitiesMinDimensionsPair(primaryContainer.getTopNonFinishingActivity(),
+                            topContainer.getTopNonFinishingActivity()));
+            if (!SplitPresenter.shouldShowSplit(calculatedSplitAttributes)) {
+                Log.w(TAG, "No space to split, abort pinning top ActivityStack.");
+                return false;
+            }
+
             // Registers a Split
             final SplitPinContainer splitPinContainer = new SplitPinContainer(primaryContainer,
-                    topContainer, splitPinRule, splitPinRule.getDefaultSplitAttributes());
+                    topContainer, splitPinRule, calculatedSplitAttributes);
             task.addSplitContainer(splitPinContainer);
 
             // Updates the Split
@@ -263,7 +274,33 @@
 
     @Override
     public void unpinTopActivityStack(int taskId){
-        // TODO
+        synchronized (mLock) {
+            final TaskContainer task = getTaskContainer(taskId);
+            if (task == null) {
+                Log.e(TAG, "Cannot find the task to unpin, id: " + taskId);
+                return;
+            }
+
+            final SplitPinContainer splitPinContainer = task.getSplitPinContainer();
+            if (splitPinContainer == null) {
+                Log.e(TAG, "No ActivityStack is pinned.");
+                return;
+            }
+
+            // Remove the SplitPinContainer from the task.
+            final TaskFragmentContainer containerToUnpin =
+                    splitPinContainer.getSecondaryContainer();
+            task.removeSplitPinContainer();
+
+            // Resets the isolated navigation and updates the container.
+            final TransactionRecord transactionRecord = mTransactionManager.startNewTransaction();
+            final WindowContainerTransaction wct = transactionRecord.getTransaction();
+            mPresenter.setTaskFragmentIsolatedNavigation(wct,
+                    containerToUnpin.getTaskFragmentToken(), false /* isolated */);
+            updateContainer(wct, containerToUnpin);
+            transactionRecord.apply(false /* shouldApplyIndependently */);
+            updateCallbackIfNecessary();
+        }
     }
 
     @Override
@@ -831,7 +868,8 @@
             return true;
         }
 
-        if (!isOnReparent && getContainerWithActivity(activity) == null
+        final TaskFragmentContainer container = getContainerWithActivity(activity);
+        if (!isOnReparent && container == null
                 && getTaskFragmentTokenFromActivityClientRecord(activity) != null) {
             // We can't find the new launched activity in any recorded container, but it is
             // currently placed in an embedded TaskFragment. This can happen in two cases:
@@ -843,11 +881,21 @@
             return true;
         }
 
-        final TaskFragmentContainer container = getContainerWithActivity(activity);
-        if (!isOnReparent && container != null
-                && container.getTaskContainer().getTopNonFinishingTaskFragmentContainer()
+        // Skip resolving if the activity is on a pinned TaskFragmentContainer.
+        // TODO(b/243518738): skip resolving for overlay container.
+        if (container != null) {
+            final TaskContainer taskContainer = container.getTaskContainer();
+            if (taskContainer.isTaskFragmentContainerPinned(container)) {
+                return true;
+            }
+        }
+
+        final TaskContainer taskContainer = container != null ? container.getTaskContainer() : null;
+        if (!isOnReparent && taskContainer != null
+                && taskContainer.getTopNonFinishingTaskFragmentContainer(false /* includePin */)
                         != container) {
-            // Do not resolve if the launched activity is not the top-most container in the Task.
+            // Do not resolve if the launched activity is not the top-most container (excludes
+            // the pinned container) in the Task.
             return true;
         }
 
@@ -1244,6 +1292,19 @@
     @GuardedBy("mLock")
     TaskFragmentContainer resolveStartActivityIntent(@NonNull WindowContainerTransaction wct,
             int taskId, @NonNull Intent intent, @Nullable Activity launchingActivity) {
+        // Skip resolving if started from pinned TaskFragmentContainer.
+        // TODO(b/243518738): skip resolving for overlay container.
+        if (launchingActivity != null) {
+            final TaskFragmentContainer taskFragmentContainer = getContainerWithActivity(
+                    launchingActivity);
+            final TaskContainer taskContainer =
+                    taskFragmentContainer != null ? taskFragmentContainer.getTaskContainer() : null;
+            if (taskContainer != null && taskContainer.isTaskFragmentContainerPinned(
+                    taskFragmentContainer)) {
+                return null;
+            }
+        }
+
         /*
          * We will check the following to see if there is any embedding rule matched:
          * 1. Whether the new activity intent should always expand.
@@ -1584,6 +1645,13 @@
             return;
         }
 
+        // If the secondary container is pinned, it should not be removed.
+        final SplitContainer activeContainer =
+                getActiveSplitForContainer(existingSplitContainer.getSecondaryContainer());
+        if (activeContainer instanceof SplitPinContainer) {
+            return;
+        }
+
         existingSplitContainer.getSecondaryContainer().finish(
                 false /* shouldFinishDependent */, mPresenter, wct, this);
     }
@@ -1625,12 +1693,7 @@
             // background.
             return;
         }
-        final SplitContainer splitContainer = getActiveSplitForContainer(container);
-        if (splitContainer instanceof SplitPinContainer
-                && updateSplitContainerIfNeeded(splitContainer, wct, null /* splitAttributes */)) {
-            // A SplitPinContainer exists and is updated.
-            return;
-        }
+
         if (launchPlaceholderIfNecessary(wct, container)) {
             // Placeholder was launched, the positions will be updated when the activity is added
             // to the secondary container.
@@ -1643,6 +1706,7 @@
             // If the info is not available yet the task fragment will be expanded when it's ready
             return;
         }
+        final SplitContainer splitContainer = getActiveSplitForContainer(container);
         if (splitContainer == null) {
             return;
         }
@@ -1826,6 +1890,10 @@
             // Don't launch placeholder for primary split container.
             return false;
         }
+        if (splitContainer instanceof SplitPinContainer) {
+            // Don't launch placeholder if pinned
+            return false;
+        }
         return true;
     }
 
@@ -1908,8 +1976,8 @@
         if (mEmbeddingCallback == null || !readyToReportToClient()) {
             return;
         }
-        final List<SplitInfo> currentSplitStates = getActiveSplitStates();
-        if (mLastReportedSplitStates.equals(currentSplitStates)) {
+        final List<SplitInfo> currentSplitStates = getActiveSplitStatesIfStable();
+        if (currentSplitStates == null || mLastReportedSplitStates.equals(currentSplitStates)) {
             return;
         }
         mLastReportedSplitStates.clear();
@@ -1919,13 +1987,21 @@
 
     /**
      * Returns a list of descriptors for currently active split states.
+     *
+     * @return a list of descriptors for currently active split states if all the containers are in
+     * a stable state, or {@code null} otherwise.
      */
     @GuardedBy("mLock")
-    @NonNull
-    private List<SplitInfo> getActiveSplitStates() {
+    @Nullable
+    private List<SplitInfo> getActiveSplitStatesIfStable() {
         final List<SplitInfo> splitStates = new ArrayList<>();
         for (int i = mTaskContainers.size() - 1; i >= 0; i--) {
-            mTaskContainers.valueAt(i).getSplitStates(splitStates);
+            final List<SplitInfo> taskSplitStates =
+                    mTaskContainers.valueAt(i).getSplitStatesIfStable();
+            if (taskSplitStates == null) {
+                return null;
+            }
+            splitStates.addAll(taskSplitStates);
         }
         return splitStates;
     }
@@ -2072,8 +2148,9 @@
      * Returns {@code true} if an Activity with the provided component name should always be
      * expanded to occupy full task bounds. Such activity must not be put in a split.
      */
+    @VisibleForTesting
     @GuardedBy("mLock")
-    private boolean shouldExpand(@Nullable Activity activity, @Nullable Intent intent) {
+    boolean shouldExpand(@Nullable Activity activity, @Nullable Intent intent) {
         for (EmbeddingRule rule : mSplitRules) {
             if (!(rule instanceof ActivityRule)) {
                 continue;
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskContainer.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskContainer.java
index 969e3ed..9a0769a 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskContainer.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskContainer.java
@@ -179,8 +179,16 @@
 
     @Nullable
     TaskFragmentContainer getTopNonFinishingTaskFragmentContainer() {
+        return getTopNonFinishingTaskFragmentContainer(true /* includePin */);
+    }
+
+    @Nullable
+    TaskFragmentContainer getTopNonFinishingTaskFragmentContainer(boolean includePin) {
         for (int i = mContainers.size() - 1; i >= 0; i--) {
             final TaskFragmentContainer container = mContainers.get(i);
+            if (!includePin && isTaskFragmentContainerPinned(container)) {
+                continue;
+            }
             if (!container.isFinished()) {
                 return container;
             }
@@ -257,8 +265,25 @@
     }
 
     void removeSplitPinContainer() {
+        if (mSplitPinContainer == null) {
+            return;
+        }
+
+        final TaskFragmentContainer primaryContainer = mSplitPinContainer.getPrimaryContainer();
+        final TaskFragmentContainer secondaryContainer = mSplitPinContainer.getSecondaryContainer();
         mSplitContainers.remove(mSplitPinContainer);
         mSplitPinContainer = null;
+
+        // Remove the other SplitContainers that contains the unpinned container (unless it
+        // is the current top-most split-pair), since the state are no longer valid.
+        final List<SplitContainer> splitsToRemove = new ArrayList<>();
+        for (SplitContainer splitContainer : mSplitContainers) {
+            if (splitContainer.getSecondaryContainer().equals(secondaryContainer)
+                    && !splitContainer.getPrimaryContainer().equals(primaryContainer)) {
+                splitsToRemove.add(splitContainer);
+            }
+        }
+        removeSplitContainers(splitsToRemove);
     }
 
     @Nullable
@@ -266,6 +291,11 @@
         return mSplitPinContainer;
     }
 
+    boolean isTaskFragmentContainerPinned(@NonNull TaskFragmentContainer taskFragmentContainer) {
+        return mSplitPinContainer != null
+                && mSplitPinContainer.getSecondaryContainer() == taskFragmentContainer;
+    }
+
     void addTaskFragmentContainer(@NonNull TaskFragmentContainer taskFragmentContainer) {
         mContainers.add(taskFragmentContainer);
         onTaskFragmentContainerUpdated();
@@ -329,11 +359,23 @@
         }
     }
 
-    /** Adds the descriptors of split states in this Task to {@code outSplitStates}. */
-    void getSplitStates(@NonNull List<SplitInfo> outSplitStates) {
+    /**
+     * Gets the descriptors of split states in this Task.
+     *
+     * @return a list of {@code SplitInfo} if all the SplitContainers are stable, or {@code null} if
+     * any SplitContainer is in an intermediate state.
+     */
+    @Nullable
+    List<SplitInfo> getSplitStatesIfStable() {
+        final List<SplitInfo> splitStates = new ArrayList<>();
         for (SplitContainer container : mSplitContainers) {
-            outSplitStates.add(container.toSplitInfo());
+            final SplitInfo splitInfo = container.toSplitInfoIfStable();
+            if (splitInfo == null) {
+                return null;
+            }
+            splitStates.add(splitInfo);
         }
+        return splitStates;
     }
 
     /** A wrapper class which contains the information of {@link TaskContainer} */
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java
index 61df335..0a694b5 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java
@@ -217,6 +217,30 @@
     /** List of non-finishing activities that belong to this container and live in this process. */
     @NonNull
     List<Activity> collectNonFinishingActivities() {
+        final List<Activity> activities = collectNonFinishingActivities(false /* checkIfStable */);
+        if (activities == null) {
+            throw new IllegalStateException(
+                    "Result activities should never be null when checkIfstable is false.");
+        }
+        return activities;
+    }
+
+    /**
+     * Collects non-finishing activities that belong to this container and live in this process.
+     *
+     * @param checkIfStable if {@code true}, returns {@code null} when the container is in an
+     *                      intermediate state.
+     * @return List of non-finishing activities that belong to this container and live in this
+     * process, {@code null} if checkIfStable is {@code true} and the container is in an
+     * intermediate state.
+     */
+    @Nullable
+    List<Activity> collectNonFinishingActivities(boolean checkIfStable) {
+        if (checkIfStable
+                && (mInfo == null || mInfo.isEmpty() || !mPendingAppearedActivities.isEmpty())) {
+            return null;
+        }
+
         final List<Activity> allActivities = new ArrayList<>();
         if (mInfo != null) {
             // Add activities reported from the server.
@@ -224,6 +248,15 @@
                 final Activity activity = mController.getActivity(token);
                 if (activity != null && !activity.isFinishing()) {
                     allActivities.add(activity);
+                } else {
+                    if (checkIfStable) {
+                        // Return null except for a special case when the activity is started in
+                        // background.
+                        if (activity == null && !mTaskContainer.isVisible()) {
+                            continue;
+                        }
+                        return null;
+                    }
                 }
             }
         }
@@ -277,9 +310,19 @@
         return false;
     }
 
-    @NonNull
-    ActivityStack toActivityStack() {
-        return new ActivityStack(collectNonFinishingActivities(), isEmpty(), mToken);
+    /**
+     * Returns the ActivityStack representing this container.
+     *
+     * @return ActivityStack representing this container if it is in a stable state. {@code null} if
+     * in an intermediate state.
+     */
+    @Nullable
+    ActivityStack toActivityStackIfStable() {
+        final List<Activity> activities = collectNonFinishingActivities(true /* checkIfStable */);
+        if (activities == null) {
+            return null;
+        }
+        return new ActivityStack(activities, isEmpty(), mToken);
     }
 
     /** Adds the activity that will be reparented to this container. */
diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java
index 9af1fe91..d440a3e 100644
--- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java
+++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java
@@ -595,6 +595,18 @@
     }
 
     @Test
+    public void testResolveStartActivityIntent_skipIfPinned() {
+        final TaskFragmentContainer container = createMockTaskFragmentContainer(mActivity);
+        final TaskContainer taskContainer = container.getTaskContainer();
+        spyOn(taskContainer);
+        final Intent intent = new Intent();
+        setupSplitRule(mActivity, intent);
+        doReturn(true).when(taskContainer).isTaskFragmentContainerPinned(container);
+        assertNull(mSplitController.resolveStartActivityIntent(mTransaction, TASK_ID, intent,
+                mActivity));
+    }
+
+    @Test
     public void testPlaceActivityInTopContainer() {
         mSplitController.placeActivityInTopContainer(mTransaction, mActivity);
 
@@ -1044,6 +1056,29 @@
     }
 
     @Test
+    public void testResolveActivityToContainer_skipIfNonTopOrPinned() {
+        final TaskFragmentContainer container = createMockTaskFragmentContainer(mActivity);
+        final Activity pinnedActivity = createMockActivity();
+        final TaskFragmentContainer topContainer = mSplitController.newContainer(pinnedActivity,
+                TASK_ID);
+        final TaskContainer taskContainer = container.getTaskContainer();
+        spyOn(taskContainer);
+        doReturn(container).when(taskContainer).getTopNonFinishingTaskFragmentContainer(false);
+        doReturn(true).when(taskContainer).isTaskFragmentContainerPinned(topContainer);
+
+        // No need to handle when the new launched activity is in a pinned TaskFragment.
+        assertTrue(mSplitController.resolveActivityToContainer(mTransaction, pinnedActivity,
+                false /* isOnReparent */));
+        verify(mSplitController, never()).shouldExpand(any(), any());
+
+        // Should proceed to resolve if the new launched activity is in the next top TaskFragment
+        // (e.g. the top-most TaskFragment is pinned)
+        mSplitController.resolveActivityToContainer(mTransaction, mActivity,
+                false /* isOnReparent */);
+        verify(mSplitController).shouldExpand(any(), any());
+    }
+
+    @Test
     public void testGetPlaceholderOptions() {
         // Setup to make sure a transaction record is started.
         mTransactionManager.startNewTransaction();
@@ -1251,6 +1286,34 @@
     }
 
     @Test
+    public void testSplitInfoCallback_NotReportSplitIfUnstable() {
+        final Activity r0 = createMockActivity();
+        final Activity r1 = createMockActivity();
+        addSplitTaskFragments(r0, r1);
+
+        // Should report new SplitInfo list if stable.
+        mSplitController.updateCallbackIfNecessary();
+        assertEquals(1, mSplitInfos.size());
+
+        // Should not report new SplitInfo list if unstable, e.g. any Activity is finishing.
+        mSplitInfos.clear();
+        final Activity r2 = createMockActivity();
+        final Activity r3 = createMockActivity();
+        doReturn(true).when(r2).isFinishing();
+        addSplitTaskFragments(r2, r3);
+
+        mSplitController.updateCallbackIfNecessary();
+        assertTrue(mSplitInfos.isEmpty());
+
+        // Should report SplitInfo list if it becomes stable again.
+        mSplitInfos.clear();
+        doReturn(false).when(r2).isFinishing();
+
+        mSplitController.updateCallbackIfNecessary();
+        assertEquals(2, mSplitInfos.size());
+    }
+
+    @Test
     public void testSplitInfoCallback_reportSplitInMultipleTasks() {
         final int taskId0 = 1;
         final int taskId1 = 2;
diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java
index 000c65a..2188996 100644
--- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java
+++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java
@@ -48,6 +48,8 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
+import java.util.List;
+
 /**
  * Test class for {@link TaskContainer}.
  *
@@ -165,4 +167,35 @@
         doReturn(activity1).when(tf1).getTopNonFinishingActivity();
         assertEquals(activity1, taskContainer.getTopNonFinishingActivity());
     }
+
+    @Test
+    public void testGetSplitStatesIfStable() {
+        final TaskContainer taskContainer = createTestTaskContainer();
+
+        final SplitContainer splitContainer0 = mock(SplitContainer.class);
+        final SplitContainer splitContainer1 = mock(SplitContainer.class);
+        final SplitInfo splitInfo0 = mock(SplitInfo.class);
+        final SplitInfo splitInfo1 = mock(SplitInfo.class);
+        taskContainer.addSplitContainer(splitContainer0);
+        taskContainer.addSplitContainer(splitContainer1);
+
+        // When all the SplitContainers are stable, getSplitStatesIfStable() returns the list of
+        // SplitInfo representing the SplitContainers.
+        doReturn(splitInfo0).when(splitContainer0).toSplitInfoIfStable();
+        doReturn(splitInfo1).when(splitContainer1).toSplitInfoIfStable();
+
+        List<SplitInfo> splitInfoList = taskContainer.getSplitStatesIfStable();
+
+        assertEquals(2, splitInfoList.size());
+        assertEquals(splitInfo0, splitInfoList.get(0));
+        assertEquals(splitInfo1, splitInfoList.get(1));
+
+        // When any SplitContainer is in an intermediate state, getSplitStatesIfStable() returns
+        // null.
+        doReturn(null).when(splitContainer0).toSplitInfoIfStable();
+
+        splitInfoList = taskContainer.getSplitStatesIfStable();
+
+        assertNull(splitInfoList);
+    }
 }
diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java
index 78b85e6..cc00a49 100644
--- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java
+++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java
@@ -321,6 +321,32 @@
     }
 
     @Test
+    public void testCollectNonFinishingActivities_checkIfStable() {
+        final TaskContainer taskContainer = createTestTaskContainer();
+        final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */,
+                mIntent, taskContainer, mController, null /* pairedPrimaryContainer */);
+
+        // In case mInfo is null, collectNonFinishingActivities(true) should return null.
+        List<Activity> activities =
+                container.collectNonFinishingActivities(true /* checkIfStable */);
+        assertNull(activities);
+
+        // collectNonFinishingActivities(true) should return proper value when the container is in a
+        // stable state.
+        final List<IBinder> runningActivities = Lists.newArrayList(mActivity.getActivityToken());
+        doReturn(runningActivities).when(mInfo).getActivities();
+        container.setInfo(mTransaction, mInfo);
+        activities = container.collectNonFinishingActivities(true /* checkIfStable */);
+        assertEquals(1, activities.size());
+
+        // In case any activity is finishing, collectNonFinishingActivities(true) should return
+        // null.
+        doReturn(true).when(mActivity).isFinishing();
+        activities = container.collectNonFinishingActivities(true /* checkIfStable */);
+        assertNull(activities);
+    }
+
+    @Test
     public void testAddPendingActivity() {
         final TaskContainer taskContainer = createTestTaskContainer();
         final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */,
diff --git a/libs/WindowManager/Shell/res/drawable/user_aspect_ratio_settings_button.xml b/libs/WindowManager/Shell/res/drawable/user_aspect_ratio_settings_button.xml
new file mode 100644
index 0000000..6e4752c
--- /dev/null
+++ b/libs/WindowManager/Shell/res/drawable/user_aspect_ratio_settings_button.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2023 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT 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="48dp"
+        android:height="48dp"
+        android:viewportWidth="48"
+        android:viewportHeight="48">
+    <path
+        android:fillColor="@color/compat_controls_background"
+        android:strokeAlpha="0.8"
+        android:fillAlpha="0.8"
+        android:pathData="M0,24 a24,24 0 1,0 48,0 a24,24 0 1,0 -48,0"/>
+    <group
+        android:translateX="12"
+        android:translateY="12">
+        <path
+            android:fillColor="@color/compat_controls_text"
+            android:pathData="M19,12h-2v3h-3v2h5v-5zM7,9h3L10,7L5,7v5h2L7,9zM21,3L3,3c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h18c1.1,0 2,-0.9 2,-2L23,5c0,-1.1 -0.9,-2 -2,-2zM21,19.01L3,19.01L3,4.99h18v14.02z"/>
+    </group>
+</vector>
diff --git a/libs/WindowManager/Shell/res/drawable/user_aspect_ratio_settings_button_ripple.xml b/libs/WindowManager/Shell/res/drawable/user_aspect_ratio_settings_button_ripple.xml
new file mode 100644
index 0000000..141a1ce
--- /dev/null
+++ b/libs/WindowManager/Shell/res/drawable/user_aspect_ratio_settings_button_ripple.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2023 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT 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="@color/compat_background_ripple">
+    <item android:drawable="@drawable/user_aspect_ratio_settings_button"/>
+</ripple>
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/res/layout/compat_ui_layout.xml b/libs/WindowManager/Shell/res/layout/compat_ui_layout.xml
index dfaeeeb..257fe15 100644
--- a/libs/WindowManager/Shell/res/layout/compat_ui_layout.xml
+++ b/libs/WindowManager/Shell/res/layout/compat_ui_layout.xml
@@ -55,7 +55,7 @@
 
     <include android:id="@+id/size_compat_hint"
         android:visibility="gone"
-        android:layout_width="@dimen/size_compat_hint_width"
+        android:layout_width="@dimen/compat_hint_width"
         android:layout_height="wrap_content"
         layout="@layout/compat_mode_hint"/>
 
diff --git a/libs/WindowManager/Shell/res/layout/user_aspect_ratio_settings_layout.xml b/libs/WindowManager/Shell/res/layout/user_aspect_ratio_settings_layout.xml
new file mode 100644
index 0000000..433d854
--- /dev/null
+++ b/libs/WindowManager/Shell/res/layout/user_aspect_ratio_settings_layout.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2023 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT 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.wm.shell.compatui.UserAspectRatioSettingsLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:orientation="vertical"
+    android:gravity="bottom|end">
+
+    <include android:id="@+id/user_aspect_ratio_settings_hint"
+        android:visibility="gone"
+        android:layout_width="@dimen/compat_hint_width"
+        android:layout_height="wrap_content"
+        layout="@layout/compat_mode_hint"/>
+
+    <ImageButton
+        android:id="@+id/user_aspect_ratio_settings_button"
+        android:visibility="gone"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginEnd="@dimen/compat_button_margin"
+        android:layout_marginBottom="@dimen/compat_button_margin"
+        android:src="@drawable/user_aspect_ratio_settings_button_ripple"
+        android:background="@android:color/transparent"
+        android:contentDescription="@string/user_aspect_ratio_settings_button_description"/>
+
+</com.android.wm.shell.compatui.UserAspectRatioSettingsLayout>
diff --git a/libs/WindowManager/Shell/res/values/dimen.xml b/libs/WindowManager/Shell/res/values/dimen.xml
index ac73e1d..597e899d 100644
--- a/libs/WindowManager/Shell/res/values/dimen.xml
+++ b/libs/WindowManager/Shell/res/values/dimen.xml
@@ -260,8 +260,8 @@
         + compat_button_margin - compat_hint_corner_radius - compat_hint_point_width / 2). -->
     <dimen name="compat_hint_padding_end">7dp</dimen>
 
-    <!-- The width of the size compat hint. -->
-    <dimen name="size_compat_hint_width">188dp</dimen>
+    <!-- The width of the compat hint. -->
+    <dimen name="compat_hint_width">188dp</dimen>
 
     <!-- The width of the camera compat hint. -->
     <dimen name="camera_compat_hint_width">143dp</dimen>
diff --git a/libs/WindowManager/Shell/res/values/strings.xml b/libs/WindowManager/Shell/res/values/strings.xml
index b192fdf..8cbc3d0 100644
--- a/libs/WindowManager/Shell/res/values/strings.xml
+++ b/libs/WindowManager/Shell/res/values/strings.xml
@@ -173,7 +173,13 @@
     <string name="accessibility_bubble_dismissed">Bubble dismissed.</string>
 
     <!-- Description of the restart button in the hint of size compatibility mode. [CHAR LIMIT=NONE] -->
-    <string name="restart_button_description">Tap to restart this app for a better view.</string>
+    <string name="restart_button_description">Tap to restart this app for a better view</string>
+
+    <!-- Tooltip text of the button for the user aspect ratio settings. [CHAR LIMIT=NONE] -->
+    <string name="user_aspect_ratio_settings_button_hint">Change this app\'s aspect ratio in Settings</string>
+
+    <!-- Content description of the button for the user aspect ratio settings. [CHAR LIMIT=NONE] -->
+    <string name="user_aspect_ratio_settings_button_description">Change aspect ratio</string>
 
     <!-- Description of the camera compat button for applying stretched issues treatment in the hint for
          compatibility control. [CHAR LIMIT=NONE] -->
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingController.java
index 57d374b..06ce371 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingController.java
@@ -186,6 +186,6 @@
         if (callback == null) {
             throw new IllegalStateException("No finish callback found");
         }
-        callback.onTransitionFinished(null /* wct */, null /* wctCB */);
+        callback.onTransitionFinished(null /* wct */);
     }
 }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationBackground.java b/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationBackground.java
index 9bf3b80..42dc19c 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationBackground.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationBackground.java
@@ -52,12 +52,13 @@
 
     /**
      * Ensures the back animation background color layer is present.
+     *
      * @param startRect The start bounds of the closing target.
      * @param color The background color.
      * @param transaction The animation transaction.
      */
-    void ensureBackground(Rect startRect, int color,
-            @NonNull SurfaceControl.Transaction transaction) {
+    public void ensureBackground(
+            Rect startRect, int color, @NonNull SurfaceControl.Transaction transaction) {
         if (mBackgroundSurface != null) {
             return;
         }
@@ -81,7 +82,12 @@
         mIsRequestingStatusBarAppearance = false;
     }
 
-    void removeBackground(@NonNull SurfaceControl.Transaction transaction) {
+    /**
+     * Remove the back animation background.
+     *
+     * @param transaction The animation transaction.
+     */
+    public void removeBackground(@NonNull SurfaceControl.Transaction transaction) {
         if (mBackgroundSurface == null) {
             return;
         }
@@ -93,11 +99,21 @@
         mIsRequestingStatusBarAppearance = false;
     }
 
+    /**
+     * Attach a {@link StatusBarCustomizer} instance to allow status bar animate with back progress.
+     *
+     * @param customizer The {@link StatusBarCustomizer} to be used.
+     */
     void setStatusBarCustomizer(StatusBarCustomizer customizer) {
         mCustomizer = customizer;
     }
 
-    void onBackProgressed(float progress) {
+    /**
+     * Update back animation background with for the progress.
+     *
+     * @param progress Progress value from {@link android.window.BackProgressAnimator}
+     */
+    public void onBackProgressed(float progress) {
         if (mCustomizer == null || mStartBounds.isEmpty()) {
             return;
         }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationController.java
index bb543f2..3790f04 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationController.java
@@ -25,6 +25,7 @@
 import android.animation.ValueAnimator;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.annotation.SuppressLint;
 import android.app.ActivityTaskManager;
 import android.app.IActivityTaskManager;
 import android.content.ContentResolver;
@@ -43,7 +44,6 @@
 import android.util.DisplayMetrics;
 import android.util.Log;
 import android.util.MathUtils;
-import android.util.SparseArray;
 import android.view.IRemoteAnimationRunner;
 import android.view.InputDevice;
 import android.view.KeyCharacterMap;
@@ -70,6 +70,7 @@
 import com.android.wm.shell.sysui.ShellController;
 import com.android.wm.shell.sysui.ShellInit;
 
+
 import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
@@ -113,7 +114,11 @@
     private boolean mShouldStartOnNextMoveEvent = false;
     /** @see #setTriggerBack(boolean) */
     private boolean mTriggerBack;
-    private FlingAnimationUtils mFlingAnimationUtils;
+
+    private final FlingAnimationUtils mFlingAnimationUtils;
+
+    /** Registry for the back animations */
+    private final ShellBackAnimationRegistry mShellBackAnimationRegistry;
 
     @Nullable
     private BackNavigationInfo mBackNavigationInfo;
@@ -135,13 +140,9 @@
 
     private final TouchTracker mTouchTracker = new TouchTracker();
 
-    private final SparseArray<BackAnimationRunner> mAnimationDefinition = new SparseArray<>();
     @Nullable
     private IOnBackInvokedCallback mActiveCallback;
 
-    private CrossActivityAnimation mDefaultActivityAnimation;
-    private CustomizeActivityAnimation mCustomizeActivityAnimation;
-
     @VisibleForTesting
     final RemoteCallback mNavigationObserver = new RemoteCallback(
             new RemoteCallback.OnResultListener() {
@@ -169,10 +170,18 @@
             @NonNull @ShellMainThread ShellExecutor shellExecutor,
             @NonNull @ShellBackgroundThread Handler backgroundHandler,
             Context context,
-            @NonNull BackAnimationBackground backAnimationBackground) {
-        this(shellInit, shellController, shellExecutor, backgroundHandler,
-                ActivityTaskManager.getService(), context, context.getContentResolver(),
-                backAnimationBackground);
+            @NonNull BackAnimationBackground backAnimationBackground,
+            ShellBackAnimationRegistry shellBackAnimationRegistry) {
+        this(
+                shellInit,
+                shellController,
+                shellExecutor,
+                backgroundHandler,
+                ActivityTaskManager.getService(),
+                context,
+                context.getContentResolver(),
+                backAnimationBackground,
+                shellBackAnimationRegistry);
     }
 
     @VisibleForTesting
@@ -182,8 +191,10 @@
             @NonNull @ShellMainThread ShellExecutor shellExecutor,
             @NonNull @ShellBackgroundThread Handler bgHandler,
             @NonNull IActivityTaskManager activityTaskManager,
-            Context context, ContentResolver contentResolver,
-            @NonNull BackAnimationBackground backAnimationBackground) {
+            Context context,
+            ContentResolver contentResolver,
+            @NonNull BackAnimationBackground backAnimationBackground,
+            ShellBackAnimationRegistry shellBackAnimationRegistry) {
         mShellController = shellController;
         mShellExecutor = shellExecutor;
         mActivityTaskManager = activityTaskManager;
@@ -197,11 +208,7 @@
                 .setMaxLengthSeconds(FLING_MAX_LENGTH_SECONDS)
                 .setSpeedUpFactor(FLING_SPEED_UP_FACTOR)
                 .build();
-    }
-
-    @VisibleForTesting
-    void setEnableUAnimation(boolean enable) {
-        IS_U_ANIMATION_ENABLED = enable;
+        mShellBackAnimationRegistry = shellBackAnimationRegistry;
     }
 
     private void onInit() {
@@ -209,26 +216,6 @@
         createAdapter();
         mShellController.addExternalInterface(KEY_EXTRA_SHELL_BACK_ANIMATION,
                 this::createExternalInterface, this);
-
-        initBackAnimationRunners();
-    }
-
-    private void initBackAnimationRunners() {
-        if (!IS_U_ANIMATION_ENABLED) {
-            return;
-        }
-
-        final CrossTaskBackAnimation crossTaskAnimation =
-                new CrossTaskBackAnimation(mContext, mAnimationBackground);
-        mAnimationDefinition.set(BackNavigationInfo.TYPE_CROSS_TASK,
-                crossTaskAnimation.mBackAnimationRunner);
-        mDefaultActivityAnimation =
-                new CrossActivityAnimation(mContext, mAnimationBackground);
-        mAnimationDefinition.set(BackNavigationInfo.TYPE_CROSS_ACTIVITY,
-                mDefaultActivityAnimation.mBackAnimationRunner);
-        mCustomizeActivityAnimation =
-                new CustomizeActivityAnimation(mContext, mAnimationBackground);
-        // TODO (236760237): register dialog close animation when it's completed.
     }
 
     private void setupAnimationDeveloperSettingsObserver(
@@ -359,11 +346,11 @@
 
     void registerAnimation(@BackNavigationInfo.BackTargetType int type,
             @NonNull BackAnimationRunner runner) {
-        mAnimationDefinition.set(type, runner);
+        mShellBackAnimationRegistry.registerAnimation(type, runner);
     }
 
     void unregisterAnimation(@BackNavigationInfo.BackTargetType int type) {
-        mAnimationDefinition.remove(type);
+        mShellBackAnimationRegistry.unregisterAnimation(type);
     }
 
     /**
@@ -434,9 +421,7 @@
         final int backType = backNavigationInfo.getType();
         final boolean shouldDispatchToAnimator = shouldDispatchToAnimator();
         if (shouldDispatchToAnimator) {
-            if (mAnimationDefinition.contains(backType)) {
-                mAnimationDefinition.get(backType).startGesture();
-            } else {
+            if (!mShellBackAnimationRegistry.startGesture(backType)) {
                 mActiveCallback = null;
             }
         } else {
@@ -459,6 +444,7 @@
         sendBackEvent(KeyEvent.ACTION_UP);
     }
 
+    @SuppressLint("MissingPermission")
     private void sendBackEvent(int action) {
         final long when = SystemClock.uptimeMillis();
         final KeyEvent ev = new KeyEvent(when, when, action, KeyEvent.KEYCODE_BACK, 0 /* repeat */,
@@ -671,21 +657,17 @@
         }
 
         final int backType = mBackNavigationInfo.getType();
-        final BackAnimationRunner runner = mAnimationDefinition.get(backType);
         // Simply trigger and finish back navigation when no animator defined.
-        if (!shouldDispatchToAnimator() || runner == null) {
+        if (!shouldDispatchToAnimator()
+                || mShellBackAnimationRegistry.isAnimationCancelledOrNull(backType)) {
             invokeOrCancelBack();
             return;
-        }
-        if (runner.isWaitingAnimation()) {
+        } else if (mShellBackAnimationRegistry.isWaitingAnimation(backType)) {
             ProtoLog.w(WM_SHELL_BACK_PREVIEW, "Gesture released, but animation didn't ready.");
             // Supposed it is in post commit animation state, and start the timeout to watch
             // if the animation is ready.
             mShellExecutor.executeDelayed(mAnimationTimeoutRunnable, MAX_ANIMATION_DURATION);
             return;
-        } else if (runner.isAnimationCancelled()) {
-            invokeOrCancelBack();
-            return;
         }
         startPostCommitAnimation();
     }
@@ -737,12 +719,7 @@
         mShouldStartOnNextMoveEvent = false;
         mTouchTracker.reset();
         mActiveCallback = null;
-        // reset to default
-        if (mDefaultActivityAnimation != null
-                && mAnimationDefinition.contains(BackNavigationInfo.TYPE_CROSS_ACTIVITY)) {
-            mAnimationDefinition.set(BackNavigationInfo.TYPE_CROSS_ACTIVITY,
-                    mDefaultActivityAnimation.mBackAnimationRunner);
-        }
+        mShellBackAnimationRegistry.resetDefaultCrossActivity();
         if (mBackNavigationInfo != null) {
             mBackNavigationInfo.onBackNavigationFinished(mTriggerBack);
             mBackNavigationInfo = null;
@@ -750,86 +727,88 @@
         mTriggerBack = false;
     }
 
-    private BackAnimationRunner getAnimationRunnerAndInit() {
-        int type = mBackNavigationInfo.getType();
-        // Initiate customized cross-activity animation, or fall back to cross activity animation
-        if (type == BackNavigationInfo.TYPE_CROSS_ACTIVITY && mAnimationDefinition.contains(type)) {
-            final BackNavigationInfo.CustomAnimationInfo animationInfo =
-                    mBackNavigationInfo.getCustomAnimationInfo();
-            if (animationInfo != null && mCustomizeActivityAnimation != null
-                    && mCustomizeActivityAnimation.prepareNextAnimation(animationInfo)) {
-                mAnimationDefinition.get(type).resetWaitingAnimation();
-                mAnimationDefinition.set(BackNavigationInfo.TYPE_CROSS_ACTIVITY,
-                        mCustomizeActivityAnimation.mBackAnimationRunner);
-            }
-        }
-        return mAnimationDefinition.get(type);
-    }
 
     private void createAdapter() {
-        IBackAnimationRunner runner = new IBackAnimationRunner.Stub() {
-            @Override
-            public void onAnimationStart(RemoteAnimationTarget[] apps,
-                    RemoteAnimationTarget[] wallpapers, RemoteAnimationTarget[] nonApps,
-                    IBackAnimationFinishedCallback finishedCallback) {
-                mShellExecutor.execute(() -> {
-                    if (mBackNavigationInfo == null) {
-                        Log.e(TAG, "Lack of navigation info to start animation.");
-                        return;
-                    }
-                    final int type = mBackNavigationInfo.getType();
-                    final BackAnimationRunner runner = getAnimationRunnerAndInit();
-                    if (runner == null) {
-                        Log.e(TAG, "Animation didn't be defined for type "
-                                + BackNavigationInfo.typeToString(type));
-                        if (finishedCallback != null) {
-                            try {
-                                finishedCallback.onAnimationFinished(false);
-                            } catch (RemoteException e) {
-                                Log.w(TAG, "Failed call IBackNaviAnimationController", e);
-                            }
-                        }
-                        return;
-                    }
-                    mActiveCallback = runner.getCallback();
-                    mBackAnimationFinishedCallback = finishedCallback;
+        IBackAnimationRunner runner =
+                new IBackAnimationRunner.Stub() {
+                    @Override
+                    public void onAnimationStart(
+                            RemoteAnimationTarget[] apps,
+                            RemoteAnimationTarget[] wallpapers,
+                            RemoteAnimationTarget[] nonApps,
+                            IBackAnimationFinishedCallback finishedCallback) {
+                        mShellExecutor.execute(
+                                () -> {
+                                    if (mBackNavigationInfo == null) {
+                                        Log.e(TAG, "Lack of navigation info to start animation.");
+                                        return;
+                                    }
+                                    final BackAnimationRunner runner =
+                                            mShellBackAnimationRegistry.getAnimationRunnerAndInit(
+                                                    mBackNavigationInfo);
+                                    if (runner == null) {
+                                        if (finishedCallback != null) {
+                                            try {
+                                                finishedCallback.onAnimationFinished(false);
+                                            } catch (RemoteException e) {
+                                                Log.w(
+                                                        TAG,
+                                                        "Failed call IBackNaviAnimationController",
+                                                        e);
+                                            }
+                                        }
+                                        return;
+                                    }
+                                    mActiveCallback = runner.getCallback();
+                                    mBackAnimationFinishedCallback = finishedCallback;
 
-                    ProtoLog.d(WM_SHELL_BACK_PREVIEW, "BackAnimationController: startAnimation()");
-                    runner.startAnimation(apps, wallpapers, nonApps, () -> mShellExecutor.execute(
-                            BackAnimationController.this::onBackAnimationFinished));
+                                    ProtoLog.d(
+                                            WM_SHELL_BACK_PREVIEW,
+                                            "BackAnimationController: startAnimation()");
+                                    runner.startAnimation(
+                                            apps,
+                                            wallpapers,
+                                            nonApps,
+                                            () ->
+                                                    mShellExecutor.execute(
+                                                            BackAnimationController.this
+                                                                    ::onBackAnimationFinished));
 
-                    if (apps.length >= 1) {
-                        dispatchOnBackStarted(
-                                mActiveCallback, mTouchTracker.createStartEvent(apps[0]));
+                                    if (apps.length >= 1) {
+                                        dispatchOnBackStarted(
+                                                mActiveCallback,
+                                                mTouchTracker.createStartEvent(apps[0]));
+                                    }
+
+                                    // Dispatch the first progress after animation start for
+                                    // smoothing the initial animation, instead of waiting for next
+                                    // onMove.
+                                    final BackMotionEvent backFinish =
+                                            mTouchTracker.createProgressEvent();
+                                    dispatchOnBackProgressed(mActiveCallback, backFinish);
+                                    if (!mBackGestureStarted) {
+                                        // if the down -> up gesture happened before animation
+                                        // start, we have to trigger the uninterruptible transition
+                                        // to finish the back animation.
+                                        startPostCommitAnimation();
+                                    }
+                                });
                     }
 
-                    // Dispatch the first progress after animation start for smoothing the initial
-                    // animation, instead of waiting for next onMove.
-                    final BackMotionEvent backFinish = mTouchTracker.createProgressEvent();
-                    dispatchOnBackProgressed(mActiveCallback, backFinish);
-                    if (!mBackGestureStarted) {
-                        // if the down -> up gesture happened before animation start, we have to
-                        // trigger the uninterruptible transition to finish the back animation.
-                        startPostCommitAnimation();
+                    @Override
+                    public void onAnimationCancelled() {
+                        mShellExecutor.execute(
+                                () -> {
+                                    if (!mShellBackAnimationRegistry.cancel(
+                                            mBackNavigationInfo.getType())) {
+                                        return;
+                                    }
+                                    if (!mBackGestureStarted) {
+                                        invokeOrCancelBack();
+                                    }
+                                });
                     }
-                });
-            }
-
-            @Override
-            public void onAnimationCancelled() {
-                mShellExecutor.execute(() -> {
-                    final BackAnimationRunner runner = mAnimationDefinition.get(
-                            mBackNavigationInfo.getType());
-                    if (runner == null) {
-                        return;
-                    }
-                    runner.cancelAnimation();
-                    if (!mBackGestureStarted) {
-                        invokeOrCancelBack();
-                    }
-                });
-            }
-        };
+                };
         mBackAnimationAdapter = new BackAnimationAdapter(runner);
     }
 }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationRunner.java b/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationRunner.java
index 913239f7..431df21 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationRunner.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationRunner.java
@@ -32,7 +32,7 @@
  * before it received IBackAnimationRunner#onAnimationStart, so the controller could continue
  * trigger the real back behavior.
  */
-class BackAnimationRunner {
+public class BackAnimationRunner {
     private static final String TAG = "ShellBackPreview";
 
     private final IOnBackInvokedCallback mCallback;
@@ -44,8 +44,8 @@
     /** True when the back animation is cancelled */
     private boolean mAnimationCancelled;
 
-    BackAnimationRunner(@NonNull IOnBackInvokedCallback callback,
-            @NonNull IRemoteAnimationRunner runner) {
+    public BackAnimationRunner(
+            @NonNull IOnBackInvokedCallback callback, @NonNull IRemoteAnimationRunner runner) {
         mCallback = callback;
         mRunner = runner;
     }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/back/CrossActivityAnimation.java b/libs/WindowManager/Shell/src/com/android/wm/shell/back/CrossActivityAnimation.java
index edefe9e..114486e 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/back/CrossActivityAnimation.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/back/CrossActivityAnimation.java
@@ -51,9 +51,11 @@
 import com.android.internal.protolog.common.ProtoLog;
 import com.android.wm.shell.common.annotations.ShellMainThread;
 
+import javax.inject.Inject;
+
 /** Class that defines cross-activity animation. */
 @ShellMainThread
-class CrossActivityAnimation {
+public class CrossActivityAnimation extends ShellBackAnimation {
     /**
      * Minimum scale of the entering/closing window.
      */
@@ -106,6 +108,7 @@
     private final SpringAnimation mLeavingProgressSpring;
     // Max window x-shift in pixels.
     private final float mWindowXShift;
+    private final BackAnimationRunner mBackAnimationRunner;
 
     private float mEnteringProgress = 0f;
     private float mLeavingProgress = 0f;
@@ -126,11 +129,11 @@
     private IRemoteAnimationFinishedCallback mFinishCallback;
 
     private final BackProgressAnimator mProgressAnimator = new BackProgressAnimator();
-    final BackAnimationRunner mBackAnimationRunner;
 
     private final BackAnimationBackground mBackground;
 
-    CrossActivityAnimation(Context context, BackAnimationBackground background) {
+    @Inject
+    public CrossActivityAnimation(Context context, BackAnimationBackground background) {
         mCornerRadius = ScreenDecorationsUtils.getWindowCornerRadius(context);
         mBackAnimationRunner = new BackAnimationRunner(new Callback(), new Runner());
         mBackground = background;
@@ -357,6 +360,11 @@
         mTransaction.apply();
     }
 
+    @Override
+    public BackAnimationRunner getRunner() {
+        return mBackAnimationRunner;
+    }
+
     private final class Callback extends IOnBackInvokedCallback.Default {
         @Override
         public void onBackStarted(BackMotionEvent backEvent) {
@@ -371,7 +379,15 @@
 
         @Override
         public void onBackCancelled() {
-            mProgressAnimator.onBackCancelled(CrossActivityAnimation.this::finishAnimation);
+            mProgressAnimator.onBackCancelled(() -> {
+                // mProgressAnimator can reach finish stage earlier than mLeavingProgressSpring,
+                // and if we release all animation leash first, the leavingProgressSpring won't
+                // able to update the animation anymore, which cause flicker.
+                // Here should force update the closing animation target to the final stage before
+                // release it.
+                setLeavingProgress(0);
+                finishAnimation();
+            });
         }
 
         @Override
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/back/CrossTaskBackAnimation.java b/libs/WindowManager/Shell/src/com/android/wm/shell/back/CrossTaskBackAnimation.java
index a7dd27a..209d853 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/back/CrossTaskBackAnimation.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/back/CrossTaskBackAnimation.java
@@ -47,21 +47,23 @@
 import com.android.internal.protolog.common.ProtoLog;
 import com.android.wm.shell.common.annotations.ShellMainThread;
 
+import javax.inject.Inject;
+
 /**
  * Controls the animation of swiping back and returning to another task.
  *
- * This is a two part animation. The first part is an animation that tracks gesture location to
- * scale and move the closing and entering app windows.
- * Once the gesture is committed, the second part remains the closing window in place.
- * The entering window plays the rest of app opening transition to enter full screen.
+ * <p>This is a two part animation. The first part is an animation that tracks gesture location to
+ * scale and move the closing and entering app windows. Once the gesture is committed, the second
+ * part remains the closing window in place. The entering window plays the rest of app opening
+ * transition to enter full screen.
  *
- * This animation is used only for apps that enable back dispatching via
- * {@link android.window.OnBackInvokedDispatcher}. The controller registers
- * an {@link IOnBackInvokedCallback} with WM Shell and receives back dispatches when a back
- * navigation to launcher starts.
+ * <p>This animation is used only for apps that enable back dispatching via {@link
+ * android.window.OnBackInvokedDispatcher}. The controller registers an {@link
+ * IOnBackInvokedCallback} with WM Shell and receives back dispatches when a back navigation to
+ * launcher starts.
  */
 @ShellMainThread
-class CrossTaskBackAnimation {
+public class CrossTaskBackAnimation extends ShellBackAnimation {
     private static final int BACKGROUNDCOLOR = 0x43433A;
 
     /**
@@ -104,28 +106,41 @@
 
     private final float[] mTmpFloat9 = new float[9];
     private final float[] mTmpTranslate = {0, 0, 0};
-
+    private final BackAnimationRunner mBackAnimationRunner;
+    private final BackAnimationBackground mBackground;
     private RemoteAnimationTarget mEnteringTarget;
     private RemoteAnimationTarget mClosingTarget;
     private SurfaceControl.Transaction mTransaction = new SurfaceControl.Transaction();
-
     private boolean mBackInProgress = false;
-
     private boolean mIsRightEdge;
     private float mProgress = 0;
     private PointF mTouchPos = new PointF();
     private IRemoteAnimationFinishedCallback mFinishCallback;
     private BackProgressAnimator mProgressAnimator = new BackProgressAnimator();
-    final BackAnimationRunner mBackAnimationRunner;
 
-    private final BackAnimationBackground mBackground;
-
-    CrossTaskBackAnimation(Context context, BackAnimationBackground background) {
+    @Inject
+    public CrossTaskBackAnimation(Context context, BackAnimationBackground background) {
         mCornerRadius = ScreenDecorationsUtils.getWindowCornerRadius(context);
         mBackAnimationRunner = new BackAnimationRunner(new Callback(), new Runner());
         mBackground = background;
     }
 
+    private static void computeScaleTransformMatrix(float scale, float[] matrix) {
+        matrix[0] = scale;
+        matrix[1] = 0;
+        matrix[2] = 0;
+        matrix[3] = 0;
+        matrix[4] = scale;
+        matrix[5] = 0;
+        matrix[6] = 0;
+        matrix[7] = 0;
+        matrix[8] = scale;
+    }
+
+    private static float mapRange(float value, float min, float max) {
+        return min + (value * (max - min));
+    }
+
     private float getInterpolatedProgress(float backProgress) {
         return 1 - (1 - backProgress) * (1 - backProgress) * (1 - backProgress);
     }
@@ -233,18 +248,6 @@
         mTransaction.setColorTransform(leash, mTmpFloat9, mTmpTranslate);
     }
 
-    static void computeScaleTransformMatrix(float scale, float[] matrix) {
-        matrix[0] = scale;
-        matrix[1] = 0;
-        matrix[2] = 0;
-        matrix[3] = 0;
-        matrix[4] = scale;
-        matrix[5] = 0;
-        matrix[6] = 0;
-        matrix[7] = 0;
-        matrix[8] = scale;
-    }
-
     private void finishAnimation() {
         if (mEnteringTarget != null) {
             mEnteringTarget.leash.release();
@@ -314,11 +317,12 @@
         valueAnimator.start();
     }
 
-    private static float mapRange(float value, float min, float max) {
-        return min + (value * (max - min));
+    @Override
+    public BackAnimationRunner getRunner() {
+        return mBackAnimationRunner;
     }
 
-    private final class Callback extends IOnBackInvokedCallback.Default  {
+    private final class Callback extends IOnBackInvokedCallback.Default {
         @Override
         public void onBackStarted(BackMotionEvent backEvent) {
             mProgressAnimator.onBackStarted(backEvent,
@@ -340,7 +344,7 @@
             mProgressAnimator.reset();
             onGestureCommitted();
         }
-    };
+    }
 
     private final class Runner extends IRemoteAnimationRunner.Default {
         @Override
@@ -360,5 +364,5 @@
             startBackAnimation();
             mFinishCallback = finishedCallback;
         }
-    };
+    }
 }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/back/CustomizeActivityAnimation.java b/libs/WindowManager/Shell/src/com/android/wm/shell/back/CustomizeActivityAnimation.java
index 2d6ec75..aca638c 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/back/CustomizeActivityAnimation.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/back/CustomizeActivityAnimation.java
@@ -55,13 +55,13 @@
 import com.android.internal.protolog.common.ProtoLog;
 import com.android.wm.shell.common.annotations.ShellMainThread;
 
-/**
- * Class that handle customized close activity transition animation.
- */
+import javax.inject.Inject;
+
+/** Class that handle customized close activity transition animation. */
 @ShellMainThread
-class CustomizeActivityAnimation {
+public class CustomizeActivityAnimation extends ShellBackAnimation {
     private final BackProgressAnimator mProgressAnimator = new BackProgressAnimator();
-    final BackAnimationRunner mBackAnimationRunner;
+    private final BackAnimationRunner mBackAnimationRunner;
     private final float mCornerRadius;
     private final SurfaceControl.Transaction mTransaction;
     private final BackAnimationBackground mBackground;
@@ -88,7 +88,8 @@
 
     private final Choreographer mChoreographer;
 
-    CustomizeActivityAnimation(Context context, BackAnimationBackground background) {
+    @Inject
+    public CustomizeActivityAnimation(Context context, BackAnimationBackground background) {
         this(context, background, new SurfaceControl.Transaction(), null);
     }
 
@@ -258,10 +259,12 @@
         valueAnimator.start();
     }
 
-    /**
-     * Load customize animation before animation start.
-     */
-    boolean prepareNextAnimation(BackNavigationInfo.CustomAnimationInfo animationInfo) {
+    /** Load customize animation before animation start. */
+    @Override
+    public boolean prepareNextAnimation(BackNavigationInfo.CustomAnimationInfo animationInfo) {
+        if (animationInfo == null) {
+            return false;
+        }
         final AnimationLoadResult result = mCustomAnimationLoader.loadAll(animationInfo);
         if (result != null) {
             mCloseAnimation = result.mCloseAnimation;
@@ -272,6 +275,11 @@
         return false;
     }
 
+    @Override
+    public BackAnimationRunner getRunner() {
+        return mBackAnimationRunner;
+    }
+
     private final class Callback extends IOnBackInvokedCallback.Default {
         @Override
         public void onBackStarted(BackMotionEvent backEvent) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/back/ShellBackAnimation.java b/libs/WindowManager/Shell/src/com/android/wm/shell/back/ShellBackAnimation.java
new file mode 100644
index 0000000..312e88d
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/back/ShellBackAnimation.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.back;
+
+import android.window.BackNavigationInfo;
+
+import javax.inject.Qualifier;
+
+/** Base class for all back animations. */
+public abstract class ShellBackAnimation {
+    @Qualifier
+    public @interface CrossActivity {}
+
+    @Qualifier
+    public @interface CrossTask {}
+
+    @Qualifier
+    public @interface CustomizeActivity {}
+
+    @Qualifier
+    public @interface ReturnToHome {}
+
+    /** Retrieve the {@link BackAnimationRunner} associated with this animation. */
+    public abstract BackAnimationRunner getRunner();
+
+    /**
+     * Prepare the next animation with customized animation.
+     *
+     * @return true if this type of back animation should override the default.
+     */
+    public boolean prepareNextAnimation(BackNavigationInfo.CustomAnimationInfo animationInfo) {
+        return false;
+    }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/back/ShellBackAnimationRegistry.java b/libs/WindowManager/Shell/src/com/android/wm/shell/back/ShellBackAnimationRegistry.java
new file mode 100644
index 0000000..62b18f3
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/back/ShellBackAnimationRegistry.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.back;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.util.Log;
+import android.util.SparseArray;
+import android.window.BackNavigationInfo;
+
+/** Registry for all types of default back animations */
+public class ShellBackAnimationRegistry {
+    private static final String TAG = "ShellBackPreview";
+
+    private final SparseArray<BackAnimationRunner> mAnimationDefinition = new SparseArray<>();
+    private final ShellBackAnimation mDefaultCrossActivityAnimation;
+    private final ShellBackAnimation mCustomizeActivityAnimation;
+
+    public ShellBackAnimationRegistry(
+            @ShellBackAnimation.CrossActivity @Nullable ShellBackAnimation crossActivityAnimation,
+            @ShellBackAnimation.CrossTask @Nullable ShellBackAnimation crossTaskAnimation,
+            @ShellBackAnimation.CustomizeActivity @Nullable
+                    ShellBackAnimation customizeActivityAnimation,
+            @ShellBackAnimation.ReturnToHome @Nullable
+                    ShellBackAnimation defaultBackToHomeAnimation) {
+        if (crossActivityAnimation != null) {
+            mAnimationDefinition.set(
+                    BackNavigationInfo.TYPE_CROSS_TASK, crossTaskAnimation.getRunner());
+        }
+        if (crossActivityAnimation != null) {
+            mAnimationDefinition.set(
+                    BackNavigationInfo.TYPE_CROSS_ACTIVITY, crossActivityAnimation.getRunner());
+        }
+        if (defaultBackToHomeAnimation != null) {
+            mAnimationDefinition.set(
+                    BackNavigationInfo.TYPE_RETURN_TO_HOME, defaultBackToHomeAnimation.getRunner());
+        }
+
+        mDefaultCrossActivityAnimation = crossActivityAnimation;
+        mCustomizeActivityAnimation = customizeActivityAnimation;
+
+        // TODO(b/236760237): register dialog close animation when it's completed.
+    }
+
+    void registerAnimation(
+            @BackNavigationInfo.BackTargetType int type, @NonNull BackAnimationRunner runner) {
+        mAnimationDefinition.set(type, runner);
+    }
+
+    void unregisterAnimation(@BackNavigationInfo.BackTargetType int type) {
+        mAnimationDefinition.remove(type);
+    }
+
+    /**
+     * Start the {@link BackAnimationRunner} associated with a back target type.
+     *
+     * @param type back target type
+     * @return true if the animation is started, false if animation is not found for that type.
+     */
+    boolean startGesture(@BackNavigationInfo.BackTargetType int type) {
+        BackAnimationRunner runner = mAnimationDefinition.get(type);
+        if (runner == null) {
+            return false;
+        }
+        runner.startGesture();
+        return true;
+    }
+
+    /**
+     * Cancel the {@link BackAnimationRunner} associated with a back target type.
+     *
+     * @param type back target type
+     * @return true if the animation is started, false if animation is not found for that type.
+     */
+    boolean cancel(@BackNavigationInfo.BackTargetType int type) {
+        BackAnimationRunner runner = mAnimationDefinition.get(type);
+        if (runner == null) {
+            return false;
+        }
+        runner.cancelAnimation();
+        return true;
+    }
+
+    boolean isAnimationCancelledOrNull(@BackNavigationInfo.BackTargetType int type) {
+        BackAnimationRunner runner = mAnimationDefinition.get(type);
+        if (runner == null) {
+            return true;
+        }
+        return runner.isAnimationCancelled();
+    }
+
+    boolean isWaitingAnimation(@BackNavigationInfo.BackTargetType int type) {
+        BackAnimationRunner runner = mAnimationDefinition.get(type);
+        if (runner == null) {
+            return false;
+        }
+        return runner.isWaitingAnimation();
+    }
+
+    void resetDefaultCrossActivity() {
+        if (mDefaultCrossActivityAnimation == null
+                || !mAnimationDefinition.contains(BackNavigationInfo.TYPE_CROSS_ACTIVITY)) {
+            return;
+        }
+        mAnimationDefinition.set(
+                BackNavigationInfo.TYPE_CROSS_ACTIVITY, mDefaultCrossActivityAnimation.getRunner());
+    }
+
+    BackAnimationRunner getAnimationRunnerAndInit(BackNavigationInfo backNavigationInfo) {
+        int type = backNavigationInfo.getType();
+        // Initiate customized cross-activity animation, or fall back to cross activity animation
+        if (type == BackNavigationInfo.TYPE_CROSS_ACTIVITY && mAnimationDefinition.contains(type)) {
+            if (mCustomizeActivityAnimation != null
+                    && mCustomizeActivityAnimation.prepareNextAnimation(
+                            backNavigationInfo.getCustomAnimationInfo())) {
+                mAnimationDefinition.get(type).resetWaitingAnimation();
+                mAnimationDefinition.set(
+                        BackNavigationInfo.TYPE_CROSS_ACTIVITY,
+                        mCustomizeActivityAnimation.getRunner());
+            }
+        }
+        BackAnimationRunner runner = mAnimationDefinition.get(type);
+        if (runner == null) {
+            Log.e(
+                    TAG,
+                    "Animation didn't be defined for type "
+                            + BackNavigationInfo.typeToString(type));
+        }
+        return runner;
+    }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
index 66b9ade6..8400dde 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
@@ -25,7 +25,6 @@
 import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
 
 import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_BUBBLE_CONTROLLER;
-import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_BUBBLE_GESTURE;
 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES;
 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_BLOCKED;
@@ -37,6 +36,7 @@
 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_PACKAGE_REMOVED;
 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_SHORTCUT_REMOVED;
 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_USER_CHANGED;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_BUBBLES;
 import static com.android.wm.shell.sysui.ShellSharedConstants.KEY_EXTRA_SHELL_BUBBLES;
 
 import android.annotation.BinderThread;
@@ -85,6 +85,7 @@
 import androidx.annotation.Nullable;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.protolog.common.ProtoLog;
 import com.android.internal.statusbar.IStatusBarService;
 import com.android.launcher3.icons.BubbleIconFactory;
 import com.android.wm.shell.R;
@@ -1008,9 +1009,7 @@
     }
 
     private void onNotificationPanelExpandedChanged(boolean expanded) {
-        if (DEBUG_BUBBLE_GESTURE) {
-            Log.d(TAG, "onNotificationPanelExpandedChanged: expanded=" + expanded);
-        }
+        ProtoLog.d(WM_SHELL_BUBBLES, "onNotificationPanelExpandedChanged: expanded=%b", expanded);
         if (mStackView != null && mStackView.isExpanded()) {
             if (expanded) {
                 mStackView.stopMonitoringSwipeUpGesture();
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleDebugConfig.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleDebugConfig.java
index dce6b56..250e010 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleDebugConfig.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleDebugConfig.java
@@ -47,7 +47,6 @@
     static final boolean DEBUG_USER_EDUCATION = false;
     static final boolean DEBUG_POSITIONER = false;
     public static final boolean DEBUG_COLLAPSE_ANIMATOR = false;
-    static final boolean DEBUG_BUBBLE_GESTURE = false;
     public static boolean DEBUG_EXPANDED_VIEW_DRAGGING = false;
 
     private static final boolean FORCE_SHOW_USER_EDUCATION = false;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java
index ee6996d..2c10065 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java
@@ -661,14 +661,26 @@
         final boolean startOnLeft =
                 mContext.getResources().getConfiguration().getLayoutDirection()
                         != LAYOUT_DIRECTION_RTL;
-        final float startingVerticalOffset = mContext.getResources().getDimensionPixelOffset(
-                R.dimen.bubble_stack_starting_offset_y);
-        // TODO: placement bug here because mPositionRect doesn't handle the overhanging edge
-        return new BubbleStackView.RelativeStackPosition(
-                startOnLeft,
-                startingVerticalOffset / mPositionRect.height())
-                .getAbsolutePositionInRegion(getAllowableStackPositionRegion(
-                        1 /* default starts with 1 bubble */));
+        final RectF allowableStackPositionRegion = getAllowableStackPositionRegion(
+                1 /* default starts with 1 bubble */);
+        if (isLargeScreen()) {
+            // We want the stack to be visually centered on the edge, so we need to base it
+            // of a rect that includes insets.
+            final float desiredY = mScreenRect.height() / 2f - (mBubbleSize / 2f);
+            final float offset = desiredY / mScreenRect.height();
+            return new BubbleStackView.RelativeStackPosition(
+                    startOnLeft,
+                    offset)
+                    .getAbsolutePositionInRegion(allowableStackPositionRegion);
+        } else {
+            final float startingVerticalOffset = mContext.getResources().getDimensionPixelOffset(
+                    R.dimen.bubble_stack_starting_offset_y);
+            // TODO: placement bug here because mPositionRect doesn't handle the overhanging edge
+            return new BubbleStackView.RelativeStackPosition(
+                    startOnLeft,
+                    startingVerticalOffset / mPositionRect.height())
+                    .getAbsolutePositionInRegion(allowableStackPositionRegion);
+        }
     }
 
     /**
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
index f58b121..da5974f 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
@@ -21,11 +21,11 @@
 
 import static com.android.wm.shell.animation.Interpolators.ALPHA_IN;
 import static com.android.wm.shell.animation.Interpolators.ALPHA_OUT;
-import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_BUBBLE_GESTURE;
 import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_BUBBLE_STACK_VIEW;
 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES;
 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.wm.shell.bubbles.BubblePositioner.NUM_VISIBLE_WHEN_RESTING;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_BUBBLES;
 
 import android.animation.Animator;
 import android.animation.AnimatorListenerAdapter;
@@ -75,6 +75,7 @@
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.policy.ScreenDecorationsUtils;
+import com.android.internal.protolog.common.ProtoLog;
 import com.android.internal.util.FrameworkStatsLog;
 import com.android.wm.shell.R;
 import com.android.wm.shell.animation.Interpolators;
@@ -2024,9 +2025,7 @@
      * Monitor for swipe up gesture that is used to collapse expanded view
      */
     void startMonitoringSwipeUpGesture() {
-        if (DEBUG_BUBBLE_GESTURE) {
-            Log.d(TAG, "startMonitoringSwipeUpGesture");
-        }
+        ProtoLog.d(WM_SHELL_BUBBLES, "startMonitoringSwipeUpGesture");
         stopMonitoringSwipeUpGestureInternal();
 
         if (isGestureNavEnabled()) {
@@ -2046,9 +2045,7 @@
      * Stop monitoring for swipe up gesture
      */
     void stopMonitoringSwipeUpGesture() {
-        if (DEBUG_BUBBLE_GESTURE) {
-            Log.d(TAG, "stopMonitoringSwipeUpGesture");
-        }
+        ProtoLog.d(WM_SHELL_BUBBLES, "stopMonitoringSwipeUpGesture");
         stopMonitoringSwipeUpGestureInternal();
     }
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarGestureTracker.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarGestureTracker.java
index 3a3a378..1375684 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarGestureTracker.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarGestureTracker.java
@@ -18,10 +18,10 @@
 
 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES;
 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_BUBBLES;
 
 import android.content.Context;
 import android.hardware.input.InputManager;
-import android.util.Log;
 import android.view.Choreographer;
 import android.view.InputChannel;
 import android.view.InputEventReceiver;
@@ -29,6 +29,7 @@
 
 import androidx.annotation.Nullable;
 
+import com.android.internal.protolog.common.ProtoLog;
 import com.android.wm.shell.bubbles.BubblesNavBarMotionEventHandler.MotionEventListener;
 
 /**
@@ -58,9 +59,7 @@
      * @param listener listener that is notified of touch events
      */
     void start(MotionEventListener listener) {
-        if (BubbleDebugConfig.DEBUG_BUBBLE_GESTURE) {
-            Log.d(TAG, "start monitoring bubbles swipe up gesture");
-        }
+        ProtoLog.d(WM_SHELL_BUBBLES, "start monitoring bubbles swipe up gesture");
 
         stopInternal();
 
@@ -76,9 +75,7 @@
     }
 
     void stop() {
-        if (BubbleDebugConfig.DEBUG_BUBBLE_GESTURE) {
-            Log.d(TAG, "stop monitoring bubbles swipe up gesture");
-        }
+        ProtoLog.d(WM_SHELL_BUBBLES, "stop monitoring bubbles swipe up gesture");
         stopInternal();
     }
 
@@ -94,9 +91,7 @@
     }
 
     private void onInterceptTouch() {
-        if (BubbleDebugConfig.DEBUG_BUBBLE_GESTURE) {
-            Log.d(TAG, "intercept touch event");
-        }
+        ProtoLog.d(WM_SHELL_BUBBLES, "intercept touch event");
         if (mInputMonitor != null) {
             mInputMonitor.pilferPointers();
         }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandler.java
index 844526c..b7107f0 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandler.java
@@ -16,19 +16,20 @@
 
 package com.android.wm.shell.bubbles;
 
-import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_BUBBLE_GESTURE;
 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES;
 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_BUBBLES;
 
 import android.content.Context;
 import android.graphics.PointF;
-import android.util.Log;
 import android.view.MotionEvent;
 import android.view.VelocityTracker;
 import android.view.ViewConfiguration;
 
 import androidx.annotation.Nullable;
 
+import com.android.internal.protolog.common.ProtoLog;
+
 /**
  * Handles {@link MotionEvent}s for bubbles that begin in the nav bar area
  */
@@ -112,10 +113,8 @@
     private boolean isInGestureRegion(MotionEvent ev) {
         // Only handles touch events beginning in navigation bar system gesture zone
         if (mPositioner.getNavBarGestureZone().contains((int) ev.getX(), (int) ev.getY())) {
-            if (DEBUG_BUBBLE_GESTURE) {
-                Log.d(TAG, "handling touch y=" + ev.getY()
-                        + " navBarGestureZone=" + mPositioner.getNavBarGestureZone());
-            }
+            ProtoLog.d(WM_SHELL_BUBBLES, "handling touch x=%d y=%d navBarGestureZone=%s",
+                    (int) ev.getX(), (int) ev.getY(), mPositioner.getNavBarGestureZone());
             return true;
         }
         return false;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/ManageEducationView.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/ManageEducationView.kt
index e95e8e5..1b41f79 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/ManageEducationView.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/ManageEducationView.kt
@@ -41,9 +41,9 @@
     private val ANIMATE_DURATION: Long = 200
 
     private val positioner: BubblePositioner = positioner
-    private val manageView by lazy { findViewById<ViewGroup>(R.id.manage_education_view) }
-    private val manageButton by lazy { findViewById<Button>(R.id.manage_button) }
-    private val gotItButton by lazy { findViewById<Button>(R.id.got_it) }
+    private val manageView by lazy { requireViewById<ViewGroup>(R.id.manage_education_view) }
+    private val manageButton by lazy { requireViewById<Button>(R.id.manage_button) }
+    private val gotItButton by lazy { requireViewById<Button>(R.id.got_it) }
 
     private var isHiding = false
     private var realManageButtonRect = Rect()
@@ -122,7 +122,7 @@
             manageButton
                 .setOnClickListener {
                     hide()
-                    expandedView.findViewById<View>(R.id.manage_button).performClick()
+                    expandedView.requireViewById<View>(R.id.manage_button).performClick()
                 }
             gotItButton.setOnClickListener { hide() }
             setOnClickListener { hide() }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/StackEducationView.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/StackEducationView.kt
index d0598cd..5e3a077 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/StackEducationView.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/StackEducationView.kt
@@ -48,9 +48,9 @@
     private val positioner: BubblePositioner = positioner
     private val controller: BubbleController = controller
 
-    private val view by lazy { findViewById<View>(R.id.stack_education_layout) }
-    private val titleTextView by lazy { findViewById<TextView>(R.id.stack_education_title) }
-    private val descTextView by lazy { findViewById<TextView>(R.id.stack_education_description) }
+    private val view by lazy { requireViewById<View>(R.id.stack_education_layout) }
+    private val titleTextView by lazy { requireViewById<TextView>(R.id.stack_education_title) }
+    private val descTextView by lazy { requireViewById<TextView>(R.id.stack_education_description) }
 
     var isHiding = false
         private set
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/LegacySizeSpecSource.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/LegacySizeSpecSource.kt
new file mode 100644
index 0000000..fd000ee
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/LegacySizeSpecSource.kt
@@ -0,0 +1,202 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.common.pip
+
+import android.content.Context
+import android.content.res.Resources
+import android.graphics.PointF
+import android.util.Size
+import com.android.wm.shell.R
+import com.android.wm.shell.pip.PipDisplayLayoutState
+
+class LegacySizeSpecSource(
+        private val context: Context,
+        private val pipDisplayLayoutState: PipDisplayLayoutState
+) : SizeSpecSource {
+
+    private var mDefaultMinSize = 0
+    /** The absolute minimum an overridden size's edge can be */
+    private var mOverridableMinSize = 0
+    /** The preferred minimum (and default minimum) size specified by apps.  */
+    private var mOverrideMinSize: Size? = null
+
+    private var mDefaultSizePercent = 0f
+    private var mMinimumSizePercent = 0f
+    private var mMaxAspectRatioForMinSize = 0f
+    private var mMinAspectRatioForMinSize = 0f
+
+    init {
+        reloadResources()
+    }
+
+    private fun reloadResources() {
+        val res: Resources = context.getResources()
+
+        mDefaultMinSize = res.getDimensionPixelSize(
+                R.dimen.default_minimal_size_pip_resizable_task)
+        mOverridableMinSize = res.getDimensionPixelSize(
+                R.dimen.overridable_minimal_size_pip_resizable_task)
+
+        mDefaultSizePercent = res.getFloat(R.dimen.config_pictureInPictureDefaultSizePercent)
+        mMinimumSizePercent = res.getFraction(R.fraction.config_pipShortestEdgePercent, 1, 1)
+
+        mMaxAspectRatioForMinSize = res.getFloat(
+                R.dimen.config_pictureInPictureAspectRatioLimitForMinSize)
+        mMinAspectRatioForMinSize = 1f / mMaxAspectRatioForMinSize
+    }
+
+    override fun onConfigurationChanged() {
+        reloadResources()
+    }
+
+    override fun getMaxSize(aspectRatio: Float): Size {
+        val insetBounds = pipDisplayLayoutState.insetBounds
+
+        val shorterLength: Int = Math.min(getDisplayBounds().width(),
+                getDisplayBounds().height())
+        val totalHorizontalPadding: Int = (insetBounds.left +
+                (getDisplayBounds().width() - insetBounds.right))
+        val totalVerticalPadding: Int = (insetBounds.top +
+                (getDisplayBounds().height() - insetBounds.bottom))
+
+        return if (aspectRatio > 1f) {
+            val maxWidth = Math.max(getDefaultSize(aspectRatio).width,
+                    shorterLength - totalHorizontalPadding)
+            val maxHeight = (maxWidth / aspectRatio).toInt()
+            Size(maxWidth, maxHeight)
+        } else {
+            val maxHeight = Math.max(getDefaultSize(aspectRatio).height,
+                    shorterLength - totalVerticalPadding)
+            val maxWidth = (maxHeight * aspectRatio).toInt()
+            Size(maxWidth, maxHeight)
+        }
+    }
+
+    override fun getDefaultSize(aspectRatio: Float): Size {
+        if (mOverrideMinSize != null) {
+            return getMinSize(aspectRatio)
+        }
+        val smallestDisplaySize: Int = Math.min(getDisplayBounds().width(),
+                getDisplayBounds().height())
+        val minSize = Math.max(getMinEdgeSize().toFloat(),
+                smallestDisplaySize * mDefaultSizePercent).toInt()
+        val width: Int
+        val height: Int
+        if (aspectRatio <= mMinAspectRatioForMinSize ||
+                aspectRatio > mMaxAspectRatioForMinSize) {
+            // Beyond these points, we can just use the min size as the shorter edge
+            if (aspectRatio <= 1) {
+                // Portrait, width is the minimum size
+                width = minSize
+                height = Math.round(width / aspectRatio)
+            } else {
+                // Landscape, height is the minimum size
+                height = minSize
+                width = Math.round(height * aspectRatio)
+            }
+        } else {
+            // Within these points, ensure that the bounds fit within the radius of the limits
+            // at the points
+            val widthAtMaxAspectRatioForMinSize: Float = mMaxAspectRatioForMinSize * minSize
+            val radius = PointF.length(widthAtMaxAspectRatioForMinSize, minSize.toFloat())
+            height = Math.round(Math.sqrt((radius * radius /
+                    (aspectRatio * aspectRatio + 1)).toDouble())).toInt()
+            width = Math.round(height * aspectRatio)
+        }
+        return Size(width, height)
+    }
+
+    override fun getMinSize(aspectRatio: Float): Size {
+        if (mOverrideMinSize != null) {
+            return adjustOverrideMinSizeToAspectRatio(aspectRatio)!!
+        }
+        val shorterLength: Int = Math.min(getDisplayBounds().width(),
+                getDisplayBounds().height())
+        val minWidth: Int
+        val minHeight: Int
+        if (aspectRatio > 1f) {
+            minWidth = Math.min(getDefaultSize(aspectRatio).width.toFloat(),
+                    shorterLength * mMinimumSizePercent).toInt()
+            minHeight = (minWidth / aspectRatio).toInt()
+        } else {
+            minHeight = Math.min(getDefaultSize(aspectRatio).height.toFloat(),
+                    shorterLength * mMinimumSizePercent).toInt()
+            minWidth = (minHeight * aspectRatio).toInt()
+        }
+        return Size(minWidth, minHeight)
+    }
+
+    override fun getSizeForAspectRatio(size: Size, aspectRatio: Float): Size {
+        val smallestSize = Math.min(size.width, size.height)
+        val minSize = Math.max(getMinEdgeSize(), smallestSize)
+        val width: Int
+        val height: Int
+        if (aspectRatio <= 1) {
+            // Portrait, width is the minimum size.
+            width = minSize
+            height = Math.round(width / aspectRatio)
+        } else {
+            // Landscape, height is the minimum size
+            height = minSize
+            width = Math.round(height * aspectRatio)
+        }
+        return Size(width, height)
+    }
+
+    private fun getDisplayBounds() = pipDisplayLayoutState.displayBounds
+
+    /** Sets the preferred size of PIP as specified by the activity in PIP mode.  */
+    override fun setOverrideMinSize(overrideMinSize: Size?) {
+        mOverrideMinSize = overrideMinSize
+    }
+
+    /** Returns the preferred minimal size specified by the activity in PIP.  */
+    override fun getOverrideMinSize(): Size? {
+        val overrideMinSize = mOverrideMinSize ?: return null
+        return if (overrideMinSize.width < mOverridableMinSize ||
+                overrideMinSize.height < mOverridableMinSize) {
+            Size(mOverridableMinSize, mOverridableMinSize)
+        } else {
+            overrideMinSize
+        }
+    }
+
+    private fun getMinEdgeSize(): Int {
+        return if (mOverrideMinSize == null) mDefaultMinSize else getOverrideMinEdgeSize()
+    }
+
+    /**
+     * Returns the adjusted overridden min size if it is set; otherwise, returns null.
+     *
+     *
+     * Overridden min size needs to be adjusted in its own way while making sure that the target
+     * aspect ratio is maintained
+     *
+     * @param aspectRatio target aspect ratio
+     */
+    private fun adjustOverrideMinSizeToAspectRatio(aspectRatio: Float): Size? {
+        val size = getOverrideMinSize() ?: return null
+        val sizeAspectRatio = size.width / size.height.toFloat()
+        return if (sizeAspectRatio > aspectRatio) {
+            // Size is wider, fix the width and increase the height
+            Size(size.width, (size.width / aspectRatio).toInt())
+        } else {
+            // Size is taller, fix the height and adjust the width.
+            Size((size.height * aspectRatio).toInt(), size.height)
+        }
+    }
+}
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PhoneSizeSpecSource.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PhoneSizeSpecSource.kt
new file mode 100644
index 0000000..c563068
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PhoneSizeSpecSource.kt
@@ -0,0 +1,252 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.common.pip
+
+import android.content.Context
+import android.content.res.Resources
+import android.os.SystemProperties
+import android.util.Size
+import com.android.wm.shell.R
+import com.android.wm.shell.pip.PipDisplayLayoutState
+import java.io.PrintWriter
+
+class PhoneSizeSpecSource(
+        private val context: Context,
+        private val pipDisplayLayoutState: PipDisplayLayoutState
+) : SizeSpecSource {
+    private var DEFAULT_OPTIMIZED_ASPECT_RATIO = 9f / 16
+
+    private var mDefaultMinSize = 0
+    /** The absolute minimum an overridden size's edge can be */
+    private var mOverridableMinSize = 0
+    /** The preferred minimum (and default minimum) size specified by apps.  */
+    private var mOverrideMinSize: Size? = null
+
+
+    /** Default and minimum percentages for the PIP size logic.  */
+    private val mDefaultSizePercent: Float
+    private val mMinimumSizePercent: Float
+
+    /** Aspect ratio that the PIP size spec logic optimizes for.  */
+    private var mOptimizedAspectRatio = 0f
+
+    init {
+        mDefaultSizePercent = SystemProperties
+                .get("com.android.wm.shell.pip.phone.def_percentage", "0.6").toFloat()
+        mMinimumSizePercent = SystemProperties
+                .get("com.android.wm.shell.pip.phone.min_percentage", "0.5").toFloat()
+
+        reloadResources()
+    }
+
+    private fun reloadResources() {
+        val res: Resources = context.getResources()
+
+        mDefaultMinSize = res.getDimensionPixelSize(
+                R.dimen.default_minimal_size_pip_resizable_task)
+        mOverridableMinSize = res.getDimensionPixelSize(
+                R.dimen.overridable_minimal_size_pip_resizable_task)
+
+        val requestedOptAspRatio = res.getFloat(R.dimen.config_pipLargeScreenOptimizedAspectRatio)
+        // make sure the optimized aspect ratio is valid with a default value to fall back to
+        mOptimizedAspectRatio = if (requestedOptAspRatio > 1) {
+            DEFAULT_OPTIMIZED_ASPECT_RATIO
+        } else {
+            requestedOptAspRatio
+        }
+    }
+
+    override fun onConfigurationChanged() {
+        reloadResources()
+    }
+
+    /**
+     * Calculates the max size of PIP.
+     *
+     * Optimizes for 16:9 aspect ratios, making them take full length of shortest display edge.
+     * As aspect ratio approaches values close to 1:1, the logic does not let PIP occupy the
+     * whole screen. A linear function is used to calculate these sizes.
+     *
+     * @param aspectRatio aspect ratio of the PIP window
+     * @return dimensions of the max size of the PIP
+     */
+    override fun getMaxSize(aspectRatio: Float): Size {
+        val insetBounds = pipDisplayLayoutState.insetBounds
+        val displayBounds = pipDisplayLayoutState.displayBounds
+
+        val totalHorizontalPadding: Int = (insetBounds.left +
+                (displayBounds.width() - insetBounds.right))
+        val totalVerticalPadding: Int = (insetBounds.top +
+                (displayBounds.height() - insetBounds.bottom))
+        val shorterLength: Int = Math.min(displayBounds.width() - totalHorizontalPadding,
+                displayBounds.height() - totalVerticalPadding)
+        var maxWidth: Int
+        val maxHeight: Int
+
+        // use the optimized max sizing logic only within a certain aspect ratio range
+        if (aspectRatio >= mOptimizedAspectRatio && aspectRatio <= 1 / mOptimizedAspectRatio) {
+            // this formula and its derivation is explained in b/198643358#comment16
+            maxWidth = Math.round(mOptimizedAspectRatio * shorterLength +
+                    shorterLength * (aspectRatio - mOptimizedAspectRatio) / (1 + aspectRatio))
+            // make sure the max width doesn't go beyond shorter screen length after rounding
+            maxWidth = Math.min(maxWidth, shorterLength)
+            maxHeight = Math.round(maxWidth / aspectRatio)
+        } else {
+            if (aspectRatio > 1f) {
+                maxWidth = shorterLength
+                maxHeight = Math.round(maxWidth / aspectRatio)
+            } else {
+                maxHeight = shorterLength
+                maxWidth = Math.round(maxHeight * aspectRatio)
+            }
+        }
+        return Size(maxWidth, maxHeight)
+    }
+
+    /**
+     * Decreases the dimensions by a percentage relative to max size to get default size.
+     *
+     * @param aspectRatio aspect ratio of the PIP window
+     * @return dimensions of the default size of the PIP
+     */
+    override fun getDefaultSize(aspectRatio: Float): Size {
+        val minSize = getMinSize(aspectRatio)
+        if (mOverrideMinSize != null) {
+            return minSize
+        }
+        val maxSize = getMaxSize(aspectRatio)
+        val defaultWidth = Math.max(Math.round(maxSize.width * mDefaultSizePercent),
+                minSize.width)
+        val defaultHeight = Math.round(defaultWidth / aspectRatio)
+        return Size(defaultWidth, defaultHeight)
+    }
+
+    /**
+     * Decreases the dimensions by a certain percentage relative to max size to get min size.
+     *
+     * @param aspectRatio aspect ratio of the PIP window
+     * @return dimensions of the min size of the PIP
+     */
+    override fun getMinSize(aspectRatio: Float): Size {
+        // if there is an overridden min size provided, return that
+        if (mOverrideMinSize != null) {
+            return adjustOverrideMinSizeToAspectRatio(aspectRatio)!!
+        }
+        val maxSize = getMaxSize(aspectRatio)
+        var minWidth = Math.round(maxSize.width * mMinimumSizePercent)
+        var minHeight = Math.round(maxSize.height * mMinimumSizePercent)
+
+        // make sure the calculated min size is not smaller than the allowed default min size
+        if (aspectRatio > 1f) {
+            minHeight = Math.max(minHeight, mDefaultMinSize)
+            minWidth = Math.round(minHeight * aspectRatio)
+        } else {
+            minWidth = Math.max(minWidth, mDefaultMinSize)
+            minHeight = Math.round(minWidth / aspectRatio)
+        }
+        return Size(minWidth, minHeight)
+    }
+
+    /**
+     * Returns the size for target aspect ratio making sure new size conforms with the rules.
+     *
+     *
+     * Recalculates the dimensions such that the target aspect ratio is achieved, while
+     * maintaining the same maximum size to current size ratio.
+     *
+     * @param size current size
+     * @param aspectRatio target aspect ratio
+     */
+    override fun getSizeForAspectRatio(size: Size, aspectRatio: Float): Size {
+        if (size == mOverrideMinSize) {
+            return adjustOverrideMinSizeToAspectRatio(aspectRatio)!!
+        }
+
+        val currAspectRatio = size.width.toFloat() / size.height
+
+        // getting the percentage of the max size that current size takes
+        val currentMaxSize = getMaxSize(currAspectRatio)
+        val currentPercent = size.width.toFloat() / currentMaxSize.width
+
+        // getting the max size for the target aspect ratio
+        val updatedMaxSize = getMaxSize(aspectRatio)
+        var width = Math.round(updatedMaxSize.width * currentPercent)
+        var height = Math.round(updatedMaxSize.height * currentPercent)
+
+        // adjust the dimensions if below allowed min edge size
+        val minEdgeSize =
+                if (mOverrideMinSize == null) mDefaultMinSize else getOverrideMinEdgeSize()
+
+        if (width < minEdgeSize && aspectRatio <= 1) {
+            width = minEdgeSize
+            height = Math.round(width / aspectRatio)
+        } else if (height < minEdgeSize && aspectRatio > 1) {
+            height = minEdgeSize
+            width = Math.round(height * aspectRatio)
+        }
+
+        // reduce the dimensions of the updated size to the calculated percentage
+        return Size(width, height)
+    }
+
+    /** Sets the preferred size of PIP as specified by the activity in PIP mode.  */
+    override fun setOverrideMinSize(overrideMinSize: Size?) {
+        mOverrideMinSize = overrideMinSize
+    }
+
+    /** Returns the preferred minimal size specified by the activity in PIP.  */
+    override fun getOverrideMinSize(): Size? {
+        val overrideMinSize = mOverrideMinSize ?: return null
+        return if (overrideMinSize.width < mOverridableMinSize ||
+                overrideMinSize.height < mOverridableMinSize) {
+            Size(mOverridableMinSize, mOverridableMinSize)
+        } else {
+            overrideMinSize
+        }
+    }
+
+    /**
+     * Returns the adjusted overridden min size if it is set; otherwise, returns null.
+     *
+     *
+     * Overridden min size needs to be adjusted in its own way while making sure that the target
+     * aspect ratio is maintained
+     *
+     * @param aspectRatio target aspect ratio
+     */
+    private fun adjustOverrideMinSizeToAspectRatio(aspectRatio: Float): Size? {
+        val size = getOverrideMinSize() ?: return null
+        val sizeAspectRatio = size.width / size.height.toFloat()
+        return if (sizeAspectRatio > aspectRatio) {
+            // Size is wider, fix the width and increase the height
+            Size(size.width, (size.width / aspectRatio).toInt())
+        } else {
+            // Size is taller, fix the height and adjust the width.
+            Size((size.height * aspectRatio).toInt(), size.height)
+        }
+    }
+
+    override fun dump(pw: PrintWriter, prefix: String) {
+        val innerPrefix = "$prefix  "
+        pw.println(innerPrefix + "mOverrideMinSize=" + mOverrideMinSize)
+        pw.println(innerPrefix + "mOverridableMinSize=" + mOverridableMinSize)
+        pw.println(innerPrefix + "mDefaultMinSize=" + mDefaultMinSize)
+        pw.println(innerPrefix + "mDefaultSizePercent=" + mDefaultSizePercent)
+        pw.println(innerPrefix + "mMinimumSizePercent=" + mMinimumSizePercent)
+        pw.println(innerPrefix + "mOptimizedAspectRatio=" + mOptimizedAspectRatio)
+    }
+}
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PipAppOpsListener.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PipAppOpsListener.kt
new file mode 100644
index 0000000..a141ff9
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PipAppOpsListener.kt
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.common.pip
+
+import android.app.AppOpsManager
+import android.content.Context
+import android.content.pm.PackageManager
+import com.android.wm.shell.common.ShellExecutor
+import com.android.wm.shell.pip.PipUtils
+
+class PipAppOpsListener(
+    private val mContext: Context,
+    private val mCallback: Callback,
+    private val mMainExecutor: ShellExecutor
+) {
+    private val mAppOpsManager: AppOpsManager = checkNotNull(
+        mContext.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager)
+    private val mAppOpsChangedListener = AppOpsManager.OnOpChangedListener { _, packageName ->
+        try {
+            // Dismiss the PiP once the user disables the app ops setting for that package
+            val topPipActivityInfo = PipUtils.getTopPipActivity(mContext)
+            val componentName = topPipActivityInfo.first ?: return@OnOpChangedListener
+            val userId = topPipActivityInfo.second
+            val appInfo = mContext.packageManager
+                .getApplicationInfoAsUser(packageName, 0, userId)
+            if (appInfo.packageName == componentName.packageName &&
+                mAppOpsManager.checkOpNoThrow(
+                    AppOpsManager.OP_PICTURE_IN_PICTURE, appInfo.uid,
+                    packageName
+                ) != AppOpsManager.MODE_ALLOWED
+            ) {
+                mMainExecutor.execute { mCallback.dismissPip() }
+            }
+        } catch (e: PackageManager.NameNotFoundException) {
+            // Unregister the listener if the package can't be found
+            unregisterAppOpsListener()
+        }
+    }
+
+    fun onActivityPinned(packageName: String) {
+        // Register for changes to the app ops setting for this package while it is in PiP
+        registerAppOpsListener(packageName)
+    }
+
+    fun onActivityUnpinned() {
+        // Unregister for changes to the previously PiP'ed package
+        unregisterAppOpsListener()
+    }
+
+    private fun registerAppOpsListener(packageName: String) {
+        mAppOpsManager.startWatchingMode(
+            AppOpsManager.OP_PICTURE_IN_PICTURE, packageName,
+            mAppOpsChangedListener
+        )
+    }
+
+    private fun unregisterAppOpsListener() {
+        mAppOpsManager.stopWatchingMode(mAppOpsChangedListener)
+    }
+
+    /** Callback for PipAppOpsListener to request changes to the PIP window.  */
+    interface Callback {
+        /** Dismisses the PIP window.  */
+        fun dismissPip()
+    }
+}
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/SizeSpecSource.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/SizeSpecSource.kt
new file mode 100644
index 0000000..7b3b9ef
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/SizeSpecSource.kt
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.common.pip
+
+import android.util.Size
+import java.io.PrintWriter
+
+interface SizeSpecSource {
+    /** Returns max size allowed for the PIP window  */
+    fun getMaxSize(aspectRatio: Float): Size
+
+    /** Returns default size for the PIP window  */
+    fun getDefaultSize(aspectRatio: Float): Size
+
+    /** Returns min size allowed for the PIP window  */
+    fun getMinSize(aspectRatio: Float): Size
+
+    /** Returns the adjusted size based on current size and target aspect ratio  */
+    fun getSizeForAspectRatio(size: Size, aspectRatio: Float): Size
+
+    /** Overrides the minimum pip size requested by the app */
+    fun setOverrideMinSize(overrideMinSize: Size?)
+
+    /** Returns the minimum pip size requested by the app */
+    fun getOverrideMinSize(): Size?
+
+    /** Returns the minimum edge size of the override minimum size, or 0 if not set.  */
+    fun getOverrideMinEdgeSize(): Int {
+        val overrideMinSize = getOverrideMinSize() ?: return 0
+        return Math.min(overrideMinSize.width, overrideMinSize.height)
+    }
+
+    fun onConfigurationChanged() {}
+
+    /** Dumps the internal state of the size spec */
+    fun dump(pw: PrintWriter, prefix: String) {}
+}
\ No newline at end of file
diff --git a/core/java/com/android/internal/policy/DividerSnapAlgorithm.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DividerSnapAlgorithm.java
similarity index 98%
rename from core/java/com/android/internal/policy/DividerSnapAlgorithm.java
rename to libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DividerSnapAlgorithm.java
index a065e2b..1901e0b 100644
--- a/core/java/com/android/internal/policy/DividerSnapAlgorithm.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DividerSnapAlgorithm.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2015 The Android Open Source Project
+ * Copyright (C) 2023 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.internal.policy;
+package com.android.wm.shell.common.split;
 
 import static android.view.WindowManager.DOCKED_INVALID;
 import static android.view.WindowManager.DOCKED_LEFT;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DividerView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DividerView.java
index 2dbc444..0b0c693 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DividerView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DividerView.java
@@ -53,7 +53,6 @@
 import androidx.annotation.Nullable;
 
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.policy.DividerSnapAlgorithm;
 import com.android.internal.protolog.common.ProtoLog;
 import com.android.wm.shell.R;
 import com.android.wm.shell.animation.Interpolators;
diff --git a/core/java/com/android/internal/policy/DockedDividerUtils.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DockedDividerUtils.java
similarity index 97%
rename from core/java/com/android/internal/policy/DockedDividerUtils.java
rename to libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DockedDividerUtils.java
index b61b9de..f25dfea 100644
--- a/core/java/com/android/internal/policy/DockedDividerUtils.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/DockedDividerUtils.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2015 The Android Open Source Project
+ * Copyright (C) 2023 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.internal.policy;
+package com.android.wm.shell.common.split;
 
 import static android.view.WindowManager.DOCKED_BOTTOM;
 import static android.view.WindowManager.DOCKED_INVALID;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitLayout.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitLayout.java
index d3fada3..5d7e532 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitLayout.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitLayout.java
@@ -25,8 +25,8 @@
 import static android.view.WindowManager.DOCKED_TOP;
 
 import static com.android.internal.jank.InteractionJankMonitor.CUJ_SPLIT_SCREEN_RESIZE;
-import static com.android.internal.policy.DividerSnapAlgorithm.SnapTarget.FLAG_DISMISS_END;
-import static com.android.internal.policy.DividerSnapAlgorithm.SnapTarget.FLAG_DISMISS_START;
+import static com.android.wm.shell.common.split.DividerSnapAlgorithm.SnapTarget.FLAG_DISMISS_END;
+import static com.android.wm.shell.common.split.DividerSnapAlgorithm.SnapTarget.FLAG_DISMISS_START;
 import static com.android.wm.shell.animation.Interpolators.DIM_INTERPOLATOR;
 import static com.android.wm.shell.animation.Interpolators.SLOWDOWN_INTERPOLATOR;
 import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_BOTTOM_OR_RIGHT;
@@ -58,8 +58,6 @@
 import androidx.annotation.Nullable;
 
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.policy.DividerSnapAlgorithm;
-import com.android.internal.policy.DockedDividerUtils;
 import com.android.wm.shell.R;
 import com.android.wm.shell.ShellTaskOrganizer;
 import com.android.wm.shell.animation.Interpolators;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitScreenConstants.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitScreenConstants.java
index ef93a33..be1b9b1 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitScreenConstants.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitScreenConstants.java
@@ -16,6 +16,7 @@
 package com.android.wm.shell.common.split;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
 import static android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW;
 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
@@ -60,7 +61,8 @@
     public static final int[] CONTROLLED_WINDOWING_MODES =
             {WINDOWING_MODE_FULLSCREEN, WINDOWING_MODE_UNDEFINED};
     public static final int[] CONTROLLED_WINDOWING_MODES_WHEN_ACTIVE =
-            {WINDOWING_MODE_FULLSCREEN, WINDOWING_MODE_UNDEFINED, WINDOWING_MODE_MULTI_WINDOW};
+            {WINDOWING_MODE_FULLSCREEN, WINDOWING_MODE_UNDEFINED, WINDOWING_MODE_MULTI_WINDOW,
+            WINDOWING_MODE_FREEFORM};
 
     /** Flag applied to a transition change to identify it as a divider bar for animation. */
     public static final int FLAG_IS_DIVIDER_BAR = FLAG_FIRST_CUSTOM;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/CompatUIController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/CompatUIController.java
index 62b0799..54f8984 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/CompatUIController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/CompatUIController.java
@@ -16,12 +16,17 @@
 
 package com.android.wm.shell.compatui;
 
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
+
+import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.app.TaskInfo;
 import android.app.TaskInfo.CameraCompatControlState;
 import android.content.Context;
+import android.content.Intent;
 import android.content.res.Configuration;
 import android.hardware.display.DisplayManager;
+import android.provider.Settings;
 import android.util.ArraySet;
 import android.util.Log;
 import android.util.Pair;
@@ -41,7 +46,6 @@
 import com.android.wm.shell.common.DockStateReader;
 import com.android.wm.shell.common.ShellExecutor;
 import com.android.wm.shell.common.SyncTransactionQueue;
-import com.android.wm.shell.compatui.CompatUIWindowManager.CompatUIHintsState;
 import com.android.wm.shell.sysui.KeyguardChangeListener;
 import com.android.wm.shell.sysui.ShellController;
 import com.android.wm.shell.sysui.ShellInit;
@@ -104,6 +108,13 @@
     private Set<Integer> mSetOfTaskIdsShowingRestartDialog = new HashSet<>();
 
     /**
+     * The active user aspect ratio settings button layout if there is one (there can be at most
+     * one active).
+     */
+    @Nullable
+    private UserAspectRatioSettingsWindowManager mUserAspectRatioSettingsLayout;
+
+    /**
      * The active Letterbox Education layout if there is one (there can be at most one active).
      *
      * <p>An active layout is a layout that is eligible to be shown for the associated task but
@@ -121,38 +132,51 @@
     /** Avoid creating display context frequently for non-default display. */
     private final SparseArray<WeakReference<Context>> mDisplayContextCache = new SparseArray<>(0);
 
+    @NonNull
     private final Context mContext;
+    @NonNull
     private final ShellController mShellController;
+    @NonNull
     private final DisplayController mDisplayController;
+    @NonNull
     private final DisplayInsetsController mDisplayInsetsController;
+    @NonNull
     private final DisplayImeController mImeController;
+    @NonNull
     private final SyncTransactionQueue mSyncQueue;
+    @NonNull
     private final ShellExecutor mMainExecutor;
+    @NonNull
     private final Lazy<Transitions> mTransitionsLazy;
+    @NonNull
     private final DockStateReader mDockStateReader;
+    @NonNull
     private final CompatUIConfiguration mCompatUIConfiguration;
     // Only show each hint once automatically in the process life.
+    @NonNull
     private final CompatUIHintsState mCompatUIHintsState;
+    @NonNull
     private final CompatUIShellCommandHandler mCompatUIShellCommandHandler;
 
-    private CompatUICallback mCallback;
+    @Nullable
+    private CompatUICallback mCompatUICallback;
 
     // Indicates if the keyguard is currently showing, in which case compat UIs shouldn't
     // be shown.
     private boolean mKeyguardShowing;
 
-    public CompatUIController(Context context,
-            ShellInit shellInit,
-            ShellController shellController,
-            DisplayController displayController,
-            DisplayInsetsController displayInsetsController,
-            DisplayImeController imeController,
-            SyncTransactionQueue syncQueue,
-            ShellExecutor mainExecutor,
-            Lazy<Transitions> transitionsLazy,
-            DockStateReader dockStateReader,
-            CompatUIConfiguration compatUIConfiguration,
-            CompatUIShellCommandHandler compatUIShellCommandHandler) {
+    public CompatUIController(@NonNull Context context,
+            @NonNull ShellInit shellInit,
+            @NonNull ShellController shellController,
+            @NonNull DisplayController displayController,
+            @NonNull DisplayInsetsController displayInsetsController,
+            @NonNull DisplayImeController imeController,
+            @NonNull SyncTransactionQueue syncQueue,
+            @NonNull ShellExecutor mainExecutor,
+            @NonNull Lazy<Transitions> transitionsLazy,
+            @NonNull DockStateReader dockStateReader,
+            @NonNull CompatUIConfiguration compatUIConfiguration,
+            @NonNull CompatUIShellCommandHandler compatUIShellCommandHandler) {
         mContext = context;
         mShellController = shellController;
         mDisplayController = displayController;
@@ -175,9 +199,9 @@
         mCompatUIShellCommandHandler.onInit();
     }
 
-    /** Sets the callback for UI interactions. */
-    public void setCompatUICallback(CompatUICallback callback) {
-        mCallback = callback;
+    /** Sets the callback for Compat UI interactions. */
+    public void setCompatUICallback(@NonNull CompatUICallback compatUiCallback) {
+        mCompatUICallback = compatUiCallback;
     }
 
     /**
@@ -187,7 +211,7 @@
      * @param taskInfo {@link TaskInfo} task the activity is in.
      * @param taskListener listener to handle the Task Surface placement.
      */
-    public void onCompatInfoChanged(TaskInfo taskInfo,
+    public void onCompatInfoChanged(@NonNull TaskInfo taskInfo,
             @Nullable ShellTaskOrganizer.TaskListener taskListener) {
         if (taskInfo != null && !taskInfo.topActivityInSizeCompat) {
             mSetOfTaskIdsShowingRestartDialog.remove(taskInfo.taskId);
@@ -203,6 +227,16 @@
         createOrUpdateRestartDialogLayout(taskInfo, taskListener);
         if (mCompatUIConfiguration.getHasSeenLetterboxEducation(taskInfo.userId)) {
             createOrUpdateReachabilityEduLayout(taskInfo, taskListener);
+            // The user aspect ratio button should not be handled when a new TaskInfo is
+            // sent because of a double tap or when in multi-window mode.
+            if (taskInfo.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
+                mUserAspectRatioSettingsLayout.release();
+                mUserAspectRatioSettingsLayout = null;
+                return;
+            }
+            if (!taskInfo.isFromLetterboxDoubleTap) {
+                createOrUpdateUserAspectRatioSettingsLayout(taskInfo, taskListener);
+            }
         }
     }
 
@@ -280,8 +314,8 @@
         return mDisplaysWithIme.contains(displayId);
     }
 
-    private void createOrUpdateCompatLayout(TaskInfo taskInfo,
-            ShellTaskOrganizer.TaskListener taskListener) {
+    private void createOrUpdateCompatLayout(@NonNull TaskInfo taskInfo,
+            @Nullable ShellTaskOrganizer.TaskListener taskListener) {
         CompatUIWindowManager layout = mActiveCompatLayouts.get(taskInfo.taskId);
         if (layout != null) {
             if (layout.needsToBeRecreated(taskInfo, taskListener)) {
@@ -314,7 +348,7 @@
     CompatUIWindowManager createCompatUiWindowManager(Context context, TaskInfo taskInfo,
             ShellTaskOrganizer.TaskListener taskListener) {
         return new CompatUIWindowManager(context,
-                taskInfo, mSyncQueue, mCallback, taskListener,
+                taskInfo, mSyncQueue, mCompatUICallback, taskListener,
                 mDisplayController.getDisplayLayout(taskInfo.displayId), mCompatUIHintsState,
                 mCompatUIConfiguration, this::onRestartButtonClicked);
     }
@@ -328,12 +362,12 @@
             mSetOfTaskIdsShowingRestartDialog.add(taskInfoState.first.taskId);
             onCompatInfoChanged(taskInfoState.first, taskInfoState.second);
         } else {
-            mCallback.onSizeCompatRestartButtonClicked(taskInfoState.first.taskId);
+            mCompatUICallback.onSizeCompatRestartButtonClicked(taskInfoState.first.taskId);
         }
     }
 
-    private void createOrUpdateLetterboxEduLayout(TaskInfo taskInfo,
-            ShellTaskOrganizer.TaskListener taskListener) {
+    private void createOrUpdateLetterboxEduLayout(@NonNull TaskInfo taskInfo,
+            @Nullable ShellTaskOrganizer.TaskListener taskListener) {
         if (mActiveLetterboxEduLayout != null) {
             if (mActiveLetterboxEduLayout.needsToBeRecreated(taskInfo, taskListener)) {
                 mActiveLetterboxEduLayout.release();
@@ -342,6 +376,7 @@
                 if (!mActiveLetterboxEduLayout.updateCompatInfo(taskInfo, taskListener,
                         showOnDisplay(mActiveLetterboxEduLayout.getDisplayId()))) {
                     // The layout is no longer eligible to be shown, clear active layout.
+                    mActiveLetterboxEduLayout.release();
                     mActiveLetterboxEduLayout = null;
                 }
                 return;
@@ -371,19 +406,13 @@
             ShellTaskOrganizer.TaskListener taskListener) {
         return new LetterboxEduWindowManager(context, taskInfo,
                 mSyncQueue, taskListener, mDisplayController.getDisplayLayout(taskInfo.displayId),
-                mTransitionsLazy.get(), this::onLetterboxEduDismissed, mDockStateReader,
-                mCompatUIConfiguration);
+                mTransitionsLazy.get(),
+                stateInfo -> createOrUpdateReachabilityEduLayout(stateInfo.first, stateInfo.second),
+                mDockStateReader, mCompatUIConfiguration);
     }
 
-    private void onLetterboxEduDismissed(
-            Pair<TaskInfo, ShellTaskOrganizer.TaskListener> stateInfo) {
-        mActiveLetterboxEduLayout = null;
-        // We need to update the UI
-        createOrUpdateReachabilityEduLayout(stateInfo.first, stateInfo.second);
-    }
-
-    private void createOrUpdateRestartDialogLayout(TaskInfo taskInfo,
-            ShellTaskOrganizer.TaskListener taskListener) {
+    private void createOrUpdateRestartDialogLayout(@NonNull TaskInfo taskInfo,
+            @Nullable ShellTaskOrganizer.TaskListener taskListener) {
         RestartDialogWindowManager layout =
                 mTaskIdToRestartDialogWindowManagerMap.get(taskInfo.taskId);
         if (layout != null) {
@@ -428,7 +457,7 @@
     private void onRestartDialogCallback(
             Pair<TaskInfo, ShellTaskOrganizer.TaskListener> stateInfo) {
         mTaskIdToRestartDialogWindowManagerMap.remove(stateInfo.first.taskId);
-        mCallback.onSizeCompatRestartButtonClicked(stateInfo.first.taskId);
+        mCompatUICallback.onSizeCompatRestartButtonClicked(stateInfo.first.taskId);
     }
 
     private void onRestartDialogDismissCallback(
@@ -437,8 +466,8 @@
         onCompatInfoChanged(stateInfo.first, stateInfo.second);
     }
 
-    private void createOrUpdateReachabilityEduLayout(TaskInfo taskInfo,
-            ShellTaskOrganizer.TaskListener taskListener) {
+    private void createOrUpdateReachabilityEduLayout(@NonNull TaskInfo taskInfo,
+            @Nullable ShellTaskOrganizer.TaskListener taskListener) {
         if (mActiveReachabilityEduLayout != null) {
             if (mActiveReachabilityEduLayout.needsToBeRecreated(taskInfo, taskListener)) {
                 mActiveReachabilityEduLayout.release();
@@ -448,6 +477,7 @@
                 if (!mActiveReachabilityEduLayout.updateCompatInfo(taskInfo, taskListener,
                         showOnDisplay(mActiveReachabilityEduLayout.getDisplayId()))) {
                     // The layout is no longer eligible to be shown, remove from active layouts.
+                    mActiveReachabilityEduLayout.release();
                     mActiveReachabilityEduLayout = null;
                 }
                 return;
@@ -478,14 +508,67 @@
             ShellTaskOrganizer.TaskListener taskListener) {
         return new ReachabilityEduWindowManager(context, taskInfo, mSyncQueue,
                 taskListener, mDisplayController.getDisplayLayout(taskInfo.displayId),
-                mCompatUIConfiguration, mMainExecutor);
+                mCompatUIConfiguration, mMainExecutor, this::onInitialReachabilityEduDismissed);
     }
 
+    private void onInitialReachabilityEduDismissed(@NonNull TaskInfo taskInfo,
+            @NonNull ShellTaskOrganizer.TaskListener taskListener) {
+        // We need to update the UI otherwise it will not be shown until the user relaunches the app
+        createOrUpdateUserAspectRatioSettingsLayout(taskInfo, taskListener);
+    }
+
+    private void createOrUpdateUserAspectRatioSettingsLayout(@NonNull TaskInfo taskInfo,
+            @Nullable ShellTaskOrganizer.TaskListener taskListener) {
+        if (mUserAspectRatioSettingsLayout != null) {
+            if (mUserAspectRatioSettingsLayout.needsToBeRecreated(taskInfo, taskListener)) {
+                mUserAspectRatioSettingsLayout.release();
+                mUserAspectRatioSettingsLayout = null;
+            } else {
+                // UI already exists, update the UI layout.
+                if (!mUserAspectRatioSettingsLayout.updateCompatInfo(taskInfo, taskListener,
+                        showOnDisplay(mUserAspectRatioSettingsLayout.getDisplayId()))) {
+                    mUserAspectRatioSettingsLayout.release();
+                    mUserAspectRatioSettingsLayout = null;
+                }
+                return;
+            }
+        }
+
+        // Create a new UI layout.
+        final Context context = getOrCreateDisplayContext(taskInfo.displayId);
+        if (context == null) {
+            return;
+        }
+        final UserAspectRatioSettingsWindowManager newLayout =
+                createUserAspectRatioSettingsWindowManager(context, taskInfo, taskListener);
+        if (newLayout.createLayout(showOnDisplay(taskInfo.displayId))) {
+            // The new layout is eligible to be shown, add it the active layouts.
+            mUserAspectRatioSettingsLayout = newLayout;
+        }
+    }
+
+    @VisibleForTesting
+    @NonNull
+    UserAspectRatioSettingsWindowManager createUserAspectRatioSettingsWindowManager(
+            @NonNull Context context, @NonNull TaskInfo taskInfo,
+            @Nullable ShellTaskOrganizer.TaskListener taskListener) {
+        return new UserAspectRatioSettingsWindowManager(context, taskInfo, mSyncQueue,
+                taskListener, mDisplayController.getDisplayLayout(taskInfo.displayId),
+                mCompatUIHintsState, this::launchUserAspectRatioSettings, mMainExecutor);
+    }
+
+    private void launchUserAspectRatioSettings(
+            @NonNull TaskInfo taskInfo, @NonNull ShellTaskOrganizer.TaskListener taskListener) {
+        final Intent intent = new Intent(Settings.ACTION_MANAGE_USER_ASPECT_RATIO_SETTINGS);
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
+        mContext.startActivity(intent);
+    }
 
     private void removeLayouts(int taskId) {
-        final CompatUIWindowManager layout = mActiveCompatLayouts.get(taskId);
-        if (layout != null) {
-            layout.release();
+        final CompatUIWindowManager compatLayout = mActiveCompatLayouts.get(taskId);
+        if (compatLayout != null) {
+            compatLayout.release();
             mActiveCompatLayouts.remove(taskId);
         }
 
@@ -506,6 +589,12 @@
             mActiveReachabilityEduLayout.release();
             mActiveReachabilityEduLayout = null;
         }
+
+        if (mUserAspectRatioSettingsLayout != null
+                && mUserAspectRatioSettingsLayout.getTaskId() == taskId) {
+            mUserAspectRatioSettingsLayout.release();
+            mUserAspectRatioSettingsLayout = null;
+        }
     }
 
     private Context getOrCreateDisplayContext(int displayId) {
@@ -561,6 +650,10 @@
         if (mActiveReachabilityEduLayout != null && condition.test(mActiveReachabilityEduLayout)) {
             callback.accept(mActiveReachabilityEduLayout);
         }
+        if (mUserAspectRatioSettingsLayout != null && condition.test(
+                mUserAspectRatioSettingsLayout)) {
+            callback.accept(mUserAspectRatioSettingsLayout);
+        }
     }
 
     /** An implementation of {@link OnInsetsChangedListener} for a given display id. */
@@ -595,4 +688,14 @@
             insetsChanged(insetsState);
         }
     }
+
+    /**
+     * A class holding the state of the compat UI hints, which is shared between all compat UI
+     * window managers.
+     */
+    static class CompatUIHintsState {
+        boolean mHasShownSizeCompatHint;
+        boolean mHasShownCameraCompatHint;
+        boolean mHasShownUserAspectRatioSettingsButtonHint;
+    }
 }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/CompatUIWindowManager.java b/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/CompatUIWindowManager.java
index 065806d..ce3c509 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/CompatUIWindowManager.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/CompatUIWindowManager.java
@@ -38,6 +38,7 @@
 import com.android.wm.shell.common.DisplayLayout;
 import com.android.wm.shell.common.SyncTransactionQueue;
 import com.android.wm.shell.compatui.CompatUIController.CompatUICallback;
+import com.android.wm.shell.compatui.CompatUIController.CompatUIHintsState;
 
 import java.util.function.Consumer;
 
@@ -235,15 +236,4 @@
         return mCameraCompatControlState != CAMERA_COMPAT_CONTROL_HIDDEN
                 && mCameraCompatControlState != CAMERA_COMPAT_CONTROL_DISMISSED;
     }
-
-    /**
-     * A class holding the state of the compat UI hints, which is shared between all compat UI
-     * window managers.
-     */
-    static class CompatUIHintsState {
-        @VisibleForTesting
-        boolean mHasShownSizeCompatHint;
-        @VisibleForTesting
-        boolean mHasShownCameraCompatHint;
-    }
 }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/ReachabilityEduWindowManager.java b/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/ReachabilityEduWindowManager.java
index 95bb1fe..9de3f9d 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/ReachabilityEduWindowManager.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/ReachabilityEduWindowManager.java
@@ -36,6 +36,8 @@
 import com.android.wm.shell.common.ShellExecutor;
 import com.android.wm.shell.common.SyncTransactionQueue;
 
+import java.util.function.BiConsumer;
+
 /**
  * Window manager for the reachability education
  */
@@ -73,6 +75,8 @@
     // we need to animate them.
     private boolean mHasLetterboxSizeChanged;
 
+    private final BiConsumer<TaskInfo, ShellTaskOrganizer.TaskListener> mOnDismissCallback;
+
     @Nullable
     @VisibleForTesting
     ReachabilityEduLayout mLayout;
@@ -80,7 +84,8 @@
     ReachabilityEduWindowManager(Context context, TaskInfo taskInfo,
             SyncTransactionQueue syncQueue,
             ShellTaskOrganizer.TaskListener taskListener, DisplayLayout displayLayout,
-            CompatUIConfiguration compatUIConfiguration, ShellExecutor mainExecutor) {
+            CompatUIConfiguration compatUIConfiguration, ShellExecutor mainExecutor,
+            BiConsumer<TaskInfo, ShellTaskOrganizer.TaskListener> onDismissCallback) {
         super(context, taskInfo, syncQueue, taskListener, displayLayout);
         mIsActivityLetterboxed = taskInfo.isLetterboxDoubleTapEnabled;
         mLetterboxVerticalPosition = taskInfo.topActivityLetterboxVerticalPosition;
@@ -89,6 +94,7 @@
         mTopActivityLetterboxHeight = taskInfo.topActivityLetterboxHeight;
         mCompatUIConfiguration = compatUIConfiguration;
         mMainExecutor = mainExecutor;
+        mOnDismissCallback = onDismissCallback;
     }
 
     @Override
@@ -217,13 +223,17 @@
             return;
         }
         final TaskInfo lastTaskInfo = getLastTaskInfo();
+        final boolean hasSeenHorizontalReachabilityEdu =
+                mCompatUIConfiguration.hasSeenHorizontalReachabilityEducation(lastTaskInfo);
+        final boolean hasSeenVerticalReachabilityEdu =
+                mCompatUIConfiguration.hasSeenVerticalReachabilityEducation(lastTaskInfo);
         final boolean eligibleForDisplayHorizontalEducation = mForceUpdate
-                || !mCompatUIConfiguration.hasSeenHorizontalReachabilityEducation(lastTaskInfo)
+                || !hasSeenHorizontalReachabilityEdu
                 || (mHasUserDoubleTapped
                     && (mLetterboxHorizontalPosition == REACHABILITY_LEFT_OR_UP_POSITION
                         || mLetterboxHorizontalPosition == REACHABILITY_RIGHT_OR_BOTTOM_POSITION));
         final boolean eligibleForDisplayVerticalEducation = mForceUpdate
-                || !mCompatUIConfiguration.hasSeenVerticalReachabilityEducation(lastTaskInfo)
+                || !hasSeenVerticalReachabilityEdu
                 || (mHasUserDoubleTapped
                     && (mLetterboxVerticalPosition == REACHABILITY_LEFT_OR_UP_POSITION
                         || mLetterboxVerticalPosition == REACHABILITY_RIGHT_OR_BOTTOM_POSITION));
@@ -239,6 +249,14 @@
             if (!mHasLetterboxSizeChanged) {
                 updateHideTime();
                 mMainExecutor.executeDelayed(this::hideReachability, DISAPPEAR_DELAY_MS);
+                // If reachability education has been seen for the first time, trigger callback to
+                // display aspect ratio settings button once reachability education disappears
+                if (hasShownHorizontalReachabilityEduFirstTime(hasSeenHorizontalReachabilityEdu)
+                        || hasShownVerticalReachabilityEduFirstTime(
+                        hasSeenVerticalReachabilityEdu)) {
+                    mMainExecutor.executeDelayed(this::triggerOnDismissCallback,
+                            DISAPPEAR_DELAY_MS);
+                }
             }
             mHasUserDoubleTapped = false;
         } else {
@@ -246,6 +264,38 @@
         }
     }
 
+    /**
+     * Compares the value of
+     * {@link CompatUIConfiguration#hasSeenHorizontalReachabilityEducation} before and after the
+     * layout is shown. Horizontal reachability education is considered seen for the first time if
+     * prior to viewing the layout,
+     * {@link CompatUIConfiguration#hasSeenHorizontalReachabilityEducation} is {@code false}
+     * but becomes {@code true} once the current layout is shown.
+     */
+    private boolean hasShownHorizontalReachabilityEduFirstTime(
+            boolean previouslyShownHorizontalReachabilityEducation) {
+        return !previouslyShownHorizontalReachabilityEducation
+                && mCompatUIConfiguration.hasSeenHorizontalReachabilityEducation(getLastTaskInfo());
+    }
+
+    /**
+     * Compares the value of
+     * {@link CompatUIConfiguration#hasSeenVerticalReachabilityEducation} before and after the
+     * layout is shown. Horizontal reachability education is considered seen for the first time if
+     * prior to viewing the layout,
+     * {@link CompatUIConfiguration#hasSeenVerticalReachabilityEducation} is {@code false}
+     * but becomes {@code true} once the current layout is shown.
+     */
+    private boolean hasShownVerticalReachabilityEduFirstTime(
+            boolean previouslyShownVerticalReachabilityEducation) {
+        return !previouslyShownVerticalReachabilityEducation
+                && mCompatUIConfiguration.hasSeenVerticalReachabilityEducation(getLastTaskInfo());
+    }
+
+    private void triggerOnDismissCallback() {
+        mOnDismissCallback.accept(getLastTaskInfo(), getTaskListener());
+    }
+
     private void hideReachability() {
         if (mLayout == null || !shouldHideEducation()) {
             return;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/UserAspectRatioSettingsLayout.java b/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/UserAspectRatioSettingsLayout.java
new file mode 100644
index 0000000..5eeb3b6
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/UserAspectRatioSettingsLayout.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.compatui;
+
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.animation.ObjectAnimator;
+import android.annotation.IdRes;
+import android.annotation.NonNull;
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.View;
+import android.widget.ImageButton;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import com.android.wm.shell.R;
+
+/**
+ * Layout for the user aspect ratio button which opens the app list page in settings
+ * and allows users to change apps aspect ratio.
+ */
+public class UserAspectRatioSettingsLayout extends LinearLayout {
+
+    private static final float ALPHA_FULL_TRANSPARENT = 0f;
+
+    private static final float ALPHA_FULL_OPAQUE = 1f;
+
+    private static final long VISIBILITY_ANIMATION_DURATION_MS = 50;
+
+    private static final String ALPHA_PROPERTY_NAME = "alpha";
+
+    private UserAspectRatioSettingsWindowManager mWindowManager;
+
+    public UserAspectRatioSettingsLayout(Context context) {
+        this(context, null);
+    }
+
+    public UserAspectRatioSettingsLayout(Context context, AttributeSet attrs) {
+        this(context, attrs, 0);
+    }
+
+    public UserAspectRatioSettingsLayout(Context context, AttributeSet attrs, int defStyleAttr) {
+        this(context, attrs, defStyleAttr, 0);
+    }
+
+    public UserAspectRatioSettingsLayout(Context context, AttributeSet attrs, int defStyleAttr,
+            int defStyleRes) {
+        super(context, attrs, defStyleAttr, defStyleRes);
+    }
+
+    void inject(@NonNull UserAspectRatioSettingsWindowManager windowManager) {
+        mWindowManager = windowManager;
+    }
+
+    void setUserAspectRatioSettingsHintVisibility(boolean show) {
+        setViewVisibility(R.id.user_aspect_ratio_settings_hint, show);
+    }
+
+    void setUserAspectRatioButtonVisibility(boolean show) {
+        setViewVisibility(R.id.user_aspect_ratio_settings_button, show);
+        // Hint should never be visible without button.
+        if (!show) {
+            setUserAspectRatioSettingsHintVisibility(/* show= */ false);
+        }
+    }
+
+    private void setViewVisibility(@IdRes int resId, boolean show) {
+        final View view = findViewById(resId);
+        int visibility = show ? View.VISIBLE : View.GONE;
+        if (view.getVisibility() == visibility) {
+            return;
+        }
+        if (show) {
+            showItem(view);
+        } else {
+            view.setVisibility(visibility);
+        }
+    }
+
+    @Override
+    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
+        super.onLayout(changed, left, top, right, bottom);
+        // Need to relayout after changes like hiding / showing a hint since they affect size.
+        // Doing this directly in setUserAspectRatioButtonVisibility can result in flaky animation.
+        mWindowManager.relayout();
+    }
+
+    @Override
+    protected void onFinishInflate() {
+        super.onFinishInflate();
+
+        final ImageButton userAspectRatioButton =
+                findViewById(R.id.user_aspect_ratio_settings_button);
+        userAspectRatioButton.setOnClickListener(
+                view -> mWindowManager.onUserAspectRatioSettingsButtonClicked());
+        userAspectRatioButton.setOnLongClickListener(view -> {
+            mWindowManager.onUserAspectRatioSettingsButtonLongClicked();
+            return true;
+        });
+
+        final LinearLayout sizeCompatHint = findViewById(R.id.user_aspect_ratio_settings_hint);
+        ((TextView) sizeCompatHint.findViewById(R.id.compat_mode_hint_text))
+                .setText(R.string.user_aspect_ratio_settings_button_hint);
+        sizeCompatHint.setOnClickListener(
+                view -> setUserAspectRatioSettingsHintVisibility(/* show= */ false));
+    }
+
+    private void showItem(@NonNull View view) {
+        view.setVisibility(View.VISIBLE);
+        final ObjectAnimator fadeIn = ObjectAnimator.ofFloat(view, ALPHA_PROPERTY_NAME,
+                ALPHA_FULL_TRANSPARENT, ALPHA_FULL_OPAQUE);
+        fadeIn.setDuration(VISIBILITY_ANIMATION_DURATION_MS);
+        fadeIn.addListener(new AnimatorListenerAdapter() {
+            @Override
+            public void onAnimationEnd(Animator animation) {
+                view.setVisibility(View.VISIBLE);
+            }
+        });
+        fadeIn.start();
+    }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/UserAspectRatioSettingsWindowManager.java b/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/UserAspectRatioSettingsWindowManager.java
new file mode 100644
index 0000000..bd53dc7
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/compatui/UserAspectRatioSettingsWindowManager.java
@@ -0,0 +1,211 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.compatui;
+
+import static android.window.TaskConstants.TASK_CHILD_LAYER_COMPAT_UI;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.app.TaskInfo;
+import android.content.Context;
+import android.graphics.Rect;
+import android.os.SystemClock;
+import android.view.LayoutInflater;
+import android.view.View;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.wm.shell.R;
+import com.android.wm.shell.ShellTaskOrganizer;
+import com.android.wm.shell.common.DisplayLayout;
+import com.android.wm.shell.common.ShellExecutor;
+import com.android.wm.shell.common.SyncTransactionQueue;
+import com.android.wm.shell.compatui.CompatUIController.CompatUIHintsState;
+
+import java.util.function.BiConsumer;
+
+/**
+ * Window manager for the user aspect ratio settings button which allows users to go to
+ * app settings and change apps aspect ratio.
+ */
+class UserAspectRatioSettingsWindowManager extends CompatUIWindowManagerAbstract {
+
+    private static final long SHOW_USER_ASPECT_RATIO_BUTTON_DELAY_MS = 500L;
+
+    private static final long HIDE_USER_ASPECT_RATIO_BUTTON_DELAY_MS = 4000L;
+
+    private long mNextButtonHideTimeMs = -1L;
+
+    private final BiConsumer<TaskInfo, ShellTaskOrganizer.TaskListener> mOnButtonClicked;
+
+    private final ShellExecutor mShellExecutor;
+
+    @VisibleForTesting
+    @NonNull
+    final CompatUIHintsState mCompatUIHintsState;
+
+    @Nullable
+    private UserAspectRatioSettingsLayout mLayout;
+
+    // Remember the last reported states in case visibility changes due to keyguard or IME updates.
+    @VisibleForTesting
+    boolean mHasUserAspectRatioSettingsButton;
+
+    UserAspectRatioSettingsWindowManager(@NonNull Context context, @NonNull TaskInfo taskInfo,
+            @NonNull SyncTransactionQueue syncQueue,
+            @Nullable ShellTaskOrganizer.TaskListener taskListener,
+            @NonNull DisplayLayout displayLayout, @NonNull CompatUIHintsState compatUIHintsState,
+            @NonNull BiConsumer<TaskInfo, ShellTaskOrganizer.TaskListener> onButtonClicked,
+            @NonNull ShellExecutor shellExecutor) {
+        super(context, taskInfo, syncQueue, taskListener, displayLayout);
+        mShellExecutor = shellExecutor;
+        mHasUserAspectRatioSettingsButton = getHasUserAspectRatioSettingsButton(taskInfo);
+        mCompatUIHintsState = compatUIHintsState;
+        mOnButtonClicked = onButtonClicked;
+    }
+
+    @Override
+    protected int getZOrder() {
+        return TASK_CHILD_LAYER_COMPAT_UI + 1;
+    }
+
+    @Override
+    protected @Nullable View getLayout() {
+        return mLayout;
+    }
+
+    @Override
+    protected void removeLayout() {
+        mLayout = null;
+    }
+
+    @Override
+    protected boolean eligibleToShowLayout() {
+        return mHasUserAspectRatioSettingsButton;
+    }
+
+    @Override
+    protected View createLayout() {
+        mLayout = inflateLayout();
+        mLayout.inject(this);
+
+        updateVisibilityOfViews();
+
+        return mLayout;
+    }
+
+    @VisibleForTesting
+    UserAspectRatioSettingsLayout inflateLayout() {
+        return (UserAspectRatioSettingsLayout) LayoutInflater.from(mContext).inflate(
+                R.layout.user_aspect_ratio_settings_layout, null);
+    }
+
+    @Override
+    public boolean updateCompatInfo(@NonNull TaskInfo taskInfo,
+            @NonNull ShellTaskOrganizer.TaskListener taskListener, boolean canShow) {
+        final boolean prevHasUserAspectRatioSettingsButton = mHasUserAspectRatioSettingsButton;
+        mHasUserAspectRatioSettingsButton = getHasUserAspectRatioSettingsButton(taskInfo);
+
+        if (!super.updateCompatInfo(taskInfo, taskListener, canShow)) {
+            return false;
+        }
+
+        if (prevHasUserAspectRatioSettingsButton != mHasUserAspectRatioSettingsButton) {
+            updateVisibilityOfViews();
+        }
+        return true;
+    }
+
+    /** Called when the user aspect ratio settings button is clicked. */
+    void onUserAspectRatioSettingsButtonClicked() {
+        mOnButtonClicked.accept(getLastTaskInfo(), getTaskListener());
+    }
+
+    /** Called when the user aspect ratio settings button is long clicked. */
+    void onUserAspectRatioSettingsButtonLongClicked() {
+        if (mLayout == null) {
+            return;
+        }
+        mLayout.setUserAspectRatioSettingsHintVisibility(/* show= */ true);
+        mNextButtonHideTimeMs = updateHideTime(HIDE_USER_ASPECT_RATIO_BUTTON_DELAY_MS);
+        mShellExecutor.executeDelayed(this::hideUserAspectRatioButton,
+                HIDE_USER_ASPECT_RATIO_BUTTON_DELAY_MS);
+    }
+
+    @Override
+    @VisibleForTesting
+    public void updateSurfacePosition() {
+        if (mLayout == null) {
+            return;
+        }
+        // Position of the button in the container coordinate.
+        final Rect taskBounds = getTaskBounds();
+        final Rect taskStableBounds = getTaskStableBounds();
+        final int positionX = getLayoutDirection() == View.LAYOUT_DIRECTION_RTL
+                ? taskStableBounds.left - taskBounds.left
+                : taskStableBounds.right - taskBounds.left - mLayout.getMeasuredWidth();
+        final int positionY = taskStableBounds.bottom - taskBounds.top
+                - mLayout.getMeasuredHeight();
+        updateSurfacePosition(positionX, positionY);
+    }
+
+    @VisibleForTesting
+    void updateVisibilityOfViews() {
+        if (mHasUserAspectRatioSettingsButton) {
+            mShellExecutor.executeDelayed(this::showUserAspectRatioButton,
+                    SHOW_USER_ASPECT_RATIO_BUTTON_DELAY_MS);
+            mNextButtonHideTimeMs = updateHideTime(HIDE_USER_ASPECT_RATIO_BUTTON_DELAY_MS);
+            mShellExecutor.executeDelayed(this::hideUserAspectRatioButton,
+                    HIDE_USER_ASPECT_RATIO_BUTTON_DELAY_MS);
+        } else {
+            mShellExecutor.removeCallbacks(this::showUserAspectRatioButton);
+            mShellExecutor.execute(this::hideUserAspectRatioButton);
+        }
+    }
+
+    private void showUserAspectRatioButton() {
+        if (mLayout == null) {
+            return;
+        }
+        mLayout.setUserAspectRatioButtonVisibility(true);
+        // Only show by default for the first time.
+        if (!mCompatUIHintsState.mHasShownUserAspectRatioSettingsButtonHint) {
+            mLayout.setUserAspectRatioSettingsHintVisibility(/* show= */ true);
+            mCompatUIHintsState.mHasShownUserAspectRatioSettingsButtonHint = true;
+        }
+    }
+
+    private void hideUserAspectRatioButton() {
+        if (mLayout == null || !isHideDelayReached(mNextButtonHideTimeMs)) {
+            return;
+        }
+        mLayout.setUserAspectRatioButtonVisibility(false);
+    }
+
+    private boolean isHideDelayReached(long nextHideTime) {
+        return SystemClock.uptimeMillis() >= nextHideTime;
+    }
+
+    private long updateHideTime(long hideDelay) {
+        return SystemClock.uptimeMillis() + hideDelay;
+    }
+
+    private boolean getHasUserAspectRatioSettingsButton(@NonNull TaskInfo taskInfo) {
+        return  taskInfo.topActivityEligibleForUserAspectRatioButton
+                && (taskInfo.topActivityBoundsLetterboxed
+                    || taskInfo.isUserFullscreenOverrideEnabled);
+    }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvWMShellModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvWMShellModule.java
index 9facbd5..b52a118 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvWMShellModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvWMShellModule.java
@@ -49,11 +49,11 @@
 import java.util.Optional;
 
 /**
- * Provides dependencies from {@link com.android.wm.shell}, these dependencies are only
- * accessible from components within the WM subcomponent (can be explicitly exposed to the
- * SysUIComponent, see {@link WMComponent}).
+ * Provides dependencies from {@link com.android.wm.shell}, these dependencies are only accessible
+ * from components within the WM subcomponent (can be explicitly exposed to the SysUIComponent, see
+ * {@link com.android.systemui.dagger.WMComponent}).
  *
- * This module only defines Shell dependencies for the TV SystemUI implementation.  Common
+ * <p>This module only defines Shell dependencies for the TV SystemUI implementation. Common
  * dependencies should go into {@link WMShellBaseModule}.
  */
 @Module(includes = {TvPipModule.class})
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
index 422e3b0..c06b22c 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
@@ -36,6 +36,7 @@
 import com.android.wm.shell.back.BackAnimation;
 import com.android.wm.shell.back.BackAnimationBackground;
 import com.android.wm.shell.back.BackAnimationController;
+import com.android.wm.shell.back.ShellBackAnimationRegistry;
 import com.android.wm.shell.bubbles.BubbleController;
 import com.android.wm.shell.bubbles.Bubbles;
 import com.android.wm.shell.common.DevicePostureController;
@@ -44,6 +45,7 @@
 import com.android.wm.shell.common.DisplayInsetsController;
 import com.android.wm.shell.common.DisplayLayout;
 import com.android.wm.shell.common.DockStateReader;
+import com.android.wm.shell.common.FloatingContentCoordinator;
 import com.android.wm.shell.common.LaunchAdjacentController;
 import com.android.wm.shell.common.ShellExecutor;
 import com.android.wm.shell.common.SyncTransactionQueue;
@@ -73,7 +75,6 @@
 import com.android.wm.shell.keyguard.KeyguardTransitions;
 import com.android.wm.shell.onehanded.OneHanded;
 import com.android.wm.shell.onehanded.OneHandedController;
-import com.android.wm.shell.pip.Pip;
 import com.android.wm.shell.recents.RecentTasks;
 import com.android.wm.shell.recents.RecentTasksController;
 import com.android.wm.shell.recents.RecentsTransitionHandler;
@@ -107,9 +108,9 @@
 /**
  * Provides basic dependencies from {@link com.android.wm.shell}, these dependencies are only
  * accessible from components within the WM subcomponent (can be explicitly exposed to the
- * SysUIComponent, see {@link WMComponent}).
+ * SysUIComponent, see {@link com.android.systemui.dagger.WMComponent}).
  *
- * This module only defines *common* dependencies across various SystemUI implementations,
+ * <p>This module only defines *common* dependencies across various SystemUI implementations,
  * dependencies that are device/form factor SystemUI implementation specific should go into their
  * respective modules (ie. {@link WMShellModule} for handheld, {@link TvWMShellModule} for tv, etc.)
  */
@@ -122,6 +123,12 @@
 
     @WMSingleton
     @Provides
+    static FloatingContentCoordinator provideFloatingContentCoordinator() {
+        return new FloatingContentCoordinator();
+    }
+
+    @WMSingleton
+    @Provides
     static DisplayController provideDisplayController(Context context,
             IWindowManager wmService,
             ShellInit shellInit,
@@ -303,16 +310,25 @@
             ShellController shellController,
             @ShellMainThread ShellExecutor shellExecutor,
             @ShellBackgroundThread Handler backgroundHandler,
-            BackAnimationBackground backAnimationBackground
-    ) {
+            BackAnimationBackground backAnimationBackground,
+            Optional<ShellBackAnimationRegistry> shellBackAnimationRegistry) {
         if (BackAnimationController.IS_ENABLED) {
-            return Optional.of(
-                    new BackAnimationController(shellInit, shellController, shellExecutor,
-                            backgroundHandler, context, backAnimationBackground));
+            return shellBackAnimationRegistry.map(
+                    (animations) ->
+                            new BackAnimationController(
+                                    shellInit,
+                                    shellController,
+                                    shellExecutor,
+                                    backgroundHandler,
+                                    context,
+                                    backAnimationBackground,
+                                    animations));
         }
         return Optional.empty();
     }
 
+    @BindsOptionalOf
+    abstract ShellBackAnimationRegistry optionalBackAnimationRegistry();
 
     //
     // Bubbles (optional feature)
@@ -797,7 +813,6 @@
             ShellTaskOrganizer shellTaskOrganizer,
             Optional<BubbleController> bubblesOptional,
             Optional<SplitScreenController> splitScreenOptional,
-            Optional<Pip> pipOptional,
             FullscreenTaskListener fullscreenTaskListener,
             Optional<UnfoldAnimationController> unfoldAnimationController,
             Optional<UnfoldTransitionHandler> unfoldTransitionHandler,
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
index 881c8f5..36d2a70 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
@@ -52,6 +52,7 @@
 import com.android.wm.shell.common.annotations.ShellAnimationThread;
 import com.android.wm.shell.common.annotations.ShellBackgroundThread;
 import com.android.wm.shell.common.annotations.ShellMainThread;
+import com.android.wm.shell.dagger.back.ShellBackAnimationModule;
 import com.android.wm.shell.dagger.pip.PipModule;
 import com.android.wm.shell.desktopmode.DesktopModeController;
 import com.android.wm.shell.desktopmode.DesktopModeStatus;
@@ -100,17 +101,19 @@
 import java.util.Optional;
 
 /**
- * Provides dependencies from {@link com.android.wm.shell}, these dependencies are only
- * accessible from components within the WM subcomponent (can be explicitly exposed to the
- * SysUIComponent, see {@link WMComponent}).
+ * Provides dependencies from {@link com.android.wm.shell}, these dependencies are only accessible
+ * from components within the WM subcomponent (can be explicitly exposed to the SysUIComponent, see
+ * {@link WMComponent}).
  *
- * This module only defines Shell dependencies for handheld SystemUI implementation.  Common
+ * <p>This module only defines Shell dependencies for handheld SystemUI implementation. Common
  * dependencies should go into {@link WMShellBaseModule}.
  */
-@Module(includes = {
-        WMShellBaseModule.class,
-        PipModule.class
-})
+@Module(
+        includes = {
+            WMShellBaseModule.class,
+            PipModule.class,
+            ShellBackAnimationModule.class,
+        })
 public abstract class WMShellModule {
 
     //
@@ -325,12 +328,13 @@
             Optional<RecentTasksController> recentTasks,
             LaunchAdjacentController launchAdjacentController,
             Optional<WindowDecorViewModel> windowDecorViewModel,
+            Optional<DesktopTasksController> desktopTasksController,
             @ShellMainThread ShellExecutor mainExecutor) {
         return new SplitScreenController(context, shellInit, shellCommandHandler, shellController,
                 shellTaskOrganizer, syncQueue, rootTaskDisplayAreaOrganizer, displayController,
                 displayImeController, displayInsetsController, dragAndDropController, transitions,
                 transactionPool, iconProvider, recentTasks, launchAdjacentController,
-                windowDecorViewModel, mainExecutor);
+                windowDecorViewModel, desktopTasksController, mainExecutor);
     }
 
     //
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/back/ShellBackAnimationModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/back/ShellBackAnimationModule.java
new file mode 100644
index 0000000..b34c6b2
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/back/ShellBackAnimationModule.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.dagger.back;
+
+import com.android.wm.shell.back.CrossActivityAnimation;
+import com.android.wm.shell.back.CrossTaskBackAnimation;
+import com.android.wm.shell.back.CustomizeActivityAnimation;
+import com.android.wm.shell.back.ShellBackAnimation;
+import com.android.wm.shell.back.ShellBackAnimationRegistry;
+
+import dagger.Binds;
+import dagger.Module;
+import dagger.Provides;
+
+/** Default animation definitions for predictive back. */
+@Module
+public interface ShellBackAnimationModule {
+    /** Default animation registry */
+    @Provides
+    static ShellBackAnimationRegistry provideBackAnimationRegistry(
+            @ShellBackAnimation.CrossActivity ShellBackAnimation crossActivity,
+            @ShellBackAnimation.CrossTask ShellBackAnimation crossTask,
+            @ShellBackAnimation.CustomizeActivity ShellBackAnimation customizeActivity) {
+        return new ShellBackAnimationRegistry(
+                crossActivity,
+                crossTask,
+                customizeActivity,
+                /* defaultBackToHomeAnimation= */ null);
+    }
+
+    /** Default cross activity back animation */
+    @Binds
+    @ShellBackAnimation.CrossActivity
+    ShellBackAnimation bindCrossActivityShellBackAnimation(
+            CrossActivityAnimation crossActivityAnimation);
+
+    /** Default cross task back animation */
+    @Binds
+    @ShellBackAnimation.CrossTask
+    ShellBackAnimation provideCrossTaskShellBackAnimation(
+            CrossTaskBackAnimation crossTaskBackAnimation);
+
+    /** Default customized activity back animation */
+    @Binds
+    @ShellBackAnimation.CustomizeActivity
+    ShellBackAnimation provideCustomizeActivityShellBackAnimation(
+            CustomizeActivityAnimation customizeActivityAnimation);
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java
index 16c3960..9bf973f 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java
@@ -30,12 +30,14 @@
 import com.android.wm.shell.common.TabletopModeController;
 import com.android.wm.shell.common.TaskStackListenerImpl;
 import com.android.wm.shell.common.annotations.ShellMainThread;
+import com.android.wm.shell.common.pip.PhoneSizeSpecSource;
+import com.android.wm.shell.common.pip.PipAppOpsListener;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.dagger.WMShellBaseModule;
 import com.android.wm.shell.dagger.WMSingleton;
 import com.android.wm.shell.onehanded.OneHandedController;
 import com.android.wm.shell.pip.Pip;
 import com.android.wm.shell.pip.PipAnimationController;
-import com.android.wm.shell.pip.PipAppOpsListener;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
 import com.android.wm.shell.pip.PipDisplayLayoutState;
@@ -53,7 +55,6 @@
 import com.android.wm.shell.pip.phone.PhonePipMenuController;
 import com.android.wm.shell.pip.phone.PipController;
 import com.android.wm.shell.pip.phone.PipMotionHelper;
-import com.android.wm.shell.pip.phone.PipSizeSpecHandler;
 import com.android.wm.shell.pip.phone.PipTouchHandler;
 import com.android.wm.shell.splitscreen.SplitScreenController;
 import com.android.wm.shell.sysui.ShellCommandHandler;
@@ -87,7 +88,6 @@
             PipBoundsAlgorithm pipBoundsAlgorithm,
             PhonePipKeepClearAlgorithm pipKeepClearAlgorithm,
             PipBoundsState pipBoundsState,
-            PipSizeSpecHandler pipSizeSpecHandler,
             PipDisplayLayoutState pipDisplayLayoutState,
             PipMotionHelper pipMotionHelper,
             PipMediaController pipMediaController,
@@ -110,8 +110,7 @@
                     context, shellInit, shellCommandHandler, shellController,
                     displayController, pipAnimationController, pipAppOpsListener,
                     pipBoundsAlgorithm,
-                    pipKeepClearAlgorithm, pipBoundsState, pipSizeSpecHandler,
-                    pipDisplayLayoutState,
+                    pipKeepClearAlgorithm, pipBoundsState, pipDisplayLayoutState,
                     pipMotionHelper, pipMediaController, phonePipMenuController, pipTaskOrganizer,
                     pipTransitionState, pipTouchHandler, pipTransitionController,
                     windowManagerShellWrapper, taskStackListener, pipParamsChangedForwarder,
@@ -123,8 +122,8 @@
     @WMSingleton
     @Provides
     static PipBoundsState providePipBoundsState(Context context,
-            PipSizeSpecHandler pipSizeSpecHandler, PipDisplayLayoutState pipDisplayLayoutState) {
-        return new PipBoundsState(context, pipSizeSpecHandler, pipDisplayLayoutState);
+            SizeSpecSource sizeSpecSource, PipDisplayLayoutState pipDisplayLayoutState) {
+        return new PipBoundsState(context, sizeSpecSource, pipDisplayLayoutState);
     }
 
     @WMSingleton
@@ -141,19 +140,12 @@
 
     @WMSingleton
     @Provides
-    static PipSizeSpecHandler providePipSizeSpecHelper(Context context,
-            PipDisplayLayoutState pipDisplayLayoutState) {
-        return new PipSizeSpecHandler(context, pipDisplayLayoutState);
-    }
-
-    @WMSingleton
-    @Provides
     static PipBoundsAlgorithm providesPipBoundsAlgorithm(Context context,
             PipBoundsState pipBoundsState, PipSnapAlgorithm pipSnapAlgorithm,
             PhonePipKeepClearAlgorithm pipKeepClearAlgorithm,
-            PipSizeSpecHandler pipSizeSpecHandler) {
+            PipDisplayLayoutState pipDisplayLayoutState, SizeSpecSource sizeSpecSource) {
         return new PipBoundsAlgorithm(context, pipBoundsState, pipSnapAlgorithm,
-                pipKeepClearAlgorithm, pipSizeSpecHandler);
+                pipKeepClearAlgorithm, pipDisplayLayoutState, sizeSpecSource);
     }
 
     // Handler is used by Icon.loadDrawableAsync
@@ -177,14 +169,14 @@
             PhonePipMenuController menuPhoneController,
             PipBoundsAlgorithm pipBoundsAlgorithm,
             PipBoundsState pipBoundsState,
-            PipSizeSpecHandler pipSizeSpecHandler,
+            SizeSpecSource sizeSpecSource,
             PipTaskOrganizer pipTaskOrganizer,
             PipMotionHelper pipMotionHelper,
             FloatingContentCoordinator floatingContentCoordinator,
             PipUiEventLogger pipUiEventLogger,
             @ShellMainThread ShellExecutor mainExecutor) {
         return new PipTouchHandler(context, shellInit, menuPhoneController, pipBoundsAlgorithm,
-                pipBoundsState, pipSizeSpecHandler, pipTaskOrganizer, pipMotionHelper,
+                pipBoundsState, sizeSpecSource, pipTaskOrganizer, pipMotionHelper,
                 floatingContentCoordinator, pipUiEventLogger, mainExecutor);
     }
 
@@ -243,6 +235,13 @@
 
     @WMSingleton
     @Provides
+    static SizeSpecSource provideSizeSpecSource(Context context,
+            PipDisplayLayoutState pipDisplayLayoutState) {
+        return new PhoneSizeSpecSource(context, pipDisplayLayoutState);
+    }
+
+    @WMSingleton
+    @Provides
     static PipAppOpsListener providePipAppOpsListener(Context context,
             PipTouchHandler pipTouchHandler,
             @ShellMainThread ShellExecutor mainExecutor) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1SharedModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1SharedModule.java
index f29b3a3..e8fae24 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1SharedModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1SharedModule.java
@@ -21,7 +21,6 @@
 import android.os.Handler;
 
 import com.android.internal.logging.UiEventLogger;
-import com.android.wm.shell.common.FloatingContentCoordinator;
 import com.android.wm.shell.common.annotations.ShellMainThread;
 import com.android.wm.shell.dagger.WMSingleton;
 import com.android.wm.shell.pip.PipMediaController;
@@ -37,12 +36,6 @@
  */
 @Module
 public abstract class Pip1SharedModule {
-    @WMSingleton
-    @Provides
-    static FloatingContentCoordinator provideFloatingContentCoordinator() {
-        return new FloatingContentCoordinator();
-    }
-
     // Needs handler for registering broadcast receivers
     @WMSingleton
     @Provides
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java
index 360bf8b..80ffbb0 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java
@@ -28,11 +28,13 @@
 import com.android.wm.shell.common.SystemWindows;
 import com.android.wm.shell.common.TaskStackListenerImpl;
 import com.android.wm.shell.common.annotations.ShellMainThread;
+import com.android.wm.shell.common.pip.LegacySizeSpecSource;
+import com.android.wm.shell.common.pip.PipAppOpsListener;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.dagger.WMShellBaseModule;
 import com.android.wm.shell.dagger.WMSingleton;
 import com.android.wm.shell.pip.Pip;
 import com.android.wm.shell.pip.PipAnimationController;
-import com.android.wm.shell.pip.PipAppOpsListener;
 import com.android.wm.shell.pip.PipDisplayLayoutState;
 import com.android.wm.shell.pip.PipMediaController;
 import com.android.wm.shell.pip.PipParamsChangedForwarder;
@@ -42,7 +44,6 @@
 import com.android.wm.shell.pip.PipTransitionController;
 import com.android.wm.shell.pip.PipTransitionState;
 import com.android.wm.shell.pip.PipUiEventLogger;
-import com.android.wm.shell.pip.phone.PipSizeSpecHandler;
 import com.android.wm.shell.pip.tv.TvPipBoundsAlgorithm;
 import com.android.wm.shell.pip.tv.TvPipBoundsController;
 import com.android.wm.shell.pip.tv.TvPipBoundsState;
@@ -138,23 +139,23 @@
     @Provides
     static TvPipBoundsAlgorithm provideTvPipBoundsAlgorithm(Context context,
             TvPipBoundsState tvPipBoundsState, PipSnapAlgorithm pipSnapAlgorithm,
-            PipSizeSpecHandler pipSizeSpecHandler) {
+            PipDisplayLayoutState pipDisplayLayoutState, SizeSpecSource sizeSpecSource) {
         return new TvPipBoundsAlgorithm(context, tvPipBoundsState, pipSnapAlgorithm,
-                pipSizeSpecHandler);
+                pipDisplayLayoutState, sizeSpecSource);
     }
 
     @WMSingleton
     @Provides
     static TvPipBoundsState provideTvPipBoundsState(Context context,
-            PipSizeSpecHandler pipSizeSpecHandler, PipDisplayLayoutState pipDisplayLayoutState) {
-        return new TvPipBoundsState(context, pipSizeSpecHandler, pipDisplayLayoutState);
+            SizeSpecSource sizeSpecSource, PipDisplayLayoutState pipDisplayLayoutState) {
+        return new TvPipBoundsState(context, sizeSpecSource, pipDisplayLayoutState);
     }
 
     @WMSingleton
     @Provides
-    static PipSizeSpecHandler providePipSizeSpecHelper(Context context,
+    static SizeSpecSource provideSizeSpecSource(Context context,
             PipDisplayLayoutState pipDisplayLayoutState) {
-        return new PipSizeSpecHandler(context, pipDisplayLayoutState);
+        return new LegacySizeSpecSource(context, pipDisplayLayoutState);
     }
 
     // Handler needed for loadDrawableAsync() in PipControlsViewController
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeController.java
index db6c258..5b24d7a 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeController.java
@@ -535,6 +535,11 @@
         }
 
         @Override
+        public void onDesktopSplitSelectAnimComplete(RunningTaskInfo taskInfo) {
+
+        }
+
+        @Override
         public void stashDesktopApps(int displayId) throws RemoteException {
             // Stashing of desktop apps not needed. Apps always launch on desktop
         }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
index b15fd91..633f627 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
@@ -18,10 +18,12 @@
 
 import android.R
 import android.app.ActivityManager.RunningTaskInfo
+import android.app.WindowConfiguration
 import android.app.WindowConfiguration.ACTIVITY_TYPE_HOME
 import android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD
 import android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM
 import android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN
+import android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW
 import android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED
 import android.app.WindowConfiguration.WindowingMode
 import android.content.Context
@@ -33,7 +35,6 @@
 import android.os.SystemProperties
 import android.util.DisplayMetrics.DENSITY_DEFAULT
 import android.view.SurfaceControl
-import android.view.SurfaceControl.Transaction
 import android.view.WindowManager.TRANSIT_CHANGE
 import android.view.WindowManager.TRANSIT_NONE
 import android.view.WindowManager.TRANSIT_OPEN
@@ -56,6 +57,7 @@
 import com.android.wm.shell.common.annotations.ShellMainThread
 import com.android.wm.shell.desktopmode.DesktopModeTaskRepository.VisibleTasksListener
 import com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_DESKTOP_MODE
+import com.android.wm.shell.splitscreen.SplitScreenController
 import com.android.wm.shell.sysui.ShellCommandHandler
 import com.android.wm.shell.sysui.ShellController
 import com.android.wm.shell.sysui.ShellInit
@@ -105,6 +107,9 @@
         get() = context.resources.getDimensionPixelSize(
                 com.android.wm.shell.R.dimen.desktop_mode_transition_area_height)
 
+    // This is public to avoid cyclic dependency; it is set by SplitScreenController
+    lateinit var splitScreenController: SplitScreenController
+
     init {
         desktopMode = DesktopModeImpl()
         if (DesktopModeStatus.isProto2Enabled()) {
@@ -262,6 +267,19 @@
         }
     }
 
+    /**
+     * Perform needed cleanup transaction once animation is complete. Bounds need to be set
+     * here instead of initial wct to both avoid flicker and to have task bounds to use for
+     * the staging animation.
+     *
+     * @param taskInfo task entering split that requires a bounds update
+     */
+    fun onDesktopSplitSelectAnimComplete(taskInfo: RunningTaskInfo) {
+        val wct = WindowContainerTransaction()
+        wct.setBounds(taskInfo.token, Rect())
+        shellTaskOrganizer.applyTransaction(wct)
+    }
+
     /** Move a task with given `taskId` to fullscreen */
     fun moveToFullscreen(taskId: Int) {
         shellTaskOrganizer.getRunningTaskInfo(taskId)?.let { task -> moveToFullscreen(task) }
@@ -284,6 +302,24 @@
         }
     }
 
+    /** Move a desktop app to split screen. */
+    fun moveToSplit(task: RunningTaskInfo) {
+        KtProtoLog.v(
+            WM_SHELL_DESKTOP_MODE,
+            "DesktopTasksController: moveToSplit taskId=%d",
+            task.taskId
+        )
+        val wct = WindowContainerTransaction()
+        wct.setWindowingMode(task.token, WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW)
+        wct.setBounds(task.token, null)
+        wct.setDensityDpi(task.token, getDefaultDensityDpi())
+        if (Transitions.ENABLE_SHELL_TRANSITIONS) {
+            transitions.startTransition(TRANSIT_CHANGE, wct, null /* handler */)
+        } else {
+            shellTaskOrganizer.applyTransaction(wct)
+        }
+    }
+
     /**
      * The second part of the animated move to desktop transition, called after
      * {@link startMoveToDesktop}. Move a task to fullscreen after being dragged from fullscreen
@@ -296,7 +332,7 @@
             task.taskId
         )
         val wct = WindowContainerTransaction()
-        wct.setBounds(task.token, null)
+        wct.setBounds(task.token, Rect())
 
         if (Transitions.ENABLE_SHELL_TRANSITIONS) {
             enterDesktopTaskTransitionHandler.startCancelMoveToDesktopMode(wct,
@@ -533,6 +569,7 @@
         )
         // Check if we should skip handling this transition
         var reason = ""
+        val triggerTask = request.triggerTask
         val shouldHandleRequest =
             when {
                 // Only handle open or to front transitions
@@ -541,19 +578,19 @@
                     false
                 }
                 // Only handle when it is a task transition
-                request.triggerTask == null -> {
+                triggerTask == null -> {
                     reason = "triggerTask is null"
                     false
                 }
                 // Only handle standard type tasks
-                request.triggerTask.activityType != ACTIVITY_TYPE_STANDARD -> {
-                    reason = "activityType not handled (${request.triggerTask.activityType})"
+                triggerTask.activityType != ACTIVITY_TYPE_STANDARD -> {
+                    reason = "activityType not handled (${triggerTask.activityType})"
                     false
                 }
                 // Only handle fullscreen or freeform tasks
-                request.triggerTask.windowingMode != WINDOWING_MODE_FULLSCREEN &&
-                        request.triggerTask.windowingMode != WINDOWING_MODE_FREEFORM -> {
-                    reason = "windowingMode not handled (${request.triggerTask.windowingMode})"
+                triggerTask.windowingMode != WINDOWING_MODE_FULLSCREEN &&
+                        triggerTask.windowingMode != WINDOWING_MODE_FREEFORM -> {
+                    reason = "windowingMode not handled (${triggerTask.windowingMode})"
                     false
                 }
                 // Otherwise process it
@@ -569,17 +606,17 @@
             return null
         }
 
-        val task: RunningTaskInfo = request.triggerTask
-
-        val result = when {
-            // If display has tasks stashed, handle as stashed launch
-            desktopModeTaskRepository.isStashed(task.displayId) -> handleStashedTaskLaunch(task)
-            // Check if fullscreen task should be updated
-            task.windowingMode == WINDOWING_MODE_FULLSCREEN -> handleFullscreenTaskLaunch(task)
-            // Check if freeform task should be updated
-            task.windowingMode == WINDOWING_MODE_FREEFORM -> handleFreeformTaskLaunch(task)
-            else -> {
-                null
+        val result = triggerTask?.let { task ->
+            when {
+                // If display has tasks stashed, handle as stashed launch
+                desktopModeTaskRepository.isStashed(task.displayId) -> handleStashedTaskLaunch(task)
+                // Check if fullscreen task should be updated
+                task.windowingMode == WINDOWING_MODE_FULLSCREEN -> handleFullscreenTaskLaunch(task)
+                // Check if freeform task should be updated
+                task.windowingMode == WINDOWING_MODE_FREEFORM -> handleFreeformTaskLaunch(task)
+                else -> {
+                    null
+                }
             }
         }
         KtProtoLog.v(
@@ -686,13 +723,43 @@
             WINDOWING_MODE_FULLSCREEN
         }
         wct.setWindowingMode(taskInfo.token, targetWindowingMode)
-        wct.setBounds(taskInfo.token, null)
+        wct.setBounds(taskInfo.token, Rect())
         if (isDesktopDensityOverrideSet()) {
-            wct.setDensityDpi(taskInfo.token, getFullscreenDensityDpi())
+            wct.setDensityDpi(taskInfo.token, getDefaultDensityDpi())
         }
     }
 
-    private fun getFullscreenDensityDpi(): Int {
+    /**
+     * Adds split screen changes to a transaction. Note that bounds are not reset here due to
+     * animation; see {@link onDesktopSplitSelectAnimComplete}
+     */
+    private fun addMoveToSplitChanges(
+        wct: WindowContainerTransaction,
+        taskInfo: RunningTaskInfo
+    ) {
+        wct.setWindowingMode(taskInfo.token, WINDOWING_MODE_MULTI_WINDOW)
+        // The task's density may have been overridden in freeform; revert it here as we don't
+        // want it overridden in multi-window.
+        wct.setDensityDpi(taskInfo.token, getDefaultDensityDpi())
+    }
+
+    /**
+     * Requests a task be transitioned from desktop to split select. Applies needed windowing
+     * changes if this transition is enabled.
+     */
+    fun requestSplit(
+        taskInfo: RunningTaskInfo
+    ) {
+        val windowingMode = taskInfo.windowingMode
+        if (windowingMode == WINDOWING_MODE_FULLSCREEN || windowingMode == WINDOWING_MODE_FREEFORM
+        ) {
+            val wct = WindowContainerTransaction()
+            addMoveToSplitChanges(wct, taskInfo)
+            splitScreenController.requestEnterSplitSelect(taskInfo, wct)
+        }
+    }
+
+    private fun getDefaultDensityDpi(): Int {
         return context.resources.displayMetrics.densityDpi
     }
 
@@ -969,6 +1036,13 @@
             return result[0]
         }
 
+        override fun onDesktopSplitSelectAnimComplete(taskInfo: RunningTaskInfo) {
+            ExecutorUtils.executeRemoteCallWithTaskPermission(
+                controller,
+                "onDesktopSplitSelectAnimComplete"
+            ) { c -> c.onDesktopSplitSelectAnimComplete(taskInfo) }
+        }
+
         override fun setTaskListener(listener: IDesktopTaskListener?) {
             KtProtoLog.v(
                     WM_SHELL_DESKTOP_MODE,
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/EnterDesktopTaskTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/EnterDesktopTaskTransitionHandler.java
index 16b2393..024465b 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/EnterDesktopTaskTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/EnterDesktopTaskTransitionHandler.java
@@ -241,7 +241,7 @@
             public void onAnimationEnd(Animator animation) {
                 mDesktopModeWindowDecoration.hideResizeVeil();
                 mTransitions.getMainExecutor().execute(
-                        () -> finishCallback.onTransitionFinished(null, null));
+                        () -> finishCallback.onTransitionFinished(null));
             }
         });
         animator.start();
@@ -271,8 +271,7 @@
 
         startT.apply();
 
-        mTransitions.getMainExecutor().execute(
-                () -> finishCallback.onTransitionFinished(null, null));
+        mTransitions.getMainExecutor().execute(() -> finishCallback.onTransitionFinished(null));
 
         return true;
     }
@@ -324,7 +323,7 @@
                     mOnAnimationFinishedCallback.accept(finishT);
                 }
                 mTransitions.getMainExecutor().execute(
-                        () -> finishCallback.onTransitionFinished(null, null));
+                        () -> finishCallback.onTransitionFinished(null));
             }
         });
 
@@ -378,7 +377,7 @@
                     mOnAnimationFinishedCallback.accept(finishT);
                 }
                 mTransitions.getMainExecutor().execute(
-                        () -> finishCallback.onTransitionFinished(null, null));
+                        () -> finishCallback.onTransitionFinished(null));
             }
         });
         animator.start();
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/ExitDesktopTaskTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/ExitDesktopTaskTransitionHandler.java
index 3ad5edf..7342bd1 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/ExitDesktopTaskTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/ExitDesktopTaskTransitionHandler.java
@@ -168,7 +168,7 @@
                         mOnAnimationFinishedCallback.accept(finishT);
                     }
                     mTransitions.getMainExecutor().execute(
-                            () -> finishCallback.onTransitionFinished(null, null));
+                            () -> finishCallback.onTransitionFinished(null));
                 }
             });
             animator.start();
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/IDesktopMode.aidl b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/IDesktopMode.aidl
index ee3a080..47edfd4 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/IDesktopMode.aidl
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/IDesktopMode.aidl
@@ -16,6 +16,7 @@
 
 package com.android.wm.shell.desktopmode;
 
+import android.app.ActivityManager.RunningTaskInfo;
 import com.android.wm.shell.desktopmode.IDesktopTaskListener;
 
 /**
@@ -38,6 +39,9 @@
     /** Get count of visible desktop tasks on the given display */
     int getVisibleTaskCount(int displayId);
 
+    /** Perform cleanup transactions after the animation to split select is complete */
+    oneway void onDesktopSplitSelectAnimComplete(in RunningTaskInfo taskInfo);
+
     /** Set listener that will receive callbacks about updates to desktop tasks */
     oneway void setTaskListener(IDesktopTaskListener listener);
 }
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/ToggleResizeDesktopTaskTransitionHandler.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/ToggleResizeDesktopTaskTransitionHandler.kt
index 94788e4..9debb25 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/ToggleResizeDesktopTaskTransitionHandler.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/ToggleResizeDesktopTaskTransitionHandler.kt
@@ -69,7 +69,7 @@
     ): Boolean {
         val change = findRelevantChange(info)
         val leash = change.leash
-        val taskId = change.taskInfo.taskId
+        val taskId = checkNotNull(change.taskInfo).taskId
         val startBounds = change.startAbsBounds
         val endBounds = change.endAbsBounds
         val windowDecor =
@@ -104,7 +104,7 @@
                                 .setWindowCrop(leash, endBounds.width(), endBounds.height())
                                 .show(leash)
                             windowDecor.hideResizeVeil()
-                            finishCallback.onTransitionFinished(null, null)
+                            finishCallback.onTransitionFinished(null)
                             boundsAnimator = null
                         }
                     )
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java
index 55e34fe..8402775 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java
@@ -130,7 +130,7 @@
             if (!animations.isEmpty()) return;
             mMainExecutor.execute(() -> {
                 mAnimations.remove(transition);
-                finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */);
+                finishCallback.onTransitionFinished(null /* wct */);
             });
         };
         for (TransitionInfo.Change change : info.getChanges()) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/keyguard/KeyguardTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/keyguard/KeyguardTransitionHandler.java
index 56bd188..2ef92ad 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/keyguard/KeyguardTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/keyguard/KeyguardTransitionHandler.java
@@ -19,7 +19,6 @@
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_DREAM;
 import static android.view.WindowManager.KEYGUARD_VISIBILITY_TRANSIT_FLAGS;
 import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY;
-import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_APPEARING;
 import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_OCCLUDING;
 import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_UNOCCLUDING;
 import static android.view.WindowManager.TRANSIT_SLEEP;
@@ -169,7 +168,7 @@
                             // Post our finish callback to let startAnimation finish first.
                             mMainExecutor.executeDelayed(() -> {
                                 mStartedTransitions.remove(transition);
-                                finishCallback.onTransitionFinished(wct, null);
+                                finishCallback.onTransitionFinished(wct);
                             }, 0);
                         }
                     });
@@ -206,7 +205,7 @@
                 // implementing an AIDL interface.
                 Log.wtf(TAG, "RemoteException thrown from KeyguardService transition", e);
             }
-            nextFinishCallback.onTransitionFinished(null, null);
+            nextFinishCallback.onTransitionFinished(null);
         } else if (nextInfo.getType() == TRANSIT_SLEEP) {
             // An empty SLEEP transition comes in as a signal to abort transitions whenever a sleep
             // token is held. In cases where keyguard is showing, we are running the animation for
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipAppOpsListener.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipAppOpsListener.java
deleted file mode 100644
index 48a3fc2..0000000
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipAppOpsListener.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.pip;
-
-import static android.app.AppOpsManager.MODE_ALLOWED;
-import static android.app.AppOpsManager.OP_PICTURE_IN_PICTURE;
-
-import android.app.AppOpsManager;
-import android.app.AppOpsManager.OnOpChangedListener;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.util.Pair;
-
-import com.android.wm.shell.common.ShellExecutor;
-
-public class PipAppOpsListener {
-    private static final String TAG = PipAppOpsListener.class.getSimpleName();
-
-    private Context mContext;
-    private ShellExecutor mMainExecutor;
-    private AppOpsManager mAppOpsManager;
-    private Callback mCallback;
-
-    private AppOpsManager.OnOpChangedListener mAppOpsChangedListener = new OnOpChangedListener() {
-        @Override
-        public void onOpChanged(String op, String packageName) {
-            try {
-                // Dismiss the PiP once the user disables the app ops setting for that package
-                final Pair<ComponentName, Integer> topPipActivityInfo =
-                        PipUtils.getTopPipActivity(mContext);
-                if (topPipActivityInfo.first != null) {
-                    final ApplicationInfo appInfo = mContext.getPackageManager()
-                            .getApplicationInfoAsUser(packageName, 0, topPipActivityInfo.second);
-                    if (appInfo.packageName.equals(topPipActivityInfo.first.getPackageName()) &&
-                            mAppOpsManager.checkOpNoThrow(OP_PICTURE_IN_PICTURE, appInfo.uid,
-                                    packageName) != MODE_ALLOWED) {
-                        mMainExecutor.execute(() -> mCallback.dismissPip());
-                    }
-                }
-            } catch (NameNotFoundException e) {
-                // Unregister the listener if the package can't be found
-                unregisterAppOpsListener();
-            }
-        }
-    };
-
-    public PipAppOpsListener(Context context, Callback callback, ShellExecutor mainExecutor) {
-        mContext = context;
-        mMainExecutor = mainExecutor;
-        mAppOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
-        mCallback = callback;
-    }
-
-    public void onActivityPinned(String packageName) {
-        // Register for changes to the app ops setting for this package while it is in PiP
-        registerAppOpsListener(packageName);
-    }
-
-    public void onActivityUnpinned() {
-        // Unregister for changes to the previously PiP'ed package
-        unregisterAppOpsListener();
-    }
-
-    private void registerAppOpsListener(String packageName) {
-        mAppOpsManager.startWatchingMode(OP_PICTURE_IN_PICTURE, packageName,
-                mAppOpsChangedListener);
-    }
-
-    private void unregisterAppOpsListener() {
-        mAppOpsManager.stopWatchingMode(mAppOpsChangedListener);
-    }
-
-    /** Callback for PipAppOpsListener to request changes to the PIP window. */
-    public interface Callback {
-        /** Dismisses the PIP window. */
-        void dismissPip();
-    }
-}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipBoundsAlgorithm.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipBoundsAlgorithm.java
index f51eb52..ac711ea 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipBoundsAlgorithm.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipBoundsAlgorithm.java
@@ -28,7 +28,7 @@
 import android.view.Gravity;
 
 import com.android.wm.shell.R;
-import com.android.wm.shell.pip.phone.PipSizeSpecHandler;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 
 import java.io.PrintWriter;
 
@@ -41,7 +41,8 @@
     private static final float INVALID_SNAP_FRACTION = -1f;
 
     @NonNull private final PipBoundsState mPipBoundsState;
-    @NonNull protected final PipSizeSpecHandler mPipSizeSpecHandler;
+    @NonNull protected final PipDisplayLayoutState mPipDisplayLayoutState;
+    @NonNull protected final SizeSpecSource mSizeSpecSource;
     private final PipSnapAlgorithm mSnapAlgorithm;
     private final PipKeepClearAlgorithmInterface mPipKeepClearAlgorithm;
 
@@ -53,11 +54,13 @@
     public PipBoundsAlgorithm(Context context, @NonNull PipBoundsState pipBoundsState,
             @NonNull PipSnapAlgorithm pipSnapAlgorithm,
             @NonNull PipKeepClearAlgorithmInterface pipKeepClearAlgorithm,
-            @NonNull PipSizeSpecHandler pipSizeSpecHandler) {
+            @NonNull PipDisplayLayoutState pipDisplayLayoutState,
+            @NonNull SizeSpecSource sizeSpecSource) {
         mPipBoundsState = pipBoundsState;
         mSnapAlgorithm = pipSnapAlgorithm;
         mPipKeepClearAlgorithm = pipKeepClearAlgorithm;
-        mPipSizeSpecHandler = pipSizeSpecHandler;
+        mPipDisplayLayoutState = pipDisplayLayoutState;
+        mSizeSpecSource = sizeSpecSource;
         reloadResources(context);
         // Initialize the aspect ratio to the default aspect ratio.  Don't do this in reload
         // resources as it would clobber mAspectRatio when entering PiP from fullscreen which
@@ -74,11 +77,6 @@
                 R.dimen.config_pictureInPictureDefaultAspectRatio);
         mDefaultStackGravity = res.getInteger(
                 R.integer.config_defaultPictureInPictureGravity);
-        final String screenEdgeInsetsDpString = res.getString(
-                R.string.config_defaultPictureInPictureScreenEdgeInsets);
-        final Size screenEdgeInsetsDp = !screenEdgeInsetsDpString.isEmpty()
-                ? Size.parseSize(screenEdgeInsetsDpString)
-                : null;
         mMinAspectRatio = res.getFloat(
                 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
         mMaxAspectRatio = res.getFloat(
@@ -160,8 +158,8 @@
             // If either dimension is smaller than the allowed minimum, adjust them
             // according to mOverridableMinSize
             return new Size(
-                    Math.max(windowLayout.minWidth, mPipSizeSpecHandler.getOverrideMinEdgeSize()),
-                    Math.max(windowLayout.minHeight, mPipSizeSpecHandler.getOverrideMinEdgeSize()));
+                    Math.max(windowLayout.minWidth, getOverrideMinEdgeSize()),
+                    Math.max(windowLayout.minHeight, getOverrideMinEdgeSize()));
         }
         return null;
     }
@@ -255,10 +253,10 @@
         final Size size;
         if (useCurrentMinEdgeSize || useCurrentSize) {
             // Use the existing size but adjusted to the new aspect ratio.
-            size = mPipSizeSpecHandler.getSizeForAspectRatio(
+            size = mSizeSpecSource.getSizeForAspectRatio(
                     new Size(stackBounds.width(), stackBounds.height()), aspectRatio);
         } else {
-            size = mPipSizeSpecHandler.getDefaultSize(aspectRatio);
+            size = mSizeSpecSource.getDefaultSize(aspectRatio);
         }
 
         final int left = (int) (stackBounds.centerX() - size.getWidth() / 2f);
@@ -287,7 +285,7 @@
         getInsetBounds(insetBounds);
 
         // Calculate the default size
-        defaultSize = mPipSizeSpecHandler.getDefaultSize(mDefaultAspectRatio);
+        defaultSize = mSizeSpecSource.getDefaultSize(mDefaultAspectRatio);
 
         // Now that we have the default size, apply the snap fraction if valid or position the
         // bounds using the default gravity.
@@ -309,7 +307,11 @@
      * Populates the bounds on the screen that the PIP can be visible in.
      */
     public void getInsetBounds(Rect outRect) {
-        outRect.set(mPipSizeSpecHandler.getInsetBounds());
+        outRect.set(mPipDisplayLayoutState.getInsetBounds());
+    }
+
+    private int getOverrideMinEdgeSize() {
+        return mSizeSpecSource.getOverrideMinEdgeSize();
     }
 
     /**
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipBoundsState.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipBoundsState.java
index 9a775df..279ffc5 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipBoundsState.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipBoundsState.java
@@ -36,7 +36,7 @@
 import com.android.internal.util.function.TriConsumer;
 import com.android.wm.shell.R;
 import com.android.wm.shell.common.DisplayLayout;
-import com.android.wm.shell.pip.phone.PipSizeSpecHandler;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.protolog.ShellProtoLogGroup;
 
 import java.io.PrintWriter;
@@ -87,7 +87,7 @@
     private int mStashOffset;
     private @Nullable PipReentryState mPipReentryState;
     private final LauncherState mLauncherState = new LauncherState();
-    private final @Nullable PipSizeSpecHandler mPipSizeSpecHandler;
+    private final @NonNull SizeSpecSource mSizeSpecSource;
     private @Nullable ComponentName mLastPipComponentName;
     private final @NonNull MotionBoundsState mMotionBoundsState = new MotionBoundsState();
     private boolean mIsImeShowing;
@@ -127,17 +127,20 @@
     private @Nullable TriConsumer<Boolean, Integer, Boolean> mOnShelfVisibilityChangeCallback;
     private List<Consumer<Rect>> mOnPipExclusionBoundsChangeCallbacks = new ArrayList<>();
 
-    public PipBoundsState(@NonNull Context context, PipSizeSpecHandler pipSizeSpecHandler,
-            PipDisplayLayoutState pipDisplayLayoutState) {
+    public PipBoundsState(@NonNull Context context, @NonNull SizeSpecSource sizeSpecSource,
+            @NonNull PipDisplayLayoutState pipDisplayLayoutState) {
         mContext = context;
         reloadResources();
-        mPipSizeSpecHandler = pipSizeSpecHandler;
+        mSizeSpecSource = sizeSpecSource;
         mPipDisplayLayoutState = pipDisplayLayoutState;
     }
 
     /** Reloads the resources. */
     public void onConfigurationChanged() {
         reloadResources();
+
+        // update the size spec resources upon config change too
+        mSizeSpecSource.onConfigurationChanged();
     }
 
     private void reloadResources() {
@@ -319,7 +322,7 @@
     /** Sets the preferred size of PIP as specified by the activity in PIP mode. */
     public void setOverrideMinSize(@Nullable Size overrideMinSize) {
         final boolean changed = !Objects.equals(overrideMinSize, getOverrideMinSize());
-        mPipSizeSpecHandler.setOverrideMinSize(overrideMinSize);
+        mSizeSpecSource.setOverrideMinSize(overrideMinSize);
         if (changed && mOnMinimalSizeChangeCallback != null) {
             mOnMinimalSizeChangeCallback.run();
         }
@@ -328,12 +331,12 @@
     /** Returns the preferred minimal size specified by the activity in PIP. */
     @Nullable
     public Size getOverrideMinSize() {
-        return mPipSizeSpecHandler.getOverrideMinSize();
+        return mSizeSpecSource.getOverrideMinSize();
     }
 
     /** Returns the minimum edge size of the override minimum size, or 0 if not set. */
     public int getOverrideMinEdgeSize() {
-        return mPipSizeSpecHandler.getOverrideMinEdgeSize();
+        return mSizeSpecSource.getOverrideMinEdgeSize();
     }
 
     /** Get the state of the bounds in motion. */
@@ -613,5 +616,6 @@
         }
         mLauncherState.dump(pw, innerPrefix);
         mMotionBoundsState.dump(pw, innerPrefix);
+        mSizeSpecSource.dump(pw, innerPrefix);
     }
 }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipDisplayLayoutState.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipDisplayLayoutState.java
index 0f76af4..456f85b 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipDisplayLayoutState.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipDisplayLayoutState.java
@@ -16,12 +16,18 @@
 
 package com.android.wm.shell.pip;
 
+import static com.android.wm.shell.pip.PipUtils.dpToPx;
+
 import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Point;
 import android.graphics.Rect;
+import android.util.Size;
 import android.view.Surface;
 
 import androidx.annotation.NonNull;
 
+import com.android.wm.shell.R;
 import com.android.wm.shell.common.DisplayLayout;
 import com.android.wm.shell.dagger.WMSingleton;
 
@@ -40,13 +46,51 @@
     private int mDisplayId;
     @NonNull private DisplayLayout mDisplayLayout;
 
+    private Point mScreenEdgeInsets = null;
+
     @Inject
     public PipDisplayLayoutState(Context context) {
         mContext = context;
         mDisplayLayout = new DisplayLayout();
+        reloadResources();
     }
 
-    /** Update the display layout. */
+    /** Responds to configuration change. */
+    public void onConfigurationChanged() {
+        reloadResources();
+    }
+
+    private void reloadResources() {
+        Resources res = mContext.getResources();
+
+        final String screenEdgeInsetsDpString = res.getString(
+                R.string.config_defaultPictureInPictureScreenEdgeInsets);
+        final Size screenEdgeInsetsDp = !screenEdgeInsetsDpString.isEmpty()
+                ? Size.parseSize(screenEdgeInsetsDpString)
+                : null;
+        mScreenEdgeInsets = screenEdgeInsetsDp == null ? new Point()
+                : new Point(dpToPx(screenEdgeInsetsDp.getWidth(), res.getDisplayMetrics()),
+                        dpToPx(screenEdgeInsetsDp.getHeight(), res.getDisplayMetrics()));
+    }
+
+    public Point getScreenEdgeInsets() {
+        return mScreenEdgeInsets;
+    }
+
+    /**
+     * Returns the inset bounds the PIP window can be visible in.
+     */
+    public Rect getInsetBounds() {
+        Rect insetBounds = new Rect();
+        Rect insets = getDisplayLayout().stableInsets();
+        insetBounds.set(insets.left + getScreenEdgeInsets().x,
+                insets.top + getScreenEdgeInsets().y,
+                getDisplayLayout().width() - insets.right - getScreenEdgeInsets().x,
+                getDisplayLayout().height() - insets.bottom - getScreenEdgeInsets().y);
+        return insetBounds;
+    }
+
+    /** Set the display layout. */
     public void setDisplayLayout(@NonNull DisplayLayout displayLayout) {
         mDisplayLayout.set(displayLayout);
     }
@@ -87,5 +131,6 @@
         pw.println(prefix + TAG);
         pw.println(innerPrefix + "mDisplayId=" + mDisplayId);
         pw.println(innerPrefix + "getDisplayBounds=" + getDisplayBounds());
+        pw.println(innerPrefix + "mScreenEdgeInsets=" + mScreenEdgeInsets);
     }
 }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
index 0d55018..19c60c2 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
@@ -63,7 +63,6 @@
 import android.content.res.Configuration;
 import android.graphics.Rect;
 import android.os.RemoteException;
-import android.os.SystemProperties;
 import android.view.Choreographer;
 import android.view.Display;
 import android.view.Surface;
@@ -1735,17 +1734,13 @@
                 // animation.
                 // TODO(b/272819817): cleanup the null-check and extra logging.
                 final boolean hasTopActivityInfo = mTaskInfo.topActivityInfo != null;
-                if (!hasTopActivityInfo) {
-                    ProtoLog.w(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
-                            "%s: TaskInfo.topActivityInfo is null", TAG);
-                }
-                if (SystemProperties.getBoolean(
-                        "persist.wm.debug.enable_pip_app_icon_overlay", true)
-                        && hasTopActivityInfo) {
+                if (hasTopActivityInfo) {
                     animator.setAppIconContentOverlay(
                             mContext, currentBounds, mTaskInfo.topActivityInfo,
                             mPipBoundsState.getLauncherState().getAppIconSizePx());
                 } else {
+                    ProtoLog.w(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
+                            "%s: TaskInfo.topActivityInfo is null", TAG);
                     animator.setColorContentOverlay(mContext);
                 }
             } else {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java
index e3d53fc..db7e2c0 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java
@@ -49,7 +49,6 @@
 import android.graphics.Point;
 import android.graphics.Rect;
 import android.os.IBinder;
-import android.os.SystemProperties;
 import android.view.Surface;
 import android.view.SurfaceControl;
 import android.view.WindowManager;
@@ -447,7 +446,7 @@
         // handler if there is a pending PiP animation.
         final Transitions.TransitionFinishCallback finishCallback = mFinishCallback;
         mFinishCallback = null;
-        finishCallback.onTransitionFinished(wct, null /* callback */);
+        finishCallback.onTransitionFinished(wct);
     }
 
     @Override
@@ -456,7 +455,7 @@
         // for example, when app crashes while in PiP and exit transition has not started
         mCurrentPipTaskToken = null;
         if (mFinishCallback == null) return;
-        mFinishCallback.onTransitionFinished(null /* wct */, null /* callback */);
+        mFinishCallback.onTransitionFinished(null /* wct */);
         mFinishCallback = null;
         mFinishTransaction = null;
     }
@@ -586,7 +585,7 @@
         final boolean useLocalLeash = activitySc != null;
         final boolean toFullscreen = pipChange.getEndAbsBounds().equals(
                 mPipBoundsState.getDisplayBounds());
-        mFinishCallback = (wct, wctCB) -> {
+        mFinishCallback = (wct) -> {
             mPipOrganizer.onExitPipFinished(taskInfo);
 
             // TODO(b/286346098): remove the OPEN app flicker completely
@@ -610,7 +609,7 @@
                 mPipAnimationController.resetAnimatorState();
                 finishTransaction.remove(pipLeash);
             }
-            finishCallback.onTransitionFinished(wct, wctCB);
+            finishCallback.onTransitionFinished(wct);
         };
         mFinishTransaction = finishTransaction;
 
@@ -750,7 +749,7 @@
         finishTransaction.setWindowCrop(info.getChanges().get(0).getLeash(),
                 mPipDisplayLayoutState.getDisplayBounds());
         mPipOrganizer.onExitPipFinished(taskInfo);
-        finishCallback.onTransitionFinished(null, null);
+        finishCallback.onTransitionFinished(null);
     }
 
     /** Whether we should handle the given {@link TransitionInfo} animation as entering PIP. */
@@ -902,17 +901,13 @@
                 // animation.
                 // TODO(b/272819817): cleanup the null-check and extra logging.
                 final boolean hasTopActivityInfo = taskInfo.topActivityInfo != null;
-                if (!hasTopActivityInfo) {
-                    ProtoLog.w(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
-                            "%s: TaskInfo.topActivityInfo is null", TAG);
-                }
-                if (SystemProperties.getBoolean(
-                        "persist.wm.debug.enable_pip_app_icon_overlay", true)
-                        && hasTopActivityInfo) {
+                if (hasTopActivityInfo) {
                     animator.setAppIconContentOverlay(
                             mContext, currentBounds, taskInfo.topActivityInfo,
                             mPipBoundsState.getLauncherState().getAppIconSizePx());
                 } else {
+                    ProtoLog.w(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
+                            "%s: TaskInfo.topActivityInfo is null", TAG);
                     animator.setColorContentOverlay(mContext);
                 }
             } else {
@@ -1045,7 +1040,7 @@
         startTransaction.apply();
 
         mPipOrganizer.onExitPipFinished(taskInfo);
-        finishCallback.onTransitionFinished(null, null);
+        finishCallback.onTransitionFinished(null);
     }
 
     private void resetPrevPip(@NonNull TransitionInfo.Change prevPipTaskChange,
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PhonePipKeepClearAlgorithm.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PhonePipKeepClearAlgorithm.java
index f9332e4..2d34035 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PhonePipKeepClearAlgorithm.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PhonePipKeepClearAlgorithm.java
@@ -40,6 +40,7 @@
                     "persist.wm.debug.enable_pip_keep_clear_algorithm_gravity", false);
 
     protected int mKeepClearAreasPadding;
+    private int mImeOffset;
 
     public PhonePipKeepClearAlgorithm(Context context) {
         reloadResources(context);
@@ -48,6 +49,7 @@
     private void reloadResources(Context context) {
         final Resources res = context.getResources();
         mKeepClearAreasPadding = res.getDimensionPixelSize(R.dimen.pip_keep_clear_areas_padding);
+        mImeOffset = res.getDimensionPixelSize(R.dimen.pip_ime_offset);
     }
 
     /**
@@ -61,7 +63,7 @@
         Rect insets = new Rect();
         pipBoundsAlgorithm.getInsetBounds(insets);
         if (pipBoundsState.isImeShowing()) {
-            insets.bottom -= pipBoundsState.getImeHeight();
+            insets.bottom -= (pipBoundsState.getImeHeight() + mImeOffset);
         }
         // if PiP is stashed we only adjust the vertical position if it's outside of insets and
         // ignore all keep clear areas, since it's already on the side
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java
index 26b7b68..f25110a 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java
@@ -75,6 +75,7 @@
 import com.android.wm.shell.common.TabletopModeController;
 import com.android.wm.shell.common.TaskStackListenerCallback;
 import com.android.wm.shell.common.TaskStackListenerImpl;
+import com.android.wm.shell.common.pip.PipAppOpsListener;
 import com.android.wm.shell.onehanded.OneHandedController;
 import com.android.wm.shell.onehanded.OneHandedTransitionCallback;
 import com.android.wm.shell.pip.IPip;
@@ -82,7 +83,6 @@
 import com.android.wm.shell.pip.PinnedStackListenerForwarder;
 import com.android.wm.shell.pip.Pip;
 import com.android.wm.shell.pip.PipAnimationController;
-import com.android.wm.shell.pip.PipAppOpsListener;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
 import com.android.wm.shell.pip.PipDisplayLayoutState;
@@ -123,14 +123,6 @@
     private static final long PIP_KEEP_CLEAR_AREAS_DELAY =
             SystemProperties.getLong("persist.wm.debug.pip_keep_clear_areas_delay", 200);
 
-    private boolean mEnablePipKeepClearAlgorithm =
-            SystemProperties.getBoolean("persist.wm.debug.enable_pip_keep_clear_algorithm", true);
-
-    @VisibleForTesting
-    void setEnablePipKeepClearAlgorithm(boolean value) {
-        mEnablePipKeepClearAlgorithm = value;
-    }
-
     private Context mContext;
     protected ShellExecutor mMainExecutor;
     private DisplayController mDisplayController;
@@ -142,7 +134,6 @@
     private PipBoundsAlgorithm mPipBoundsAlgorithm;
     private PipKeepClearAlgorithmInterface mPipKeepClearAlgorithm;
     private PipBoundsState mPipBoundsState;
-    private PipSizeSpecHandler mPipSizeSpecHandler;
     private PipDisplayLayoutState mPipDisplayLayoutState;
     private PipMotionHelper mPipMotionHelper;
     private PipTouchHandler mTouchHandler;
@@ -167,10 +158,6 @@
             // early bail out if the change was caused by keyguard showing up
             return;
         }
-        if (!mEnablePipKeepClearAlgorithm) {
-            // early bail out if the keep clear areas feature is disabled
-            return;
-        }
         if (mPipBoundsState.isStashed()) {
             // don't move when stashed
             return;
@@ -188,10 +175,6 @@
     }
 
     private void updatePipPositionForKeepClearAreas() {
-        if (!mEnablePipKeepClearAlgorithm) {
-            // early bail out if the keep clear areas feature is disabled
-            return;
-        }
         if (mIsKeyguardShowingOrAnimating) {
             // early bail out if the change was caused by keyguard showing up
             return;
@@ -344,19 +327,17 @@
                 public void onKeepClearAreasChanged(int displayId, Set<Rect> restricted,
                         Set<Rect> unrestricted) {
                     if (mPipDisplayLayoutState.getDisplayId() == displayId) {
-                        if (mEnablePipKeepClearAlgorithm) {
-                            mPipBoundsState.setKeepClearAreas(restricted, unrestricted);
+                        mPipBoundsState.setKeepClearAreas(restricted, unrestricted);
 
-                            mMainExecutor.removeCallbacks(
-                                    mMovePipInResponseToKeepClearAreasChangeCallback);
-                            mMainExecutor.executeDelayed(
-                                    mMovePipInResponseToKeepClearAreasChangeCallback,
-                                    PIP_KEEP_CLEAR_AREAS_DELAY);
+                        mMainExecutor.removeCallbacks(
+                                mMovePipInResponseToKeepClearAreasChangeCallback);
+                        mMainExecutor.executeDelayed(
+                                mMovePipInResponseToKeepClearAreasChangeCallback,
+                                PIP_KEEP_CLEAR_AREAS_DELAY);
 
-                            ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
-                                    "onKeepClearAreasChanged: restricted=%s, unrestricted=%s",
-                                    restricted, unrestricted);
-                        }
+                        ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
+                                "onKeepClearAreasChanged: restricted=%s, unrestricted=%s",
+                                restricted, unrestricted);
                     }
                 }
             };
@@ -406,7 +387,6 @@
             PipBoundsAlgorithm pipBoundsAlgorithm,
             PipKeepClearAlgorithmInterface pipKeepClearAlgorithm,
             PipBoundsState pipBoundsState,
-            PipSizeSpecHandler pipSizeSpecHandler,
             PipDisplayLayoutState pipDisplayLayoutState,
             PipMotionHelper pipMotionHelper,
             PipMediaController pipMediaController,
@@ -430,7 +410,7 @@
 
         return new PipController(context, shellInit, shellCommandHandler, shellController,
                 displayController, pipAnimationController, pipAppOpsListener,
-                pipBoundsAlgorithm, pipKeepClearAlgorithm, pipBoundsState, pipSizeSpecHandler,
+                pipBoundsAlgorithm, pipKeepClearAlgorithm, pipBoundsState,
                 pipDisplayLayoutState, pipMotionHelper, pipMediaController, phonePipMenuController,
                 pipTaskOrganizer, pipTransitionState, pipTouchHandler, pipTransitionController,
                 windowManagerShellWrapper, taskStackListener, pipParamsChangedForwarder,
@@ -448,7 +428,6 @@
             PipBoundsAlgorithm pipBoundsAlgorithm,
             PipKeepClearAlgorithmInterface pipKeepClearAlgorithm,
             @NonNull PipBoundsState pipBoundsState,
-            PipSizeSpecHandler pipSizeSpecHandler,
             @NonNull PipDisplayLayoutState pipDisplayLayoutState,
             PipMotionHelper pipMotionHelper,
             PipMediaController pipMediaController,
@@ -474,7 +453,6 @@
         mPipBoundsAlgorithm = pipBoundsAlgorithm;
         mPipKeepClearAlgorithm = pipKeepClearAlgorithm;
         mPipBoundsState = pipBoundsState;
-        mPipSizeSpecHandler = pipSizeSpecHandler;
         mPipDisplayLayoutState = pipDisplayLayoutState;
         mPipMotionHelper = pipMotionHelper;
         mPipTaskOrganizer = pipTaskOrganizer;
@@ -664,25 +642,9 @@
                             // there's a keyguard present
                             return;
                         }
-                        int oldMaxMovementBound = mPipBoundsState.getMovementBounds().bottom;
                         onDisplayChangedUncheck(mDisplayController
                                         .getDisplayLayout(mPipDisplayLayoutState.getDisplayId()),
                                 false /* saveRestoreSnapFraction */);
-                        int newMaxMovementBound = mPipBoundsState.getMovementBounds().bottom;
-                        if (!mEnablePipKeepClearAlgorithm) {
-                            // offset PiP to adjust for bottom inset change
-                            int pipTop = mPipBoundsState.getBounds().top;
-                            int diff = newMaxMovementBound - oldMaxMovementBound;
-                            if (diff < 0 && pipTop > newMaxMovementBound) {
-                                // bottom inset has increased, move PiP up if it is too low
-                                mPipMotionHelper.animateToOffset(mPipBoundsState.getBounds(),
-                                        newMaxMovementBound - pipTop);
-                            }
-                            if (diff > 0 && oldMaxMovementBound == pipTop) {
-                                // bottom inset has decreased, move PiP down if it was by the edge
-                                mPipMotionHelper.animateToOffset(mPipBoundsState.getBounds(), diff);
-                            }
-                        }
                     }
                 });
 
@@ -711,7 +673,7 @@
             // Try to move the PiP window if we have entered PiP mode.
             if (mPipTransitionState.hasEnteredPip()) {
                 final Rect pipBounds = mPipBoundsState.getBounds();
-                final Point edgeInsets = mPipSizeSpecHandler.getScreenEdgeInsets();
+                final Point edgeInsets = mPipDisplayLayoutState.getScreenEdgeInsets();
                 if ((pipBounds.height() + 2 * edgeInsets.y) > (displayBounds.height() / 2)) {
                     // PiP bounds is too big to fit either half, bail early.
                     return;
@@ -770,7 +732,7 @@
         mPipBoundsAlgorithm.onConfigurationChanged(mContext);
         mTouchHandler.onConfigurationChanged();
         mPipBoundsState.onConfigurationChanged();
-        mPipSizeSpecHandler.onConfigurationChanged();
+        mPipDisplayLayoutState.onConfigurationChanged();
     }
 
     @Override
@@ -951,14 +913,8 @@
      * Sets both shelf visibility and its height.
      */
     private void setShelfHeight(boolean visible, int height) {
-        if (mEnablePipKeepClearAlgorithm) {
-            // turn this into Launcher keep clear area registration instead
-            setLauncherKeepClearAreaHeight(visible, height);
-            return;
-        }
-        if (!mIsKeyguardShowingOrAnimating) {
-            setShelfHeightLocked(visible, height);
-        }
+        // turn this into Launcher keep clear area registration instead
+        setLauncherKeepClearAreaHeight(visible, height);
     }
 
     private void setLauncherKeepClearAreaHeight(boolean visible, int height) {
@@ -1019,16 +975,10 @@
     private Rect startSwipePipToHome(ComponentName componentName, ActivityInfo activityInfo,
             PictureInPictureParams pictureInPictureParams,
             int launcherRotation, Rect hotseatKeepClearArea) {
-
-        if (mEnablePipKeepClearAlgorithm) {
-            // preemptively add the keep clear area for Hotseat, so that it is taken into account
-            // when calculating the entry destination bounds of PiP window
-            mPipBoundsState.addNamedUnrestrictedKeepClearArea(LAUNCHER_KEEP_CLEAR_AREA_TAG,
-                    hotseatKeepClearArea);
-        } else {
-            int shelfHeight = hotseatKeepClearArea.height();
-            setShelfHeightLocked(shelfHeight > 0 /* visible */, shelfHeight);
-        }
+        // preemptively add the keep clear area for Hotseat, so that it is taken into account
+        // when calculating the entry destination bounds of PiP window
+        mPipBoundsState.addNamedUnrestrictedKeepClearArea(LAUNCHER_KEEP_CLEAR_AREA_TAG,
+                hotseatKeepClearArea);
         onDisplayRotationChangedNotInPip(mContext, launcherRotation);
         final Rect entryBounds = mPipTaskOrganizer.startSwipePipToHome(componentName, activityInfo,
                 pictureInPictureParams);
@@ -1224,7 +1174,6 @@
         mPipTaskOrganizer.dump(pw, innerPrefix);
         mPipBoundsState.dump(pw, innerPrefix);
         mPipInputConsumer.dump(pw, innerPrefix);
-        mPipSizeSpecHandler.dump(pw, innerPrefix);
         mPipDisplayLayoutState.dump(pw, innerPrefix);
     }
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java
index 43d3f36..b251f6f 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java
@@ -41,7 +41,7 @@
 import com.android.wm.shell.animation.PhysicsAnimator;
 import com.android.wm.shell.common.FloatingContentCoordinator;
 import com.android.wm.shell.common.magnetictarget.MagnetizedObject;
-import com.android.wm.shell.pip.PipAppOpsListener;
+import com.android.wm.shell.common.pip.PipAppOpsListener;
 import com.android.wm.shell.pip.PipBoundsState;
 import com.android.wm.shell.pip.PipSnapAlgorithm;
 import com.android.wm.shell.pip.PipTaskOrganizer;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipSizeSpecHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipSizeSpecHandler.java
deleted file mode 100644
index c6e5cf2..0000000
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipSizeSpecHandler.java
+++ /dev/null
@@ -1,536 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.pip.phone;
-
-import static com.android.wm.shell.pip.PipUtils.dpToPx;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.content.res.Resources;
-import android.graphics.Point;
-import android.graphics.PointF;
-import android.graphics.Rect;
-import android.os.SystemProperties;
-import android.util.Size;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.wm.shell.R;
-import com.android.wm.shell.common.DisplayLayout;
-import com.android.wm.shell.pip.PipDisplayLayoutState;
-
-import java.io.PrintWriter;
-
-/**
- * Acts as a source of truth for appropriate size spec for PIP.
- */
-public class PipSizeSpecHandler {
-    private static final String TAG = PipSizeSpecHandler.class.getSimpleName();
-
-    @NonNull private final PipDisplayLayoutState mPipDisplayLayoutState;
-
-    private final SizeSpecSource mSizeSpecSourceImpl;
-
-    /** The preferred minimum (and default minimum) size specified by apps. */
-    @Nullable private Size mOverrideMinSize;
-    private int mOverridableMinSize;
-
-    /** Used to store values obtained from resource files. */
-    private Point mScreenEdgeInsets;
-    private float mMinAspectRatioForMinSize;
-    private float mMaxAspectRatioForMinSize;
-    private int mDefaultMinSize;
-
-    @NonNull private final Context mContext;
-
-    private interface SizeSpecSource {
-        /** Returns max size allowed for the PIP window */
-        Size getMaxSize(float aspectRatio);
-
-        /** Returns default size for the PIP window */
-        Size getDefaultSize(float aspectRatio);
-
-        /** Returns min size allowed for the PIP window */
-        Size getMinSize(float aspectRatio);
-
-        /** Returns the adjusted size based on current size and target aspect ratio */
-        Size getSizeForAspectRatio(Size size, float aspectRatio);
-
-        /** Updates internal resources on configuration changes */
-        default void reloadResources() {}
-    }
-
-    /**
-     * Determines PIP window size optimized for large screens and aspect ratios close to 1:1
-     */
-    private class SizeSpecLargeScreenOptimizedImpl implements SizeSpecSource {
-        private static final float DEFAULT_OPTIMIZED_ASPECT_RATIO = 9f / 16;
-
-        /** Default and minimum percentages for the PIP size logic. */
-        private final float mDefaultSizePercent;
-        private final float mMinimumSizePercent;
-
-        /** Aspect ratio that the PIP size spec logic optimizes for. */
-        private float mOptimizedAspectRatio;
-
-        private SizeSpecLargeScreenOptimizedImpl() {
-            mDefaultSizePercent = Float.parseFloat(SystemProperties
-                    .get("com.android.wm.shell.pip.phone.def_percentage", "0.6"));
-            mMinimumSizePercent = Float.parseFloat(SystemProperties
-                    .get("com.android.wm.shell.pip.phone.min_percentage", "0.5"));
-        }
-
-        @Override
-        public void reloadResources() {
-            final Resources res = mContext.getResources();
-
-            mOptimizedAspectRatio = res.getFloat(R.dimen.config_pipLargeScreenOptimizedAspectRatio);
-            // make sure the optimized aspect ratio is valid with a default value to fall back to
-            if (mOptimizedAspectRatio > 1) {
-                mOptimizedAspectRatio = DEFAULT_OPTIMIZED_ASPECT_RATIO;
-            }
-        }
-
-        /**
-         * Calculates the max size of PIP.
-         *
-         * Optimizes for 16:9 aspect ratios, making them take full length of shortest display edge.
-         * As aspect ratio approaches values close to 1:1, the logic does not let PIP occupy the
-         * whole screen. A linear function is used to calculate these sizes.
-         *
-         * @param aspectRatio aspect ratio of the PIP window
-         * @return dimensions of the max size of the PIP
-         */
-        @Override
-        public Size getMaxSize(float aspectRatio) {
-            final int totalHorizontalPadding = getInsetBounds().left
-                    + (getDisplayBounds().width() - getInsetBounds().right);
-            final int totalVerticalPadding = getInsetBounds().top
-                    + (getDisplayBounds().height() - getInsetBounds().bottom);
-
-            final int shorterLength = Math.min(getDisplayBounds().width() - totalHorizontalPadding,
-                    getDisplayBounds().height() - totalVerticalPadding);
-
-            int maxWidth, maxHeight;
-
-            // use the optimized max sizing logic only within a certain aspect ratio range
-            if (aspectRatio >= mOptimizedAspectRatio && aspectRatio <= 1 / mOptimizedAspectRatio) {
-                // this formula and its derivation is explained in b/198643358#comment16
-                maxWidth = Math.round(mOptimizedAspectRatio * shorterLength
-                        + shorterLength * (aspectRatio - mOptimizedAspectRatio) / (1
-                        + aspectRatio));
-                // make sure the max width doesn't go beyond shorter screen length after rounding
-                maxWidth = Math.min(maxWidth, shorterLength);
-                maxHeight = Math.round(maxWidth / aspectRatio);
-            } else {
-                if (aspectRatio > 1f) {
-                    maxWidth = shorterLength;
-                    maxHeight = Math.round(maxWidth / aspectRatio);
-                } else {
-                    maxHeight = shorterLength;
-                    maxWidth = Math.round(maxHeight * aspectRatio);
-                }
-            }
-
-            return new Size(maxWidth, maxHeight);
-        }
-
-        /**
-         * Decreases the dimensions by a percentage relative to max size to get default size.
-         *
-         * @param aspectRatio aspect ratio of the PIP window
-         * @return dimensions of the default size of the PIP
-         */
-        @Override
-        public Size getDefaultSize(float aspectRatio) {
-            Size minSize = this.getMinSize(aspectRatio);
-
-            if (mOverrideMinSize != null) {
-                return minSize;
-            }
-
-            Size maxSize = this.getMaxSize(aspectRatio);
-
-            int defaultWidth = Math.max(Math.round(maxSize.getWidth() * mDefaultSizePercent),
-                    minSize.getWidth());
-            int defaultHeight = Math.round(defaultWidth / aspectRatio);
-
-            return new Size(defaultWidth, defaultHeight);
-        }
-
-        /**
-         * Decreases the dimensions by a certain percentage relative to max size to get min size.
-         *
-         * @param aspectRatio aspect ratio of the PIP window
-         * @return dimensions of the min size of the PIP
-         */
-        @Override
-        public Size getMinSize(float aspectRatio) {
-            // if there is an overridden min size provided, return that
-            if (mOverrideMinSize != null) {
-                return adjustOverrideMinSizeToAspectRatio(aspectRatio);
-            }
-
-            Size maxSize = this.getMaxSize(aspectRatio);
-
-            int minWidth = Math.round(maxSize.getWidth() * mMinimumSizePercent);
-            int minHeight = Math.round(maxSize.getHeight() * mMinimumSizePercent);
-
-            // make sure the calculated min size is not smaller than the allowed default min size
-            if (aspectRatio > 1f) {
-                minHeight = Math.max(minHeight, mDefaultMinSize);
-                minWidth = Math.round(minHeight * aspectRatio);
-            } else {
-                minWidth = Math.max(minWidth, mDefaultMinSize);
-                minHeight = Math.round(minWidth / aspectRatio);
-            }
-            return new Size(minWidth, minHeight);
-        }
-
-        /**
-         * Returns the size for target aspect ratio making sure new size conforms with the rules.
-         *
-         * <p>Recalculates the dimensions such that the target aspect ratio is achieved, while
-         * maintaining the same maximum size to current size ratio.
-         *
-         * @param size current size
-         * @param aspectRatio target aspect ratio
-         */
-        @Override
-        public Size getSizeForAspectRatio(Size size, float aspectRatio) {
-            float currAspectRatio = (float) size.getWidth() / size.getHeight();
-
-            // getting the percentage of the max size that current size takes
-            Size currentMaxSize = getMaxSize(currAspectRatio);
-            float currentPercent = (float) size.getWidth() / currentMaxSize.getWidth();
-
-            // getting the max size for the target aspect ratio
-            Size updatedMaxSize = getMaxSize(aspectRatio);
-
-            int width = Math.round(updatedMaxSize.getWidth() * currentPercent);
-            int height = Math.round(updatedMaxSize.getHeight() * currentPercent);
-
-            // adjust the dimensions if below allowed min edge size
-            if (width < getMinEdgeSize() && aspectRatio <= 1) {
-                width = getMinEdgeSize();
-                height = Math.round(width / aspectRatio);
-            } else if (height < getMinEdgeSize() && aspectRatio > 1) {
-                height = getMinEdgeSize();
-                width = Math.round(height * aspectRatio);
-            }
-
-            // reduce the dimensions of the updated size to the calculated percentage
-            return new Size(width, height);
-        }
-    }
-
-    private class SizeSpecDefaultImpl implements SizeSpecSource {
-        private float mDefaultSizePercent;
-        private float mMinimumSizePercent;
-
-        @Override
-        public void reloadResources() {
-            final Resources res = mContext.getResources();
-
-            mMaxAspectRatioForMinSize = res.getFloat(
-                    R.dimen.config_pictureInPictureAspectRatioLimitForMinSize);
-            mMinAspectRatioForMinSize = 1f / mMaxAspectRatioForMinSize;
-
-            mDefaultSizePercent = res.getFloat(R.dimen.config_pictureInPictureDefaultSizePercent);
-            mMinimumSizePercent = res.getFraction(R.fraction.config_pipShortestEdgePercent, 1, 1);
-        }
-
-        @Override
-        public Size getMaxSize(float aspectRatio) {
-            final int shorterLength = Math.min(getDisplayBounds().width(),
-                    getDisplayBounds().height());
-
-            final int totalHorizontalPadding = getInsetBounds().left
-                    + (getDisplayBounds().width() - getInsetBounds().right);
-            final int totalVerticalPadding = getInsetBounds().top
-                    + (getDisplayBounds().height() - getInsetBounds().bottom);
-
-            final int maxWidth, maxHeight;
-
-            if (aspectRatio > 1f) {
-                maxWidth = (int) Math.max(getDefaultSize(aspectRatio).getWidth(),
-                        shorterLength - totalHorizontalPadding);
-                maxHeight = (int) (maxWidth / aspectRatio);
-            } else {
-                maxHeight = (int) Math.max(getDefaultSize(aspectRatio).getHeight(),
-                        shorterLength - totalVerticalPadding);
-                maxWidth = (int) (maxHeight * aspectRatio);
-            }
-
-            return new Size(maxWidth, maxHeight);
-        }
-
-        @Override
-        public Size getDefaultSize(float aspectRatio) {
-            if (mOverrideMinSize != null) {
-                return this.getMinSize(aspectRatio);
-            }
-
-            final int smallestDisplaySize = Math.min(getDisplayBounds().width(),
-                    getDisplayBounds().height());
-            final int minSize = (int) Math.max(getMinEdgeSize(),
-                    smallestDisplaySize * mDefaultSizePercent);
-
-            final int width;
-            final int height;
-
-            if (aspectRatio <= mMinAspectRatioForMinSize
-                    || aspectRatio > mMaxAspectRatioForMinSize) {
-                // Beyond these points, we can just use the min size as the shorter edge
-                if (aspectRatio <= 1) {
-                    // Portrait, width is the minimum size
-                    width = minSize;
-                    height = Math.round(width / aspectRatio);
-                } else {
-                    // Landscape, height is the minimum size
-                    height = minSize;
-                    width = Math.round(height * aspectRatio);
-                }
-            } else {
-                // Within these points, ensure that the bounds fit within the radius of the limits
-                // at the points
-                final float widthAtMaxAspectRatioForMinSize = mMaxAspectRatioForMinSize * minSize;
-                final float radius = PointF.length(widthAtMaxAspectRatioForMinSize, minSize);
-                height = (int) Math.round(Math.sqrt((radius * radius)
-                        / (aspectRatio * aspectRatio + 1)));
-                width = Math.round(height * aspectRatio);
-            }
-
-            return new Size(width, height);
-        }
-
-        @Override
-        public Size getMinSize(float aspectRatio) {
-            if (mOverrideMinSize != null) {
-                return adjustOverrideMinSizeToAspectRatio(aspectRatio);
-            }
-
-            final int shorterLength = Math.min(getDisplayBounds().width(),
-                    getDisplayBounds().height());
-            final int minWidth, minHeight;
-
-            if (aspectRatio > 1f) {
-                minWidth = (int) Math.min(getDefaultSize(aspectRatio).getWidth(),
-                        shorterLength * mMinimumSizePercent);
-                minHeight = (int) (minWidth / aspectRatio);
-            } else {
-                minHeight = (int) Math.min(getDefaultSize(aspectRatio).getHeight(),
-                        shorterLength * mMinimumSizePercent);
-                minWidth = (int) (minHeight * aspectRatio);
-            }
-
-            return new Size(minWidth, minHeight);
-        }
-
-        @Override
-        public Size getSizeForAspectRatio(Size size, float aspectRatio) {
-            final int smallestSize = Math.min(size.getWidth(), size.getHeight());
-            final int minSize = Math.max(getMinEdgeSize(), smallestSize);
-
-            final int width;
-            final int height;
-            if (aspectRatio <= 1) {
-                // Portrait, width is the minimum size.
-                width = minSize;
-                height = Math.round(width / aspectRatio);
-            } else {
-                // Landscape, height is the minimum size
-                height = minSize;
-                width = Math.round(height * aspectRatio);
-            }
-
-            return new Size(width, height);
-        }
-    }
-
-    public PipSizeSpecHandler(Context context, PipDisplayLayoutState pipDisplayLayoutState) {
-        mContext = context;
-        mPipDisplayLayoutState = pipDisplayLayoutState;
-
-        // choose between two implementations of size spec logic
-        if (supportsPipSizeLargeScreen()) {
-            mSizeSpecSourceImpl = new SizeSpecLargeScreenOptimizedImpl();
-        } else {
-            mSizeSpecSourceImpl = new SizeSpecDefaultImpl();
-        }
-
-        reloadResources();
-    }
-
-    /** Reloads the resources */
-    public void onConfigurationChanged() {
-        reloadResources();
-    }
-
-    private void reloadResources() {
-        final Resources res = mContext.getResources();
-
-        mDefaultMinSize = res.getDimensionPixelSize(
-                R.dimen.default_minimal_size_pip_resizable_task);
-        mOverridableMinSize = res.getDimensionPixelSize(
-                R.dimen.overridable_minimal_size_pip_resizable_task);
-
-        final String screenEdgeInsetsDpString = res.getString(
-                R.string.config_defaultPictureInPictureScreenEdgeInsets);
-        final Size screenEdgeInsetsDp = !screenEdgeInsetsDpString.isEmpty()
-                ? Size.parseSize(screenEdgeInsetsDpString)
-                : null;
-        mScreenEdgeInsets = screenEdgeInsetsDp == null ? new Point()
-                : new Point(dpToPx(screenEdgeInsetsDp.getWidth(), res.getDisplayMetrics()),
-                        dpToPx(screenEdgeInsetsDp.getHeight(), res.getDisplayMetrics()));
-
-        // update the internal resources of the size spec source's stub
-        mSizeSpecSourceImpl.reloadResources();
-    }
-
-    @NonNull
-    private Rect getDisplayBounds() {
-        return mPipDisplayLayoutState.getDisplayBounds();
-    }
-
-    public Point getScreenEdgeInsets() {
-        return mScreenEdgeInsets;
-    }
-
-    /**
-     * Returns the inset bounds the PIP window can be visible in.
-     */
-    public Rect getInsetBounds() {
-        Rect insetBounds = new Rect();
-        DisplayLayout displayLayout = mPipDisplayLayoutState.getDisplayLayout();
-        Rect insets = displayLayout.stableInsets();
-        insetBounds.set(insets.left + mScreenEdgeInsets.x,
-                insets.top + mScreenEdgeInsets.y,
-                displayLayout.width() - insets.right - mScreenEdgeInsets.x,
-                displayLayout.height() - insets.bottom - mScreenEdgeInsets.y);
-        return insetBounds;
-    }
-
-    /** Sets the preferred size of PIP as specified by the activity in PIP mode. */
-    public void setOverrideMinSize(@Nullable Size overrideMinSize) {
-        mOverrideMinSize = overrideMinSize;
-    }
-
-    /** Returns the preferred minimal size specified by the activity in PIP. */
-    @Nullable
-    public Size getOverrideMinSize() {
-        if (mOverrideMinSize != null
-                && (mOverrideMinSize.getWidth() < mOverridableMinSize
-                || mOverrideMinSize.getHeight() < mOverridableMinSize)) {
-            return new Size(mOverridableMinSize, mOverridableMinSize);
-        }
-
-        return mOverrideMinSize;
-    }
-
-    /** Returns the minimum edge size of the override minimum size, or 0 if not set. */
-    public int getOverrideMinEdgeSize() {
-        if (mOverrideMinSize == null) return 0;
-        return Math.min(getOverrideMinSize().getWidth(), getOverrideMinSize().getHeight());
-    }
-
-    public int getMinEdgeSize() {
-        return mOverrideMinSize == null ? mDefaultMinSize : getOverrideMinEdgeSize();
-    }
-
-    /**
-     * Returns the size for the max size spec.
-     */
-    public Size getMaxSize(float aspectRatio) {
-        return mSizeSpecSourceImpl.getMaxSize(aspectRatio);
-    }
-
-    /**
-     * Returns the size for the default size spec.
-     */
-    public Size getDefaultSize(float aspectRatio) {
-        return mSizeSpecSourceImpl.getDefaultSize(aspectRatio);
-    }
-
-    /**
-     * Returns the size for the min size spec.
-     */
-    public Size getMinSize(float aspectRatio) {
-        return mSizeSpecSourceImpl.getMinSize(aspectRatio);
-    }
-
-    /**
-     * Returns the adjusted size so that it conforms to the given aspectRatio.
-     *
-     * @param size current size
-     * @param aspectRatio target aspect ratio
-     */
-    public Size getSizeForAspectRatio(@NonNull Size size, float aspectRatio) {
-        if (size.equals(mOverrideMinSize)) {
-            return adjustOverrideMinSizeToAspectRatio(aspectRatio);
-        }
-
-        return mSizeSpecSourceImpl.getSizeForAspectRatio(size, aspectRatio);
-    }
-
-    /**
-     * Returns the adjusted overridden min size if it is set; otherwise, returns null.
-     *
-     * <p>Overridden min size needs to be adjusted in its own way while making sure that the target
-     * aspect ratio is maintained
-     *
-     * @param aspectRatio target aspect ratio
-     */
-    @Nullable
-    @VisibleForTesting
-    Size adjustOverrideMinSizeToAspectRatio(float aspectRatio) {
-        if (mOverrideMinSize == null) {
-            return null;
-        }
-        final Size size = getOverrideMinSize();
-        final float sizeAspectRatio = size.getWidth() / (float) size.getHeight();
-        if (sizeAspectRatio > aspectRatio) {
-            // Size is wider, fix the width and increase the height
-            return new Size(size.getWidth(), (int) (size.getWidth() / aspectRatio));
-        } else {
-            // Size is taller, fix the height and adjust the width.
-            return new Size((int) (size.getHeight() * aspectRatio), size.getHeight());
-        }
-    }
-
-    @VisibleForTesting
-    boolean supportsPipSizeLargeScreen() {
-        // TODO(b/271468706): switch Tv to having a dedicated SizeSpecSource once the SizeSpecSource
-        // can be injected
-        return SystemProperties
-                .getBoolean("persist.wm.debug.enable_pip_size_large_screen", true) && !isTv();
-    }
-
-    private boolean isTv() {
-        return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK);
-    }
-
-    /** Dumps internal state. */
-    public void dump(PrintWriter pw, String prefix) {
-        final String innerPrefix = prefix + "  ";
-        pw.println(prefix + TAG);
-        pw.println(innerPrefix + "mSizeSpecSourceImpl=" + mSizeSpecSourceImpl);
-        pw.println(innerPrefix + "mOverrideMinSize=" + mOverrideMinSize);
-        pw.println(innerPrefix + "mScreenEdgeInsets=" + mScreenEdgeInsets);
-    }
-}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipTouchHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipTouchHandler.java
index 372ade3..9f7dee7 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipTouchHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipTouchHandler.java
@@ -34,7 +34,6 @@
 import android.graphics.Point;
 import android.graphics.PointF;
 import android.graphics.Rect;
-import android.os.SystemProperties;
 import android.provider.DeviceConfig;
 import android.util.Size;
 import android.view.DisplayCutout;
@@ -51,6 +50,7 @@
 import com.android.wm.shell.R;
 import com.android.wm.shell.common.FloatingContentCoordinator;
 import com.android.wm.shell.common.ShellExecutor;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.PipAnimationController;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
@@ -72,20 +72,12 @@
     private static final String TAG = "PipTouchHandler";
     private static final float DEFAULT_STASH_VELOCITY_THRESHOLD = 18000.f;
 
-    private boolean mEnablePipKeepClearAlgorithm =
-            SystemProperties.getBoolean("persist.wm.debug.enable_pip_keep_clear_algorithm", true);
-
-    @VisibleForTesting
-    void setEnablePipKeepClearAlgorithm(boolean value) {
-        mEnablePipKeepClearAlgorithm = value;
-    }
-
     // Allow PIP to resize to a slightly bigger state upon touch
     private boolean mEnableResize;
     private final Context mContext;
     private final PipBoundsAlgorithm mPipBoundsAlgorithm;
     @NonNull private final PipBoundsState mPipBoundsState;
-    @NonNull private final PipSizeSpecHandler mPipSizeSpecHandler;
+    @NonNull private final SizeSpecSource mSizeSpecSource;
     private final PipUiEventLogger mPipUiEventLogger;
     private final PipDismissTargetHandler mPipDismissTargetHandler;
     private final PipTaskOrganizer mPipTaskOrganizer;
@@ -179,7 +171,7 @@
             PhonePipMenuController menuController,
             PipBoundsAlgorithm pipBoundsAlgorithm,
             @NonNull PipBoundsState pipBoundsState,
-            @NonNull PipSizeSpecHandler pipSizeSpecHandler,
+            @NonNull SizeSpecSource sizeSpecSource,
             PipTaskOrganizer pipTaskOrganizer,
             PipMotionHelper pipMotionHelper,
             FloatingContentCoordinator floatingContentCoordinator,
@@ -190,7 +182,7 @@
         mAccessibilityManager = context.getSystemService(AccessibilityManager.class);
         mPipBoundsAlgorithm = pipBoundsAlgorithm;
         mPipBoundsState = pipBoundsState;
-        mPipSizeSpecHandler = pipSizeSpecHandler;
+        mSizeSpecSource = sizeSpecSource;
         mPipTaskOrganizer = pipTaskOrganizer;
         mMenuController = menuController;
         mPipUiEventLogger = pipUiEventLogger;
@@ -413,7 +405,7 @@
 
         // Calculate the expanded size
         float aspectRatio = (float) normalBounds.width() / normalBounds.height();
-        Size expandedSize = mPipSizeSpecHandler.getDefaultSize(aspectRatio);
+        Size expandedSize = mSizeSpecSource.getDefaultSize(aspectRatio);
         mPipBoundsState.setExpandedBounds(
                 new Rect(0, 0, expandedSize.getWidth(), expandedSize.getHeight()));
         Rect expandedMovementBounds = new Rect();
@@ -429,48 +421,6 @@
                 mIsImeShowing ? mImeOffset : 0,
                 !mIsImeShowing && mIsShelfShowing ? mShelfHeight : 0);
 
-        // If this is from an IME or shelf adjustment, then we should move the PiP so that it is not
-        // occluded by the IME or shelf.
-        if (fromImeAdjustment || fromShelfAdjustment) {
-            if (mTouchState.isUserInteracting() && mTouchState.isDragging()) {
-                // Defer the update of the current movement bounds until after the user finishes
-                // touching the screen
-            } else if (mEnablePipKeepClearAlgorithm) {
-                // Ignore moving PiP if keep clear algorithm is enabled, since IME and shelf height
-                // now are accounted for in the keep clear algorithm calculations
-            } else {
-                final boolean isExpanded = mMenuState == MENU_STATE_FULL && willResizeMenu();
-                final Rect toMovementBounds = new Rect();
-                mPipBoundsAlgorithm.getMovementBounds(curBounds, insetBounds,
-                        toMovementBounds, mIsImeShowing ? mImeHeight : 0);
-                final int prevBottom = mPipBoundsState.getMovementBounds().bottom
-                        - mMovementBoundsExtraOffsets;
-                // This is to handle landscape fullscreen IMEs, don't apply the extra offset in this
-                // case
-                final int toBottom = toMovementBounds.bottom < toMovementBounds.top
-                        ? toMovementBounds.bottom
-                        : toMovementBounds.bottom - extraOffset;
-
-                if (isExpanded) {
-                    curBounds.set(mPipBoundsState.getExpandedBounds());
-                    mPipBoundsAlgorithm.getSnapAlgorithm().applySnapFraction(curBounds,
-                            toMovementBounds, mSavedSnapFraction);
-                }
-
-                if (prevBottom < toBottom) {
-                    // The movement bounds are expanding
-                    if (curBounds.top > prevBottom - mBottomOffsetBufferPx) {
-                        mMotionHelper.animateToOffset(curBounds, toBottom - curBounds.top);
-                    }
-                } else if (prevBottom > toBottom) {
-                    // The movement bounds are shrinking
-                    if (curBounds.top > toBottom - mBottomOffsetBufferPx) {
-                        mMotionHelper.animateToOffset(curBounds, toBottom - curBounds.top);
-                    }
-                }
-            }
-        }
-
         // Update the movement bounds after doing the calculations based on the old movement bounds
         // above
         mPipBoundsState.setNormalMovementBounds(normalMovementBounds);
@@ -517,10 +467,10 @@
     private void updatePinchResizeSizeConstraints(float aspectRatio) {
         final int minWidth, minHeight, maxWidth, maxHeight;
 
-        minWidth = mPipSizeSpecHandler.getMinSize(aspectRatio).getWidth();
-        minHeight = mPipSizeSpecHandler.getMinSize(aspectRatio).getHeight();
-        maxWidth = mPipSizeSpecHandler.getMaxSize(aspectRatio).getWidth();
-        maxHeight = mPipSizeSpecHandler.getMaxSize(aspectRatio).getHeight();
+        minWidth = mSizeSpecSource.getMinSize(aspectRatio).getWidth();
+        minHeight = mSizeSpecSource.getMinSize(aspectRatio).getHeight();
+        maxWidth = mSizeSpecSource.getMaxSize(aspectRatio).getWidth();
+        maxHeight = mSizeSpecSource.getMaxSize(aspectRatio).getHeight();
 
         mPipResizeGestureHandler.updateMinSize(minWidth, minHeight);
         mPipResizeGestureHandler.updateMaxSize(maxWidth, maxHeight);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsAlgorithm.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsAlgorithm.java
index 825b969..cd58ff4 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsAlgorithm.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsAlgorithm.java
@@ -36,10 +36,11 @@
 import com.android.internal.protolog.common.ProtoLog;
 import com.android.wm.shell.R;
 import com.android.wm.shell.common.DisplayLayout;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
+import com.android.wm.shell.pip.PipDisplayLayoutState;
 import com.android.wm.shell.pip.PipKeepClearAlgorithmInterface;
 import com.android.wm.shell.pip.PipSnapAlgorithm;
-import com.android.wm.shell.pip.phone.PipSizeSpecHandler;
 import com.android.wm.shell.pip.tv.TvPipKeepClearAlgorithm.Placement;
 import com.android.wm.shell.protolog.ShellProtoLogGroup;
 
@@ -62,9 +63,10 @@
     public TvPipBoundsAlgorithm(Context context,
             @NonNull TvPipBoundsState tvPipBoundsState,
             @NonNull PipSnapAlgorithm pipSnapAlgorithm,
-            @NonNull PipSizeSpecHandler pipSizeSpecHandler) {
+            @NonNull PipDisplayLayoutState pipDisplayLayoutState,
+            @NonNull SizeSpecSource sizeSpecSource) {
         super(context, tvPipBoundsState, pipSnapAlgorithm,
-                new PipKeepClearAlgorithmInterface() {}, pipSizeSpecHandler);
+                new PipKeepClearAlgorithmInterface() {}, pipDisplayLayoutState, sizeSpecSource);
         this.mTvPipBoundsState = tvPipBoundsState;
         this.mKeepClearAlgorithm = new TvPipKeepClearAlgorithm();
         reloadResources(context);
@@ -291,7 +293,7 @@
                 expandedSize = mTvPipBoundsState.getTvExpandedSize();
             } else {
                 int maxHeight = displayLayout.height()
-                        - (2 * mPipSizeSpecHandler.getScreenEdgeInsets().y)
+                        - (2 * mPipDisplayLayoutState.getScreenEdgeInsets().y)
                         - pipDecorations.top - pipDecorations.bottom;
                 float aspectRatioHeight = mFixedExpandedWidthInPx / expandedRatio;
 
@@ -311,7 +313,7 @@
                 expandedSize = mTvPipBoundsState.getTvExpandedSize();
             } else {
                 int maxWidth = displayLayout.width()
-                        - (2 * mPipSizeSpecHandler.getScreenEdgeInsets().x)
+                        - (2 * mPipDisplayLayoutState.getScreenEdgeInsets().x)
                         - pipDecorations.left - pipDecorations.right;
                 float aspectRatioWidth = mFixedExpandedHeightInPx * expandedRatio;
                 if (maxWidth > aspectRatioWidth) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsState.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsState.java
index 3f3951a..d11f4d5 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsState.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsState.java
@@ -29,10 +29,10 @@
 import android.view.Gravity;
 import android.view.View;
 
+import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
 import com.android.wm.shell.pip.PipDisplayLayoutState;
-import com.android.wm.shell.pip.phone.PipSizeSpecHandler;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -76,9 +76,9 @@
     private Insets mPipMenuTemporaryDecorInsets = Insets.NONE;
 
     public TvPipBoundsState(@NonNull Context context,
-            @NonNull PipSizeSpecHandler pipSizeSpecHandler,
+            @NonNull SizeSpecSource sizeSpecSource,
             @NonNull PipDisplayLayoutState pipDisplayLayoutState) {
-        super(context, pipSizeSpecHandler, pipDisplayLayoutState);
+        super(context, sizeSpecSource, pipDisplayLayoutState);
         mContext = context;
         updateDefaultGravity();
         mTvPipGravity = mDefaultGravity;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java
index 2482acf..e3544c6 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java
@@ -47,10 +47,10 @@
 import com.android.wm.shell.common.ShellExecutor;
 import com.android.wm.shell.common.TaskStackListenerCallback;
 import com.android.wm.shell.common.TaskStackListenerImpl;
+import com.android.wm.shell.common.pip.PipAppOpsListener;
 import com.android.wm.shell.pip.PinnedStackListenerForwarder;
 import com.android.wm.shell.pip.Pip;
 import com.android.wm.shell.pip.PipAnimationController;
-import com.android.wm.shell.pip.PipAppOpsListener;
 import com.android.wm.shell.pip.PipDisplayLayoutState;
 import com.android.wm.shell.pip.PipMediaController;
 import com.android.wm.shell.pip.PipParamsChangedForwarder;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java
index b2a189b..ee55211 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java
@@ -62,13 +62,16 @@
     private SurfaceControl mLeash;
     private TvPipMenuView mPipMenuView;
     private TvPipBackgroundView mPipBackgroundView;
-    private boolean mMenuIsFocused;
 
     @TvPipMenuMode
     private int mCurrentMenuMode = MODE_NO_MENU;
     @TvPipMenuMode
     private int mPrevMenuMode = MODE_NO_MENU;
 
+    /** When the window gains focus, enter this menu mode */
+    @TvPipMenuMode
+    private int mMenuModeOnFocus = MODE_ALL_ACTIONS_MENU;
+
     @IntDef(prefix = { "MODE_" }, value = {
         MODE_NO_MENU,
         MODE_MOVE_MENU,
@@ -170,6 +173,9 @@
         mPipMenuView = createTvPipMenuView();
         setUpViewSurfaceZOrder(mPipMenuView, 1);
         addPipMenuViewToSystemWindows(mPipMenuView, MENU_WINDOW_TITLE);
+        mPipMenuView.getViewTreeObserver().addOnWindowFocusChangeListener(hasFocus -> {
+            onPipWindowFocusChanged(hasFocus);
+        });
     }
 
     @VisibleForTesting
@@ -224,13 +230,14 @@
     void showMovementMenu() {
         ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
                 "%s: showMovementMenu()", TAG);
-        switchToMenuMode(MODE_MOVE_MENU);
+        requestMenuMode(MODE_MOVE_MENU);
     }
 
     @Override
     public void showMenu() {
         ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE, "%s: showMenu()", TAG);
-        switchToMenuMode(MODE_ALL_ACTIONS_MENU, true);
+        mPipMenuView.resetMenu();
+        requestMenuMode(MODE_ALL_ACTIONS_MENU);
     }
 
     void onPipTransitionToTargetBoundsStarted(Rect targetBounds) {
@@ -250,7 +257,7 @@
     void closeMenu() {
         ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
                 "%s: closeMenu()", TAG);
-        switchToMenuMode(MODE_NO_MENU);
+        requestMenuMode(MODE_NO_MENU);
     }
 
     @Override
@@ -392,11 +399,15 @@
         }
     }
 
-    // Start methods handling {@link TvPipMenuMode}
+    // Beginning of convenience methods for {@link TvPipMenuMode}
 
     @VisibleForTesting
     boolean isMenuOpen() {
-        return mCurrentMenuMode != MODE_NO_MENU;
+        return isMenuOpen(mCurrentMenuMode);
+    }
+
+    private static boolean isMenuOpen(@TvPipMenuMode int menuMode) {
+        return menuMode != MODE_NO_MENU;
     }
 
     @VisibleForTesting
@@ -409,46 +420,6 @@
         return mCurrentMenuMode == MODE_ALL_ACTIONS_MENU;
     }
 
-    private void switchToMenuMode(@TvPipMenuMode int menuMode) {
-        switchToMenuMode(menuMode, false);
-    }
-
-    private void switchToMenuMode(@TvPipMenuMode int menuMode, boolean resetMenu) {
-        // Note: we intentionally don't return early here, because the TvPipMenuView needs to
-        // refresh the Ui even if there is no menu mode change.
-        mPrevMenuMode = mCurrentMenuMode;
-        mCurrentMenuMode = menuMode;
-
-        ProtoLog.i(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
-                "%s: switchToMenuMode: setting mCurrentMenuMode=%s, mPrevMenuMode=%s", TAG,
-                getMenuModeString(), getMenuModeString(mPrevMenuMode));
-
-        updateUiOnNewMenuModeRequest(resetMenu);
-        updateDelegateOnNewMenuModeRequest();
-    }
-
-    private void updateUiOnNewMenuModeRequest(boolean resetMenu) {
-        if (mPipMenuView == null || mPipBackgroundView == null) return;
-
-        mPipMenuView.setPipGravity(mTvPipBoundsState.getTvPipGravity());
-        mPipMenuView.transitionToMenuMode(mCurrentMenuMode, resetMenu);
-        mPipBackgroundView.transitionToMenuMode(mCurrentMenuMode);
-        grantPipMenuFocus(mCurrentMenuMode != MODE_NO_MENU);
-    }
-
-    private void updateDelegateOnNewMenuModeRequest() {
-        if (mPrevMenuMode == mCurrentMenuMode) return;
-        if (mDelegate == null) return;
-
-        if (mPrevMenuMode == MODE_MOVE_MENU || isInMoveMode()) {
-            mDelegate.onInMoveModeChanged();
-        }
-
-        if (mCurrentMenuMode == MODE_NO_MENU) {
-            mDelegate.onMenuClosed();
-        }
-    }
-
     @VisibleForTesting
     String getMenuModeString() {
         return getMenuModeString(mCurrentMenuMode);
@@ -467,6 +438,90 @@
         }
     }
 
+    // Beginning of methods handling switching between menu modes
+
+    private void requestMenuMode(@TvPipMenuMode int menuMode) {
+        if (isMenuOpen() == isMenuOpen(menuMode)) {
+            // No need to request a focus change. We can directly switch to the new mode.
+            switchToMenuMode(menuMode);
+        } else {
+            if (isMenuOpen(menuMode)) {
+                mMenuModeOnFocus = menuMode;
+            }
+
+            // Send a request to gain window focus if the menu is open, or lose window focus
+            // otherwise. Once the focus change happens, we will request the new mode in the
+            // callback {@link #onPipWindowFocusChanged}.
+            requestPipMenuFocus(isMenuOpen(menuMode));
+        }
+        // Note: we don't handle cases where there is a focus change currently in flight, because
+        // this is very unlikely to happen in practice and would complicate the logic.
+    }
+
+    private void requestPipMenuFocus(boolean focus) {
+        ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
+                "%s: requestPipMenuFocus(%b)", TAG, focus);
+
+        try {
+            WindowManagerGlobal.getWindowSession().grantEmbeddedWindowFocus(null /* window */,
+                    mSystemWindows.getFocusGrantToken(mPipMenuView), focus);
+        } catch (Exception e) {
+            ProtoLog.e(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
+                    "%s: Unable to update focus, %s", TAG, e);
+        }
+    }
+
+    /**
+     * Called when the menu window gains or loses focus.
+     */
+    @VisibleForTesting
+    void onPipWindowFocusChanged(boolean focused) {
+        ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
+                "%s: onPipWindowFocusChanged - focused=%b", TAG, focused);
+        switchToMenuMode(focused ? mMenuModeOnFocus : MODE_NO_MENU);
+
+        // Reset the default menu mode for focused state.
+        mMenuModeOnFocus = MODE_ALL_ACTIONS_MENU;
+    }
+
+    /**
+     * Immediately switches to the menu mode in the given request. Updates the mDelegate and the UI.
+     * Doesn't handle any focus changes.
+     */
+    private void switchToMenuMode(@TvPipMenuMode int menuMode) {
+        ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
+                "%s: switchToMenuMode: from=%s, to=%s", TAG, getMenuModeString(),
+                getMenuModeString(menuMode));
+
+        if (mCurrentMenuMode == menuMode) return;
+
+        mPrevMenuMode = mCurrentMenuMode;
+        mCurrentMenuMode = menuMode;
+        updateUiOnNewMenuModeRequest();
+        updateDelegateOnNewMenuModeRequest();
+    }
+
+    private void updateUiOnNewMenuModeRequest() {
+        if (mPipMenuView == null || mPipBackgroundView == null) return;
+
+        mPipMenuView.setPipGravity(mTvPipBoundsState.getTvPipGravity());
+        mPipMenuView.transitionToMenuMode(mCurrentMenuMode);
+        mPipBackgroundView.transitionToMenuMode(mCurrentMenuMode);
+    }
+
+    private void updateDelegateOnNewMenuModeRequest() {
+        if (mPrevMenuMode == mCurrentMenuMode) return;
+        if (mDelegate == null) return;
+
+        if (mPrevMenuMode == MODE_MOVE_MENU || isInMoveMode()) {
+            mDelegate.onInMoveModeChanged();
+        }
+
+        if (!isMenuOpen()) {
+            mDelegate.onMenuClosed();
+        }
+    }
+
     // Start {@link TvPipMenuView.Delegate} methods
 
     @Override
@@ -476,42 +531,19 @@
     }
 
     @Override
-    public void onBackPress() {
-        if (!onExitMoveMode()) {
-            closeMenu();
-        }
-    }
-
-    @Override
-    public boolean onExitMoveMode() {
+    public void onExitCurrentMenuMode() {
         ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
-                "%s: onExitMoveMode - mCurrentMenuMode=%s", TAG, getMenuModeString());
-
-        final int saveMenuMode = mCurrentMenuMode;
-        if (isInMoveMode()) {
-            switchToMenuMode(mPrevMenuMode);
-        }
-        return saveMenuMode == MODE_MOVE_MENU;
+                "%s: onExitCurrentMenuMode - mCurrentMenuMode=%s", TAG, getMenuModeString());
+        requestMenuMode(isInMoveMode() ? mPrevMenuMode : MODE_NO_MENU);
     }
 
     @Override
-    public boolean onPipMovement(int keycode) {
+    public void onPipMovement(int keycode) {
         ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
                 "%s: onPipMovement - mCurrentMenuMode=%s", TAG, getMenuModeString());
         if (isInMoveMode()) {
             mDelegate.movePip(keycode);
         }
-        return isInMoveMode();
-    }
-
-    @Override
-    public void onPipWindowFocusChanged(boolean focused) {
-        ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
-                "%s: onPipWindowFocusChanged - focused=%b", TAG, focused);
-        mMenuIsFocused = focused;
-        if (!focused && isMenuOpen()) {
-            closeMenu();
-        }
     }
 
     interface Delegate {
@@ -524,21 +556,6 @@
         void closeEduText();
     }
 
-    private void grantPipMenuFocus(boolean grantFocus) {
-        if (mMenuIsFocused == grantFocus) return;
-
-        ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
-                "%s: grantWindowFocus(%b)", TAG, grantFocus);
-
-        try {
-            WindowManagerGlobal.getWindowSession().grantEmbeddedWindowFocus(null /* window */,
-                    mSystemWindows.getFocusGrantToken(mPipMenuView), grantFocus);
-        } catch (Exception e) {
-            ProtoLog.e(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
-                    "%s: Unable to update focus, %s", TAG, e);
-        }
-    }
-
     private class PipMenuSurfaceChangedCallback implements ViewRootImpl.SurfaceChangedCallback {
         private final View mView;
         private final int mZOrder;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuView.java
index 613791c..7c15637 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuView.java
@@ -328,7 +328,7 @@
         return menuUiBounds;
     }
 
-    void transitionToMenuMode(int menuMode, boolean resetMenu) {
+    void transitionToMenuMode(int menuMode) {
         switch (menuMode) {
             case MODE_NO_MENU:
                 hideAllUserControls();
@@ -337,7 +337,7 @@
                 showMoveMenu();
                 break;
             case MODE_ALL_ACTIONS_MENU:
-                showAllActionsMenu(resetMenu);
+                showAllActionsMenu();
                 break;
             default:
                 throw new IllegalArgumentException(
@@ -362,13 +362,13 @@
         mEduTextDrawer.closeIfNeeded();
     }
 
-    private void showAllActionsMenu(boolean resetMenu) {
-        ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
-                "%s: showAllActionsMenu(), resetMenu %b", TAG, resetMenu);
+    void resetMenu() {
+        scrollToFirstAction();
+    }
 
-        if (resetMenu) {
-            scrollToFirstAction();
-        }
+    private void showAllActionsMenu() {
+        ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
+                "%s: showAllActionsMenu()", TAG);
 
         if (mCurrentMenuMode == MODE_ALL_ACTIONS_MENU) return;
 
@@ -431,12 +431,6 @@
         }
     }
 
-    @Override
-    public void onWindowFocusChanged(boolean hasWindowFocus) {
-        super.onWindowFocusChanged(hasWindowFocus);
-        mListener.onPipWindowFocusChanged(hasWindowFocus);
-    }
-
     private void animateAlphaTo(float alpha, View view) {
         if (view.getAlpha() == alpha) {
             return;
@@ -483,28 +477,28 @@
         if (event.getAction() == ACTION_UP) {
 
             if (event.getKeyCode() == KEYCODE_BACK) {
-                mListener.onBackPress();
+                mListener.onExitCurrentMenuMode();
                 return true;
             }
 
-            if (mA11yManager.isEnabled()) {
-                return super.dispatchKeyEvent(event);
-            }
-
-            switch (event.getKeyCode()) {
-                case KEYCODE_DPAD_UP:
-                case KEYCODE_DPAD_DOWN:
-                case KEYCODE_DPAD_LEFT:
-                case KEYCODE_DPAD_RIGHT:
-                    return mListener.onPipMovement(event.getKeyCode()) || super.dispatchKeyEvent(
-                            event);
-                case KEYCODE_ENTER:
-                case KEYCODE_DPAD_CENTER:
-                    return mListener.onExitMoveMode() || super.dispatchKeyEvent(event);
-                default:
-                    break;
+            if (mCurrentMenuMode == MODE_MOVE_MENU && !mA11yManager.isEnabled()) {
+                switch (event.getKeyCode()) {
+                    case KEYCODE_DPAD_UP:
+                    case KEYCODE_DPAD_DOWN:
+                    case KEYCODE_DPAD_LEFT:
+                    case KEYCODE_DPAD_RIGHT:
+                        mListener.onPipMovement(event.getKeyCode());
+                        return true;
+                    case KEYCODE_ENTER:
+                    case KEYCODE_DPAD_CENTER:
+                        mListener.onExitCurrentMenuMode();
+                        return true;
+                    default:
+                        // Dispatch key event as normal below
+                }
             }
         }
+
         return super.dispatchKeyEvent(event);
     }
 
@@ -529,7 +523,7 @@
         if (a11yEnabled) {
             mA11yDoneButton.setVisibility(VISIBLE);
             mA11yDoneButton.setOnClickListener(v -> {
-                mListener.onExitMoveMode();
+                mListener.onExitCurrentMenuMode();
             });
             mA11yDoneButton.requestFocus();
             mA11yDoneButton.requestAccessibilityFocus();
@@ -626,26 +620,15 @@
 
     interface Listener {
 
-        void onBackPress();
+        /**
+         * Called when a button for exiting the current menu mode was pressed.
+         */
+        void onExitCurrentMenuMode();
 
         /**
-         * Called when a button for exiting move mode was pressed.
-         *
-         * @return true if the event was handled or false if the key event should be handled by the
-         * next receiver.
+         * Called when a button to move the PiP in a certain direction, indicated by keycode.
          */
-        boolean onExitMoveMode();
-
-        /**
-         * @return whether pip movement was handled.
-         */
-        boolean onPipMovement(int keycode);
-
-        /**
-         * Called when the TvPipMenuView loses focus. This also means that the TV PiP menu window
-         * has lost focus.
-         */
-        void onPipWindowFocusChanged(boolean focused);
+        void onPipMovement(int keycode);
 
         /**
          *  The edu text closing impacts the size of the Picture-in-Picture window and influences
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/protolog/ShellProtoLogGroup.java b/libs/WindowManager/Shell/src/com/android/wm/shell/protolog/ShellProtoLogGroup.java
index 3af1b75..05e4af3 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/protolog/ShellProtoLogGroup.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/protolog/ShellProtoLogGroup.java
@@ -55,6 +55,8 @@
             Consts.TAG_WM_SHELL),
     WM_SHELL_FOLDABLE(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
             Consts.TAG_WM_SHELL),
+    WM_SHELL_BUBBLES(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            "Bubbles"),
     TEST_GROUP(true, true, false, "WindowManagerShellProtoLogTest");
 
     private final boolean mEnabled;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentsTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentsTransitionHandler.java
index 88a81fc..a11d952 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentsTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentsTransitionHandler.java
@@ -771,7 +771,7 @@
                     Slog.e(TAG, "Error sending appeared tasks to recents animation", e);
                 }
             }
-            finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */);
+            finishCallback.onTransitionFinished(null /* wct */);
         }
 
         /** For now, just set-up a jump-cut to the new activity. */
@@ -937,7 +937,7 @@
                 }
             }
             cleanUp();
-            finishCB.onTransitionFinished(wct.isEmpty() ? null : wct, null /* wctCB */);
+            finishCB.onTransitionFinished(wct.isEmpty() ? null : wct);
         }
 
         @Override
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/ISplitScreen.aidl b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/ISplitScreen.aidl
index c414e70..14304a3 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/ISplitScreen.aidl
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/ISplitScreen.aidl
@@ -27,6 +27,7 @@
 import android.window.RemoteTransition;
 
 import com.android.wm.shell.splitscreen.ISplitScreenListener;
+import com.android.wm.shell.splitscreen.ISplitSelectListener;
 
 /**
  * Interface that is exposed to remote callers to manipulate the splitscreen feature.
@@ -44,6 +45,16 @@
     oneway void unregisterSplitScreenListener(in ISplitScreenListener listener) = 2;
 
     /**
+     * Registers a split select listener.
+     */
+    oneway void registerSplitSelectListener(in ISplitSelectListener listener) = 20;
+
+    /**
+     * Unregisters a split select listener.
+     */
+    oneway void unregisterSplitSelectListener(in ISplitSelectListener listener) = 21;
+
+    /**
      * Removes a task from the side stage.
      */
     oneway void removeFromSideStage(int taskId) = 4;
@@ -148,4 +159,4 @@
      */
     RemoteAnimationTarget[] onStartingSplitLegacy(in RemoteAnimationTarget[] appTargets) = 14;
 }
-// Last id = 19
\ No newline at end of file
+// Last id = 21
\ No newline at end of file
diff --git a/core/java/android/view/selectiontoolbar/WidgetInfo.aidl b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/ISplitSelectListener.aidl
similarity index 63%
copy from core/java/android/view/selectiontoolbar/WidgetInfo.aidl
copy to libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/ISplitSelectListener.aidl
index 1057c51..7171da5 100644
--- a/core/java/android/view/selectiontoolbar/WidgetInfo.aidl
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/ISplitSelectListener.aidl
@@ -14,9 +14,16 @@
  * limitations under the License.
  */
 
-package android.view.selectiontoolbar;
+package com.android.wm.shell.splitscreen;
+
+import android.app.ActivityManager.RunningTaskInfo;
 
 /**
- * @hide
+ * Listener interface that Launcher attaches to SystemUI to get split-select callbacks.
  */
-parcelable WidgetInfo;
+interface ISplitSelectListener {
+    /**
+     * Called when a task requests to enter split select
+     */
+    boolean onRequestSplitSelect(in RunningTaskInfo taskInfo);
+}
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreen.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreen.java
index 2f2bc77..f20fe0b 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreen.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreen.java
@@ -18,6 +18,7 @@
 
 import android.annotation.IntDef;
 import android.annotation.NonNull;
+import android.app.ActivityManager;
 import android.graphics.Rect;
 
 import com.android.wm.shell.common.annotations.ExternalThread;
@@ -63,6 +64,13 @@
         default void onSplitVisibilityChanged(boolean visible) {}
     }
 
+    /** Callback interface for listening to requests to enter split select */
+    interface SplitSelectListener {
+        default boolean onRequestEnterSplitSelect(ActivityManager.RunningTaskInfo taskInfo) {
+            return false;
+        }
+    }
+
     /** Registers listener that gets split screen callback. */
     void registerSplitScreenListener(@NonNull SplitScreenListener listener,
             @NonNull Executor executor);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java
index 5fa2654..210bf68 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java
@@ -87,6 +87,7 @@
 import com.android.wm.shell.common.annotations.ExternalThread;
 import com.android.wm.shell.common.split.SplitScreenConstants.SplitPosition;
 import com.android.wm.shell.common.split.SplitScreenUtils;
+import com.android.wm.shell.desktopmode.DesktopTasksController;
 import com.android.wm.shell.draganddrop.DragAndDropController;
 import com.android.wm.shell.draganddrop.DragAndDropPolicy;
 import com.android.wm.shell.protolog.ShellProtoLogGroup;
@@ -104,6 +105,7 @@
 import java.lang.annotation.RetentionPolicy;
 import java.util.Optional;
 import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
  * Class manages split-screen multitasking mode and implements the main interface
@@ -177,6 +179,7 @@
     private final Optional<RecentTasksController> mRecentTasksOptional;
     private final LaunchAdjacentController mLaunchAdjacentController;
     private final Optional<WindowDecorViewModel> mWindowDecorViewModel;
+    private final Optional<DesktopTasksController> mDesktopTasksController;
     private final SplitScreenShellCommandHandler mSplitScreenShellCommandHandler;
     private final String[] mAppsSupportMultiInstances;
 
@@ -205,6 +208,7 @@
             Optional<RecentTasksController> recentTasks,
             LaunchAdjacentController launchAdjacentController,
             Optional<WindowDecorViewModel> windowDecorViewModel,
+            Optional<DesktopTasksController> desktopTasksController,
             ShellExecutor mainExecutor) {
         mShellCommandHandler = shellCommandHandler;
         mShellController = shellController;
@@ -223,6 +227,7 @@
         mRecentTasksOptional = recentTasks;
         mLaunchAdjacentController = launchAdjacentController;
         mWindowDecorViewModel = windowDecorViewModel;
+        mDesktopTasksController = desktopTasksController;
         mSplitScreenShellCommandHandler = new SplitScreenShellCommandHandler(this);
         // TODO(b/238217847): Temporarily add this check here until we can remove the dynamic
         //                    override for this controller from the base module
@@ -254,6 +259,7 @@
             RecentTasksController recentTasks,
             LaunchAdjacentController launchAdjacentController,
             WindowDecorViewModel windowDecorViewModel,
+            DesktopTasksController desktopTasksController,
             ShellExecutor mainExecutor,
             StageCoordinator stageCoordinator) {
         mShellCommandHandler = shellCommandHandler;
@@ -273,6 +279,7 @@
         mRecentTasksOptional = Optional.of(recentTasks);
         mLaunchAdjacentController = launchAdjacentController;
         mWindowDecorViewModel = Optional.of(windowDecorViewModel);
+        mDesktopTasksController = Optional.of(desktopTasksController);
         mStageCoordinator = stageCoordinator;
         mSplitScreenShellCommandHandler = new SplitScreenShellCommandHandler(this);
         shellInit.addInitCallback(this::onInit, this);
@@ -306,6 +313,7 @@
         }
         mDragAndDropController.ifPresent(controller -> controller.setSplitScreenController(this));
         mWindowDecorViewModel.ifPresent(viewModel -> viewModel.setSplitScreenController(this));
+        mDesktopTasksController.ifPresent(controller -> controller.setSplitScreenController(this));
     }
 
     protected StageCoordinator createStageCoordinator() {
@@ -468,6 +476,16 @@
         mStageCoordinator.unregisterSplitScreenListener(listener);
     }
 
+    /** Register a split select listener */
+    public void registerSplitSelectListener(SplitScreen.SplitSelectListener listener) {
+        mStageCoordinator.registerSplitSelectListener(listener);
+    }
+
+    /** Unregister a split select listener */
+    public void unregisterSplitSelectListener(SplitScreen.SplitSelectListener listener) {
+        mStageCoordinator.unregisterSplitSelectListener(listener);
+    }
+
     public void goToFullscreenFromSplit() {
         mStageCoordinator.goToFullscreenFromSplit();
     }
@@ -485,6 +503,16 @@
         return mStageCoordinator.getActivateSplitPosition(taskInfo);
     }
 
+    /**
+     * Move a task to split select
+     * @param taskInfo the task being moved to split select
+     * @param wct transaction to apply if this is a valid request
+     */
+    public void requestEnterSplitSelect(ActivityManager.RunningTaskInfo taskInfo,
+            WindowContainerTransaction wct) {
+        mStageCoordinator.requestEnterSplitSelect(taskInfo, wct);
+    }
+
     public void startTask(int taskId, @SplitPosition int position, @Nullable Bundle options) {
         final int[] result = new int[1];
         IRemoteAnimationRunner wrapper = new IRemoteAnimationRunner.Stub() {
@@ -1088,6 +1116,8 @@
         private SplitScreenController mController;
         private final SingleInstanceRemoteListener<SplitScreenController,
                 ISplitScreenListener> mListener;
+        private final SingleInstanceRemoteListener<SplitScreenController,
+                ISplitSelectListener> mSelectListener;
         private final SplitScreen.SplitScreenListener mSplitScreenListener =
                 new SplitScreen.SplitScreenListener() {
                     @Override
@@ -1101,11 +1131,25 @@
                     }
                 };
 
+        private final SplitScreen.SplitSelectListener mSplitSelectListener =
+                new SplitScreen.SplitSelectListener() {
+                    @Override
+                    public boolean onRequestEnterSplitSelect(
+                            ActivityManager.RunningTaskInfo taskInfo) {
+                        AtomicBoolean result = new AtomicBoolean(false);
+                        mSelectListener.call(l -> result.set(l.onRequestSplitSelect(taskInfo)));
+                        return result.get();
+                    }
+                };
+
         public ISplitScreenImpl(SplitScreenController controller) {
             mController = controller;
             mListener = new SingleInstanceRemoteListener<>(controller,
                     c -> c.registerSplitScreenListener(mSplitScreenListener),
                     c -> c.unregisterSplitScreenListener(mSplitScreenListener));
+            mSelectListener = new SingleInstanceRemoteListener<>(controller,
+                    c -> c.registerSplitSelectListener(mSplitSelectListener),
+                    c -> c.unregisterSplitSelectListener(mSplitSelectListener));
         }
 
         /**
@@ -1131,6 +1175,18 @@
         }
 
         @Override
+        public void registerSplitSelectListener(ISplitSelectListener listener) {
+            executeRemoteCallWithTaskPermission(mController, "registerSplitSelectListener",
+                    (controller) -> mSelectListener.register(listener));
+        }
+
+        @Override
+        public void unregisterSplitSelectListener(ISplitSelectListener listener) {
+            executeRemoteCallWithTaskPermission(mController, "unregisterSplitSelectListener",
+                    (controller) -> mSelectListener.unregister());
+        }
+
+        @Override
         public void exitSplitScreen(int toTopTaskId) {
             executeRemoteCallWithTaskPermission(mController, "exitSplitScreen",
                     (controller) -> controller.exitSplitScreen(toTopTaskId, EXIT_REASON_UNKNOWN));
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenTransitions.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenTransitions.java
index d21f8a4..7dec12a 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenTransitions.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenTransitions.java
@@ -43,7 +43,6 @@
 import android.window.TransitionInfo;
 import android.window.WindowContainerToken;
 import android.window.WindowContainerTransaction;
-import android.window.WindowContainerTransactionCallback;
 
 import com.android.internal.protolog.common.ProtoLog;
 import com.android.wm.shell.common.TransactionPool;
@@ -109,7 +108,7 @@
             if (pendingTransition.mCanceled) {
                 // The pending transition was canceled, so skip playing animation.
                 startTransaction.apply();
-                onFinish(null /* wct */, null /* wctCB */);
+                onFinish(null /* wct */);
                 return;
             }
 
@@ -211,7 +210,7 @@
             }
         }
         t.apply();
-        onFinish(null /* wct */, null /* wctCB */);
+        onFinish(null /* wct */);
     }
 
     /** Play animation for drag divider dismiss transition. */
@@ -238,7 +237,7 @@
                     mAnimations.remove(va);
                     if (animated) {
                         mTransitions.getMainExecutor().execute(() -> {
-                            onFinish(null /* wct */, null /* wctCB */);
+                            onFinish(null /* wct */);
                         });
                     }
                 });
@@ -250,7 +249,7 @@
             }
         }
         startTransaction.apply();
-        onFinish(null /* wct */, null /* wctCB */);
+        onFinish(null /* wct */);
     }
 
     /** Play animation for resize transition. */
@@ -283,7 +282,7 @@
                     mAnimations.remove(va);
                     if (animated) {
                         mTransitions.getMainExecutor().execute(() -> {
-                            onFinish(null /* wct */, null /* wctCB */);
+                            onFinish(null /* wct */);
                         });
                     }
                 });
@@ -291,7 +290,7 @@
         }
 
         startTransaction.apply();
-        onFinish(null /* wct */, null /* wctCB */);
+        onFinish(null /* wct */);
     }
 
     boolean isPendingTransition(IBinder transition) {
@@ -325,8 +324,10 @@
 
     void startFullscreenTransition(WindowContainerTransaction wct,
             @Nullable RemoteTransition handler) {
-        mTransitions.startTransition(TRANSIT_OPEN, wct,
-                new OneShotRemoteHandler(mTransitions.getMainExecutor(), handler));
+        OneShotRemoteHandler fullscreenHandler =
+                new OneShotRemoteHandler(mTransitions.getMainExecutor(), handler);
+        fullscreenHandler.setTransition(mTransitions
+                .startTransition(TRANSIT_OPEN, wct, fullscreenHandler));
     }
 
 
@@ -391,7 +392,7 @@
         if (mPendingResize != null) {
             mPendingResize.cancel(null);
             mAnimations.clear();
-            onFinish(null /* wct */, null /* wctCB */);
+            onFinish(null /* wct */);
         }
 
         IBinder transition = mTransitions.startTransition(TRANSIT_CHANGE, wct, handler);
@@ -450,7 +451,7 @@
         }
     }
 
-    void onFinish(WindowContainerTransaction wct, WindowContainerTransactionCallback wctCB) {
+    void onFinish(WindowContainerTransaction wct) {
         if (!mAnimations.isEmpty()) return;
 
         if (wct == null) wct = new WindowContainerTransaction();
@@ -470,7 +471,7 @@
 
         mOnFinish.run();
         if (mFinishCallback != null) {
-            mFinishCallback.onTransitionFinished(wct /* wct */, wctCB /* wctCB */);
+            mFinishCallback.onTransitionFinished(wct /* wct */);
             mFinishCallback = null;
         }
     }
@@ -495,7 +496,7 @@
                 mTransactionPool.release(transaction);
                 mTransitions.getMainExecutor().execute(() -> {
                     mAnimations.remove(va);
-                    onFinish(null /* wct */, null /* wctCB */);
+                    onFinish(null /* wct */);
                 });
             }
         });
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
index 69609ac..6970068 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
@@ -144,8 +144,10 @@
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Optional;
+import java.util.Set;
 
 /**
  * Coordinates the staging (visibility, sizing, ...) of the split-screen {@link MainStage} and
@@ -185,6 +187,7 @@
     private final ShellTaskOrganizer mTaskOrganizer;
     private final Context mContext;
     private final List<SplitScreen.SplitScreenListener> mListeners = new ArrayList<>();
+    private final Set<SplitScreen.SplitSelectListener> mSelectListeners = new HashSet<>();
     private final DisplayController mDisplayController;
     private final DisplayImeController mDisplayImeController;
     private final DisplayInsetsController mDisplayInsetsController;
@@ -462,6 +465,15 @@
         return mLogger;
     }
 
+    void requestEnterSplitSelect(ActivityManager.RunningTaskInfo taskInfo,
+            WindowContainerTransaction wct) {
+        boolean enteredSplitSelect = false;
+        for (SplitScreen.SplitSelectListener listener : mSelectListeners) {
+            enteredSplitSelect |= listener.onRequestEnterSplitSelect(taskInfo);
+        }
+        if (enteredSplitSelect) mTaskOrganizer.applyTransaction(wct);
+    }
+
     void startShortcut(String packageName, String shortcutId, @SplitPosition int position,
             Bundle options, UserHandle user) {
         final boolean isEnteringSplit = !isSplitActive();
@@ -1657,6 +1669,14 @@
         mListeners.remove(listener);
     }
 
+    void registerSplitSelectListener(SplitScreen.SplitSelectListener listener) {
+        mSelectListeners.add(listener);
+    }
+
+    void unregisterSplitSelectListener(SplitScreen.SplitSelectListener listener) {
+        mSelectListeners.remove(listener);
+    }
+
     void sendStatusToListener(SplitScreen.SplitScreenListener listener) {
         listener.onStagePositionChanged(STAGE_TYPE_MAIN, getMainStagePosition());
         listener.onStagePositionChanged(STAGE_TYPE_SIDE, getSideStagePosition());
@@ -2720,7 +2740,8 @@
                 == TRANSIT_SPLIT_SCREEN_OPEN_TO_SIDE) {
             // Open to side should only be used when split already active and foregorund.
             if (mainChild == null && sideChild == null) {
-                Log.w(TAG, "Launched a task in split, but didn't receive any task in transition.");
+                Log.w(TAG, splitFailureMessage("startPendingEnterAnimation",
+                        "Launched a task in split, but didn't receive any task in transition."));
                 // This should happen when the target app is already on front, so just cancel.
                 mSplitTransitions.mPendingEnter.cancel(null);
                 return true;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/tv/TvSplitScreenController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/tv/TvSplitScreenController.java
index a2301b1..c101425 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/tv/TvSplitScreenController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/tv/TvSplitScreenController.java
@@ -87,7 +87,7 @@
                 syncQueue, rootTDAOrganizer, displayController, displayImeController,
                 displayInsetsController, dragAndDropController, transitions, transactionPool,
                 iconProvider, recentTasks, launchAdjacentController, Optional.empty(),
-                mainExecutor);
+                Optional.empty(), mainExecutor);
 
         mTaskOrganizer = shellTaskOrganizer;
         mSyncQueue = syncQueue;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenContentDrawer.java b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenContentDrawer.java
index 84dcd4d..0c6adc9 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenContentDrawer.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenContentDrawer.java
@@ -376,8 +376,8 @@
     private static int estimateWindowBGColor(Drawable themeBGDrawable) {
         final DrawableColorTester themeBGTester = new DrawableColorTester(
                 themeBGDrawable, DrawableColorTester.TRANSLUCENT_FILTER /* filterType */);
-        if (themeBGTester.passFilterRatio() != 1) {
-            // the window background is translucent, unable to draw
+        if (themeBGTester.passFilterRatio() < 0.5f) {
+            // more than half pixels of the window background is translucent, unable to draw
             Slog.w(TAG, "Window background is translucent, fill background with black color");
             return getSystemBGColor();
         } else {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/taskview/TaskViewTaskController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/taskview/TaskViewTaskController.java
index a743e99..adae21b 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/taskview/TaskViewTaskController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/taskview/TaskViewTaskController.java
@@ -94,9 +94,11 @@
         mShellExecutor = organizer.getExecutor();
         mSyncQueue = syncQueue;
         mTaskViewTransitions = taskViewTransitions;
-        if (mTaskViewTransitions != null) {
-            mTaskViewTransitions.addTaskView(this);
-        }
+        mShellExecutor.execute(() -> {
+            if (mTaskViewTransitions != null) {
+                mTaskViewTransitions.addTaskView(this);
+            }
+        });
         mGuard.open("release");
     }
 
@@ -225,10 +227,10 @@
     }
 
     private void performRelease() {
-        if (mTaskViewTransitions != null) {
-            mTaskViewTransitions.removeTaskView(this);
-        }
         mShellExecutor.execute(() -> {
+            if (mTaskViewTransitions != null) {
+                mTaskViewTransitions.removeTaskView(this);
+            }
             mTaskOrganizer.removeListener(this);
             resetTaskInfo();
         });
@@ -410,9 +412,12 @@
         if (mTaskToken == null) {
             return;
         }
-        // Sync Transactions can't operate simultaneously with shell transition collection.
+
         if (isUsingShellTransitions()) {
-            mTaskViewTransitions.setTaskBounds(this, boundsOnScreen);
+            mShellExecutor.execute(() -> {
+                // Sync Transactions can't operate simultaneously with shell transition collection.
+                mTaskViewTransitions.setTaskBounds(this, boundsOnScreen);
+            });
             return;
         }
 
@@ -430,9 +435,11 @@
             Slog.w(TAG, "Trying to remove a task that was never added? (no taskToken)");
             return;
         }
-        WindowContainerTransaction wct = new WindowContainerTransaction();
-        wct.removeTask(mTaskToken);
-        mTaskViewTransitions.closeTaskView(wct, this);
+        mShellExecutor.execute(() -> {
+            WindowContainerTransaction wct = new WindowContainerTransaction();
+            wct.removeTask(mTaskToken);
+            mTaskViewTransitions.closeTaskView(wct, this);
+        });
     }
 
     /**
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/taskview/TaskViewTransitions.java b/libs/WindowManager/Shell/src/com/android/wm/shell/taskview/TaskViewTransitions.java
index daf8be6..e03f825 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/taskview/TaskViewTransitions.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/taskview/TaskViewTransitions.java
@@ -390,7 +390,7 @@
         }
         // No animation, just show it immediately.
         startTransaction.apply();
-        finishCallback.onTransitionFinished(wct, null /* wctCB */);
+        finishCallback.onTransitionFinished(wct);
         startNextTransition();
         return true;
     }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultMixedHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultMixedHandler.java
index 052af3a..986560b 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultMixedHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultMixedHandler.java
@@ -40,7 +40,6 @@
 import android.window.TransitionInfo;
 import android.window.TransitionRequestInfo;
 import android.window.WindowContainerTransaction;
-import android.window.WindowContainerTransactionCallback;
 
 import com.android.internal.protolog.common.ProtoLog;
 import com.android.wm.shell.common.split.SplitScreenUtils;
@@ -124,14 +123,7 @@
             mTransition = transition;
         }
 
-        void joinFinishArgs(WindowContainerTransaction wct,
-                WindowContainerTransactionCallback wctCB) {
-            if (wctCB != null) {
-                // Technically can probably support 1, but don't want to encourage CB usage since
-                // it creates instabliity, so just throw.
-                throw new IllegalArgumentException("Can't mix transitions that require finish"
-                        + " sync callback");
-            }
+        void joinFinishArgs(WindowContainerTransaction wct) {
             if (wct != null) {
                 if (mFinishWCT == null) {
                     mFinishWCT = wct;
@@ -389,12 +381,12 @@
                 info.getChanges().remove(i);
             }
         }
-        Transitions.TransitionFinishCallback finishCB = (wct, wctCB) -> {
+        Transitions.TransitionFinishCallback finishCB = (wct) -> {
             --mixed.mInFlightSubAnimations;
-            mixed.joinFinishArgs(wct, wctCB);
+            mixed.joinFinishArgs(wct);
             if (mixed.mInFlightSubAnimations > 0) return;
             mActiveTransitions.remove(mixed);
-            finishCallback.onTransitionFinished(mixed.mFinishWCT, wctCB);
+            finishCallback.onTransitionFinished(mixed.mFinishWCT);
         };
         if (pipChange == null) {
             if (mixed.mLeftoversHandler != null) {
@@ -461,15 +453,15 @@
             return false;
         }
         final boolean isGoingHome = homeIsOpening;
-        Transitions.TransitionFinishCallback finishCB = (wct, wctCB) -> {
+        Transitions.TransitionFinishCallback finishCB = (wct) -> {
             --mixed.mInFlightSubAnimations;
-            mixed.joinFinishArgs(wct, wctCB);
+            mixed.joinFinishArgs(wct);
             if (mixed.mInFlightSubAnimations > 0) return;
             mActiveTransitions.remove(mixed);
             if (isGoingHome) {
                 mSplitHandler.onTransitionAnimationComplete();
             }
-            finishCallback.onTransitionFinished(mixed.mFinishWCT, wctCB);
+            finishCallback.onTransitionFinished(mixed.mFinishWCT);
         };
         if (isGoingHome || mSplitHandler.getSplitItemPosition(pipChange.getLastParent())
                 != SPLIT_POSITION_UNDEFINED) {
@@ -586,12 +578,12 @@
         // We need to split the transition into 2 parts: the split part and the display part.
         mixed.mInFlightSubAnimations = 2;
 
-        Transitions.TransitionFinishCallback finishCB = (wct, wctCB) -> {
+        Transitions.TransitionFinishCallback finishCB = (wct) -> {
             --mixed.mInFlightSubAnimations;
-            mixed.joinFinishArgs(wct, wctCB);
+            mixed.joinFinishArgs(wct);
             if (mixed.mInFlightSubAnimations > 0) return;
             mActiveTransitions.remove(mixed);
-            finishCallback.onTransitionFinished(mixed.mFinishWCT, null /* wctCB */);
+            finishCallback.onTransitionFinished(mixed.mFinishWCT);
         };
 
         // Dispatch the display change. This will most-likely be taken by the default handler.
@@ -614,7 +606,7 @@
             @NonNull Transitions.TransitionFinishCallback finishCallback) {
         // Split-screen is only interested in the recents transition finishing (and merging), so
         // just wrap finish and start recents animation directly.
-        Transitions.TransitionFinishCallback finishCB = (wct, wctCB) -> {
+        Transitions.TransitionFinishCallback finishCB = (wct) -> {
             mixed.mInFlightSubAnimations = 0;
             mActiveTransitions.remove(mixed);
             // If pair-to-pair switching, the post-recents clean-up isn't needed.
@@ -626,7 +618,7 @@
                 mSplitHandler.onRecentsPairToPairAnimationFinish(wct);
             }
             mSplitHandler.onTransitionAnimationComplete();
-            finishCallback.onTransitionFinished(wct, wctCB);
+            finishCallback.onTransitionFinished(wct);
         };
         mixed.mInFlightSubAnimations = 1;
         mSplitHandler.onRecentsInSplitAnimationStart(info);
@@ -644,11 +636,11 @@
             @NonNull SurfaceControl.Transaction startTransaction,
             @NonNull SurfaceControl.Transaction finishTransaction,
             @NonNull Transitions.TransitionFinishCallback finishCallback) {
-        final Transitions.TransitionFinishCallback finishCB = (wct, wctCB) -> {
+        final Transitions.TransitionFinishCallback finishCB = (wct) -> {
             mixed.mInFlightSubAnimations--;
             if (mixed.mInFlightSubAnimations == 0) {
                 mActiveTransitions.remove(mixed);
-                finishCallback.onTransitionFinished(wct, wctCB);
+                finishCallback.onTransitionFinished(wct);
             }
         };
         mixed.mInFlightSubAnimations++;
@@ -693,11 +685,11 @@
             @NonNull SurfaceControl.Transaction startTransaction,
             @NonNull SurfaceControl.Transaction finishTransaction,
             @NonNull Transitions.TransitionFinishCallback finishCallback) {
-        final Transitions.TransitionFinishCallback finishCB = (wct, wctCB) -> {
+        final Transitions.TransitionFinishCallback finishCB = (wct) -> {
             mixed.mInFlightSubAnimations--;
             if (mixed.mInFlightSubAnimations > 0) return;
             mActiveTransitions.remove(mixed);
-            finishCallback.onTransitionFinished(wct, wctCB);
+            finishCallback.onTransitionFinished(wct);
         };
         mixed.mInFlightSubAnimations = 1;
         // Sync pip state.
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
index dc78c9b..7df658e 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
@@ -300,7 +300,7 @@
         // immediately finishes since there is no animation for screen-wake.
         if (info.getType() == WindowManager.TRANSIT_WAKE && !info.isKeyguardGoingAway()) {
             startTransaction.apply();
-            finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */);
+            finishCallback.onTransitionFinished(null /* wct */);
             return true;
         }
 
@@ -309,7 +309,7 @@
                 || (info.getFlags() & WindowManager.TRANSIT_FLAG_INVISIBLE) != 0) {
             startTransaction.apply();
             finishTransaction.apply();
-            finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */);
+            finishCallback.onTransitionFinished(null /* wct */);
             return true;
         }
 
@@ -323,7 +323,7 @@
         final Runnable onAnimFinish = () -> {
             if (!animations.isEmpty()) return;
             mAnimations.remove(transition);
-            finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */);
+            finishCallback.onTransitionFinished(null /* wct */);
         };
 
         final List<Consumer<SurfaceControl.Transaction>> postStartTransactionCallbacks =
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/OneShotRemoteHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/OneShotRemoteHandler.java
index 4e3d220..fab2dd2 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/OneShotRemoteHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/OneShotRemoteHandler.java
@@ -68,7 +68,7 @@
         final IBinder.DeathRecipient remoteDied = () -> {
             Log.e(Transitions.TAG, "Remote transition died, finishing");
             mMainExecutor.execute(
-                    () -> finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */));
+                    () -> finishCallback.onTransitionFinished(null /* wct */));
         };
         IRemoteTransitionFinishedCallback cb = new IRemoteTransitionFinishedCallback.Stub() {
             @Override
@@ -81,7 +81,7 @@
                     finishTransaction.merge(sct);
                 }
                 mMainExecutor.execute(() -> {
-                    finishCallback.onTransitionFinished(wct, null /* wctCB */);
+                    finishCallback.onTransitionFinished(wct);
                 });
             }
         };
@@ -104,7 +104,7 @@
             if (mRemote.asBinder() != null) {
                 mRemote.asBinder().unlinkToDeath(remoteDied, 0 /* flags */);
             }
-            finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */);
+            finishCallback.onTransitionFinished(null /* wct */);
         }
         return true;
     }
@@ -122,8 +122,7 @@
                 // remote applied the transaction, but applying twice will break surfaceflinger
                 // so just assume the worst-case and clear the local transaction.
                 t.clear();
-                mMainExecutor.execute(
-                        () -> finishCallback.onTransitionFinished(wct, null /* wctCB */));
+                mMainExecutor.execute(() -> finishCallback.onTransitionFinished(wct));
             }
         };
         try {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/RemoteTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/RemoteTransitionHandler.java
index c22cc6f..bbf67a6 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/RemoteTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/RemoteTransitionHandler.java
@@ -133,7 +133,7 @@
                 }
                 mMainExecutor.execute(() -> {
                     mRequestedRemotes.remove(transition);
-                    finishCallback.onTransitionFinished(wct, null /* wctCB */);
+                    finishCallback.onTransitionFinished(wct);
                 });
             }
         };
@@ -153,8 +153,7 @@
             Log.e(Transitions.TAG, "Error running remote transition.", e);
             unhandleDeath(remote.asBinder(), finishCallback);
             mRequestedRemotes.remove(transition);
-            mMainExecutor.execute(
-                    () -> finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */));
+            mMainExecutor.execute(() -> finishCallback.onTransitionFinished(null /* wct */));
         }
         return true;
     }
@@ -210,7 +209,7 @@
                                 + "that the mergeTarget's RemoteTransition impl erroneously "
                                 + "accepted/ran the merge request after finishing the mergeTarget");
                     }
-                    finishCallback.onTransitionFinished(wct, null /* wctCB */);
+                    finishCallback.onTransitionFinished(wct);
                 });
             }
         };
@@ -316,8 +315,7 @@
                     }
                 }
                 for (int i = mPendingFinishCallbacks.size() - 1; i >= 0; --i) {
-                    mPendingFinishCallbacks.get(i).onTransitionFinished(
-                            null /* wct */, null /* wctCB */);
+                    mPendingFinishCallbacks.get(i).onTransitionFinished(null /* wct */);
                 }
                 mPendingFinishCallbacks.clear();
             });
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/SleepHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/SleepHandler.java
index d279595..87c438a 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/SleepHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/SleepHandler.java
@@ -43,7 +43,7 @@
             @NonNull Transitions.TransitionFinishCallback finishCallback) {
         mSleepTransitions.remove(transition);
         startTransaction.apply();
-        finishCallback.onTransitionFinished(null, null);
+        finishCallback.onTransitionFinished(null);
         return true;
     }
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java
index e2dce88..b4d0a31 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java
@@ -62,7 +62,6 @@
 import android.window.TransitionMetrics;
 import android.window.TransitionRequestInfo;
 import android.window.WindowContainerTransaction;
-import android.window.WindowContainerTransactionCallback;
 import android.window.WindowOrganizer;
 
 import androidx.annotation.BinderThread;
@@ -829,7 +828,7 @@
                     ready.mStartT.apply();
                 }
                 // finish now since there's nothing to animate. Calls back into processReadyQueue
-                onFinish(ready, null, null);
+                onFinish(ready, null);
                 return;
             }
             playTransition(ready);
@@ -849,7 +848,7 @@
                 + " in case they can be merged", ready, playing);
         mTracer.logMergeRequested(ready.mInfo.getDebugId(), playing.mInfo.getDebugId());
         playing.mHandler.mergeAnimation(ready.mToken, ready.mInfo, ready.mStartT,
-                playing.mToken, (wct, cb) -> onMerged(playing, ready));
+                playing.mToken, (wct) -> onMerged(playing, ready));
     }
 
     private void onMerged(@NonNull ActiveTransition playing, @NonNull ActiveTransition merged) {
@@ -899,7 +898,7 @@
             ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, " try firstHandler %s",
                     active.mHandler);
             boolean consumed = active.mHandler.startAnimation(active.mToken, active.mInfo,
-                    active.mStartT, active.mFinishT, (wct, cb) -> onFinish(active, wct, cb));
+                    active.mStartT, active.mFinishT, (wct) -> onFinish(active, wct));
             if (consumed) {
                 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, " animated by firstHandler");
                 mTracer.logDispatched(active.mInfo.getDebugId(), active.mHandler);
@@ -908,7 +907,7 @@
         }
         // Otherwise give every other handler a chance
         active.mHandler = dispatchTransition(active.mToken, active.mInfo, active.mStartT,
-                active.mFinishT, (wct, cb) -> onFinish(active, wct, cb), active.mHandler);
+                active.mFinishT, (wct) -> onFinish(active, wct), active.mHandler);
     }
 
     /**
@@ -985,8 +984,7 @@
     }
 
     private void onFinish(ActiveTransition active,
-            @Nullable WindowContainerTransaction wct,
-            @Nullable WindowContainerTransactionCallback wctCB) {
+            @Nullable WindowContainerTransaction wct) {
         final Track track = mTracks.get(active.getTrack());
         if (track.mActiveTransition != active) {
             Log.e(TAG, "Trying to finish a non-running transition. Either remote crashed or "
@@ -1035,11 +1033,11 @@
         // Now perform all the finish callbacks (starting with the playing one and then all the
         // transitions merged into it).
         releaseSurfaces(active.mInfo);
-        mOrganizer.finishTransition(active.mToken, wct, wctCB);
+        mOrganizer.finishTransition(active.mToken, wct);
         if (active.mMerged != null) {
             for (int iM = 0; iM < active.mMerged.size(); ++iM) {
                 ActiveTransition merged = active.mMerged.get(iM);
-                mOrganizer.finishTransition(merged.mToken, null /* wct */, null /* wctCB */);
+                mOrganizer.finishTransition(merged.mToken, null /* wct */);
                 releaseSurfaces(merged.mInfo);
             }
             active.mMerged.clear();
@@ -1178,7 +1176,7 @@
                     forceFinish.mHandler.onTransitionConsumed(
                             forceFinish.mToken, true /* aborted */, null /* finishTransaction */);
                 }
-                onFinish(forceFinish, null, null);
+                onFinish(forceFinish, null);
             }
         }
         if (track.isIdle() || mReadyDuringSync.isEmpty()) {
@@ -1198,7 +1196,7 @@
             ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, " Attempt to merge sync %s"
                     + " into %s via a SLEEP proxy", nextSync, playing);
             playing.mHandler.mergeAnimation(nextSync.mToken, dummyInfo, dummyT,
-                    playing.mToken, (wct, cb) -> {});
+                    playing.mToken, (wct) -> {});
             // it's possible to complete immediately. If that happens, just repeat the signal
             // loop until we either finish everything or start playing an animation that isn't
             // finishing immediately.
@@ -1226,11 +1224,8 @@
          * The transition must not touch the surfaces after this has been called.
          *
          * @param wct A WindowContainerTransaction to run along with the transition clean-up.
-         * @param wctCB A sync callback that will be run when the transition clean-up is done and
-         *              wct has been applied.
          */
-        void onTransitionFinished(@Nullable WindowContainerTransaction wct,
-                @Nullable WindowContainerTransactionCallback wctCB);
+        void onTransitionFinished(@Nullable WindowContainerTransaction wct);
     }
 
     /**
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/unfold/UnfoldTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/unfold/UnfoldTransitionHandler.java
index f148412..2eb6e71 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/unfold/UnfoldTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/unfold/UnfoldTransitionHandler.java
@@ -169,7 +169,7 @@
             animator.stop();
         }
 
-        mFinishCallback.onTransitionFinished(null, null);
+        mFinishCallback.onTransitionFinished(null);
         mFinishCallback = null;
         mTransition = null;
     }
@@ -193,7 +193,7 @@
             }
             // Apply changes happening during the unfold animation immediately
             t.apply();
-            finishCallback.onTransitionFinished(null, null);
+            finishCallback.onTransitionFinished(null);
         }
     }
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
index 2b19da2..29fff03 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
@@ -71,6 +71,7 @@
 import com.android.wm.shell.desktopmode.DesktopModeStatus;
 import com.android.wm.shell.desktopmode.DesktopTasksController;
 import com.android.wm.shell.freeform.FreeformTaskTransitionStarter;
+import com.android.wm.shell.splitscreen.SplitScreen;
 import com.android.wm.shell.splitscreen.SplitScreenController;
 import com.android.wm.shell.sysui.KeyguardChangeListener;
 import com.android.wm.shell.sysui.ShellController;
@@ -200,6 +201,19 @@
     @Override
     public void setSplitScreenController(SplitScreenController splitScreenController) {
         mSplitScreenController = splitScreenController;
+        mSplitScreenController.registerSplitScreenListener(new SplitScreen.SplitScreenListener() {
+            @Override
+            public void onTaskStageChanged(int taskId, int stage, boolean visible) {
+                if (visible) {
+                    DesktopModeWindowDecoration decor = mWindowDecorByTaskId.get(taskId);
+                    if (decor != null && DesktopModeStatus.isActive(mContext)
+                            && decor.mTaskInfo.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
+                        mDesktopModeController.ifPresent(c -> c.setDesktopModeActive(false));
+                        mDesktopTasksController.ifPresent(c -> c.moveToSplit(decor.mTaskInfo));
+                    }
+                }
+            }
+        });
     }
 
     @Override
@@ -365,6 +379,11 @@
                 mDesktopModeController.ifPresent(c -> c.setDesktopModeActive(false));
                 mDesktopTasksController.ifPresent(c -> c.moveToFullscreen(mTaskId));
                 decoration.closeHandleMenu();
+            } else if (id == R.id.split_screen_button) {
+                decoration.closeHandleMenu();
+                mDesktopTasksController.ifPresent(c -> {
+                    c.requestSplit(decoration.mTaskInfo);
+                });
             } else if (id == R.id.collapse_menu_button) {
                 decoration.closeHandleMenu();
             } else if (id == R.id.select_button) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/VeiledResizeTaskPositioner.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/VeiledResizeTaskPositioner.java
index fb05c69..c9c58de 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/VeiledResizeTaskPositioner.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/VeiledResizeTaskPositioner.java
@@ -168,7 +168,7 @@
         startTransaction.apply();
         mDesktopWindowDecoration.hideResizeVeil();
         mCtrlType = CTRL_TYPE_UNDEFINED;
-        finishCallback.onTransitionFinished(null, null);
+        finishCallback.onTransitionFinished(null);
         return true;
     }
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeAppControlsWindowDecorationViewHolder.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeAppControlsWindowDecorationViewHolder.kt
index 672e57a..a9eb882 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeAppControlsWindowDecorationViewHolder.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeAppControlsWindowDecorationViewHolder.kt
@@ -23,14 +23,14 @@
         appIcon: Drawable
 ) : DesktopModeWindowDecorationViewHolder(rootView) {
 
-    private val captionView: View = rootView.findViewById(R.id.desktop_mode_caption)
-    private val captionHandle: View = rootView.findViewById(R.id.caption_handle)
-    private val openMenuButton: View = rootView.findViewById(R.id.open_menu_button)
-    private val closeWindowButton: ImageButton = rootView.findViewById(R.id.close_window)
-    private val expandMenuButton: ImageButton = rootView.findViewById(R.id.expand_menu_button)
-    private val maximizeWindowButton: ImageButton = rootView.findViewById(R.id.maximize_window)
-    private val appNameTextView: TextView = rootView.findViewById(R.id.application_name)
-    private val appIconImageView: ImageView = rootView.findViewById(R.id.application_icon)
+    private val captionView: View = rootView.requireViewById(R.id.desktop_mode_caption)
+    private val captionHandle: View = rootView.requireViewById(R.id.caption_handle)
+    private val openMenuButton: View = rootView.requireViewById(R.id.open_menu_button)
+    private val closeWindowButton: ImageButton = rootView.requireViewById(R.id.close_window)
+    private val expandMenuButton: ImageButton = rootView.requireViewById(R.id.expand_menu_button)
+    private val maximizeWindowButton: ImageButton = rootView.requireViewById(R.id.maximize_window)
+    private val appNameTextView: TextView = rootView.requireViewById(R.id.application_name)
+    private val appIconImageView: ImageView = rootView.requireViewById(R.id.application_icon)
 
     init {
         captionView.setOnTouchListener(onCaptionTouchListener)
@@ -47,7 +47,9 @@
     override fun bindData(taskInfo: RunningTaskInfo) {
 
         val captionDrawable = captionView.background as GradientDrawable
-        captionDrawable.setColor(taskInfo.taskDescription.statusBarColor)
+        taskInfo.taskDescription?.statusBarColor?.let {
+            captionDrawable.setColor(it)
+        }
 
         closeWindowButton.imageTintList = ColorStateList.valueOf(
                 getCaptionCloseButtonColor(taskInfo))
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeFocusedWindowDecorationViewHolder.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeFocusedWindowDecorationViewHolder.kt
index 47a12a0..9374ac9 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeFocusedWindowDecorationViewHolder.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeFocusedWindowDecorationViewHolder.kt
@@ -17,8 +17,8 @@
         onCaptionButtonClickListener: View.OnClickListener
 ) : DesktopModeWindowDecorationViewHolder(rootView) {
 
-    private val captionView: View = rootView.findViewById(R.id.desktop_mode_caption)
-    private val captionHandle: ImageButton = rootView.findViewById(R.id.caption_handle)
+    private val captionView: View = rootView.requireViewById(R.id.desktop_mode_caption)
+    private val captionHandle: ImageButton = rootView.requireViewById(R.id.caption_handle)
 
     init {
         captionView.setOnTouchListener(onCaptionTouchListener)
@@ -27,9 +27,10 @@
     }
 
     override fun bindData(taskInfo: RunningTaskInfo) {
-        val captionColor = taskInfo.taskDescription.statusBarColor
-        val captionDrawable = captionView.background as GradientDrawable
-        captionDrawable.setColor(captionColor)
+        taskInfo.taskDescription?.statusBarColor?.let { captionColor ->
+            val captionDrawable = captionView.background as GradientDrawable
+            captionDrawable.setColor(captionColor)
+        }
 
         captionHandle.imageTintList = ColorStateList.valueOf(getCaptionHandleBarColor(taskInfo))
     }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeWindowDecorationViewHolder.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeWindowDecorationViewHolder.kt
index d293cf7..49e8d15 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeWindowDecorationViewHolder.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/DesktopModeWindowDecorationViewHolder.kt
@@ -25,11 +25,14 @@
    * with the caption background color.
    */
   protected fun shouldUseLightCaptionColors(taskInfo: RunningTaskInfo): Boolean {
-    return if (Color.alpha(taskInfo.taskDescription.statusBarColor) != 0 &&
-        taskInfo.windowingMode == WINDOWING_MODE_FREEFORM) {
-      Color.valueOf(taskInfo.taskDescription.statusBarColor).luminance() < 0.5
-    } else {
-      taskInfo.taskDescription.statusBarAppearance and APPEARANCE_LIGHT_STATUS_BARS == 0
-    }
+    return taskInfo.taskDescription
+        ?.let { taskDescription ->
+          if (Color.alpha(taskDescription.statusBarColor) != 0 &&
+              taskInfo.windowingMode == WINDOWING_MODE_FREEFORM) {
+            Color.valueOf(taskDescription.statusBarColor).luminance() < 0.5
+          } else {
+            taskDescription.statusBarAppearance and APPEARANCE_LIGHT_STATUS_BARS == 0
+          }
+        } ?: false
   }
 }
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/ChangeActiveActivityFromBubbleTest.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/ChangeActiveActivityFromBubbleTest.kt
index 9cc9fb9..55039f5 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/ChangeActiveActivityFromBubbleTest.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/ChangeActiveActivityFromBubbleTest.kt
@@ -17,11 +17,11 @@
 package com.android.wm.shell.flicker.bubble
 
 import android.os.SystemClock
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
+import androidx.test.filters.FlakyTest
 import androidx.test.uiautomator.By
 import androidx.test.uiautomator.UiObject2
 import androidx.test.uiautomator.Until
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/OpenActivityFromBubbleOnLocksreenTest.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/OpenActivityFromBubbleOnLocksreenTest.kt
index 26aca18..b007e6b 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/OpenActivityFromBubbleOnLocksreenTest.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/OpenActivityFromBubbleOnLocksreenTest.kt
@@ -16,7 +16,6 @@
 
 package com.android.wm.shell.flicker.bubble
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Postsubmit
 import android.tools.common.traces.component.ComponentNameMatcher
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
@@ -24,6 +23,7 @@
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.view.WindowInsets
 import android.view.WindowManager
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import androidx.test.uiautomator.By
 import androidx.test.uiautomator.Until
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/AutoEnterPipOnGoToHomeTest.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/AutoEnterPipOnGoToHomeTest.kt
index bf686d6..e38c4c3 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/AutoEnterPipOnGoToHomeTest.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/AutoEnterPipOnGoToHomeTest.kt
@@ -16,11 +16,11 @@
 
 package com.android.wm.shell.flicker.pip
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import org.junit.Assume
 import org.junit.FixMethodOrder
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/EnterPipToOtherOrientation.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/EnterPipToOtherOrientation.kt
index c003da6..b4cedd9 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/EnterPipToOtherOrientation.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/EnterPipToOtherOrientation.kt
@@ -17,7 +17,6 @@
 package com.android.wm.shell.flicker.pip
 
 import android.app.Activity
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Postsubmit
 import android.platform.test.annotations.Presubmit
 import android.tools.common.Rotation
@@ -28,6 +27,7 @@
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
 import android.tools.device.helpers.WindowUtils
+import androidx.test.filters.FlakyTest
 import com.android.server.wm.flicker.entireScreenCovered
 import com.android.server.wm.flicker.helpers.FixedOrientationAppHelper
 import com.android.server.wm.flicker.testapp.ActivityOptions.Pip.ACTION_ENTER_PIP
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/PipDragThenSnapTest.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/PipDragThenSnapTest.kt
index de64f78..42be818 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/PipDragThenSnapTest.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/PipDragThenSnapTest.kt
@@ -24,6 +24,7 @@
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
 import android.tools.device.flicker.rules.RemoveAllTasksButHomeRule
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.server.wm.flicker.helpers.setRotation
 import com.android.server.wm.flicker.testapp.ActivityOptions
@@ -34,6 +35,7 @@
 import org.junit.runners.Parameterized
 
 /** Test the snapping of a PIP window via dragging, releasing, and checking its final location. */
+@FlakyTest(bugId = 294993100)
 @RequiresDevice
 @RunWith(Parameterized::class)
 @Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class)
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/SetRequestedOrientationWhilePinned.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/SetRequestedOrientationWhilePinned.kt
index c315e74..a236126 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/SetRequestedOrientationWhilePinned.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/pip/SetRequestedOrientationWhilePinned.kt
@@ -17,7 +17,6 @@
 package com.android.wm.shell.flicker.pip
 
 import android.app.Activity
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Postsubmit
 import android.platform.test.annotations.Presubmit
 import android.tools.common.Rotation
@@ -27,6 +26,7 @@
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
 import android.tools.device.helpers.WindowUtils
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.server.wm.flicker.testapp.ActivityOptions
 import com.android.server.wm.flicker.testapp.ActivityOptions.PortraitOnlyActivity.EXTRA_FIXED_ORIENTATION
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt
index 3702be9..6b97169 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt
@@ -16,7 +16,6 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.traces.component.ComponentNameMatcher
 import android.tools.common.traces.component.EdgeExtensionComponentMatcher
@@ -24,6 +23,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.CopyContentInSplitBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt
index 8b90630..51588569 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt
@@ -16,13 +16,13 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Postsubmit
 import android.platform.test.annotations.Presubmit
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.helpers.WindowUtils
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.DismissSplitScreenByDividerBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt
index 50f6a38..fc6c2b3 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt
@@ -16,12 +16,12 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.DismissSplitScreenByGoHomeBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt
index cc3b783..8b1689a 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt
@@ -16,12 +16,12 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.DragDividerToResizeBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt
index f8d1e1f..99613f3 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt
@@ -16,7 +16,6 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Postsubmit
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
@@ -24,6 +23,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.EnterSplitScreenByDragFromAllAppsBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt
index ff5d935..756a7fa 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt
@@ -16,7 +16,6 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Postsubmit
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
@@ -24,6 +23,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.EnterSplitScreenByDragFromNotificationBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromShortcut.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromShortcut.kt
index 7c71077..121b46a 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromShortcut.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromShortcut.kt
@@ -16,13 +16,13 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.EnterSplitScreenByDragFromShortcutBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt
index 8371706..99deb92 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt
@@ -16,7 +16,6 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Postsubmit
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
@@ -24,6 +23,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.EnterSplitScreenByDragFromTaskbarBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenFromOverview.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenFromOverview.kt
index 0bfdbb4..212a4e3 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenFromOverview.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenFromOverview.kt
@@ -16,12 +16,12 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.EnterSplitScreenFromOverviewBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt
index 88bbc0e..284c32e 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt
@@ -16,13 +16,13 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.SwitchBackToSplitFromAnotherAppBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt
index e85dc24..9e6448f 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt
@@ -16,13 +16,13 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.SwitchBackToSplitFromHomeBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt
index f7a9ed0..8e28712 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt
@@ -16,13 +16,13 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.SwitchBackToSplitFromRecentBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBetweenSplitPairs.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBetweenSplitPairs.kt
index 66f9b85..fb0193b 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBetweenSplitPairs.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBetweenSplitPairs.kt
@@ -16,12 +16,12 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.SwitchBetweenSplitPairsBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/UnlockKeyguardToSplitScreen.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/UnlockKeyguardToSplitScreen.kt
index 4c44028..f3145c9 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/UnlockKeyguardToSplitScreen.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/UnlockKeyguardToSplitScreen.kt
@@ -16,7 +16,6 @@
 
 package com.android.wm.shell.flicker.splitscreen
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Postsubmit
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
@@ -27,6 +26,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.wm.shell.flicker.splitscreen.benchmark.UnlockKeyguardToSplitScreenBenchmark
 import com.android.wm.shell.flicker.utils.ICommonAssertions
diff --git a/libs/WindowManager/Shell/tests/unittest/Android.bp b/libs/WindowManager/Shell/tests/unittest/Android.bp
index 38e9f39..54f9498 100644
--- a/libs/WindowManager/Shell/tests/unittest/Android.bp
+++ b/libs/WindowManager/Shell/tests/unittest/Android.bp
@@ -43,6 +43,7 @@
         "frameworks-base-testutils",
         "kotlinx-coroutines-android",
         "kotlinx-coroutines-core",
+        "mockito-kotlin2",
         "mockito-target-extended-minus-junit4",
         "truth-prebuilt",
         "testables",
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunnerTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunnerTests.java
index 4fca8b4..2d93047 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunnerTests.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunnerTests.java
@@ -92,7 +92,7 @@
                 .build();
         final Animator animator = mAnimRunner.createAnimator(
                 info, mStartTransaction, mFinishTransaction,
-                () -> mFinishCallback.onTransitionFinished(null /* wct */, null /* wctCB */),
+                () -> mFinishCallback.onTransitionFinished(null /* wct */),
                 new ArrayList());
 
         // The animation should be empty when it is behind starting window.
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationTestBase.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationTestBase.java
index ab1ccd4..0b2265d 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationTestBase.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationTestBase.java
@@ -75,7 +75,7 @@
         assertNotNull(mAnimRunner);
         mAnimSpec = mAnimRunner.mAnimationSpec;
         assertNotNull(mAnimSpec);
-        mFinishCallback = (wct, wctCB) -> {};
+        mFinishCallback = (wct) -> {};
         spyOn(mController);
         spyOn(mAnimRunner);
         spyOn(mAnimSpec);
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingControllerTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingControllerTests.java
index ba34f1f7..270dbc4 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingControllerTests.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingControllerTests.java
@@ -217,12 +217,10 @@
         doReturn(animator).when(mAnimRunner).createAnimator(any(), any(), any(), any(), any());
         mController.startAnimation(mTransition, info, mStartTransaction,
                 mFinishTransaction, mFinishCallback);
-        verify(mFinishCallback, never()).onTransitionFinished(any(), any());
+        verify(mFinishCallback, never()).onTransitionFinished(any());
         mController.mergeAnimation(mTransition, info, new SurfaceControl.Transaction(),
-                mTransition,
-                (wct, cb) -> {
-                });
-        verify(mFinishCallback).onTransitionFinished(any(), any());
+                mTransition, (wct) -> {});
+        verify(mFinishCallback).onTransitionFinished(any());
     }
 
     @Test
@@ -238,9 +236,9 @@
         mController.startAnimation(mTransition, info, mStartTransaction,
                 mFinishTransaction, mFinishCallback);
 
-        verify(mFinishCallback, never()).onTransitionFinished(any(), any());
+        verify(mFinishCallback, never()).onTransitionFinished(any());
         mController.onAnimationFinished(mTransition);
-        verify(mFinishCallback).onTransitionFinished(any(), any());
+        verify(mFinishCallback).onTransitionFinished(any());
 
         // Should not call finish when the finish has already been called.
         assertThrows(IllegalStateException.class,
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/back/BackAnimationControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/back/BackAnimationControllerTest.java
index 3d8bd38..e7d0f60 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/back/BackAnimationControllerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/back/BackAnimationControllerTest.java
@@ -67,6 +67,7 @@
 import com.android.wm.shell.sysui.ShellInit;
 import com.android.wm.shell.sysui.ShellSharedConstants;
 
+
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -85,12 +86,11 @@
 
     private static final String ANIMATION_ENABLED = "1";
     private final TestShellExecutor mShellExecutor = new TestShellExecutor();
-    private ShellInit mShellInit;
-
     @Rule
     public TestableContext mContext =
             new TestableContext(InstrumentationRegistry.getInstrumentation().getContext());
 
+    private ShellInit mShellInit;
     @Mock
     private IActivityTaskManager mActivityTaskManager;
 
@@ -116,6 +116,8 @@
     private TestableContentResolver mContentResolver;
     private TestableLooper mTestableLooper;
 
+    private ShellBackAnimationRegistry mShellBackAnimationRegistry;
+
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
@@ -126,11 +128,23 @@
                 ANIMATION_ENABLED);
         mTestableLooper = TestableLooper.get(this);
         mShellInit = spy(new ShellInit(mShellExecutor));
-        mController = new BackAnimationController(mShellInit, mShellController,
-                mShellExecutor, new Handler(mTestableLooper.getLooper()),
-                mActivityTaskManager, mContext,
-                mContentResolver, mAnimationBackground);
-        mController.setEnableUAnimation(true);
+        mShellBackAnimationRegistry =
+                new ShellBackAnimationRegistry(
+                        new CrossActivityAnimation(mContext, mAnimationBackground),
+                        new CrossTaskBackAnimation(mContext, mAnimationBackground),
+                        new CustomizeActivityAnimation(mContext, mAnimationBackground),
+                        null);
+        mController =
+                new BackAnimationController(
+                        mShellInit,
+                        mShellController,
+                        mShellExecutor,
+                        new Handler(mTestableLooper.getLooper()),
+                        mActivityTaskManager,
+                        mContext,
+                        mContentResolver,
+                        mAnimationBackground,
+                        mShellBackAnimationRegistry);
         mShellInit.init();
         mShellExecutor.flushAll();
     }
@@ -138,12 +152,13 @@
     private void createNavigationInfo(int backType,
             boolean enableAnimation,
             boolean isAnimationCallback) {
-        BackNavigationInfo.Builder builder = new BackNavigationInfo.Builder()
-                .setType(backType)
-                .setOnBackNavigationDone(new RemoteCallback((bundle) -> {}))
-                .setOnBackInvokedCallback(mAppCallback)
-                .setPrepareRemoteAnimation(enableAnimation)
-                .setAnimationCallback(isAnimationCallback);
+        BackNavigationInfo.Builder builder =
+                new BackNavigationInfo.Builder()
+                        .setType(backType)
+                        .setOnBackNavigationDone(new RemoteCallback((bundle) -> {}))
+                        .setOnBackInvokedCallback(mAppCallback)
+                        .setPrepareRemoteAnimation(enableAnimation)
+                        .setAnimationCallback(isAnimationCallback);
 
         createNavigationInfo(builder);
     }
@@ -188,18 +203,21 @@
 
     @Test
     public void verifyNavigationFinishes() throws RemoteException {
-        final int[] testTypes = new int[] {BackNavigationInfo.TYPE_RETURN_TO_HOME,
-                BackNavigationInfo.TYPE_CROSS_TASK,
-                BackNavigationInfo.TYPE_CROSS_ACTIVITY,
-                BackNavigationInfo.TYPE_DIALOG_CLOSE,
-                BackNavigationInfo.TYPE_CALLBACK };
+        final int[] testTypes =
+                new int[] {
+                    BackNavigationInfo.TYPE_RETURN_TO_HOME,
+                    BackNavigationInfo.TYPE_CROSS_TASK,
+                    BackNavigationInfo.TYPE_CROSS_ACTIVITY,
+                    BackNavigationInfo.TYPE_DIALOG_CLOSE,
+                    BackNavigationInfo.TYPE_CALLBACK
+                };
 
-        for (int type: testTypes) {
+        for (int type : testTypes) {
             registerAnimation(type);
         }
 
-        for (int type: testTypes) {
-            final ResultListener result  = new ResultListener();
+        for (int type : testTypes) {
+            final ResultListener result = new ResultListener();
             createNavigationInfo(new BackNavigationInfo.Builder()
                     .setType(type)
                     .setOnBackInvokedCallback(mAppCallback)
@@ -275,10 +293,17 @@
         // Toggle the setting off
         Settings.Global.putString(mContentResolver, Settings.Global.ENABLE_BACK_ANIMATION, "0");
         ShellInit shellInit = new ShellInit(mShellExecutor);
-        mController = new BackAnimationController(shellInit, mShellController,
-                mShellExecutor, new Handler(mTestableLooper.getLooper()),
-                mActivityTaskManager, mContext,
-                mContentResolver, mAnimationBackground);
+        mController =
+                new BackAnimationController(
+                        shellInit,
+                        mShellController,
+                        mShellExecutor,
+                        new Handler(mTestableLooper.getLooper()),
+                        mActivityTaskManager,
+                        mContext,
+                        mContentResolver,
+                        mAnimationBackground,
+                        mShellBackAnimationRegistry);
         shellInit.init();
         registerAnimation(BackNavigationInfo.TYPE_RETURN_TO_HOME);
 
@@ -398,17 +423,19 @@
 
     @Test
     public void animationNotDefined() throws RemoteException {
-        final int[] testTypes = new int[] {
-                BackNavigationInfo.TYPE_RETURN_TO_HOME,
-                BackNavigationInfo.TYPE_CROSS_TASK,
-                BackNavigationInfo.TYPE_CROSS_ACTIVITY,
-                BackNavigationInfo.TYPE_DIALOG_CLOSE};
+        final int[] testTypes =
+                new int[] {
+                    BackNavigationInfo.TYPE_RETURN_TO_HOME,
+                    BackNavigationInfo.TYPE_CROSS_TASK,
+                    BackNavigationInfo.TYPE_CROSS_ACTIVITY,
+                    BackNavigationInfo.TYPE_DIALOG_CLOSE
+                };
 
-        for (int type: testTypes) {
+        for (int type : testTypes) {
             unregisterAnimation(type);
         }
 
-        for (int type: testTypes) {
+        for (int type : testTypes) {
             final ResultListener result = new ResultListener();
             createNavigationInfo(new BackNavigationInfo.Builder()
                     .setType(type)
@@ -468,16 +495,14 @@
     public void testBackToActivity() throws RemoteException {
         final CrossActivityAnimation animation = new CrossActivityAnimation(mContext,
                 mAnimationBackground);
-        verifySystemBackBehavior(
-                BackNavigationInfo.TYPE_CROSS_ACTIVITY, animation.mBackAnimationRunner);
+        verifySystemBackBehavior(BackNavigationInfo.TYPE_CROSS_ACTIVITY, animation.getRunner());
     }
 
     @Test
     public void testBackToTask() throws RemoteException {
         final CrossTaskBackAnimation animation = new CrossTaskBackAnimation(mContext,
                 mAnimationBackground);
-        verifySystemBackBehavior(
-                BackNavigationInfo.TYPE_CROSS_TASK, animation.mBackAnimationRunner);
+        verifySystemBackBehavior(BackNavigationInfo.TYPE_CROSS_TASK, animation.getRunner());
     }
 
     private void verifySystemBackBehavior(int type, BackAnimationRunner animation)
@@ -554,10 +579,12 @@
     private static class ResultListener implements RemoteCallback.OnResultListener {
         boolean mBackNavigationDone = false;
         boolean mTriggerBack = false;
+
         @Override
         public void onResult(@Nullable Bundle result) {
             mBackNavigationDone = true;
             mTriggerBack = result.getBoolean(KEY_TRIGGER_BACK);
         }
-    };
+    }
+    ;
 }
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/back/CustomizeActivityAnimationTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/back/CustomizeActivityAnimationTest.java
index e7d4598..cebbbd8 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/back/CustomizeActivityAnimationTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/back/CustomizeActivityAnimationTest.java
@@ -102,15 +102,17 @@
         // start animation with remote animation targets
         final CountDownLatch finishCalled = new CountDownLatch(1);
         final Runnable finishCallback = finishCalled::countDown;
-        mCustomizeActivityAnimation.mBackAnimationRunner.startAnimation(
-                new RemoteAnimationTarget[]{close, open}, null, null, finishCallback);
+        mCustomizeActivityAnimation
+                .getRunner()
+                .startAnimation(
+                        new RemoteAnimationTarget[] {close, open}, null, null, finishCallback);
         verify(mMockCloseAnimation).initialize(eq(BOUND_SIZE), eq(BOUND_SIZE),
                 eq(BOUND_SIZE), eq(BOUND_SIZE));
         verify(mMockOpenAnimation).initialize(eq(BOUND_SIZE), eq(BOUND_SIZE),
                 eq(BOUND_SIZE), eq(BOUND_SIZE));
 
         try {
-            mCustomizeActivityAnimation.mBackAnimationRunner.getCallback().onBackInvoked();
+            mCustomizeActivityAnimation.getRunner().getCallback().onBackInvoked();
         } catch (RemoteException r) {
             fail("onBackInvoked throw remote exception");
         }
@@ -133,15 +135,17 @@
         // start animation with remote animation targets
         final CountDownLatch finishCalled = new CountDownLatch(1);
         final Runnable finishCallback = finishCalled::countDown;
-        mCustomizeActivityAnimation.mBackAnimationRunner.startAnimation(
-                new RemoteAnimationTarget[]{close, open}, null, null, finishCallback);
+        mCustomizeActivityAnimation
+                .getRunner()
+                .startAnimation(
+                        new RemoteAnimationTarget[] {close, open}, null, null, finishCallback);
         verify(mMockCloseAnimation).initialize(eq(BOUND_SIZE), eq(BOUND_SIZE),
                 eq(BOUND_SIZE), eq(BOUND_SIZE));
         verify(mMockOpenAnimation).initialize(eq(BOUND_SIZE), eq(BOUND_SIZE),
                 eq(BOUND_SIZE), eq(BOUND_SIZE));
 
         try {
-            mCustomizeActivityAnimation.mBackAnimationRunner.getCallback().onBackCancelled();
+            mCustomizeActivityAnimation.getRunner().getCallback().onBackCancelled();
         } catch (RemoteException r) {
             fail("onBackCancelled throw remote exception");
         }
@@ -155,11 +159,12 @@
         // start animation without any remote animation targets
         final CountDownLatch finishCalled = new CountDownLatch(1);
         final Runnable finishCallback = finishCalled::countDown;
-        mCustomizeActivityAnimation.mBackAnimationRunner.startAnimation(
-                new RemoteAnimationTarget[]{}, null, null, finishCallback);
+        mCustomizeActivityAnimation
+                .getRunner()
+                .startAnimation(new RemoteAnimationTarget[] {}, null, null, finishCallback);
 
         try {
-            mCustomizeActivityAnimation.mBackAnimationRunner.getCallback().onBackInvoked();
+            mCustomizeActivityAnimation.getRunner().getCallback().onBackInvoked();
         } catch (RemoteException r) {
             fail("onBackInvoked throw remote exception");
         }
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/BubbleDataRepositoryTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/BubbleDataRepositoryTest.kt
index 0e05e01..e359957 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/BubbleDataRepositoryTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/BubbleDataRepositoryTest.kt
@@ -29,11 +29,11 @@
 import org.junit.After
 import org.junit.Before
 import org.junit.Test
-import org.mockito.Mockito
-import org.mockito.Mockito.mock
-import org.mockito.Mockito.never
-import org.mockito.Mockito.spy
-import org.mockito.Mockito.verify
+import org.mockito.kotlin.any
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.never
+import org.mockito.kotlin.spy
+import org.mockito.kotlin.verify
 
 class BubbleDataRepositoryTest : ShellTestCase() {
 
@@ -124,7 +124,7 @@
 
     private val testHandler = Handler(Looper.getMainLooper())
     private val mainExecutor = HandlerExecutor(testHandler)
-    private val launcherApps = mock(LauncherApps::class.java)
+    private val launcherApps = mock<LauncherApps>()
 
     private val persistedBubbles = SparseArray<List<BubbleEntity>>()
 
@@ -158,8 +158,7 @@
         assertThat(persistedBubbles).isEqualTo(validEntitiesByUser)
 
         // No invalid users, so no persist to disk happened
-        verify(dataRepository, never()).persistToDisk(
-            any(SparseArray<List<BubbleEntity>>()::class.java))
+        verify(dataRepository, never()).persistToDisk(any())
     }
 
     @Test
@@ -199,6 +198,4 @@
         // Verify that persist to disk happened with the new valid entities list.
         verify(dataRepository).persistToDisk(validEntitiesByUser)
     }
-
-    fun <T> any(type: Class<T>): T = Mockito.any<T>(type)
 }
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/BubblePositionerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/BubblePositionerTest.java
new file mode 100644
index 0000000..139724f
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/BubblePositionerTest.java
@@ -0,0 +1,281 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.bubbles;
+
+import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
+import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
+import static android.view.View.LAYOUT_DIRECTION_LTR;
+import static android.view.View.LAYOUT_DIRECTION_RTL;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import android.content.res.Configuration;
+import android.graphics.Insets;
+import android.graphics.PointF;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+import android.testing.TestableResources;
+import android.view.WindowInsets;
+import android.view.WindowManager;
+import android.view.WindowMetrics;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.wm.shell.R;
+import com.android.wm.shell.ShellTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+/**
+ * Tests operations and the resulting state managed by {@link BubblePositioner}.
+ */
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper(setAsMainLooper = true)
+public class BubblePositionerTest extends ShellTestCase {
+
+    private static final int MIN_WIDTH_FOR_TABLET = 600;
+
+    private BubblePositioner mPositioner;
+    private Configuration mConfiguration;
+
+    @Mock
+    private WindowManager mWindowManager;
+    @Mock
+    private WindowMetrics mWindowMetrics;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+
+        mConfiguration = spy(new Configuration());
+        TestableResources testableResources = mContext.getOrCreateTestableResources();
+        testableResources.overrideConfiguration(mConfiguration);
+
+        mPositioner = new BubblePositioner(mContext, mWindowManager);
+    }
+
+    @Test
+    public void testUpdate() {
+        Insets insets = Insets.of(10, 20, 5, 15);
+        Rect screenBounds = new Rect(0, 0, 1000, 1200);
+        Rect availableRect = new Rect(screenBounds);
+        availableRect.inset(insets);
+
+        new WindowManagerConfig()
+                .setInsets(insets)
+                .setScreenBounds(screenBounds)
+                .setUpConfig();
+        mPositioner.update();
+
+        assertThat(mPositioner.getAvailableRect()).isEqualTo(availableRect);
+        assertThat(mPositioner.isLandscape()).isFalse();
+        assertThat(mPositioner.isLargeScreen()).isFalse();
+        assertThat(mPositioner.getInsets()).isEqualTo(insets);
+    }
+
+    @Test
+    public void testShowBubblesVertically_phonePortrait() {
+        new WindowManagerConfig().setOrientation(ORIENTATION_PORTRAIT).setUpConfig();
+        mPositioner.update();
+
+        assertThat(mPositioner.showBubblesVertically()).isFalse();
+    }
+
+    @Test
+    public void testShowBubblesVertically_phoneLandscape() {
+        new WindowManagerConfig().setOrientation(ORIENTATION_LANDSCAPE).setUpConfig();
+        mPositioner.update();
+
+        assertThat(mPositioner.isLandscape()).isTrue();
+        assertThat(mPositioner.showBubblesVertically()).isTrue();
+    }
+
+    @Test
+    public void testShowBubblesVertically_tablet() {
+        new WindowManagerConfig().setLargeScreen().setUpConfig();
+        mPositioner.update();
+
+        assertThat(mPositioner.showBubblesVertically()).isTrue();
+    }
+
+    /** If a resting position hasn't been set, calling it will return the default position. */
+    @Test
+    public void testGetRestingPosition_returnsDefaultPosition() {
+        new WindowManagerConfig().setUpConfig();
+        mPositioner.update();
+
+        PointF restingPosition = mPositioner.getRestingPosition();
+        PointF defaultPosition = mPositioner.getDefaultStartPosition();
+
+        assertThat(restingPosition).isEqualTo(defaultPosition);
+    }
+
+    /** If a resting position has been set, it'll return that instead of the default position. */
+    @Test
+    public void testGetRestingPosition_returnsRestingPosition() {
+        new WindowManagerConfig().setUpConfig();
+        mPositioner.update();
+
+        PointF restingPosition = new PointF(100, 100);
+        mPositioner.setRestingPosition(restingPosition);
+
+        assertThat(mPositioner.getRestingPosition()).isEqualTo(restingPosition);
+    }
+
+    /** Test that the default resting position on phone is in upper left. */
+    @Test
+    public void testGetRestingPosition_bubble_onPhone() {
+        new WindowManagerConfig().setUpConfig();
+        mPositioner.update();
+
+        RectF allowableStackRegion =
+                mPositioner.getAllowableStackPositionRegion(1 /* bubbleCount */);
+        PointF restingPosition = mPositioner.getRestingPosition();
+
+        assertThat(restingPosition.x).isEqualTo(allowableStackRegion.left);
+        assertThat(restingPosition.y).isEqualTo(getDefaultYPosition());
+    }
+
+    @Test
+    public void testGetRestingPosition_bubble_onPhone_RTL() {
+        new WindowManagerConfig().setLayoutDirection(LAYOUT_DIRECTION_RTL).setUpConfig();
+        mPositioner.update();
+
+        RectF allowableStackRegion =
+                mPositioner.getAllowableStackPositionRegion(1 /* bubbleCount */);
+        PointF restingPosition = mPositioner.getRestingPosition();
+
+        assertThat(restingPosition.x).isEqualTo(allowableStackRegion.right);
+        assertThat(restingPosition.y).isEqualTo(getDefaultYPosition());
+    }
+
+    /** Test that the default resting position on tablet is middle left. */
+    @Test
+    public void testGetRestingPosition_chatBubble_onTablet() {
+        new WindowManagerConfig().setLargeScreen().setUpConfig();
+        mPositioner.update();
+
+        RectF allowableStackRegion =
+                mPositioner.getAllowableStackPositionRegion(1 /* bubbleCount */);
+        PointF restingPosition = mPositioner.getRestingPosition();
+
+        assertThat(restingPosition.x).isEqualTo(allowableStackRegion.left);
+        assertThat(restingPosition.y).isEqualTo(getDefaultYPosition());
+    }
+
+    @Test
+    public void testGetRestingPosition_chatBubble_onTablet_RTL() {
+        new WindowManagerConfig().setLargeScreen().setLayoutDirection(
+                LAYOUT_DIRECTION_RTL).setUpConfig();
+        mPositioner.update();
+
+        RectF allowableStackRegion =
+                mPositioner.getAllowableStackPositionRegion(1 /* bubbleCount */);
+        PointF restingPosition = mPositioner.getRestingPosition();
+
+        assertThat(restingPosition.x).isEqualTo(allowableStackRegion.right);
+        assertThat(restingPosition.y).isEqualTo(getDefaultYPosition());
+    }
+
+    /**
+     * Calculates the Y position bubbles should be placed based on the config. Based on
+     * the calculations in {@link BubblePositioner#getDefaultStartPosition()} and
+     * {@link BubbleStackView.RelativeStackPosition}.
+     */
+    private float getDefaultYPosition() {
+        final boolean isTablet = mPositioner.isLargeScreen();
+
+        // On tablet the position is centered, on phone it is an offset from the top.
+        final float desiredY = isTablet
+                ? mPositioner.getScreenRect().height() / 2f - (mPositioner.getBubbleSize() / 2f)
+                : mContext.getResources().getDimensionPixelOffset(
+                        R.dimen.bubble_stack_starting_offset_y);
+        // Since we're visually centering the bubbles on tablet, use total screen height rather
+        // than the available height.
+        final float height = isTablet
+                ? mPositioner.getScreenRect().height()
+                : mPositioner.getAvailableRect().height();
+        float offsetPercent = desiredY / height;
+        offsetPercent = Math.max(0f, Math.min(1f, offsetPercent));
+        final RectF allowableStackRegion =
+                mPositioner.getAllowableStackPositionRegion(1 /* bubbleCount */);
+        return allowableStackRegion.top + allowableStackRegion.height() * offsetPercent;
+    }
+
+    /**
+     * Sets up window manager to return config values based on what you need for the test.
+     * By default it sets up a portrait phone without any insets.
+     */
+    private class WindowManagerConfig {
+        private Rect mScreenBounds = new Rect(0, 0, 1000, 2000);
+        private boolean mIsLargeScreen = false;
+        private int mOrientation = ORIENTATION_PORTRAIT;
+        private int mLayoutDirection = LAYOUT_DIRECTION_LTR;
+        private Insets mInsets = Insets.of(0, 0, 0, 0);
+
+        public WindowManagerConfig setScreenBounds(Rect screenBounds) {
+            mScreenBounds = screenBounds;
+            return this;
+        }
+
+        public WindowManagerConfig setLargeScreen() {
+            mIsLargeScreen = true;
+            return this;
+        }
+
+        public WindowManagerConfig setOrientation(int orientation) {
+            mOrientation = orientation;
+            return this;
+        }
+
+        public WindowManagerConfig setLayoutDirection(int layoutDirection) {
+            mLayoutDirection = layoutDirection;
+            return this;
+        }
+
+        public WindowManagerConfig setInsets(Insets insets) {
+            mInsets = insets;
+            return this;
+        }
+
+        public void setUpConfig() {
+            mConfiguration.smallestScreenWidthDp = mIsLargeScreen
+                    ? MIN_WIDTH_FOR_TABLET
+                    : MIN_WIDTH_FOR_TABLET - 1;
+            mConfiguration.orientation = mOrientation;
+
+            when(mConfiguration.getLayoutDirection()).thenReturn(mLayoutDirection);
+            WindowInsets windowInsets = mock(WindowInsets.class);
+            when(windowInsets.getInsetsIgnoringVisibility(anyInt())).thenReturn(mInsets);
+            when(mWindowMetrics.getWindowInsets()).thenReturn(windowInsets);
+            when(mWindowMetrics.getBounds()).thenReturn(mScreenBounds);
+            when(mWindowManager.getCurrentWindowMetrics()).thenReturn(mWindowMetrics);
+        }
+    }
+}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/common/split/SplitLayoutTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/common/split/SplitLayoutTests.java
index 443cea2..fe2da5d 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/common/split/SplitLayoutTests.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/common/split/SplitLayoutTests.java
@@ -38,7 +38,6 @@
 import androidx.test.ext.junit.runners.AndroidJUnit4;
 import androidx.test.filters.SmallTest;
 
-import com.android.internal.policy.DividerSnapAlgorithm;
 import com.android.wm.shell.ShellTaskOrganizer;
 import com.android.wm.shell.ShellTestCase;
 import com.android.wm.shell.TestRunningTaskInfoBuilder;
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUIControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUIControllerTest.java
index a6501f0..efc69ebd 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUIControllerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUIControllerTest.java
@@ -58,6 +58,8 @@
 import com.android.wm.shell.sysui.ShellInit;
 import com.android.wm.shell.transition.Transitions;
 
+import dagger.Lazy;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -66,8 +68,6 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
-import dagger.Lazy;
-
 /**
  * Tests for {@link CompatUIController}.
  *
@@ -82,21 +82,36 @@
 
     private CompatUIController mController;
     private ShellInit mShellInit;
-    private @Mock ShellController mMockShellController;
-    private @Mock DisplayController mMockDisplayController;
-    private @Mock DisplayInsetsController mMockDisplayInsetsController;
-    private @Mock DisplayLayout mMockDisplayLayout;
-    private @Mock DisplayImeController mMockImeController;
-    private @Mock ShellTaskOrganizer.TaskListener mMockTaskListener;
-    private @Mock SyncTransactionQueue mMockSyncQueue;
-    private @Mock ShellExecutor mMockExecutor;
-    private @Mock Lazy<Transitions> mMockTransitionsLazy;
-    private @Mock CompatUIWindowManager mMockCompatLayout;
-    private @Mock LetterboxEduWindowManager mMockLetterboxEduLayout;
-    private @Mock RestartDialogWindowManager mMockRestartDialogLayout;
-    private @Mock DockStateReader mDockStateReader;
-    private @Mock CompatUIConfiguration mCompatUIConfiguration;
-    private @Mock CompatUIShellCommandHandler mCompatUIShellCommandHandler;
+    @Mock
+    private ShellController mMockShellController;
+    @Mock
+    private DisplayController mMockDisplayController;
+    @Mock
+    private DisplayInsetsController mMockDisplayInsetsController;
+    @Mock
+    private DisplayLayout mMockDisplayLayout;
+    @Mock
+    private DisplayImeController mMockImeController;
+    @Mock
+    private ShellTaskOrganizer.TaskListener mMockTaskListener;
+    @Mock
+    private SyncTransactionQueue mMockSyncQueue;
+    @Mock
+    private ShellExecutor mMockExecutor;
+    @Mock
+    private Lazy<Transitions> mMockTransitionsLazy;
+    @Mock
+    private CompatUIWindowManager mMockCompatLayout;
+    @Mock
+    private LetterboxEduWindowManager mMockLetterboxEduLayout;
+    @Mock
+    private RestartDialogWindowManager mMockRestartDialogLayout;
+    @Mock
+    private DockStateReader mDockStateReader;
+    @Mock
+    private CompatUIConfiguration mCompatUIConfiguration;
+    @Mock
+    private CompatUIShellCommandHandler mCompatUIShellCommandHandler;
 
     @Captor
     ArgumentCaptor<OnInsetsChangedListener> mOnInsetsChangedListenerCaptor;
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUILayoutTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUILayoutTest.java
index 5f294d5..3bce2b8 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUILayoutTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUILayoutTest.java
@@ -44,7 +44,7 @@
 import com.android.wm.shell.ShellTestCase;
 import com.android.wm.shell.common.DisplayLayout;
 import com.android.wm.shell.common.SyncTransactionQueue;
-import com.android.wm.shell.compatui.CompatUIWindowManager.CompatUIHintsState;
+import com.android.wm.shell.compatui.CompatUIController.CompatUIHintsState;
 
 import junit.framework.Assert;
 
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUIWindowManagerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUIWindowManagerTest.java
index 78c3cbd..4c837e6 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUIWindowManagerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/CompatUIWindowManagerTest.java
@@ -53,7 +53,7 @@
 import com.android.wm.shell.ShellTestCase;
 import com.android.wm.shell.common.DisplayLayout;
 import com.android.wm.shell.common.SyncTransactionQueue;
-import com.android.wm.shell.compatui.CompatUIWindowManager.CompatUIHintsState;
+import com.android.wm.shell.compatui.CompatUIController.CompatUIHintsState;
 
 import junit.framework.Assert;
 
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/ReachabilityEduWindowManagerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/ReachabilityEduWindowManagerTest.java
index 973a99c..a802f15a 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/ReachabilityEduWindowManagerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/ReachabilityEduWindowManagerTest.java
@@ -40,6 +40,8 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
+import java.util.function.BiConsumer;
+
 /**
  * Tests for {@link ReachabilityEduWindowManager}.
  *
@@ -57,6 +59,8 @@
     private CompatUIConfiguration mCompatUIConfiguration;
     @Mock
     private DisplayLayout mDisplayLayout;
+    @Mock
+    private BiConsumer<TaskInfo, ShellTaskOrganizer.TaskListener> mOnDismissCallback;
     private TestShellExecutor mExecutor;
     private TaskInfo mTaskInfo;
     private ReachabilityEduWindowManager mWindowManager;
@@ -104,6 +108,7 @@
 
     private ReachabilityEduWindowManager createReachabilityEduWindowManager(TaskInfo taskInfo) {
         return new ReachabilityEduWindowManager(mContext, taskInfo, mSyncTransactionQueue,
-                mTaskListener, mDisplayLayout, mCompatUIConfiguration, mExecutor);
+                mTaskListener, mDisplayLayout, mCompatUIConfiguration, mExecutor,
+                mOnDismissCallback);
     }
 }
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/UserAspectRatioSettingsLayoutTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/UserAspectRatioSettingsLayoutTest.java
new file mode 100644
index 0000000..1fee153
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/UserAspectRatioSettingsLayoutTest.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.compatui;
+
+import static android.app.TaskInfo.CAMERA_COMPAT_CONTROL_HIDDEN;
+
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
+
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.verify;
+
+import android.app.ActivityManager;
+import android.app.TaskInfo;
+import android.app.TaskInfo.CameraCompatControlState;
+import android.content.ComponentName;
+import android.testing.AndroidTestingRunner;
+import android.util.Pair;
+import android.view.LayoutInflater;
+import android.view.SurfaceControlViewHost;
+import android.widget.ImageButton;
+import android.widget.LinearLayout;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.wm.shell.R;
+import com.android.wm.shell.ShellTaskOrganizer;
+import com.android.wm.shell.ShellTestCase;
+import com.android.wm.shell.TestShellExecutor;
+import com.android.wm.shell.common.DisplayLayout;
+import com.android.wm.shell.common.SyncTransactionQueue;
+
+import junit.framework.Assert;
+
+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 java.util.function.BiConsumer;
+
+/**
+ * Tests for {@link UserAspectRatioSettingsLayout}.
+ *
+ * Build/Install/Run:
+ * atest WMShellUnitTests:UserAspectRatioSettingsLayoutTest
+ */
+@RunWith(AndroidTestingRunner.class)
+@SmallTest
+public class UserAspectRatioSettingsLayoutTest extends ShellTestCase {
+
+    private static final int TASK_ID = 1;
+
+    @Mock
+    private SyncTransactionQueue mSyncTransactionQueue;
+    @Mock
+    private BiConsumer<TaskInfo, ShellTaskOrganizer.TaskListener>
+            mOnUserAspectRatioSettingsButtonClicked;
+    @Mock
+    private ShellTaskOrganizer.TaskListener mTaskListener;
+    @Mock
+    private SurfaceControlViewHost mViewHost;
+    @Captor
+    private ArgumentCaptor<ShellTaskOrganizer.TaskListener> mUserAspectRatioTaskListenerCaptor;
+    @Captor
+    private ArgumentCaptor<TaskInfo> mUserAspectRationTaskInfoCaptor;
+
+    private UserAspectRatioSettingsWindowManager mWindowManager;
+    private UserAspectRatioSettingsLayout mLayout;
+    private TaskInfo mTaskInfo;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mTaskInfo = createTaskInfo(/* hasSizeCompat= */ false, CAMERA_COMPAT_CONTROL_HIDDEN);
+        mWindowManager = new UserAspectRatioSettingsWindowManager(mContext, mTaskInfo,
+                mSyncTransactionQueue, mTaskListener, new DisplayLayout(),
+                new CompatUIController.CompatUIHintsState(),
+                mOnUserAspectRatioSettingsButtonClicked, new TestShellExecutor());
+
+        mLayout = (UserAspectRatioSettingsLayout) LayoutInflater.from(mContext).inflate(
+                R.layout.user_aspect_ratio_settings_layout, null);
+        mLayout.inject(mWindowManager);
+
+        spyOn(mWindowManager);
+        spyOn(mLayout);
+        doReturn(mViewHost).when(mWindowManager).createSurfaceViewHost();
+        doReturn(mLayout).when(mWindowManager).inflateLayout();
+    }
+
+    @Test
+    public void testOnClickForUserAspectRatioSettingsButton() {
+        final ImageButton button = mLayout.findViewById(R.id.user_aspect_ratio_settings_button);
+        button.performClick();
+
+        verify(mWindowManager).onUserAspectRatioSettingsButtonClicked();
+        verify(mOnUserAspectRatioSettingsButtonClicked).accept(
+                mUserAspectRationTaskInfoCaptor.capture(),
+                mUserAspectRatioTaskListenerCaptor.capture());
+        final Pair<TaskInfo, ShellTaskOrganizer.TaskListener> result =
+                new Pair<>(mUserAspectRationTaskInfoCaptor.getValue(),
+                        mUserAspectRatioTaskListenerCaptor.getValue());
+        Assert.assertEquals(mTaskInfo, result.first);
+        Assert.assertEquals(mTaskListener, result.second);
+    }
+
+    @Test
+    public void testOnLongClickForUserAspectRatioButton() {
+        doNothing().when(mWindowManager).onUserAspectRatioSettingsButtonLongClicked();
+
+        final ImageButton button = mLayout.findViewById(R.id.user_aspect_ratio_settings_button);
+        button.performLongClick();
+
+        verify(mWindowManager).onUserAspectRatioSettingsButtonLongClicked();
+    }
+
+    @Test
+    public void testOnClickForUserAspectRatioSettingsHint() {
+        mWindowManager.mHasUserAspectRatioSettingsButton = true;
+        mWindowManager.createLayout(/* canShow= */ true);
+        final LinearLayout sizeCompatHint = mLayout.findViewById(
+                R.id.user_aspect_ratio_settings_hint);
+        sizeCompatHint.performClick();
+
+        verify(mLayout).setUserAspectRatioSettingsHintVisibility(/* show= */ false);
+    }
+
+    private static TaskInfo createTaskInfo(boolean hasSizeCompat,
+            @CameraCompatControlState int cameraCompatControlState) {
+        ActivityManager.RunningTaskInfo taskInfo = new ActivityManager.RunningTaskInfo();
+        taskInfo.taskId = TASK_ID;
+        taskInfo.topActivityInSizeCompat = hasSizeCompat;
+        taskInfo.cameraCompatControlState = cameraCompatControlState;
+        taskInfo.realActivity = new ComponentName("com.mypackage.test", "TestActivity");
+        return taskInfo;
+    }
+}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/UserAspectRatioSettingsWindowManagerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/UserAspectRatioSettingsWindowManagerTest.java
new file mode 100644
index 0000000..b48538c
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/compatui/UserAspectRatioSettingsWindowManagerTest.java
@@ -0,0 +1,350 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.compatui;
+
+import static android.view.WindowInsets.Type.navigationBars;
+
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import android.app.ActivityManager;
+import android.app.TaskInfo;
+import android.content.ComponentName;
+import android.content.res.Configuration;
+import android.graphics.Rect;
+import android.testing.AndroidTestingRunner;
+import android.util.Pair;
+import android.view.DisplayInfo;
+import android.view.InsetsSource;
+import android.view.InsetsState;
+import android.view.SurfaceControl;
+import android.view.SurfaceControlViewHost;
+import android.view.View;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.wm.shell.ShellTaskOrganizer;
+import com.android.wm.shell.ShellTestCase;
+import com.android.wm.shell.TestShellExecutor;
+import com.android.wm.shell.common.DisplayLayout;
+import com.android.wm.shell.common.SyncTransactionQueue;
+import com.android.wm.shell.compatui.CompatUIController.CompatUIHintsState;
+
+import junit.framework.Assert;
+
+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 java.util.HashSet;
+import java.util.Set;
+import java.util.function.BiConsumer;
+
+/**
+ * Tests for {@link UserAspectRatioSettingsWindowManager}.
+ *
+ * Build/Install/Run:
+ *  atest WMShellUnitTests:UserAspectRatioSettingsWindowManagerTest
+ */
+@RunWith(AndroidTestingRunner.class)
+@SmallTest
+public class UserAspectRatioSettingsWindowManagerTest extends ShellTestCase {
+
+    private static final int TASK_ID = 1;
+
+    @Mock private SyncTransactionQueue mSyncTransactionQueue;
+    @Mock
+    private BiConsumer<TaskInfo, ShellTaskOrganizer.TaskListener>
+            mOnUserAspectRatioSettingsButtonClicked;
+    @Mock private ShellTaskOrganizer.TaskListener mTaskListener;
+    @Mock private UserAspectRatioSettingsLayout mLayout;
+    @Mock private SurfaceControlViewHost mViewHost;
+    @Captor
+    private ArgumentCaptor<ShellTaskOrganizer.TaskListener> mUserAspectRatioTaskListenerCaptor;
+    @Captor
+    private ArgumentCaptor<TaskInfo> mUserAspectRationTaskInfoCaptor;
+
+    private final Set<String> mPackageNameCache = new HashSet<>();
+
+    private UserAspectRatioSettingsWindowManager mWindowManager;
+    private TaskInfo mTaskInfo;
+
+    private TestShellExecutor mExecutor;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mExecutor = new TestShellExecutor();
+        mTaskInfo = createTaskInfo(/* eligibleForUserAspectRatioButton= */
+                false, /* topActivityBoundsLetterboxed */ true);
+        mWindowManager = new UserAspectRatioSettingsWindowManager(mContext, mTaskInfo,
+                mSyncTransactionQueue, mTaskListener, new DisplayLayout(), new CompatUIHintsState(),
+                mOnUserAspectRatioSettingsButtonClicked, mExecutor);
+        spyOn(mWindowManager);
+        doReturn(mLayout).when(mWindowManager).inflateLayout();
+        doReturn(mViewHost).when(mWindowManager).createSurfaceViewHost();
+    }
+
+    @Test
+    public void testCreateUserAspectRatioButton() {
+        // Doesn't create layout if show is false.
+        mWindowManager.mHasUserAspectRatioSettingsButton = true;
+        assertTrue(mWindowManager.createLayout(/* canShow= */ false));
+
+        verify(mWindowManager, never()).inflateLayout();
+
+        // Doesn't create hint popup.
+        mWindowManager.mCompatUIHintsState.mHasShownUserAspectRatioSettingsButtonHint = true;
+        assertTrue(mWindowManager.createLayout(/* canShow= */ true));
+
+        verify(mWindowManager).inflateLayout();
+        mExecutor.flushAll();
+        verify(mLayout).setUserAspectRatioButtonVisibility(/* show= */ true);
+        verify(mLayout, never()).setUserAspectRatioSettingsHintVisibility(/* show= */ true);
+
+        // Creates hint popup.
+        clearInvocations(mWindowManager);
+        clearInvocations(mLayout);
+        mWindowManager.release();
+        mWindowManager.mCompatUIHintsState.mHasShownUserAspectRatioSettingsButtonHint = false;
+        assertTrue(mWindowManager.createLayout(/* canShow= */ true));
+
+        verify(mWindowManager).inflateLayout();
+        assertNotNull(mLayout);
+        mExecutor.flushAll();
+        verify(mLayout).setUserAspectRatioButtonVisibility(/* show= */ true);
+        verify(mLayout).setUserAspectRatioSettingsHintVisibility(/* show= */ true);
+        assertTrue(mWindowManager.mCompatUIHintsState.mHasShownUserAspectRatioSettingsButtonHint);
+
+        // Returns false and doesn't create layout if mHasUserAspectRatioSettingsButton is false.
+        clearInvocations(mWindowManager);
+        mWindowManager.release();
+        mWindowManager.mHasUserAspectRatioSettingsButton = false;
+        assertFalse(mWindowManager.createLayout(/* canShow= */ true));
+
+        verify(mWindowManager, never()).inflateLayout();
+    }
+
+    @Test
+    public void testRelease() {
+        mWindowManager.mHasUserAspectRatioSettingsButton = true;
+        mWindowManager.createLayout(/* canShow= */ true);
+
+        verify(mWindowManager).inflateLayout();
+
+        mWindowManager.release();
+
+        verify(mViewHost).release();
+    }
+
+    @Test
+    public void testUpdateCompatInfo() {
+        mWindowManager.mHasUserAspectRatioSettingsButton = true;
+        mWindowManager.createLayout(/* canShow= */ true);
+
+        // No diff
+        clearInvocations(mWindowManager);
+        TaskInfo taskInfo = createTaskInfo(/* eligibleForUserAspectRatioButton= */
+                true, /* topActivityBoundsLetterboxed */ true);
+        assertTrue(mWindowManager.updateCompatInfo(taskInfo, mTaskListener, /* canShow= */ true));
+
+        verify(mWindowManager, never()).updateSurfacePosition();
+        verify(mWindowManager, never()).release();
+        verify(mWindowManager, never()).createLayout(anyBoolean());
+
+
+        // Change task listener, recreate button.
+        clearInvocations(mWindowManager);
+        final ShellTaskOrganizer.TaskListener newTaskListener = mock(
+                ShellTaskOrganizer.TaskListener.class);
+        assertTrue(mWindowManager.updateCompatInfo(taskInfo, newTaskListener, /* canShow= */ true));
+
+        verify(mWindowManager).release();
+        verify(mWindowManager).createLayout(/* canShow= */ true);
+
+        // Change has eligibleForUserAspectRatioButton to false, dispose the component
+        clearInvocations(mWindowManager);
+        clearInvocations(mLayout);
+        taskInfo = createTaskInfo(/* eligibleForUserAspectRatioButton= */
+                false, /* topActivityBoundsLetterboxed */ true);
+        assertFalse(
+                mWindowManager.updateCompatInfo(taskInfo, newTaskListener, /* canShow= */ true));
+        verify(mWindowManager).release();
+    }
+
+    @Test
+    public void testUpdateCompatInfoLayoutNotInflatedYet() {
+        mWindowManager.mHasUserAspectRatioSettingsButton = true;
+        mWindowManager.createLayout(/* canShow= */ false);
+
+        verify(mWindowManager, never()).inflateLayout();
+
+        // Change topActivityInSizeCompat to false and pass canShow true, layout shouldn't be
+        // inflated
+        clearInvocations(mWindowManager);
+        TaskInfo taskInfo = createTaskInfo(/* eligibleForUserAspectRatioButton= */
+                false, /* topActivityBoundsLetterboxed */ true);
+        mWindowManager.updateCompatInfo(taskInfo, mTaskListener, /* canShow= */ true);
+
+        verify(mWindowManager, never()).inflateLayout();
+
+        // Change topActivityInSizeCompat to true and pass canShow true, layout should be inflated.
+        clearInvocations(mWindowManager);
+        taskInfo = createTaskInfo(/* eligibleForUserAspectRatioButton= */
+                true, /* topActivityBoundsLetterboxed */ true);
+        mWindowManager.updateCompatInfo(taskInfo, mTaskListener, /* canShow= */ true);
+
+        verify(mWindowManager).inflateLayout();
+    }
+
+    @Test
+    public void testUpdateDisplayLayout() {
+        final DisplayInfo displayInfo = new DisplayInfo();
+        displayInfo.logicalWidth = 1000;
+        displayInfo.logicalHeight = 2000;
+        final DisplayLayout displayLayout1 = new DisplayLayout(displayInfo,
+                mContext.getResources(), /* hasNavigationBar= */ false, /* hasStatusBar= */ false);
+
+        mWindowManager.updateDisplayLayout(displayLayout1);
+        verify(mWindowManager).updateSurfacePosition();
+
+        // No update if the display bounds is the same.
+        clearInvocations(mWindowManager);
+        final DisplayLayout displayLayout2 = new DisplayLayout(displayInfo,
+                mContext.getResources(), /* hasNavigationBar= */ false, /* hasStatusBar= */ false);
+        mWindowManager.updateDisplayLayout(displayLayout2);
+        verify(mWindowManager, never()).updateSurfacePosition();
+    }
+
+    @Test
+    public void testUpdateDisplayLayoutInsets() {
+        final DisplayInfo displayInfo = new DisplayInfo();
+        displayInfo.logicalWidth = 1000;
+        displayInfo.logicalHeight = 2000;
+        final DisplayLayout displayLayout = new DisplayLayout(displayInfo,
+                mContext.getResources(), /* hasNavigationBar= */ true, /* hasStatusBar= */ false);
+
+        mWindowManager.updateDisplayLayout(displayLayout);
+        verify(mWindowManager).updateSurfacePosition();
+
+        // Update if the insets change on the existing display layout
+        clearInvocations(mWindowManager);
+        InsetsState insetsState = new InsetsState();
+        insetsState.setDisplayFrame(new Rect(0, 0, 1000, 2000));
+        InsetsSource insetsSource = new InsetsSource(
+                InsetsSource.createId(null, 0, navigationBars()), navigationBars());
+        insetsSource.setFrame(0, 1800, 1000, 2000);
+        insetsState.addSource(insetsSource);
+        displayLayout.setInsets(mContext.getResources(), insetsState);
+        mWindowManager.updateDisplayLayout(displayLayout);
+        verify(mWindowManager).updateSurfacePosition();
+    }
+
+    @Test
+    public void testUpdateVisibility() {
+        // Create button if it is not created.
+        mWindowManager.removeLayout();
+        mWindowManager.mHasUserAspectRatioSettingsButton = true;
+        mWindowManager.updateVisibility(/* canShow= */ true);
+
+        verify(mWindowManager).createLayout(/* canShow= */ true);
+
+        // Hide button.
+        clearInvocations(mWindowManager);
+        doReturn(View.VISIBLE).when(mLayout).getVisibility();
+        mWindowManager.updateVisibility(/* canShow= */ false);
+
+        verify(mWindowManager, never()).createLayout(anyBoolean());
+        verify(mLayout).setVisibility(View.GONE);
+
+        // Show button.
+        doReturn(View.GONE).when(mLayout).getVisibility();
+        mWindowManager.updateVisibility(/* canShow= */ true);
+
+        verify(mWindowManager, never()).createLayout(anyBoolean());
+        verify(mLayout).setVisibility(View.VISIBLE);
+    }
+
+    @Test
+    public void testAttachToParentSurface() {
+        final SurfaceControl.Builder b = new SurfaceControl.Builder();
+        mWindowManager.attachToParentSurface(b);
+
+        verify(mTaskListener).attachChildSurfaceToTask(TASK_ID, b);
+    }
+
+    @Test
+    public void testOnUserAspectRatioButtonClicked() {
+        mWindowManager.onUserAspectRatioSettingsButtonClicked();
+
+        verify(mOnUserAspectRatioSettingsButtonClicked).accept(
+                mUserAspectRationTaskInfoCaptor.capture(),
+                mUserAspectRatioTaskListenerCaptor.capture());
+        final Pair<TaskInfo, ShellTaskOrganizer.TaskListener> result =
+                new Pair<>(mUserAspectRationTaskInfoCaptor.getValue(),
+                        mUserAspectRatioTaskListenerCaptor.getValue());
+        Assert.assertEquals(mTaskInfo, result.first);
+        Assert.assertEquals(mTaskListener, result.second);
+    }
+
+    @Test
+    public void testOnUserAspectRatioButtonLongClicked_showHint() {
+       // Not create hint popup.
+        mWindowManager.mHasUserAspectRatioSettingsButton = true;
+        mWindowManager.mCompatUIHintsState.mHasShownUserAspectRatioSettingsButtonHint = true;
+        mWindowManager.createLayout(/* canShow= */ true);
+
+        verify(mWindowManager).inflateLayout();
+        verify(mLayout, never()).setUserAspectRatioSettingsHintVisibility(/* show= */ true);
+
+        mWindowManager.onUserAspectRatioSettingsButtonLongClicked();
+
+        verify(mLayout).setUserAspectRatioSettingsHintVisibility(/* show= */ true);
+    }
+
+    @Test
+    public void testWhenDockedStateHasChanged_needsToBeRecreated() {
+        ActivityManager.RunningTaskInfo newTaskInfo = new ActivityManager.RunningTaskInfo();
+        newTaskInfo.configuration.uiMode |= Configuration.UI_MODE_TYPE_DESK;
+
+        Assert.assertTrue(mWindowManager.needsToBeRecreated(newTaskInfo, mTaskListener));
+    }
+
+    private static TaskInfo createTaskInfo(boolean eligibleForUserAspectRatioButton,
+            boolean topActivityBoundsLetterboxed) {
+        ActivityManager.RunningTaskInfo taskInfo = new ActivityManager.RunningTaskInfo();
+        taskInfo.taskId = TASK_ID;
+        taskInfo.topActivityEligibleForUserAspectRatioButton = eligibleForUserAspectRatioButton;
+        taskInfo.topActivityBoundsLetterboxed = topActivityBoundsLetterboxed;
+        taskInfo.configuration.uiMode &= ~Configuration.UI_MODE_TYPE_DESK;
+        taskInfo.realActivity = new ComponentName("com.mypackage.test", "TestActivity");
+        return taskInfo;
+    }
+}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipBoundsAlgorithmTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipBoundsAlgorithmTest.java
index addc233..bf1b7f9 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipBoundsAlgorithmTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipBoundsAlgorithmTest.java
@@ -32,7 +32,8 @@
 import com.android.wm.shell.R;
 import com.android.wm.shell.ShellTestCase;
 import com.android.wm.shell.common.DisplayLayout;
-import com.android.wm.shell.pip.phone.PipSizeSpecHandler;
+import com.android.wm.shell.common.pip.PhoneSizeSpecSource;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -60,7 +61,8 @@
 
     private PipBoundsAlgorithm mPipBoundsAlgorithm;
     private DisplayInfo mDefaultDisplayInfo;
-    private PipBoundsState mPipBoundsState; private PipSizeSpecHandler mPipSizeSpecHandler;
+    private PipBoundsState mPipBoundsState;
+    private SizeSpecSource mSizeSpecSource;
     private PipDisplayLayoutState mPipDisplayLayoutState;
 
 
@@ -68,11 +70,12 @@
     public void setUp() throws Exception {
         initializeMockResources();
         mPipDisplayLayoutState = new PipDisplayLayoutState(mContext);
-        mPipSizeSpecHandler = new PipSizeSpecHandler(mContext, mPipDisplayLayoutState);
-        mPipBoundsState = new PipBoundsState(mContext, mPipSizeSpecHandler, mPipDisplayLayoutState);
+
+        mSizeSpecSource = new PhoneSizeSpecSource(mContext, mPipDisplayLayoutState);
+        mPipBoundsState = new PipBoundsState(mContext, mSizeSpecSource, mPipDisplayLayoutState);
         mPipBoundsAlgorithm = new PipBoundsAlgorithm(mContext, mPipBoundsState,
                 new PipSnapAlgorithm(), new PipKeepClearAlgorithmInterface() {},
-                mPipSizeSpecHandler);
+                mPipDisplayLayoutState, mSizeSpecSource);
 
         DisplayLayout layout =
                 new DisplayLayout(mDefaultDisplayInfo, mContext.getResources(), true, true);
@@ -132,7 +135,7 @@
 
     @Test
     public void getDefaultBounds_noOverrideMinSize_matchesDefaultSizeAndAspectRatio() {
-        final Size defaultSize = mPipSizeSpecHandler.getDefaultSize(DEFAULT_ASPECT_RATIO);
+        final Size defaultSize = mSizeSpecSource.getDefaultSize(DEFAULT_ASPECT_RATIO);
 
         mPipBoundsState.setOverrideMinSize(null);
         final Rect defaultBounds = mPipBoundsAlgorithm.getDefaultBounds();
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipBoundsStateTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipBoundsStateTest.java
index f320004..4341c4c 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipBoundsStateTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipBoundsStateTest.java
@@ -35,7 +35,8 @@
 import com.android.internal.util.function.TriConsumer;
 import com.android.wm.shell.R;
 import com.android.wm.shell.ShellTestCase;
-import com.android.wm.shell.pip.phone.PipSizeSpecHandler;
+import com.android.wm.shell.common.pip.PhoneSizeSpecSource;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -58,6 +59,7 @@
     private static final int OVERRIDABLE_MIN_SIZE = 40;
 
     private PipBoundsState mPipBoundsState;
+    private SizeSpecSource mSizeSpecSource;
     private ComponentName mTestComponentName1;
     private ComponentName mTestComponentName2;
 
@@ -69,8 +71,8 @@
                 OVERRIDABLE_MIN_SIZE);
 
         PipDisplayLayoutState pipDisplayLayoutState = new PipDisplayLayoutState(mContext);
-        mPipBoundsState = new PipBoundsState(mContext,
-                new PipSizeSpecHandler(mContext, pipDisplayLayoutState), pipDisplayLayoutState);
+        mSizeSpecSource = new PhoneSizeSpecSource(mContext, pipDisplayLayoutState);
+        mPipBoundsState = new PipBoundsState(mContext, mSizeSpecSource, pipDisplayLayoutState);
         mTestComponentName1 = new ComponentName(mContext, "component1");
         mTestComponentName2 = new ComponentName(mContext, "component2");
     }
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
index 842c699..1e3fe42 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
@@ -52,8 +52,9 @@
 import com.android.wm.shell.common.DisplayController;
 import com.android.wm.shell.common.DisplayLayout;
 import com.android.wm.shell.common.SyncTransactionQueue;
+import com.android.wm.shell.common.pip.PhoneSizeSpecSource;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.phone.PhonePipMenuController;
-import com.android.wm.shell.pip.phone.PipSizeSpecHandler;
 import com.android.wm.shell.splitscreen.SplitScreenController;
 
 import org.junit.Before;
@@ -87,7 +88,7 @@
     private PipBoundsState mPipBoundsState;
     private PipTransitionState mPipTransitionState;
     private PipBoundsAlgorithm mPipBoundsAlgorithm;
-    private PipSizeSpecHandler mPipSizeSpecHandler;
+    private SizeSpecSource mSizeSpecSource;
     private PipDisplayLayoutState mPipDisplayLayoutState;
 
     private ComponentName mComponent1;
@@ -99,12 +100,12 @@
         mComponent1 = new ComponentName(mContext, "component1");
         mComponent2 = new ComponentName(mContext, "component2");
         mPipDisplayLayoutState = new PipDisplayLayoutState(mContext);
-        mPipSizeSpecHandler = new PipSizeSpecHandler(mContext, mPipDisplayLayoutState);
-        mPipBoundsState = new PipBoundsState(mContext, mPipSizeSpecHandler, mPipDisplayLayoutState);
+        mSizeSpecSource = new PhoneSizeSpecSource(mContext, mPipDisplayLayoutState);
+        mPipBoundsState = new PipBoundsState(mContext, mSizeSpecSource, mPipDisplayLayoutState);
         mPipTransitionState = new PipTransitionState();
         mPipBoundsAlgorithm = new PipBoundsAlgorithm(mContext, mPipBoundsState,
                 new PipSnapAlgorithm(), new PipKeepClearAlgorithmInterface() {},
-                mPipSizeSpecHandler);
+                mPipDisplayLayoutState, mSizeSpecSource);
         mMainExecutor = new TestShellExecutor();
         mPipTaskOrganizer = new PipTaskOrganizer(mContext, mMockSyncTransactionQueue,
                 mPipTransitionState, mPipBoundsState, mPipDisplayLayoutState,
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipSizeSpecHandlerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PhoneSizeSpecSourceTest.java
similarity index 84%
rename from libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipSizeSpecHandlerTest.java
rename to libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PhoneSizeSpecSourceTest.java
index 528c23c..024cba3 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipSizeSpecHandlerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PhoneSizeSpecSourceTest.java
@@ -32,6 +32,8 @@
 import com.android.dx.mockito.inline.extended.StaticMockitoSession;
 import com.android.wm.shell.ShellTestCase;
 import com.android.wm.shell.common.DisplayLayout;
+import com.android.wm.shell.common.pip.PhoneSizeSpecSource;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.PipDisplayLayoutState;
 
 import org.junit.After;
@@ -47,10 +49,10 @@
 import java.util.function.Function;
 
 /**
- * Unit test against {@link PipSizeSpecHandler} with feature flag on.
+ * Unit test against {@link PhoneSizeSpecSource}
  */
 @RunWith(AndroidTestingRunner.class)
-public class PipSizeSpecHandlerTest extends ShellTestCase {
+public class PhoneSizeSpecSourceTest extends ShellTestCase {
     /** A sample overridden min edge size. */
     private static final int OVERRIDE_MIN_EDGE_SIZE = 40;
     /** A sample default min edge size */
@@ -75,7 +77,7 @@
     @Mock private Resources mResources;
 
     private PipDisplayLayoutState mPipDisplayLayoutState;
-    private TestPipSizeSpecHandler mPipSizeSpecHandler;
+    private SizeSpecSource mSizeSpecSource;
 
     /**
      * Sets up static Mockito session for SystemProperties and mocks necessary static methods.
@@ -158,10 +160,10 @@
         mPipDisplayLayoutState.setDisplayLayout(displayLayout);
 
         setUpStaticSystemPropertiesSession();
-        mPipSizeSpecHandler = new TestPipSizeSpecHandler(mContext, mPipDisplayLayoutState);
+        mSizeSpecSource = new PhoneSizeSpecSource(mContext, mPipDisplayLayoutState);
 
         // no overridden min edge size by default
-        mPipSizeSpecHandler.setOverrideMinSize(null);
+        mSizeSpecSource.setOverrideMinSize(null);
     }
 
     @After
@@ -172,19 +174,19 @@
     @Test
     public void testGetMaxSize() {
         forEveryTestCaseCheck(sExpectedMaxSizes,
-                (aspectRatio) -> mPipSizeSpecHandler.getMaxSize(aspectRatio));
+                (aspectRatio) -> mSizeSpecSource.getMaxSize(aspectRatio));
     }
 
     @Test
     public void testGetDefaultSize() {
         forEveryTestCaseCheck(sExpectedDefaultSizes,
-                (aspectRatio) -> mPipSizeSpecHandler.getDefaultSize(aspectRatio));
+                (aspectRatio) -> mSizeSpecSource.getDefaultSize(aspectRatio));
     }
 
     @Test
     public void testGetMinSize() {
         forEveryTestCaseCheck(sExpectedMinSizes,
-                (aspectRatio) -> mPipSizeSpecHandler.getMinSize(aspectRatio));
+                (aspectRatio) -> mSizeSpecSource.getMinSize(aspectRatio));
     }
 
     @Test
@@ -193,7 +195,7 @@
         Size initSize = new Size(600, 337);
 
         Size expectedSize = new Size(338, 601);
-        Size actualSize = mPipSizeSpecHandler.getSizeForAspectRatio(initSize, 9f / 16);
+        Size actualSize = mSizeSpecSource.getSizeForAspectRatio(initSize, 9f / 16);
 
         Assert.assertEquals(expectedSize, actualSize);
     }
@@ -201,26 +203,12 @@
     @Test
     public void testGetSizeForAspectRatio_withOverrideMinSize() {
         // an initial size with a 1:1 aspect ratio
-        mPipSizeSpecHandler.setOverrideMinSize(new Size(OVERRIDE_MIN_EDGE_SIZE,
-                OVERRIDE_MIN_EDGE_SIZE));
-        // make sure initial size is same as override min size
-        Size initSize = mPipSizeSpecHandler.getOverrideMinSize();
+        Size initSize = new Size(OVERRIDE_MIN_EDGE_SIZE, OVERRIDE_MIN_EDGE_SIZE);
+        mSizeSpecSource.setOverrideMinSize(initSize);
 
         Size expectedSize = new Size(40, 71);
-        Size actualSize = mPipSizeSpecHandler.getSizeForAspectRatio(initSize, 9f / 16);
+        Size actualSize = mSizeSpecSource.getSizeForAspectRatio(initSize, 9f / 16);
 
         Assert.assertEquals(expectedSize, actualSize);
     }
-
-    static class TestPipSizeSpecHandler extends PipSizeSpecHandler {
-
-        TestPipSizeSpecHandler(Context context, PipDisplayLayoutState displayLayoutState) {
-            super(context, displayLayoutState);
-        }
-
-        @Override
-        boolean supportsPipSizeLargeScreen() {
-            return true;
-        }
-    }
 }
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipControllerTest.java
index 85167cb..05c6ba9 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipControllerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipControllerTest.java
@@ -55,9 +55,9 @@
 import com.android.wm.shell.common.ShellExecutor;
 import com.android.wm.shell.common.TabletopModeController;
 import com.android.wm.shell.common.TaskStackListenerImpl;
+import com.android.wm.shell.common.pip.PipAppOpsListener;
 import com.android.wm.shell.onehanded.OneHandedController;
 import com.android.wm.shell.pip.PipAnimationController;
-import com.android.wm.shell.pip.PipAppOpsListener;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
 import com.android.wm.shell.pip.PipDisplayLayoutState;
@@ -76,7 +76,6 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
-import org.mockito.Mockito;
 import org.mockito.MockitoAnnotations;
 
 import java.util.Optional;
@@ -109,7 +108,6 @@
     @Mock private PipMotionHelper mMockPipMotionHelper;
     @Mock private WindowManagerShellWrapper mMockWindowManagerShellWrapper;
     @Mock private PipBoundsState mMockPipBoundsState;
-    @Mock private PipSizeSpecHandler mMockPipSizeSpecHandler;
     @Mock private PipDisplayLayoutState mMockPipDisplayLayoutState;
     @Mock private TaskStackListenerImpl mMockTaskStackListener;
     @Mock private ShellExecutor mMockExecutor;
@@ -134,7 +132,7 @@
         mPipController = new PipController(mContext, mShellInit, mMockShellCommandHandler,
                 mShellController, mMockDisplayController, mMockPipAnimationController,
                 mMockPipAppOpsListener, mMockPipBoundsAlgorithm, mMockPipKeepClearAlgorithm,
-                mMockPipBoundsState, mMockPipSizeSpecHandler, mMockPipDisplayLayoutState,
+                mMockPipBoundsState, mMockPipDisplayLayoutState,
                 mMockPipMotionHelper, mMockPipMediaController, mMockPhonePipMenuController,
                 mMockPipTaskOrganizer, mMockPipTransitionState, mMockPipTouchHandler,
                 mMockPipTransitionController, mMockWindowManagerShellWrapper,
@@ -226,7 +224,7 @@
         assertNull(PipController.create(spyContext, shellInit, mMockShellCommandHandler,
                 mShellController, mMockDisplayController, mMockPipAnimationController,
                 mMockPipAppOpsListener, mMockPipBoundsAlgorithm, mMockPipKeepClearAlgorithm,
-                mMockPipBoundsState, mMockPipSizeSpecHandler, mMockPipDisplayLayoutState,
+                mMockPipBoundsState, mMockPipDisplayLayoutState,
                 mMockPipMotionHelper, mMockPipMediaController, mMockPhonePipMenuController,
                 mMockPipTaskOrganizer, mMockPipTransitionState, mMockPipTouchHandler,
                 mMockPipTransitionController, mMockWindowManagerShellWrapper,
@@ -330,21 +328,7 @@
     }
 
     @Test
-    public void onKeepClearAreasChanged_featureDisabled_pipBoundsStateDoesntChange() {
-        mPipController.setEnablePipKeepClearAlgorithm(false);
-        final int displayId = 1;
-        final Rect keepClearArea = new Rect(0, 0, 10, 10);
-        when(mMockPipDisplayLayoutState.getDisplayId()).thenReturn(displayId);
-
-        mPipController.mDisplaysChangedListener.onKeepClearAreasChanged(
-                displayId, Set.of(keepClearArea), Set.of());
-
-        verify(mMockPipBoundsState, never()).setKeepClearAreas(Mockito.anySet(), Mockito.anySet());
-    }
-
-    @Test
-    public void onKeepClearAreasChanged_featureEnabled_updatesPipBoundsState() {
-        mPipController.setEnablePipKeepClearAlgorithm(true);
+    public void onKeepClearAreasChanged_updatesPipBoundsState() {
         final int displayId = 1;
         final Rect keepClearArea = new Rect(0, 0, 10, 10);
         when(mMockPipDisplayLayoutState.getDisplayId()).thenReturn(displayId);
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java
index 1dfdbf6..689b5c5 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java
@@ -36,6 +36,8 @@
 import com.android.wm.shell.ShellTestCase;
 import com.android.wm.shell.common.FloatingContentCoordinator;
 import com.android.wm.shell.common.ShellExecutor;
+import com.android.wm.shell.common.pip.PhoneSizeSpecSource;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
 import com.android.wm.shell.pip.PipDisplayLayoutState;
@@ -87,7 +89,7 @@
 
     private PipBoundsState mPipBoundsState;
 
-    private PipSizeSpecHandler mPipSizeSpecHandler;
+    private SizeSpecSource mSizeSpecSource;
 
     private PipDisplayLayoutState mPipDisplayLayoutState;
 
@@ -97,13 +99,14 @@
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
         mPipDisplayLayoutState = new PipDisplayLayoutState(mContext);
-        mPipSizeSpecHandler = new PipSizeSpecHandler(mContext, mPipDisplayLayoutState);
-        mPipBoundsState = new PipBoundsState(mContext, mPipSizeSpecHandler, mPipDisplayLayoutState);
+        mSizeSpecSource = new PhoneSizeSpecSource(mContext, mPipDisplayLayoutState);
+        mPipBoundsState = new PipBoundsState(mContext, mSizeSpecSource, mPipDisplayLayoutState);
         final PipSnapAlgorithm pipSnapAlgorithm = new PipSnapAlgorithm();
         final PipKeepClearAlgorithmInterface pipKeepClearAlgorithm =
                 new PipKeepClearAlgorithmInterface() {};
         final PipBoundsAlgorithm pipBoundsAlgorithm = new PipBoundsAlgorithm(mContext,
-                mPipBoundsState, pipSnapAlgorithm, pipKeepClearAlgorithm, mPipSizeSpecHandler);
+                mPipBoundsState, pipSnapAlgorithm, pipKeepClearAlgorithm, mPipDisplayLayoutState,
+                mSizeSpecSource);
         final PipMotionHelper motionHelper = new PipMotionHelper(mContext, mPipBoundsState,
                 mPipTaskOrganizer, mPhonePipMenuController, pipSnapAlgorithm,
                 mMockPipTransitionController, mFloatingContentCoordinator);
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipTouchHandlerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipTouchHandlerTest.java
index 10b1ddf..f65d7af 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipTouchHandlerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipTouchHandlerTest.java
@@ -18,7 +18,6 @@
 
 import static org.junit.Assert.assertEquals;
 import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
@@ -33,6 +32,8 @@
 import com.android.wm.shell.common.DisplayLayout;
 import com.android.wm.shell.common.FloatingContentCoordinator;
 import com.android.wm.shell.common.ShellExecutor;
+import com.android.wm.shell.common.pip.PhoneSizeSpecSource;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
 import com.android.wm.shell.pip.PipDisplayLayoutState;
@@ -92,7 +93,7 @@
     private PipSnapAlgorithm mPipSnapAlgorithm;
     private PipMotionHelper mMotionHelper;
     private PipResizeGestureHandler mPipResizeGestureHandler;
-    private PipSizeSpecHandler mPipSizeSpecHandler;
+    private SizeSpecSource mSizeSpecSource;
     private PipDisplayLayoutState mPipDisplayLayoutState;
 
     private DisplayLayout mDisplayLayout;
@@ -108,16 +109,16 @@
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
         mPipDisplayLayoutState = new PipDisplayLayoutState(mContext);
-        mPipSizeSpecHandler = new PipSizeSpecHandler(mContext, mPipDisplayLayoutState);
-        mPipBoundsState = new PipBoundsState(mContext, mPipSizeSpecHandler, mPipDisplayLayoutState);
+        mSizeSpecSource = new PhoneSizeSpecSource(mContext, mPipDisplayLayoutState);
+        mPipBoundsState = new PipBoundsState(mContext, mSizeSpecSource, mPipDisplayLayoutState);
         mPipSnapAlgorithm = new PipSnapAlgorithm();
         mPipBoundsAlgorithm = new PipBoundsAlgorithm(mContext, mPipBoundsState, mPipSnapAlgorithm,
-                new PipKeepClearAlgorithmInterface() {}, mPipSizeSpecHandler);
+                new PipKeepClearAlgorithmInterface() {}, mPipDisplayLayoutState, mSizeSpecSource);
         PipMotionHelper pipMotionHelper = new PipMotionHelper(mContext, mPipBoundsState,
                 mPipTaskOrganizer, mPhonePipMenuController, mPipSnapAlgorithm,
                 mMockPipTransitionController, mFloatingContentCoordinator);
         mPipTouchHandler = new PipTouchHandler(mContext, mShellInit, mPhonePipMenuController,
-                mPipBoundsAlgorithm, mPipBoundsState, mPipSizeSpecHandler, mPipTaskOrganizer,
+                mPipBoundsAlgorithm, mPipBoundsState, mSizeSpecSource, mPipTaskOrganizer,
                 pipMotionHelper, mFloatingContentCoordinator, mPipUiEventLogger, mMainExecutor);
         // We aren't actually using ShellInit, so just call init directly
         mPipTouchHandler.onInit();
@@ -162,8 +163,8 @@
 
         // getting the expected min and max size
         float aspectRatio = (float) mPipBounds.width() / mPipBounds.height();
-        Size expectedMinSize = mPipSizeSpecHandler.getMinSize(aspectRatio);
-        Size expectedMaxSize = mPipSizeSpecHandler.getMaxSize(aspectRatio);
+        Size expectedMinSize = mSizeSpecSource.getMinSize(aspectRatio);
+        Size expectedMaxSize = mSizeSpecSource.getMaxSize(aspectRatio);
 
         assertEquals(expectedMovementBounds, mPipBoundsState.getNormalMovementBounds());
         verify(mPipResizeGestureHandler, times(1))
@@ -172,16 +173,4 @@
         verify(mPipResizeGestureHandler, times(1))
                 .updateMaxSize(expectedMaxSize.getWidth(), expectedMaxSize.getHeight());
     }
-
-    @Test
-    public void updateMovementBounds_withImeAdjustment_movesPip() {
-        mPipTouchHandler.setEnablePipKeepClearAlgorithm(false);
-        mFromImeAdjustment = true;
-        mPipTouchHandler.onImeVisibilityChanged(true /* imeVisible */, mImeHeight);
-
-        mPipTouchHandler.onMovementBoundsChanged(mInsetBounds, mPipBounds, mCurBounds,
-                mFromImeAdjustment, mFromShelfAdjustment, mDisplayRotation);
-
-        verify(mMotionHelper, times(1)).animateToOffset(any(), anyInt());
-    }
 }
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipGravityTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipGravityTest.java
index 91ff3cb..256610b 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipGravityTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipGravityTest.java
@@ -26,9 +26,10 @@
 import android.view.Gravity;
 
 import com.android.wm.shell.ShellTestCase;
+import com.android.wm.shell.common.pip.LegacySizeSpecSource;
+import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.PipDisplayLayoutState;
 import com.android.wm.shell.pip.PipSnapAlgorithm;
-import com.android.wm.shell.pip.phone.PipSizeSpecHandler;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -47,7 +48,7 @@
 
     private TvPipBoundsState mTvPipBoundsState;
     private TvPipBoundsAlgorithm mTvPipBoundsAlgorithm;
-    private PipSizeSpecHandler mPipSizeSpecHandler;
+    private SizeSpecSource mSizeSpecSource;
     private PipDisplayLayoutState mPipDisplayLayoutState;
 
     @Before
@@ -56,11 +57,11 @@
 
         MockitoAnnotations.initMocks(this);
         mPipDisplayLayoutState = new PipDisplayLayoutState(mContext);
-        mPipSizeSpecHandler = new PipSizeSpecHandler(mContext, mPipDisplayLayoutState);
-        mTvPipBoundsState = new TvPipBoundsState(mContext, mPipSizeSpecHandler,
+        mSizeSpecSource = new LegacySizeSpecSource(mContext, mPipDisplayLayoutState);
+        mTvPipBoundsState = new TvPipBoundsState(mContext, mSizeSpecSource,
                 mPipDisplayLayoutState);
         mTvPipBoundsAlgorithm = new TvPipBoundsAlgorithm(mContext, mTvPipBoundsState,
-                mMockPipSnapAlgorithm, mPipSizeSpecHandler);
+                mMockPipSnapAlgorithm, mPipDisplayLayoutState, mSizeSpecSource);
 
         setRTL(false);
     }
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipMenuControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipMenuControllerTest.java
index 3a08d32..e26dc7c 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipMenuControllerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipMenuControllerTest.java
@@ -25,18 +25,24 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assume.assumeTrue;
 import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
+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 android.os.Handler;
+import android.os.Looper;
 import android.view.SurfaceControl;
+import android.view.ViewTreeObserver;
+import android.view.ViewTreeObserver.OnWindowFocusChangeListener;
 
 import com.android.wm.shell.ShellTestCase;
 import com.android.wm.shell.common.SystemWindows;
 
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
@@ -50,28 +56,38 @@
     @Mock
     private SystemWindows mMockSystemWindows;
     @Mock
-    private SurfaceControl mMockPipLeash;
-    @Mock
-    private Handler mMockHandler;
-    @Mock
-    private TvPipActionsProvider mMockActionsProvider;
-    @Mock
     private TvPipMenuView mMockTvPipMenuView;
     @Mock
     private TvPipBackgroundView mMockTvPipBackgroundView;
 
+    private Handler mMainHandler;
     private TvPipMenuController mTvPipMenuController;
+    private OnWindowFocusChangeListener mFocusChangeListener;
 
     @Before
     public void setUp() {
         assumeTrue(isTelevision());
 
         MockitoAnnotations.initMocks(this);
+        mMainHandler = new Handler(Looper.getMainLooper());
+
+        final ViewTreeObserver mockMenuTreeObserver = mock(ViewTreeObserver.class);
+        doReturn(mockMenuTreeObserver).when(mMockTvPipMenuView).getViewTreeObserver();
 
         mTvPipMenuController = new TestTvPipMenuController();
         mTvPipMenuController.setDelegate(mMockDelegate);
-        mTvPipMenuController.setTvPipActionsProvider(mMockActionsProvider);
-        mTvPipMenuController.attach(mMockPipLeash);
+        mTvPipMenuController.setTvPipActionsProvider(mock(TvPipActionsProvider.class));
+        mTvPipMenuController.attach(mock(SurfaceControl.class));
+        mFocusChangeListener = captureFocusChangeListener(mockMenuTreeObserver);
+    }
+
+    private OnWindowFocusChangeListener captureFocusChangeListener(
+            ViewTreeObserver mockTreeObserver) {
+        final ArgumentCaptor<OnWindowFocusChangeListener> focusChangeListenerCaptor =
+                ArgumentCaptor.forClass(OnWindowFocusChangeListener.class);
+        verify(mockTreeObserver).addOnWindowFocusChangeListener(
+                focusChangeListenerCaptor.capture());
+        return focusChangeListenerCaptor.getValue();
     }
 
     @Test
@@ -81,24 +97,25 @@
 
     @Test
     public void testSwitch_FromNoMenuMode_ToMoveMode() {
-        showAndAssertMoveMenu();
+        showAndAssertMoveMenu(true);
     }
 
     @Test
     public void testSwitch_FromNoMenuMode_ToAllActionsMode() {
-        showAndAssertAllActionsMenu();
+        showAndAssertAllActionsMenu(true);
     }
 
     @Test
     public void testSwitch_FromMoveMode_ToAllActionsMode() {
-        showAndAssertMoveMenu();
-        showAndAssertAllActionsMenu();
+        showAndAssertMoveMenu(true);
+        showAndAssertAllActionsMenu(false);
+        verify(mMockDelegate, times(2)).onInMoveModeChanged();
     }
 
     @Test
     public void testSwitch_FromAllActionsMode_ToMoveMode() {
-        showAndAssertAllActionsMenu();
-        showAndAssertMoveMenu();
+        showAndAssertAllActionsMenu(true);
+        showAndAssertMoveMenu(false);
     }
 
     @Test
@@ -110,187 +127,282 @@
 
     @Test
     public void testCloseMenu_MoveMode() {
-        showAndAssertMoveMenu();
+        showAndAssertMoveMenu(true);
 
-        closeMenuAndAssertMenuClosed();
+        closeMenuAndAssertMenuClosed(true);
         verify(mMockDelegate, times(2)).onInMoveModeChanged();
     }
 
     @Test
     public void testCloseMenu_AllActionsMode() {
-        showAndAssertAllActionsMenu();
+        showAndAssertAllActionsMenu(true);
 
-        closeMenuAndAssertMenuClosed();
+        closeMenuAndAssertMenuClosed(true);
+    }
+
+    @Test
+    public void testCloseMenu_MoveModeFollowedByMoveMode() {
+        showAndAssertMoveMenu(true);
+        showAndAssertMoveMenu(false);
+
+        closeMenuAndAssertMenuClosed(true);
+        verify(mMockDelegate, times(2)).onInMoveModeChanged();
     }
 
     @Test
     public void testCloseMenu_MoveModeFollowedByAllActionsMode() {
-        showAndAssertMoveMenu();
-        showAndAssertAllActionsMenu();
+        showAndAssertMoveMenu(true);
+        showAndAssertAllActionsMenu(false);
         verify(mMockDelegate, times(2)).onInMoveModeChanged();
 
-        closeMenuAndAssertMenuClosed();
+        closeMenuAndAssertMenuClosed(true);
     }
 
     @Test
     public void testCloseMenu_AllActionsModeFollowedByMoveMode() {
-        showAndAssertAllActionsMenu();
-        showAndAssertMoveMenu();
+        showAndAssertAllActionsMenu(true);
+        showAndAssertMoveMenu(false);
 
-        closeMenuAndAssertMenuClosed();
+        closeMenuAndAssertMenuClosed(true);
         verify(mMockDelegate, times(2)).onInMoveModeChanged();
     }
 
     @Test
-    public void testExitMoveMode_NoMenuMode() {
-        mTvPipMenuController.onExitMoveMode();
-        assertMenuIsOpen(false);
-        verify(mMockDelegate, never()).onMenuClosed();
+    public void testCloseMenu_AllActionsModeFollowedByAllActionsMode() {
+        showAndAssertAllActionsMenu(true);
+        showAndAssertAllActionsMenu(false);
+
+        closeMenuAndAssertMenuClosed(true);
+        verify(mMockDelegate, never()).onInMoveModeChanged();
     }
 
     @Test
-    public void testExitMoveMode_MoveMode() {
-        showAndAssertMoveMenu();
+    public void testExitMenuMode_NoMenuMode() {
+        mTvPipMenuController.onExitCurrentMenuMode();
+        assertMenuIsOpen(false);
+        verify(mMockDelegate, never()).onMenuClosed();
+        verify(mMockDelegate, never()).onInMoveModeChanged();
+    }
 
-        mTvPipMenuController.onExitMoveMode();
+    @Test
+    public void testExitMenuMode_MoveMode() {
+        showAndAssertMoveMenu(true);
+
+        mTvPipMenuController.onExitCurrentMenuMode();
+        mFocusChangeListener.onWindowFocusChanged(false);
         assertMenuClosed();
         verify(mMockDelegate, times(2)).onInMoveModeChanged();
     }
 
     @Test
-    public void testExitMoveMode_AllActionsMode() {
-        showAndAssertAllActionsMenu();
+    public void testExitMenuMode_AllActionsMode() {
+        showAndAssertAllActionsMenu(true);
 
-        mTvPipMenuController.onExitMoveMode();
-        assertMenuIsInAllActionsMode();
-
+        mTvPipMenuController.onExitCurrentMenuMode();
+        mFocusChangeListener.onWindowFocusChanged(false);
+        assertMenuClosed();
     }
 
     @Test
-    public void testExitMoveMode_AllActionsModeFollowedByMoveMode() {
-        showAndAssertAllActionsMenu();
-        showAndAssertMoveMenu();
+    public void testExitMenuMode_AllActionsModeFollowedByMoveMode() {
+        showAndAssertAllActionsMenu(true);
+        showAndAssertMoveMenu(false);
 
-        mTvPipMenuController.onExitMoveMode();
-        assertMenuIsInAllActionsMode();
-        verify(mMockDelegate, times(2)).onInMoveModeChanged();
-        verify(mMockTvPipMenuView).transitionToMenuMode(eq(MODE_ALL_ACTIONS_MENU), eq(false));
-        verify(mMockTvPipBackgroundView, times(2)).transitionToMenuMode(eq(MODE_ALL_ACTIONS_MENU));
-    }
-
-    @Test
-    public void testOnBackPress_NoMenuMode() {
-        mTvPipMenuController.onBackPress();
-        assertMenuIsOpen(false);
-        verify(mMockDelegate, never()).onMenuClosed();
-    }
-
-    @Test
-    public void testOnBackPress_MoveMode() {
-        showAndAssertMoveMenu();
-
-        pressBackAndAssertMenuClosed();
-        verify(mMockDelegate, times(2)).onInMoveModeChanged();
-    }
-
-    @Test
-    public void testOnBackPress_AllActionsMode() {
-        showAndAssertAllActionsMenu();
-
-        pressBackAndAssertMenuClosed();
-    }
-
-    @Test
-    public void testOnBackPress_MoveModeFollowedByAllActionsMode() {
-        showAndAssertMoveMenu();
-        showAndAssertAllActionsMenu();
+        mTvPipMenuController.onExitCurrentMenuMode();
+        assertSwitchedToAllActionsMode(2);
         verify(mMockDelegate, times(2)).onInMoveModeChanged();
 
-        pressBackAndAssertMenuClosed();
+        mTvPipMenuController.onExitCurrentMenuMode();
+        mFocusChangeListener.onWindowFocusChanged(false);
+        assertMenuClosed();
     }
 
     @Test
-    public void testOnBackPress_AllActionsModeFollowedByMoveMode() {
-        showAndAssertAllActionsMenu();
-        showAndAssertMoveMenu();
+    public void testExitMenuMode_AllActionsModeFollowedByAllActionsMode() {
+        showAndAssertAllActionsMenu(true);
+        showAndAssertAllActionsMenu(false);
 
-        mTvPipMenuController.onBackPress();
-        assertMenuIsInAllActionsMode();
+        mTvPipMenuController.onExitCurrentMenuMode();
+        mFocusChangeListener.onWindowFocusChanged(false);
+        assertMenuClosed();
+        verify(mMockDelegate, never()).onInMoveModeChanged();
+    }
+
+    @Test
+    public void testExitMenuMode_MoveModeFollowedByAllActionsMode() {
+        showAndAssertMoveMenu(true);
+
+        showAndAssertAllActionsMenu(false);
         verify(mMockDelegate, times(2)).onInMoveModeChanged();
-        verify(mMockTvPipMenuView).transitionToMenuMode(eq(MODE_ALL_ACTIONS_MENU), eq(false));
-        verify(mMockTvPipBackgroundView, times(2)).transitionToMenuMode(eq(MODE_ALL_ACTIONS_MENU));
 
-        pressBackAndAssertMenuClosed();
+        mTvPipMenuController.onExitCurrentMenuMode();
+        mFocusChangeListener.onWindowFocusChanged(false);
+        assertMenuClosed();
+    }
+
+    @Test
+    public void testExitMenuMode_MoveModeFollowedByMoveMode() {
+        showAndAssertMoveMenu(true);
+        showAndAssertMoveMenu(false);
+
+        mTvPipMenuController.onExitCurrentMenuMode();
+        mFocusChangeListener.onWindowFocusChanged(false);
+        assertMenuClosed();
+        verify(mMockDelegate, times(2)).onInMoveModeChanged();
     }
 
     @Test
     public void testOnPipMovement_NoMenuMode() {
-        assertPipMoveSuccessful(false, mTvPipMenuController.onPipMovement(TEST_MOVE_KEYCODE));
+        moveAndAssertMoveSuccessful(false);
     }
 
     @Test
     public void testOnPipMovement_MoveMode() {
-        showAndAssertMoveMenu();
-        assertPipMoveSuccessful(true, mTvPipMenuController.onPipMovement(TEST_MOVE_KEYCODE));
-        verify(mMockDelegate).movePip(eq(TEST_MOVE_KEYCODE));
+        showAndAssertMoveMenu(true);
+        moveAndAssertMoveSuccessful(true);
     }
 
     @Test
     public void testOnPipMovement_AllActionsMode() {
-        showAndAssertAllActionsMenu();
-        assertPipMoveSuccessful(false, mTvPipMenuController.onPipMovement(TEST_MOVE_KEYCODE));
+        showAndAssertAllActionsMenu(true);
+        moveAndAssertMoveSuccessful(false);
     }
 
     @Test
-    public void testOnPipWindowFocusChanged_NoMenuMode() {
-        mTvPipMenuController.onPipWindowFocusChanged(false);
-        assertMenuIsOpen(false);
-    }
+    public void testUnexpectedFocusChanges() {
+        mFocusChangeListener.onWindowFocusChanged(true);
+        assertSwitchedToAllActionsMode(1);
 
-    @Test
-    public void testOnPipWindowFocusChanged_MoveMode() {
-        showAndAssertMoveMenu();
-        mTvPipMenuController.onPipWindowFocusChanged(false);
+        mFocusChangeListener.onWindowFocusChanged(false);
         assertMenuClosed();
+
+        showAndAssertMoveMenu(true);
+        mFocusChangeListener.onWindowFocusChanged(false);
+        assertMenuClosed(2);
+        verify(mMockDelegate, times(2)).onInMoveModeChanged();
     }
 
     @Test
-    public void testOnPipWindowFocusChanged_AllActionsMode() {
-        showAndAssertAllActionsMenu();
-        mTvPipMenuController.onPipWindowFocusChanged(false);
-        assertMenuClosed();
-    }
-
-    private void showAndAssertMoveMenu() {
-        mTvPipMenuController.showMovementMenu();
-        assertMenuIsInMoveMode();
-        verify(mMockDelegate).onInMoveModeChanged();
-        verify(mMockTvPipMenuView).transitionToMenuMode(eq(MODE_MOVE_MENU), eq(false));
-        verify(mMockTvPipBackgroundView).transitionToMenuMode(eq(MODE_MOVE_MENU));
-    }
-
-    private void showAndAssertAllActionsMenu() {
+    public void testAsyncScenario_AllActionsModeRequestFollowedByAsyncMoveModeRequest() {
         mTvPipMenuController.showMenu();
-        assertMenuIsInAllActionsMode();
-        verify(mMockTvPipMenuView).transitionToMenuMode(eq(MODE_ALL_ACTIONS_MENU), eq(true));
-        verify(mMockTvPipBackgroundView).transitionToMenuMode(eq(MODE_ALL_ACTIONS_MENU));
+        // Artificially delaying the focus change update and adding a move request to simulate an
+        // async problematic situation.
+        mTvPipMenuController.showMovementMenu();
+        // The first focus change update arrives
+        mFocusChangeListener.onWindowFocusChanged(true);
+
+        // We expect that the TvPipMenuController will directly switch to the "pending" menu mode
+        // - MODE_MOVE_MENU, because no change of focus is needed.
+        assertSwitchedToMoveMode();
     }
 
-    private void closeMenuAndAssertMenuClosed() {
+    @Test
+    public void testAsyncScenario_MoveModeRequestFollowedByAsyncAllActionsModeRequest() {
+        mTvPipMenuController.showMovementMenu();
+        mTvPipMenuController.showMenu();
+
+        mFocusChangeListener.onWindowFocusChanged(true);
+        assertSwitchedToAllActionsMode(1);
+        verify(mMockDelegate, never()).onInMoveModeChanged();
+    }
+
+    @Test
+    public void testAsyncScenario_DropObsoleteIntermediateModeSwitchRequests() {
+        mTvPipMenuController.showMovementMenu();
         mTvPipMenuController.closeMenu();
+
+        // Focus change from showMovementMenu() call.
+        mFocusChangeListener.onWindowFocusChanged(true);
+        assertSwitchedToMoveMode();
+        verify(mMockDelegate).onInMoveModeChanged();
+
+        // Focus change from closeMenu() call.
+        mFocusChangeListener.onWindowFocusChanged(false);
+        assertMenuClosed();
+        verify(mMockDelegate, times(2)).onInMoveModeChanged();
+
+        // Unexpected focus gain should open MODE_ALL_ACTIONS_MENU.
+        mFocusChangeListener.onWindowFocusChanged(true);
+        assertSwitchedToAllActionsMode(1);
+
+        mTvPipMenuController.closeMenu();
+        mTvPipMenuController.showMovementMenu();
+
+        assertSwitchedToMoveMode(2);
+
+        mFocusChangeListener.onWindowFocusChanged(false);
+        assertMenuClosed(2);
+
+        // Closing the menu resets the default menu mode, so the next focus gain opens the menu in
+        // the default mode - MODE_ALL_ACTIONS_MENU.
+        mFocusChangeListener.onWindowFocusChanged(true);
+        assertSwitchedToAllActionsMode(2);
+        verify(mMockDelegate, times(4)).onInMoveModeChanged();
+
+    }
+
+    private void showAndAssertMoveMenu(boolean focusChange) {
+        mTvPipMenuController.showMovementMenu();
+        if (focusChange) {
+            mFocusChangeListener.onWindowFocusChanged(true);
+        }
+        assertSwitchedToMoveMode();
+    }
+
+    private void assertSwitchedToMoveMode() {
+        assertSwitchedToMoveMode(1);
+    }
+
+    private void assertSwitchedToMoveMode(int times) {
+        assertMenuIsInMoveMode();
+        verify(mMockDelegate, times(2 * times - 1)).onInMoveModeChanged();
+        verify(mMockTvPipMenuView, times(times)).transitionToMenuMode(eq(MODE_MOVE_MENU));
+        verify(mMockTvPipBackgroundView, times(times)).transitionToMenuMode(eq(MODE_MOVE_MENU));
+    }
+
+    private void showAndAssertAllActionsMenu(boolean focusChange) {
+        showAndAssertAllActionsMenu(focusChange, 1);
+    }
+
+    private void showAndAssertAllActionsMenu(boolean focusChange, int times) {
+        mTvPipMenuController.showMenu();
+        if (focusChange) {
+            mFocusChangeListener.onWindowFocusChanged(true);
+        }
+
+        assertSwitchedToAllActionsMode(times);
+    }
+
+    private void assertSwitchedToAllActionsMode(int times) {
+        assertMenuIsInAllActionsMode();
+        verify(mMockTvPipMenuView, times(times))
+                .transitionToMenuMode(eq(MODE_ALL_ACTIONS_MENU));
+        verify(mMockTvPipBackgroundView, times(times))
+                .transitionToMenuMode(eq(MODE_ALL_ACTIONS_MENU));
+    }
+
+    private void closeMenuAndAssertMenuClosed(boolean focusChange) {
+        mTvPipMenuController.closeMenu();
+        if (focusChange) {
+            mFocusChangeListener.onWindowFocusChanged(false);
+        }
         assertMenuClosed();
     }
 
-    private void pressBackAndAssertMenuClosed() {
-        mTvPipMenuController.onBackPress();
-        assertMenuClosed();
+    private void moveAndAssertMoveSuccessful(boolean expectedSuccess) {
+        mTvPipMenuController.onPipMovement(TEST_MOVE_KEYCODE);
+        verify(mMockDelegate, times(expectedSuccess ? 1 : 0)).movePip(eq(TEST_MOVE_KEYCODE));
     }
 
     private void assertMenuClosed() {
+        assertMenuClosed(1);
+    }
+
+    private void assertMenuClosed(int times) {
         assertMenuIsOpen(false);
-        verify(mMockDelegate).onMenuClosed();
-        verify(mMockTvPipMenuView).transitionToMenuMode(eq(MODE_NO_MENU), eq(false));
-        verify(mMockTvPipBackgroundView).transitionToMenuMode(eq(MODE_NO_MENU));
+        verify(mMockDelegate, times(times)).onMenuClosed();
+        verify(mMockTvPipMenuView, times(times)).transitionToMenuMode(eq(MODE_NO_MENU));
+        verify(mMockTvPipBackgroundView, times(times)).transitionToMenuMode(eq(MODE_NO_MENU));
     }
 
     private void assertMenuIsOpen(boolean open) {
@@ -312,15 +424,10 @@
         assertMenuIsOpen(true);
     }
 
-    private void assertPipMoveSuccessful(boolean expected, boolean actual) {
-        assertTrue("Should " + (expected ? "" : "not ") + "move PiP when the menu is in mode "
-                + mTvPipMenuController.getMenuModeString(), expected == actual);
-    }
-
     private class TestTvPipMenuController extends TvPipMenuController {
 
         TestTvPipMenuController() {
-            super(mContext, mMockTvPipBoundsState, mMockSystemWindows, mMockHandler);
+            super(mContext, mMockTvPipBoundsState, mMockSystemWindows, mMainHandler);
         }
 
         @Override
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/splitscreen/SplitScreenControllerTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/splitscreen/SplitScreenControllerTests.java
index e8a1e91..568db91 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/splitscreen/SplitScreenControllerTests.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/splitscreen/SplitScreenControllerTests.java
@@ -65,6 +65,7 @@
 import com.android.wm.shell.common.ShellExecutor;
 import com.android.wm.shell.common.SyncTransactionQueue;
 import com.android.wm.shell.common.TransactionPool;
+import com.android.wm.shell.desktopmode.DesktopTasksController;
 import com.android.wm.shell.draganddrop.DragAndDropController;
 import com.android.wm.shell.recents.RecentTasksController;
 import com.android.wm.shell.sysui.ShellCommandHandler;
@@ -106,6 +107,7 @@
     @Mock RecentTasksController mRecentTasks;
     @Mock LaunchAdjacentController mLaunchAdjacentController;
     @Mock WindowDecorViewModel mWindowDecorViewModel;
+    @Mock DesktopTasksController mDesktopTasksController;
     @Captor ArgumentCaptor<Intent> mIntentCaptor;
 
     private ShellController mShellController;
@@ -122,7 +124,7 @@
                 mRootTDAOrganizer, mDisplayController, mDisplayImeController,
                 mDisplayInsetsController, mDragAndDropController, mTransitions, mTransactionPool,
                 mIconProvider, mRecentTasks, mLaunchAdjacentController, mWindowDecorViewModel,
-                mMainExecutor, mStageCoordinator));
+                mDesktopTasksController, mMainExecutor, mStageCoordinator));
     }
 
     @Test
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/ShellTransitionTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/ShellTransitionTests.java
index ff380e9..99a1ac6 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/ShellTransitionTests.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/ShellTransitionTests.java
@@ -176,7 +176,7 @@
         assertEquals(1, mDefaultHandler.activeCount());
         mDefaultHandler.finishAll();
         mMainExecutor.flushAll();
-        verify(mOrganizer, times(1)).finishTransition(eq(transitToken), any(), any());
+        verify(mOrganizer, times(1)).finishTransition(eq(transitToken), any());
     }
 
     @Test
@@ -299,7 +299,7 @@
         assertTrue(remoteCalled[0]);
         mDefaultHandler.finishAll();
         mMainExecutor.flushAll();
-        verify(mOrganizer, times(1)).finishTransition(eq(transitToken), eq(remoteFinishWCT), any());
+        verify(mOrganizer, times(1)).finishTransition(eq(transitToken), eq(remoteFinishWCT));
     }
 
     @Test
@@ -449,7 +449,7 @@
         assertTrue(remoteCalled[0]);
         mDefaultHandler.finishAll();
         mMainExecutor.flushAll();
-        verify(mOrganizer, times(1)).finishTransition(eq(transitToken), any(), any());
+        verify(mOrganizer, times(1)).finishTransition(eq(transitToken), any());
     }
 
     @Test
@@ -524,20 +524,20 @@
         // default handler doesn't merge by default, so it shouldn't increment active count.
         assertEquals(1, mDefaultHandler.activeCount());
         assertEquals(0, mDefaultHandler.mergeCount());
-        verify(mOrganizer, times(0)).finishTransition(eq(transitToken1), any(), any());
-        verify(mOrganizer, times(0)).finishTransition(eq(transitToken2), any(), any());
+        verify(mOrganizer, times(0)).finishTransition(eq(transitToken1), any());
+        verify(mOrganizer, times(0)).finishTransition(eq(transitToken2), any());
 
         mDefaultHandler.finishAll();
         mMainExecutor.flushAll();
         // first transition finished
-        verify(mOrganizer, times(1)).finishTransition(eq(transitToken1), any(), any());
-        verify(mOrganizer, times(0)).finishTransition(eq(transitToken2), any(), any());
+        verify(mOrganizer, times(1)).finishTransition(eq(transitToken1), any());
+        verify(mOrganizer, times(0)).finishTransition(eq(transitToken2), any());
         // But now the "queued" transition is running
         assertEquals(1, mDefaultHandler.activeCount());
 
         mDefaultHandler.finishAll();
         mMainExecutor.flushAll();
-        verify(mOrganizer, times(1)).finishTransition(eq(transitToken2), any(), any());
+        verify(mOrganizer, times(1)).finishTransition(eq(transitToken2), any());
     }
 
     @Test
@@ -565,15 +565,15 @@
         // it should still only have 1 active, but then show 1 merged
         assertEquals(1, mDefaultHandler.activeCount());
         assertEquals(1, mDefaultHandler.mergeCount());
-        verify(mOrganizer, times(0)).finishTransition(eq(transitToken1), any(), any());
+        verify(mOrganizer, times(0)).finishTransition(eq(transitToken1), any());
         // We don't tell organizer it is finished yet (since we still want to maintain ordering)
-        verify(mOrganizer, times(0)).finishTransition(eq(transitToken2), any(), any());
+        verify(mOrganizer, times(0)).finishTransition(eq(transitToken2), any());
 
         mDefaultHandler.finishAll();
         mMainExecutor.flushAll();
         // transition + merged all finished.
-        verify(mOrganizer, times(1)).finishTransition(eq(transitToken1), any(), any());
-        verify(mOrganizer, times(1)).finishTransition(eq(transitToken2), any(), any());
+        verify(mOrganizer, times(1)).finishTransition(eq(transitToken1), any());
+        verify(mOrganizer, times(1)).finishTransition(eq(transitToken2), any());
         // Make sure nothing was queued
         assertEquals(0, mDefaultHandler.activeCount());
     }
@@ -599,8 +599,7 @@
         requestStartTransition(transitions, transitTokenNotReady);
 
         mDefaultHandler.setSimulateMerge(true);
-        mDefaultHandler.mFinishes.get(0).second.onTransitionFinished(
-                null /* wct */, null /* wctCB */);
+        mDefaultHandler.mFinishes.get(0).second.onTransitionFinished(null /* wct */);
 
         // Make sure that the non-ready transition is not merged.
         assertEquals(0, mDefaultHandler.mergeCount());
@@ -823,8 +822,8 @@
         mDefaultHandler.finishAll();
         mMainExecutor.flushAll();
         // first transition finished
-        verify(mOrganizer, times(1)).finishTransition(eq(transitToken1), any(), any());
-        verify(mOrganizer, times(0)).finishTransition(eq(transitToken2), any(), any());
+        verify(mOrganizer, times(1)).finishTransition(eq(transitToken1), any());
+        verify(mOrganizer, times(0)).finishTransition(eq(transitToken2), any());
         // But now the "queued" transition is running
         assertEquals(1, mDefaultHandler.activeCount());
 
@@ -835,7 +834,7 @@
 
         mDefaultHandler.finishAll();
         mMainExecutor.flushAll();
-        verify(mOrganizer, times(1)).finishTransition(eq(transitToken2), any(), any());
+        verify(mOrganizer, times(1)).finishTransition(eq(transitToken2), any());
 
         // runnable2 and runnable3 are executed after the second transition finishes because there
         // are no other active transitions, runnable1 isn't executed again.
@@ -1449,13 +1448,13 @@
             if (mFinishOnSync && info.getType() == TRANSIT_SLEEP) {
                 for (int i = 0; i < mFinishes.size(); ++i) {
                     if (mFinishes.get(i).first != mergeTarget) continue;
-                    mFinishes.remove(i).second.onTransitionFinished(null, null);
+                    mFinishes.remove(i).second.onTransitionFinished(null);
                     return;
                 }
             }
             if (!(mSimulateMerge || mShouldMerge.contains(transition))) return;
             mMerged.add(transition);
-            finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */);
+            finishCallback.onTransitionFinished(null /* wct */);
         }
 
         @Nullable
@@ -1478,7 +1477,7 @@
                     mFinishes;
             mFinishes = new ArrayList<>();
             for (int i = finishes.size() - 1; i >= 0; --i) {
-                finishes.get(i).second.onTransitionFinished(null /* wct */, null /* wctCB */);
+                finishes.get(i).second.onTransitionFinished(null /* wct */);
             }
             mShouldMerge.clear();
         }
@@ -1486,7 +1485,7 @@
         void finishOne() {
             Pair<IBinder, Transitions.TransitionFinishCallback> fin = mFinishes.remove(0);
             mMerged.clear();
-            fin.second.onTransitionFinished(null /* wct */, null /* wctCB */);
+            fin.second.onTransitionFinished(null /* wct */);
         }
 
         int activeCount() {
diff --git a/libs/androidfw/AssetManager2.cpp b/libs/androidfw/AssetManager2.cpp
index 5ffec34..b1ef4e5 100644
--- a/libs/androidfw/AssetManager2.cpp
+++ b/libs/androidfw/AssetManager2.cpp
@@ -91,17 +91,12 @@
   StringPoolRef entry_string_ref;
 };
 
-AssetManager2::AssetManager2(ApkAssetsList apk_assets, const ResTable_config& configuration) {
-  configurations_.push_back(configuration);
-
+AssetManager2::AssetManager2(ApkAssetsList apk_assets, const ResTable_config& configuration)
+    : configuration_(configuration) {
   // Don't invalidate caches here as there's nothing cached yet.
   SetApkAssets(apk_assets, false);
 }
 
-AssetManager2::AssetManager2() {
-  configurations_.resize(1);
-}
-
 bool AssetManager2::SetApkAssets(ApkAssetsList apk_assets, bool invalidate_caches) {
   BuildDynamicRefTable(apk_assets);
   RebuildFilterList();
@@ -426,16 +421,9 @@
   return false;
 }
 
-void AssetManager2::SetConfigurations(std::vector<ResTable_config> configurations) {
-  int diff = 0;
-  if (configurations_.size() != configurations.size()) {
-    diff = -1;
-  } else {
-    for (int i = 0; i < configurations_.size(); i++) {
-      diff |= configurations_[i].diff(configurations[i]);
-    }
-  }
-  configurations_ = std::move(configurations);
+void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
+  const int diff = configuration_.diff(configuration);
+  configuration_ = configuration;
 
   if (diff) {
     RebuildFilterList();
@@ -632,6 +620,16 @@
 
   auto op = StartOperation();
 
+  // Might use this if density_override != 0.
+  ResTable_config density_override_config;
+
+  // Select our configuration or generate a density override configuration.
+  const ResTable_config* desired_config = &configuration_;
+  if (density_override != 0 && density_override != configuration_.density) {
+    density_override_config = configuration_;
+    density_override_config.density = density_override;
+    desired_config = &density_override_config;
+  }
 
   // Retrieve the package group from the package id of the resource id.
   if (UNLIKELY(!is_valid_resid(resid))) {
@@ -650,160 +648,119 @@
   }
 
   const PackageGroup& package_group = package_groups_[package_idx];
-  std::optional<FindEntryResult> final_result;
-  bool final_has_locale = false;
-  bool final_overlaid = false;
-  for (auto & config : configurations_) {
-    // Might use this if density_override != 0.
-    ResTable_config density_override_config;
+  auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
+                                  stop_at_first_match, ignore_configuration);
+  if (UNLIKELY(!result.has_value())) {
+    return base::unexpected(result.error());
+  }
 
-    // Select our configuration or generate a density override configuration.
-    const ResTable_config* desired_config = &config;
-    if (density_override != 0 && density_override != config.density) {
-      density_override_config = config;
-      density_override_config.density = density_override;
-      desired_config = &density_override_config;
+  bool overlaid = false;
+  if (!stop_at_first_match && !ignore_configuration) {
+    const auto& assets = GetApkAssets(result->cookie);
+    if (!assets) {
+      ALOGE("Found expired ApkAssets #%d for resource ID 0x%08x.", result->cookie, resid);
+      return base::unexpected(std::nullopt);
     }
-
-    auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
-                                    stop_at_first_match, ignore_configuration);
-    if (UNLIKELY(!result.has_value())) {
-      return base::unexpected(result.error());
-    }
-    bool overlaid = false;
-    if (!stop_at_first_match && !ignore_configuration) {
-      const auto& assets = GetApkAssets(result->cookie);
-      if (!assets) {
-        ALOGE("Found expired ApkAssets #%d for resource ID 0x%08x.", result->cookie, resid);
-        return base::unexpected(std::nullopt);
-      }
-      if (!assets->IsLoader()) {
-        for (const auto& id_map : package_group.overlays_) {
-          auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
-          if (!overlay_entry) {
-            // No id map entry exists for this target resource.
-            continue;
-          }
-          if (overlay_entry.IsInlineValue()) {
-            // The target resource is overlaid by an inline value not represented by a resource.
-            ConfigDescription best_frro_config;
-            Res_value best_frro_value;
-            bool frro_found = false;
-            for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
-              if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
-                  && config.match(*desired_config)) {
-                frro_found = true;
-                best_frro_config = config;
-                best_frro_value = value;
-              }
+    if (!assets->IsLoader()) {
+      for (const auto& id_map : package_group.overlays_) {
+        auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
+        if (!overlay_entry) {
+          // No id map entry exists for this target resource.
+          continue;
+        }
+        if (overlay_entry.IsInlineValue()) {
+          // The target resource is overlaid by an inline value not represented by a resource.
+          ConfigDescription best_frro_config;
+          Res_value best_frro_value;
+          bool frro_found = false;
+          for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
+            if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
+                && config.match(*desired_config)) {
+              frro_found = true;
+              best_frro_config = config;
+              best_frro_value = value;
             }
-            if (!frro_found) {
-              continue;
-            }
-            result->entry = best_frro_value;
-            result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
-            result->cookie = id_map.cookie;
-
-            if (UNLIKELY(logging_enabled)) {
-              last_resolution_.steps.push_back(Resolution::Step{
-                  Resolution::Step::Type::OVERLAID_INLINE, result->cookie, String8()});
-              if (auto path = assets->GetPath()) {
-                const std::string overlay_path = path->data();
-                if (IsFabricatedOverlay(overlay_path)) {
-                  // FRRO don't have package name so we use the creating package here.
-                  String8 frro_name = String8("FRRO");
-                  // Get the first part of it since the expected one should be like
-                  // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
-                  // under /data/resource-cache/.
-                  const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
-                  const size_t end = name.find('-');
-                  if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
-                    frro_name.append(base::StringPrintf(" created by %s",
-                                                        name.substr(0 /* pos */,
-                                                                    end).c_str()).c_str());
-                  }
-                  last_resolution_.best_package_name = frro_name;
-                } else {
-                  last_resolution_.best_package_name = result->package_name->c_str();
-                }
-              }
-              overlaid = true;
-            }
+          }
+          if (!frro_found) {
             continue;
           }
-
-          auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
-                                          false /* stop_at_first_match */,
-                                          false /* ignore_configuration */);
-          if (UNLIKELY(IsIOError(overlay_result))) {
-            return base::unexpected(overlay_result.error());
-          }
-          if (!overlay_result.has_value()) {
-            continue;
-          }
-
-          if (!overlay_result->config.isBetterThan(result->config, desired_config)
-              && overlay_result->config.compare(result->config) != 0) {
-            // The configuration of the entry for the overlay must be equal to or better than the
-            // target configuration to be chosen as the better value.
-            continue;
-          }
-
-          result->cookie = overlay_result->cookie;
-          result->entry = overlay_result->entry;
-          result->config = overlay_result->config;
+          result->entry = best_frro_value;
           result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
+          result->cookie = id_map.cookie;
 
           if (UNLIKELY(logging_enabled)) {
             last_resolution_.steps.push_back(
-                Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->cookie,
-                                 overlay_result->config.toString()});
-            last_resolution_.best_package_name =
-                overlay_result->package_name->c_str();
+                Resolution::Step{Resolution::Step::Type::OVERLAID_INLINE, result->cookie, String8()});
+            if (auto path = assets->GetPath()) {
+              const std::string overlay_path = path->data();
+              if (IsFabricatedOverlay(overlay_path)) {
+                // FRRO don't have package name so we use the creating package here.
+                String8 frro_name = String8("FRRO");
+                // Get the first part of it since the expected one should be like
+                // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
+                // under /data/resource-cache/.
+                const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
+                const size_t end = name.find('-');
+                if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
+                  frro_name.append(base::StringPrintf(" created by %s",
+                                                      name.substr(0 /* pos */,
+                                                                  end).c_str()).c_str());
+                }
+                last_resolution_.best_package_name = frro_name;
+              } else {
+                last_resolution_.best_package_name = result->package_name->c_str();
+              }
+            }
             overlaid = true;
           }
+          continue;
+        }
+
+        auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
+                                        false /* stop_at_first_match */,
+                                        false /* ignore_configuration */);
+        if (UNLIKELY(IsIOError(overlay_result))) {
+          return base::unexpected(overlay_result.error());
+        }
+        if (!overlay_result.has_value()) {
+          continue;
+        }
+
+        if (!overlay_result->config.isBetterThan(result->config, desired_config)
+            && overlay_result->config.compare(result->config) != 0) {
+          // The configuration of the entry for the overlay must be equal to or better than the target
+          // configuration to be chosen as the better value.
+          continue;
+        }
+
+        result->cookie = overlay_result->cookie;
+        result->entry = overlay_result->entry;
+        result->config = overlay_result->config;
+        result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
+
+        if (UNLIKELY(logging_enabled)) {
+          last_resolution_.steps.push_back(
+              Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->cookie,
+                               overlay_result->config.toString()});
+          last_resolution_.best_package_name =
+              overlay_result->package_name->c_str();
+          overlaid = true;
         }
       }
     }
-
-    bool has_locale = false;
-    if (result->config.locale == 0) {
-      if (default_locale_ != 0) {
-        ResTable_config conf;
-        conf.locale = default_locale_;
-        // Since we know conf has a locale and only a locale, match will tell us if that locale
-        // matches
-        has_locale = conf.match(config);
-      }
-    } else {
-      has_locale = true;
-    }
-
-    // if we don't have a result yet
-    if (!final_result ||
-        // or this config is better before the locale than the existing result
-        result->config.isBetterThanBeforeLocale(final_result->config, desired_config) ||
-        // or the existing config isn't better before locale and this one specifies a locale
-        // whereas the existing one doesn't
-        (!final_result->config.isBetterThanBeforeLocale(result->config, desired_config)
-            && has_locale && !final_has_locale)) {
-      final_result = result.value();
-      final_overlaid = overlaid;
-      final_has_locale = has_locale;
-    }
   }
 
   if (UNLIKELY(logging_enabled)) {
-    last_resolution_.cookie = final_result->cookie;
-    last_resolution_.type_string_ref = final_result->type_string_ref;
-    last_resolution_.entry_string_ref = final_result->entry_string_ref;
-    last_resolution_.best_config_name = final_result->config.toString();
-    if (!final_overlaid) {
-      last_resolution_.best_package_name = final_result->package_name->c_str();
+    last_resolution_.cookie = result->cookie;
+    last_resolution_.type_string_ref = result->type_string_ref;
+    last_resolution_.entry_string_ref = result->entry_string_ref;
+    last_resolution_.best_config_name = result->config.toString();
+    if (!overlaid) {
+      last_resolution_.best_package_name = result->package_name->c_str();
     }
   }
 
-  return *final_result;
+  return result;
 }
 
 base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
@@ -821,10 +778,8 @@
   // If `desired_config` is not the same as the set configuration or the caller will accept a value
   // from any configuration, then we cannot use our filtered list of types since it only it contains
   // types matched to the set configuration.
-  const bool use_filtered = !ignore_configuration && std::find_if(
-      configurations_.begin(), configurations_.end(),
-      [&desired_config](auto& value) { return &desired_config == &value; })
-      != configurations_.end();
+  const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
+
   const size_t package_count = package_group.packages_.size();
   for (size_t pi = 0; pi < package_count; pi++) {
     const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
@@ -979,22 +934,10 @@
   }
 
   std::stringstream log_stream;
-  if (configurations_.size() == 1) {
-    log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
-                                     "\tFor config - %s", resid, resource_name_string.c_str(),
-                                     configurations_[0].toString().c_str());
-  } else {
-    ResTable_config conf = configurations_[0];
-    conf.clearLocale();
-    log_stream << base::StringPrintf("Resolution for 0x%08x %s\n\tFor config - %s and locales",
-                                     resid, resource_name_string.c_str(), conf.toString().c_str());
-    char str[40];
-    str[0] = '\0';
-    for(auto iter = configurations_.begin(); iter < configurations_.end(); iter++) {
-      iter->getBcp47Locale(str);
-      log_stream << base::StringPrintf(" %s%s", str, iter < configurations_.end() ? "," : "");
-    }
-  }
+  log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
+                                   "\tFor config - %s", resid, resource_name_string.c_str(),
+                                   configuration_.toString().c_str());
+
   for (const Resolution::Step& step : last_resolution_.steps) {
     constexpr static std::array kStepStrings = {
         "Found initial",
@@ -1484,14 +1427,11 @@
       package.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
         FilteredConfigGroup* group = nullptr;
         for (const auto& type_entry : type_spec.type_entries) {
-          for (auto & config : configurations_) {
-            if (type_entry.config.match(config)) {
-              if (!group) {
-                group = &package.filtered_configs_.editItemAt(type_id - 1);
-              }
-              group->type_entries.push_back(&type_entry);
-              break;
+          if (type_entry.config.match(configuration_)) {
+            if (!group) {
+              group = &package.filtered_configs_.editItemAt(type_id - 1);
             }
+            group->type_entries.push_back(&type_entry);
           }
         }
       });
diff --git a/libs/androidfw/OWNERS b/libs/androidfw/OWNERS
index 17f5164..436f107 100644
--- a/libs/androidfw/OWNERS
+++ b/libs/androidfw/OWNERS
@@ -4,4 +4,4 @@
 patb@google.com
 
 per-file CursorWindow.cpp=omakoto@google.com
-per-file LocaleDataTables.cpp=vichang@google.com,ngeoffray@google.com,nikitai@google.com
+per-file LocaleDataTables.cpp=vichang@google.com,ngeoffray@google.com
diff --git a/libs/androidfw/ResourceTypes.cpp b/libs/androidfw/ResourceTypes.cpp
index 06d19e0..5a63612 100644
--- a/libs/androidfw/ResourceTypes.cpp
+++ b/libs/androidfw/ResourceTypes.cpp
@@ -2568,22 +2568,6 @@
     return false;
 }
 
-bool ResTable_config::isBetterThanBeforeLocale(const ResTable_config& o,
-        const ResTable_config* requested) const {
-    if (requested) {
-        if (imsi || o.imsi) {
-            if ((mcc != o.mcc) && requested->mcc) {
-                return (mcc);
-            }
-
-            if ((mnc != o.mnc) && requested->mnc) {
-                return (mnc);
-            }
-        }
-    }
-    return false;
-}
-
 bool ResTable_config::isBetterThan(const ResTable_config& o,
         const ResTable_config* requested) const {
     if (requested) {
diff --git a/libs/androidfw/include/androidfw/AssetManager2.h b/libs/androidfw/include/androidfw/AssetManager2.h
index d9ff35b..f611d0d 100644
--- a/libs/androidfw/include/androidfw/AssetManager2.h
+++ b/libs/androidfw/include/androidfw/AssetManager2.h
@@ -100,7 +100,7 @@
   using ApkAssetsWPtr = wp<const ApkAssets>;
   using ApkAssetsList = std::span<const ApkAssetsPtr>;
 
-  AssetManager2();
+  AssetManager2() = default;
   explicit AssetManager2(AssetManager2&& other) = default;
   AssetManager2(ApkAssetsList apk_assets, const ResTable_config& configuration);
 
@@ -156,14 +156,10 @@
 
   // Sets/resets the configuration for this AssetManager. This will cause all
   // caches that are related to the configuration change to be invalidated.
-  void SetConfigurations(std::vector<ResTable_config> configurations);
+  void SetConfiguration(const ResTable_config& configuration);
 
-  inline const std::vector<ResTable_config>& GetConfigurations() const {
-    return configurations_;
-  }
-
-  inline void SetDefaultLocale(uint32_t default_locale) {
-    default_locale_ = default_locale;
+  inline const ResTable_config& GetConfiguration() const {
+    return configuration_;
   }
 
   // Returns all configurations for which there are resources defined, or an I/O error if reading
@@ -469,11 +465,9 @@
   // without taking too much memory.
   std::array<uint8_t, std::numeric_limits<uint8_t>::max() + 1> package_ids_;
 
-  uint32_t default_locale_;
-
-  // The current configurations set for this AssetManager. When this changes, cached resources
+  // The current configuration set for this AssetManager. When this changes, cached resources
   // may need to be purged.
-  std::vector<ResTable_config> configurations_;
+  ResTable_config configuration_ = {};
 
   // Cached set of bags. These are cached because they can inherit keys from parent bags,
   // which involves some calculation.
diff --git a/libs/androidfw/include/androidfw/ResourceTypes.h b/libs/androidfw/include/androidfw/ResourceTypes.h
index 52666ab..6de1d1e 100644
--- a/libs/androidfw/include/androidfw/ResourceTypes.h
+++ b/libs/androidfw/include/androidfw/ResourceTypes.h
@@ -1375,8 +1375,6 @@
     // match the requested configuration at all.
     bool isLocaleBetterThan(const ResTable_config& o, const ResTable_config* requested) const;
 
-    bool isBetterThanBeforeLocale(const ResTable_config& o, const ResTable_config* requested) const;
-
     String8 toString() const;
 };
 
@@ -1872,6 +1870,8 @@
   DataValue data_value;
   std::string data_string_value;
   std::optional<android::base::borrowed_fd> data_binary_value;
+  off64_t binary_data_offset;
+  size_t binary_data_size;
   std::string configuration;
 };
 
diff --git a/libs/androidfw/tests/AssetManager2_bench.cpp b/libs/androidfw/tests/AssetManager2_bench.cpp
index 2caa98c..6fae72a 100644
--- a/libs/androidfw/tests/AssetManager2_bench.cpp
+++ b/libs/androidfw/tests/AssetManager2_bench.cpp
@@ -228,12 +228,10 @@
 
   ResTable_config config;
   memset(&config, 0, sizeof(config));
-  std::vector<ResTable_config> configs;
-  configs.push_back(config);
 
   while (state.KeepRunning()) {
-    configs[0].sdkVersion = ~configs[0].sdkVersion;
-    assets.SetConfigurations(configs);
+    config.sdkVersion = ~config.sdkVersion;
+    assets.SetConfiguration(config);
   }
 }
 BENCHMARK(BM_AssetManagerSetConfigurationFramework);
diff --git a/libs/androidfw/tests/AssetManager2_test.cpp b/libs/androidfw/tests/AssetManager2_test.cpp
index c62f095..df3fa02 100644
--- a/libs/androidfw/tests/AssetManager2_test.cpp
+++ b/libs/androidfw/tests/AssetManager2_test.cpp
@@ -113,7 +113,7 @@
   desired_config.language[1] = 'e';
 
   AssetManager2 assetmanager;
-  assetmanager.SetConfigurations({desired_config});
+  assetmanager.SetConfiguration(desired_config);
   assetmanager.SetApkAssets({basic_assets_});
 
   auto value = assetmanager.GetResource(basic::R::string::test1);
@@ -137,7 +137,7 @@
   desired_config.language[1] = 'e';
 
   AssetManager2 assetmanager;
-  assetmanager.SetConfigurations({desired_config});
+  assetmanager.SetConfiguration(desired_config);
   assetmanager.SetApkAssets({basic_assets_, basic_de_fr_assets_});
 
   auto value = assetmanager.GetResource(basic::R::string::test1);
@@ -466,10 +466,10 @@
 TEST_F(AssetManager2Test, DensityOverride) {
   AssetManager2 assetmanager;
   assetmanager.SetApkAssets({basic_assets_, basic_xhdpi_assets_, basic_xxhdpi_assets_});
-  assetmanager.SetConfigurations({{
+  assetmanager.SetConfiguration({
     .density = ResTable_config::DENSITY_XHIGH,
     .sdkVersion = 21,
-  }});
+  });
 
   auto value = assetmanager.GetResource(basic::R::string::density, false /*may_be_bag*/);
   ASSERT_TRUE(value.has_value());
@@ -721,7 +721,7 @@
   ResTable_config desired_config;
 
   AssetManager2 assetmanager;
-  assetmanager.SetConfigurations({desired_config});
+  assetmanager.SetConfiguration(desired_config);
   assetmanager.SetApkAssets({basic_assets_});
   assetmanager.SetResourceResolutionLoggingEnabled(false);
 
@@ -736,7 +736,7 @@
   ResTable_config desired_config;
 
   AssetManager2 assetmanager;
-  assetmanager.SetConfigurations({desired_config});
+  assetmanager.SetConfiguration(desired_config);
   assetmanager.SetApkAssets({basic_assets_});
 
   auto result = assetmanager.GetLastResourceResolution();
@@ -751,7 +751,7 @@
 
   AssetManager2 assetmanager;
   assetmanager.SetResourceResolutionLoggingEnabled(true);
-  assetmanager.SetConfigurations({desired_config});
+  assetmanager.SetConfiguration(desired_config);
   assetmanager.SetApkAssets({basic_assets_});
 
   auto value = assetmanager.GetResource(basic::R::string::test1);
@@ -774,7 +774,7 @@
 
   AssetManager2 assetmanager;
   assetmanager.SetResourceResolutionLoggingEnabled(true);
-  assetmanager.SetConfigurations({desired_config});
+  assetmanager.SetConfiguration(desired_config);
   assetmanager.SetApkAssets({basic_assets_, basic_de_fr_assets_});
 
   auto value = assetmanager.GetResource(basic::R::string::test1);
@@ -796,7 +796,7 @@
 
   AssetManager2 assetmanager;
   assetmanager.SetResourceResolutionLoggingEnabled(true);
-  assetmanager.SetConfigurations({desired_config});
+  assetmanager.SetConfiguration(desired_config);
   assetmanager.SetApkAssets({basic_assets_});
 
   auto value = assetmanager.GetResource(basic::R::string::test1);
@@ -817,7 +817,7 @@
 
   AssetManager2 assetmanager;
   assetmanager.SetResourceResolutionLoggingEnabled(true);
-  assetmanager.SetConfigurations({desired_config});
+  assetmanager.SetConfiguration(desired_config);
   assetmanager.SetApkAssets({overlayable_assets_});
 
   const auto map = assetmanager.GetOverlayableMapForPackage(0x7f);
diff --git a/libs/androidfw/tests/BenchmarkHelpers.cpp b/libs/androidfw/tests/BenchmarkHelpers.cpp
index 8b883f4..b97dd96 100644
--- a/libs/androidfw/tests/BenchmarkHelpers.cpp
+++ b/libs/androidfw/tests/BenchmarkHelpers.cpp
@@ -66,7 +66,7 @@
   AssetManager2 assetmanager;
   assetmanager.SetApkAssets(apk_assets);
   if (config != nullptr) {
-    assetmanager.SetConfigurations({*config});
+    assetmanager.SetConfiguration(*config);
   }
 
   while (state.KeepRunning()) {
diff --git a/libs/androidfw/tests/Theme_test.cpp b/libs/androidfw/tests/Theme_test.cpp
index 181d141..e08a6a7 100644
--- a/libs/androidfw/tests/Theme_test.cpp
+++ b/libs/androidfw/tests/Theme_test.cpp
@@ -260,7 +260,7 @@
   ResTable_config night{};
   night.uiMode = ResTable_config::UI_MODE_NIGHT_YES;
   night.version = 8u;
-  am_night.SetConfigurations({night});
+  am_night.SetConfiguration(night);
 
   auto theme = am.NewTheme();
   {
diff --git a/libs/hwui/Android.bp b/libs/hwui/Android.bp
index b5e6f94..7f80dff 100644
--- a/libs/hwui/Android.bp
+++ b/libs/hwui/Android.bp
@@ -44,7 +44,7 @@
         "-DEGL_EGLEXT_PROTOTYPES",
         "-DGL_GLEXT_PROTOTYPES",
         "-DATRACE_TAG=ATRACE_TAG_VIEW",
-        "-DLOG_TAG=\"OpenGLRenderer\"",
+        "-DLOG_TAG=\"HWUI\"",
         "-Wall",
         "-Wthread-safety",
         "-Wno-unused-parameter",
diff --git a/libs/hwui/AutoBackendTextureRelease.cpp b/libs/hwui/AutoBackendTextureRelease.cpp
index d237cc2..4d020c5 100644
--- a/libs/hwui/AutoBackendTextureRelease.cpp
+++ b/libs/hwui/AutoBackendTextureRelease.cpp
@@ -18,9 +18,9 @@
 
 #include <SkImage.h>
 #include <include/gpu/ganesh/SkImageGanesh.h>
-#include <include/gpu/GrBackendSurfaceMutableState.h>
 #include <include/gpu/GrDirectContext.h>
 #include <include/gpu/GrBackendSurface.h>
+#include <include/gpu/MutableTextureState.h>
 #include "renderthread/RenderThread.h"
 #include "utils/Color.h"
 #include "utils/PaintUtils.h"
@@ -35,15 +35,47 @@
     AHardwareBuffer_Desc desc;
     AHardwareBuffer_describe(buffer, &desc);
     bool createProtectedImage = 0 != (desc.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT);
-    GrBackendFormat backendFormat =
-            GrAHardwareBufferUtils::GetBackendFormat(context, buffer, desc.format, false);
+
+    GrBackendFormat backendFormat;
+    GrBackendApi backend = context->backend();
+    if (backend == GrBackendApi::kOpenGL) {
+        backendFormat =
+                GrAHardwareBufferUtils::GetGLBackendFormat(context, desc.format, false);
+        mBackendTexture =
+                GrAHardwareBufferUtils::MakeGLBackendTexture(context,
+                                                             buffer,
+                                                             desc.width,
+                                                             desc.height,
+                                                             &mDeleteProc,
+                                                             &mUpdateProc,
+                                                             &mImageCtx,
+                                                             createProtectedImage,
+                                                             backendFormat,
+                                                             false);
+    } else if (backend == GrBackendApi::kVulkan) {
+        backendFormat =
+                GrAHardwareBufferUtils::GetVulkanBackendFormat(context,
+                                                               buffer,
+                                                               desc.format,
+                                                               false);
+        mBackendTexture =
+                GrAHardwareBufferUtils::MakeVulkanBackendTexture(context,
+                                                                 buffer,
+                                                                 desc.width,
+                                                                 desc.height,
+                                                                 &mDeleteProc,
+                                                                 &mUpdateProc,
+                                                                 &mImageCtx,
+                                                                 createProtectedImage,
+                                                                 backendFormat,
+                                                                 false);
+    } else {
+        LOG_ALWAYS_FATAL("Unexpected backend %d", backend);
+    }
     LOG_ALWAYS_FATAL_IF(!backendFormat.isValid(),
                         __FILE__ " Invalid GrBackendFormat. GrBackendApi==%" PRIu32
                                  ", AHardwareBuffer_Format==%" PRIu32 ".",
                         static_cast<int>(context->backend()), desc.format);
-    mBackendTexture = GrAHardwareBufferUtils::MakeBackendTexture(
-            context, buffer, desc.width, desc.height, &mDeleteProc, &mUpdateProc, &mImageCtx,
-            createProtectedImage, backendFormat, false);
     LOG_ALWAYS_FATAL_IF(!mBackendTexture.isValid(),
                         __FILE__ " Invalid GrBackendTexture. Width==%" PRIu32 ", height==%" PRIu32
                                  ", protected==%d",
@@ -110,8 +142,8 @@
     LOG_ALWAYS_FATAL_IF(Properties::getRenderPipelineType() != RenderPipelineType::SkiaVulkan);
     if (mBackendTexture.isValid()) {
         // Passing in VK_IMAGE_LAYOUT_UNDEFINED means we keep the old layout.
-        GrBackendSurfaceMutableState newState(VK_IMAGE_LAYOUT_UNDEFINED,
-                                              VK_QUEUE_FAMILY_FOREIGN_EXT);
+        skgpu::MutableTextureState newState(VK_IMAGE_LAYOUT_UNDEFINED,
+                                            VK_QUEUE_FAMILY_FOREIGN_EXT);
 
         // The unref for this ref happens in the releaseProc passed into setBackendTextureState. The
         // releaseProc callback will be made when the work to set the new state has finished on the
diff --git a/libs/hwui/DisplayList.h b/libs/hwui/DisplayList.h
index eb5878d..8c180da 100644
--- a/libs/hwui/DisplayList.h
+++ b/libs/hwui/DisplayList.h
@@ -54,6 +54,8 @@
         mImpl->updateChildren(std::move(updateFn));
     }
 
+    void visit(std::function<void(const RenderNode&)> func) const { mImpl->visit(std::move(func)); }
+
     [[nodiscard]] explicit operator bool() const {
         return mImpl.get() != nullptr;
     }
diff --git a/libs/hwui/FrameInfo.cpp b/libs/hwui/FrameInfo.cpp
index 8191f5e..a958a09 100644
--- a/libs/hwui/FrameInfo.cpp
+++ b/libs/hwui/FrameInfo.cpp
@@ -15,6 +15,8 @@
  */
 #include "FrameInfo.h"
 
+#include <gui/TraceUtils.h>
+
 #include <cstring>
 
 namespace android {
@@ -51,6 +53,30 @@
 
 void FrameInfo::importUiThreadInfo(int64_t* info) {
     memcpy(mFrameInfo, info, UI_THREAD_FRAME_INFO_SIZE * sizeof(int64_t));
+    mSkippedFrameReason.reset();
+}
+
+const char* toString(SkippedFrameReason reason) {
+    switch (reason) {
+        case SkippedFrameReason::DrawingOff:
+            return "DrawingOff";
+        case SkippedFrameReason::ContextIsStopped:
+            return "ContextIsStopped";
+        case SkippedFrameReason::NothingToDraw:
+            return "NothingToDraw";
+        case SkippedFrameReason::NoOutputTarget:
+            return "NoOutputTarget";
+        case SkippedFrameReason::NoBuffer:
+            return "NoBuffer";
+        case SkippedFrameReason::AlreadyDrawn:
+            return "AlreadyDrawn";
+    }
+}
+
+void FrameInfo::setSkippedFrameReason(android::uirenderer::SkippedFrameReason reason) {
+    ATRACE_FORMAT_INSTANT("Frame skipped: %s", toString(reason));
+    addFlag(FrameInfoFlags::SkippedFrame);
+    mSkippedFrameReason = reason;
 }
 
 } /* namespace uirenderer */
diff --git a/libs/hwui/FrameInfo.h b/libs/hwui/FrameInfo.h
index b15b6cb..f7ad139 100644
--- a/libs/hwui/FrameInfo.h
+++ b/libs/hwui/FrameInfo.h
@@ -16,15 +16,17 @@
 #ifndef FRAMEINFO_H_
 #define FRAMEINFO_H_
 
-#include "utils/Macros.h"
-
 #include <cutils/compiler.h>
+#include <memory.h>
 #include <utils/Timers.h>
 
 #include <array>
-#include <memory.h>
+#include <optional>
 #include <string>
 
+#include "SkippedFrameInfo.h"
+#include "utils/Macros.h"
+
 namespace android {
 namespace uirenderer {
 
@@ -186,8 +188,14 @@
         return mFrameInfo[static_cast<int>(index)];
     }
 
+    void setSkippedFrameReason(SkippedFrameReason reason);
+    inline std::optional<SkippedFrameReason> getSkippedFrameReason() const {
+        return mSkippedFrameReason;
+    }
+
 private:
     int64_t mFrameInfo[static_cast<int>(FrameInfoIndex::NumIndexes)];
+    std::optional<SkippedFrameReason> mSkippedFrameReason;
 };
 
 } /* namespace uirenderer */
diff --git a/libs/hwui/FrameInfoVisualizer.cpp b/libs/hwui/FrameInfoVisualizer.cpp
index 687e4dd..59f2169 100644
--- a/libs/hwui/FrameInfoVisualizer.cpp
+++ b/libs/hwui/FrameInfoVisualizer.cpp
@@ -148,7 +148,7 @@
     int fast_i = 0, janky_i = 0;
     // Set the bottom of all the shapes to the baseline
     for (int fi = mFrameSource.size() - 1; fi >= 0; fi--) {
-        if (mFrameSource[fi][FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame) {
+        if (mFrameSource[fi].getSkippedFrameReason()) {
             continue;
         }
         float lineWidth = baseLineWidth;
@@ -181,7 +181,7 @@
     int janky_i = (mNumJankyRects - 1) * 4;
 
     for (size_t fi = 0; fi < mFrameSource.size(); fi++) {
-        if (mFrameSource[fi][FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame) {
+        if (mFrameSource[fi].getSkippedFrameReason()) {
             continue;
         }
 
diff --git a/libs/hwui/RenderNode.cpp b/libs/hwui/RenderNode.cpp
index 1dd22cf..eee93c1 100644
--- a/libs/hwui/RenderNode.cpp
+++ b/libs/hwui/RenderNode.cpp
@@ -109,6 +109,13 @@
     output << std::endl;
 }
 
+void RenderNode::visit(std::function<void(const RenderNode&)> func) const {
+    func(*this);
+    if (mDisplayList) {
+        mDisplayList.visit(func);
+    }
+}
+
 int RenderNode::getUsageSize() {
     int size = sizeof(RenderNode);
     size += mStagingDisplayList.getUsedSize();
diff --git a/libs/hwui/RenderNode.h b/libs/hwui/RenderNode.h
index d1e04ad..b5b828e 100644
--- a/libs/hwui/RenderNode.h
+++ b/libs/hwui/RenderNode.h
@@ -129,10 +129,6 @@
 
     StretchMask& getStretchMask() { return mStretchMask; }
 
-    VirtualLightRefBase* getUserContext() const { return mUserContext.get(); }
-
-    void setUserContext(VirtualLightRefBase* context) { mUserContext = context; }
-
     bool isPropertyFieldDirty(DirtyPropertyMask field) const {
         return mDirtyPropertyFields & field;
     }
@@ -215,6 +211,8 @@
 
     void output(std::ostream& output, uint32_t level);
 
+    void visit(std::function<void(const RenderNode&)>) const;
+
     void setUsageHint(UsageHint usageHint) { mUsageHint = usageHint; }
 
     UsageHint usageHint() const { return mUsageHint; }
@@ -222,6 +220,7 @@
     int64_t uniqueId() const { return mUniqueId; }
 
     void setIsTextureView() { mIsTextureView = true; }
+    bool isTextureView() const { return mIsTextureView; }
 
     void markDrawStart(SkCanvas& canvas);
     void markDrawEnd(SkCanvas& canvas);
@@ -248,7 +247,6 @@
 
     const int64_t mUniqueId;
     String8 mName;
-    sp<VirtualLightRefBase> mUserContext;
 
     uint32_t mDirtyPropertyFields;
     RenderProperties mProperties;
diff --git a/packages/SystemUI/src/com/android/systemui/scene/shared/model/SceneTransitionModel.kt b/libs/hwui/SkippedFrameInfo.h
similarity index 69%
rename from packages/SystemUI/src/com/android/systemui/scene/shared/model/SceneTransitionModel.kt
rename to libs/hwui/SkippedFrameInfo.h
index c8f46a7..de56d9a 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/shared/model/SceneTransitionModel.kt
+++ b/libs/hwui/SkippedFrameInfo.h
@@ -14,12 +14,17 @@
  * limitations under the License.
  */
 
-package com.android.systemui.scene.shared.model
+#pragma once
 
-/** Models a transition between two scenes. */
-data class SceneTransitionModel(
-    /** The scene we transitioned away from. */
-    val from: SceneKey,
-    /** The scene we transitioned into. */
-    val to: SceneKey,
-)
+namespace android::uirenderer {
+
+enum class SkippedFrameReason {
+    DrawingOff,
+    ContextIsStopped,
+    NothingToDraw,
+    NoOutputTarget,
+    NoBuffer,
+    AlreadyDrawn,
+};
+
+} /* namespace android::uirenderer */
diff --git a/libs/hwui/Tonemapper.cpp b/libs/hwui/Tonemapper.cpp
index 974a5d0..ae29edf 100644
--- a/libs/hwui/Tonemapper.cpp
+++ b/libs/hwui/Tonemapper.cpp
@@ -20,6 +20,7 @@
 #include <log/log.h>
 // libshaders only exists on Android devices
 #ifdef __ANDROID__
+#include <renderthread/CanvasContext.h>
 #include <shaders/shaders.h>
 #endif
 
@@ -53,8 +54,17 @@
 
     ColorFilterRuntimeEffectBuilder effectBuilder(std::move(runtimeEffect));
 
+    auto colorTransform = android::mat4();
+    const auto* context = renderthread::CanvasContext::getActiveContext();
+    if (context) {
+        const auto ratio = context->targetSdrHdrRatio();
+        if (ratio > 1.0f) {
+            colorTransform = android::mat4::scale(vec4(ratio, ratio, ratio, 1.f));
+        }
+    }
+
     const auto uniforms =
-            shaders::buildLinearEffectUniforms(linearEffect, android::mat4(), maxDisplayLuminance,
+            shaders::buildLinearEffectUniforms(linearEffect, colorTransform, maxDisplayLuminance,
                                                currentDisplayLuminanceNits, maxLuminance);
 
     for (const auto& uniform : uniforms) {
diff --git a/libs/hwui/TreeInfo.h b/libs/hwui/TreeInfo.h
index 2bff9cb..ea25f68 100644
--- a/libs/hwui/TreeInfo.h
+++ b/libs/hwui/TreeInfo.h
@@ -16,14 +16,16 @@
 
 #pragma once
 
-#include "Properties.h"
-#include "utils/Macros.h"
-
 #include <utils/Timers.h>
-#include "SkSize.h"
 
+#include <optional>
 #include <string>
 
+#include "Properties.h"
+#include "SkSize.h"
+#include "SkippedFrameInfo.h"
+#include "utils/Macros.h"
+
 namespace android {
 namespace uirenderer {
 
@@ -110,13 +112,13 @@
         // animate itself, such as if hasFunctors is true
         // This is only set if hasAnimations is true
         bool requiresUiRedraw = false;
-        // This is set to true if draw() can be called this frame
-        // false means that we must delay until the next vsync pulse as frame
+        // This is set to nullopt if draw() can be called this frame
+        // A value means that we must delay until the next vsync pulse as frame
         // production is outrunning consumption
-        // NOTE that if this is false CanvasContext will set either requiresUiRedraw
+        // NOTE that if this has a value CanvasContext will set either requiresUiRedraw
         // *OR* will post itself for the next vsync automatically, use this
         // only to avoid calling draw()
-        bool canDrawThisFrame = true;
+        std::optional<SkippedFrameReason> skippedFrameReason;
         // Sentinel for animatedImageDelay meaning there is no need to post such
         // a message.
         static constexpr nsecs_t kNoAnimatedImageDelay = -1;
diff --git a/libs/hwui/apex/android_bitmap.cpp b/libs/hwui/apex/android_bitmap.cpp
index c442a7b..c80a9b4 100644
--- a/libs/hwui/apex/android_bitmap.cpp
+++ b/libs/hwui/apex/android_bitmap.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "Bitmap"
 #include <log/log.h>
 
 #include "android/graphics/bitmap.h"
diff --git a/libs/hwui/apex/jni_runtime.cpp b/libs/hwui/apex/jni_runtime.cpp
index 09ae7e7..883f273 100644
--- a/libs/hwui/apex/jni_runtime.cpp
+++ b/libs/hwui/apex/jni_runtime.cpp
@@ -25,9 +25,6 @@
 #include <sys/cdefs.h>
 #include <vulkan/vulkan.h>
 
-#undef LOG_TAG
-#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*);
diff --git a/libs/hwui/effects/GainmapRenderer.cpp b/libs/hwui/effects/GainmapRenderer.cpp
index 613f52b..db58b2b 100644
--- a/libs/hwui/effects/GainmapRenderer.cpp
+++ b/libs/hwui/effects/GainmapRenderer.cpp
@@ -245,11 +245,18 @@
             // This can happen if a BitmapShader is used on multiple canvas', such as a
             // software + hardware canvas, which is otherwise valid as SkShader is "immutable"
             std::lock_guard _lock(mUniformGuard);
-            const float Wunclamped = (sk_float_log(targetHdrSdrRatio) -
-                                      sk_float_log(mGainmapInfo.fDisplayRatioSdr)) /
-                                     (sk_float_log(mGainmapInfo.fDisplayRatioHdr) -
-                                      sk_float_log(mGainmapInfo.fDisplayRatioSdr));
-            const float W = std::max(std::min(Wunclamped, 1.f), 0.f);
+            // Compute the weight parameter that will be used to blend between the images.
+            float W = 0.f;
+            if (targetHdrSdrRatio > mGainmapInfo.fDisplayRatioSdr) {
+                if (targetHdrSdrRatio < mGainmapInfo.fDisplayRatioHdr) {
+                    W = (sk_float_log(targetHdrSdrRatio) -
+                         sk_float_log(mGainmapInfo.fDisplayRatioSdr)) /
+                        (sk_float_log(mGainmapInfo.fDisplayRatioHdr) -
+                         sk_float_log(mGainmapInfo.fDisplayRatioSdr));
+                } else {
+                    W = 1.f;
+                }
+            }
             mBuilder.uniform("W") = W;
             uniforms = mBuilder.uniforms();
         }
diff --git a/libs/hwui/hwui/ImageDecoder.cpp b/libs/hwui/hwui/ImageDecoder.cpp
index 701a87f..588463c 100644
--- a/libs/hwui/hwui/ImageDecoder.cpp
+++ b/libs/hwui/hwui/ImageDecoder.cpp
@@ -43,9 +43,6 @@
 
 #include <memory>
 
-#undef LOG_TAG
-#define LOG_TAG "ImageDecoder"
-
 using namespace android;
 
 sk_sp<SkColorSpace> ImageDecoder::getDefaultColorSpace() const {
diff --git a/libs/hwui/jni/Bitmap.cpp b/libs/hwui/jni/Bitmap.cpp
index 6ee7576..9e21f86 100644
--- a/libs/hwui/jni/Bitmap.cpp
+++ b/libs/hwui/jni/Bitmap.cpp
@@ -1,5 +1,3 @@
-#undef LOG_TAG
-#define LOG_TAG "Bitmap"
 // #define LOG_NDEBUG 0
 #include "Bitmap.h"
 
diff --git a/libs/hwui/jni/BitmapFactory.cpp b/libs/hwui/jni/BitmapFactory.cpp
index 8abcd9a..3d0a534 100644
--- a/libs/hwui/jni/BitmapFactory.cpp
+++ b/libs/hwui/jni/BitmapFactory.cpp
@@ -1,6 +1,3 @@
-#undef LOG_TAG
-#define LOG_TAG "BitmapFactory"
-
 #include "BitmapFactory.h"
 
 #include <Gainmap.h>
diff --git a/libs/hwui/jni/BitmapRegionDecoder.cpp b/libs/hwui/jni/BitmapRegionDecoder.cpp
index 740988f..ea5c144 100644
--- a/libs/hwui/jni/BitmapRegionDecoder.cpp
+++ b/libs/hwui/jni/BitmapRegionDecoder.cpp
@@ -14,9 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "BitmapRegionDecoder"
-
 #include "BitmapRegionDecoder.h"
 
 #include <HardwareBitmapUploader.h>
diff --git a/libs/hwui/jni/FontFamily.cpp b/libs/hwui/jni/FontFamily.cpp
index af1668f..0c3af61 100644
--- a/libs/hwui/jni/FontFamily.cpp
+++ b/libs/hwui/jni/FontFamily.cpp
@@ -14,9 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "Minikin"
-
 #include <nativehelper/ScopedPrimitiveArray.h>
 #include <nativehelper/ScopedUtfChars.h>
 #include "FontUtils.h"
diff --git a/libs/hwui/jni/Graphics.cpp b/libs/hwui/jni/Graphics.cpp
index 78b4f7b..7cc4866 100644
--- a/libs/hwui/jni/Graphics.cpp
+++ b/libs/hwui/jni/Graphics.cpp
@@ -1,6 +1,3 @@
-#undef LOG_TAG
-#define LOG_TAG "GraphicsJNI"
-
 #include <assert.h>
 #include <unistd.h>
 
diff --git a/libs/hwui/jni/GraphicsStatsService.cpp b/libs/hwui/jni/GraphicsStatsService.cpp
index e32c911..54369b9 100644
--- a/libs/hwui/jni/GraphicsStatsService.cpp
+++ b/libs/hwui/jni/GraphicsStatsService.cpp
@@ -14,9 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "GraphicsStatsService"
-
 #include <JankTracker.h>
 #include <log/log.h>
 #include <nativehelper/ScopedPrimitiveArray.h>
diff --git a/libs/hwui/jni/NinePatch.cpp b/libs/hwui/jni/NinePatch.cpp
index d50a8a2..67ef143 100644
--- a/libs/hwui/jni/NinePatch.cpp
+++ b/libs/hwui/jni/NinePatch.cpp
@@ -15,8 +15,6 @@
 ** limitations under the License.
 */
 
-#undef LOG_TAG
-#define LOG_TAG "9patch"
 #define LOG_NDEBUG 1
 
 #include <androidfw/ResourceTypes.h>
diff --git a/libs/hwui/jni/Paint.cpp b/libs/hwui/jni/Paint.cpp
index d2a4efe..1ba7f70 100644
--- a/libs/hwui/jni/Paint.cpp
+++ b/libs/hwui/jni/Paint.cpp
@@ -15,9 +15,6 @@
 ** limitations under the License.
 */
 
-#undef LOG_TAG
-#define LOG_TAG "Paint"
-
 #include <hwui/BlurDrawLooper.h>
 #include <hwui/MinikinSkia.h>
 #include <hwui/MinikinUtils.h>
diff --git a/libs/hwui/jni/Shader.cpp b/libs/hwui/jni/Shader.cpp
index 7eb79be..2c13ceb 100644
--- a/libs/hwui/jni/Shader.cpp
+++ b/libs/hwui/jni/Shader.cpp
@@ -1,6 +1,3 @@
-#undef LOG_TAG
-#define LOG_TAG "ShaderJNI"
-
 #include <vector>
 
 #include "Gainmap.h"
diff --git a/libs/hwui/jni/YuvToJpegEncoder.cpp b/libs/hwui/jni/YuvToJpegEncoder.cpp
index 69418b0..4dbfa88 100644
--- a/libs/hwui/jni/YuvToJpegEncoder.cpp
+++ b/libs/hwui/jni/YuvToJpegEncoder.cpp
@@ -1,6 +1,3 @@
-#undef LOG_TAG
-#define LOG_TAG "YuvToJpegEncoder"
-
 #include "CreateJavaOutputStreamAdaptor.h"
 #include "SkStream.h"
 #include "YuvToJpegEncoder.h"
diff --git a/libs/hwui/jni/android_graphics_HardwareBufferRenderer.cpp b/libs/hwui/jni/android_graphics_HardwareBufferRenderer.cpp
index 706f18c..e3cdee6 100644
--- a/libs/hwui/jni/android_graphics_HardwareBufferRenderer.cpp
+++ b/libs/hwui/jni/android_graphics_HardwareBufferRenderer.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "HardwareBufferRenderer"
 #define ATRACE_TAG ATRACE_TAG_VIEW
 
 #include <GraphicsJNI.h>
diff --git a/libs/hwui/jni/android_graphics_HardwareRenderer.cpp b/libs/hwui/jni/android_graphics_HardwareRenderer.cpp
index ee22f7c..422ffea 100644
--- a/libs/hwui/jni/android_graphics_HardwareRenderer.cpp
+++ b/libs/hwui/jni/android_graphics_HardwareRenderer.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "ThreadedRenderer"
 #define ATRACE_TAG ATRACE_TAG_VIEW
 
 #include <FrameInfo.h>
diff --git a/libs/hwui/jni/android_graphics_animation_NativeInterpolatorFactory.cpp b/libs/hwui/jni/android_graphics_animation_NativeInterpolatorFactory.cpp
index 764eff9..b86c74fe 100644
--- a/libs/hwui/jni/android_graphics_animation_NativeInterpolatorFactory.cpp
+++ b/libs/hwui/jni/android_graphics_animation_NativeInterpolatorFactory.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "OpenGLRenderer"
-
 #include <Interpolator.h>
 #include <cutils/log.h>
 
diff --git a/libs/hwui/jni/android_graphics_animation_RenderNodeAnimator.cpp b/libs/hwui/jni/android_graphics_animation_RenderNodeAnimator.cpp
index c6d26f8..40be924 100644
--- a/libs/hwui/jni/android_graphics_animation_RenderNodeAnimator.cpp
+++ b/libs/hwui/jni/android_graphics_animation_RenderNodeAnimator.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "OpenGLRenderer"
-
 #include <Animator.h>
 #include <Interpolator.h>
 #include <RenderProperties.h>
diff --git a/libs/hwui/jni/fonts/Font.cpp b/libs/hwui/jni/fonts/Font.cpp
index 8cfdeeb7..2ec94c9 100644
--- a/libs/hwui/jni/fonts/Font.cpp
+++ b/libs/hwui/jni/fonts/Font.cpp
@@ -14,9 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "Minikin"
-
 #include "Font.h"
 #include "SkData.h"
 #include "SkFont.h"
diff --git a/libs/hwui/jni/fonts/FontFamily.cpp b/libs/hwui/jni/fonts/FontFamily.cpp
index 1e392b1..462c8c8 100644
--- a/libs/hwui/jni/fonts/FontFamily.cpp
+++ b/libs/hwui/jni/fonts/FontFamily.cpp
@@ -14,9 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "Minikin"
-
 #include "graphics_jni_helpers.h"
 #include <nativehelper/ScopedUtfChars.h>
 
diff --git a/libs/hwui/jni/pdf/PdfEditor.cpp b/libs/hwui/jni/pdf/PdfEditor.cpp
index 427bafa..3b18f5f 100644
--- a/libs/hwui/jni/pdf/PdfEditor.cpp
+++ b/libs/hwui/jni/pdf/PdfEditor.cpp
@@ -14,9 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "PdfEditor"
-
 #include <sys/types.h>
 #include <unistd.h>
 
diff --git a/libs/hwui/jni/pdf/PdfUtils.cpp b/libs/hwui/jni/pdf/PdfUtils.cpp
index 06d2028..6887fda 100644
--- a/libs/hwui/jni/pdf/PdfUtils.cpp
+++ b/libs/hwui/jni/pdf/PdfUtils.cpp
@@ -16,14 +16,11 @@
 
 #include "PdfUtils.h"
 
-#include "jni.h"
 #include <nativehelper/JNIHelp.h>
+#include <utils/Log.h>
 
 #include "fpdfview.h"
-
-#undef LOG_TAG
-#define LOG_TAG "PdfUtils"
-#include <utils/Log.h>
+#include "jni.h"
 
 namespace android {
 
diff --git a/libs/hwui/jni/text/GraphemeBreak.cpp b/libs/hwui/jni/text/GraphemeBreak.cpp
index 55f03bd..322af7e 100644
--- a/libs/hwui/jni/text/GraphemeBreak.cpp
+++ b/libs/hwui/jni/text/GraphemeBreak.cpp
@@ -14,9 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "GraphemeBreaker"
-
 #include <minikin/GraphemeBreak.h>
 #include <nativehelper/ScopedPrimitiveArray.h>
 
diff --git a/libs/hwui/jni/text/LineBreaker.cpp b/libs/hwui/jni/text/LineBreaker.cpp
index 6986517..9ebf23c 100644
--- a/libs/hwui/jni/text/LineBreaker.cpp
+++ b/libs/hwui/jni/text/LineBreaker.cpp
@@ -14,9 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "LineBreaker"
-
 #include "utils/misc.h"
 #include "utils/Log.h"
 #include "graphics_jni_helpers.h"
diff --git a/libs/hwui/jni/text/MeasuredText.cpp b/libs/hwui/jni/text/MeasuredText.cpp
index c13c800..081713a 100644
--- a/libs/hwui/jni/text/MeasuredText.cpp
+++ b/libs/hwui/jni/text/MeasuredText.cpp
@@ -14,9 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "MeasuredText"
-
 #include "GraphicsJNI.h"
 #include "utils/misc.h"
 #include "utils/Log.h"
diff --git a/libs/hwui/jni/text/TextShaper.cpp b/libs/hwui/jni/text/TextShaper.cpp
index 8c377b9..6c05346 100644
--- a/libs/hwui/jni/text/TextShaper.cpp
+++ b/libs/hwui/jni/text/TextShaper.cpp
@@ -14,9 +14,6 @@
  * limitations under the License.
  */
 
-#undef LOG_TAG
-#define LOG_TAG "TextShaper"
-
 #include "graphics_jni_helpers.h"
 #include <nativehelper/ScopedStringChars.h>
 #include <nativehelper/ScopedPrimitiveArray.h>
diff --git a/libs/hwui/pipeline/skia/GLFunctorDrawable.cpp b/libs/hwui/pipeline/skia/GLFunctorDrawable.cpp
index dbd9ef3..5d3fb30 100644
--- a/libs/hwui/pipeline/skia/GLFunctorDrawable.cpp
+++ b/libs/hwui/pipeline/skia/GLFunctorDrawable.cpp
@@ -28,6 +28,8 @@
 #include "SkM44.h"
 #include <include/gpu/ganesh/SkSurfaceGanesh.h>
 #include "include/gpu/GpuTypes.h" // from Skia
+#include <include/gpu/gl/GrGLTypes.h>
+#include <include/gpu/ganesh/gl/GrGLBackendSurface.h>
 #include "utils/GLUtils.h"
 #include <effects/GainmapRenderer.h>
 #include "renderthread/CanvasContext.h"
@@ -47,7 +49,7 @@
 static void GetFboDetails(SkCanvas* canvas, GLuint* outFboID, SkISize* outFboSize) {
     GrBackendRenderTarget renderTarget = skgpu::ganesh::TopLayerBackendRenderTarget(canvas);
     GrGLFramebufferInfo fboInfo;
-    LOG_ALWAYS_FATAL_IF(!renderTarget.getGLFramebufferInfo(&fboInfo),
+    LOG_ALWAYS_FATAL_IF(!GrBackendRenderTargets::GetGLFramebufferInfo(renderTarget, &fboInfo),
         "getGLFrameBufferInfo failed");
 
     *outFboID = fboInfo.fFBOID;
@@ -102,9 +104,10 @@
         tmpSurface->getCanvas()->clear(SK_ColorTRANSPARENT);
 
         GrGLFramebufferInfo fboInfo;
-        if (!SkSurfaces::GetBackendRenderTarget(tmpSurface.get(),
-                                                SkSurfaces::BackendHandleAccess::kFlushWrite)
-                     .getGLFramebufferInfo(&fboInfo)) {
+        if (!GrBackendRenderTargets::GetGLFramebufferInfo(
+                    SkSurfaces::GetBackendRenderTarget(
+                        tmpSurface.get(), SkSurfaces::BackendHandleAccess::kFlushWrite),
+                    &fboInfo)) {
             ALOGW("Unable to extract renderTarget info from offscreen canvas; aborting GLFunctor");
             return;
         }
diff --git a/libs/hwui/pipeline/skia/SkiaDisplayList.cpp b/libs/hwui/pipeline/skia/SkiaDisplayList.cpp
index af2d3b3..5c8285a 100644
--- a/libs/hwui/pipeline/skia/SkiaDisplayList.cpp
+++ b/libs/hwui/pipeline/skia/SkiaDisplayList.cpp
@@ -66,6 +66,12 @@
     }
 }
 
+void SkiaDisplayList::visit(std::function<void(const RenderNode&)> func) const {
+    for (auto& child : mChildNodes) {
+        child.getRenderNode()->visit(func);
+    }
+}
+
 static bool intersects(const SkISize screenSize, const Matrix4& mat, const SkRect& bounds) {
     Vector3 points[] = { Vector3 {bounds.fLeft, bounds.fTop, 0},
                          Vector3 {bounds.fRight, bounds.fTop, 0},
diff --git a/libs/hwui/pipeline/skia/SkiaDisplayList.h b/libs/hwui/pipeline/skia/SkiaDisplayList.h
index 7af31a4..e5bd5c9 100644
--- a/libs/hwui/pipeline/skia/SkiaDisplayList.h
+++ b/libs/hwui/pipeline/skia/SkiaDisplayList.h
@@ -145,6 +145,8 @@
      */
     void updateChildren(std::function<void(RenderNode*)> updateFn);
 
+    void visit(std::function<void(const RenderNode&)> func) const;
+
     /**
      *  Returns true if there is a child render node that is a projection receiver.
      */
diff --git a/libs/hwui/pipeline/skia/SkiaOpenGLPipeline.cpp b/libs/hwui/pipeline/skia/SkiaOpenGLPipeline.cpp
index 23b3074..7744786 100644
--- a/libs/hwui/pipeline/skia/SkiaOpenGLPipeline.cpp
+++ b/libs/hwui/pipeline/skia/SkiaOpenGLPipeline.cpp
@@ -17,6 +17,8 @@
 #include "SkiaOpenGLPipeline.h"
 
 #include <include/gpu/ganesh/SkSurfaceGanesh.h>
+#include <include/gpu/ganesh/gl/GrGLBackendSurface.h>
+#include <include/gpu/gl/GrGLTypes.h>
 #include <GrBackendSurface.h>
 #include <SkBlendMode.h>
 #include <SkImageInfo.h>
@@ -139,7 +141,8 @@
         LOG_ALWAYS_FATAL("Unsupported color type.");
     }
 
-    GrBackendRenderTarget backendRT(frame.width(), frame.height(), 0, STENCIL_BUFFER_SIZE, fboInfo);
+    auto backendRT = GrBackendRenderTargets::MakeGL(frame.width(), frame.height(), 0,
+                                                    STENCIL_BUFFER_SIZE, fboInfo);
 
     SkSurfaceProps props(mColorMode == ColorMode::Default ? 0 : SkSurfaceProps::kAlwaysDither_Flag,
                          kUnknown_SkPixelGeometry);
diff --git a/libs/hwui/private/hwui/DrawGlInfo.h b/libs/hwui/private/hwui/DrawGlInfo.h
index eb1f930..ed3fabc 100644
--- a/libs/hwui/private/hwui/DrawGlInfo.h
+++ b/libs/hwui/private/hwui/DrawGlInfo.h
@@ -24,8 +24,7 @@
 namespace uirenderer {
 
 /**
- * Structure used by OpenGLRenderer::callDrawGLFunction() to pass and
- * receive data from OpenGL functors.
+ * Structure used to pass and receive data from OpenGL functors.
  */
 struct DrawGlInfo {
     // Input: current clip rect
diff --git a/libs/hwui/renderthread/CanvasContext.cpp b/libs/hwui/renderthread/CanvasContext.cpp
index 2ef7802..4064bb9 100644
--- a/libs/hwui/renderthread/CanvasContext.cpp
+++ b/libs/hwui/renderthread/CanvasContext.cpp
@@ -357,8 +357,9 @@
     return true;
 }
 
-static bool wasSkipped(FrameInfo* info) {
-    return info && ((*info)[FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame);
+static std::optional<SkippedFrameReason> wasSkipped(FrameInfo* info) {
+    if (info) return info->getSkippedFrameReason();
+    return std::nullopt;
 }
 
 bool CanvasContext::isSwapChainStuffed() {
@@ -407,13 +408,26 @@
 
     // If the previous frame was dropped we don't need to hold onto it, so
     // just keep using the previous frame's structure instead
-    if (wasSkipped(mCurrentFrameInfo)) {
+    if (const auto reason = wasSkipped(mCurrentFrameInfo)) {
         // Use the oldest skipped frame in case we skip more than a single frame
         if (!mSkippedFrameInfo) {
-            mSkippedFrameInfo.emplace();
-            mSkippedFrameInfo->vsyncId =
-                mCurrentFrameInfo->get(FrameInfoIndex::FrameTimelineVsyncId);
-            mSkippedFrameInfo->startTime = mCurrentFrameInfo->get(FrameInfoIndex::FrameStartTime);
+            switch (*reason) {
+                case SkippedFrameReason::AlreadyDrawn:
+                case SkippedFrameReason::NoBuffer:
+                case SkippedFrameReason::NoOutputTarget:
+                    mSkippedFrameInfo.emplace();
+                    mSkippedFrameInfo->vsyncId =
+                            mCurrentFrameInfo->get(FrameInfoIndex::FrameTimelineVsyncId);
+                    mSkippedFrameInfo->startTime =
+                            mCurrentFrameInfo->get(FrameInfoIndex::FrameStartTime);
+                    break;
+                case SkippedFrameReason::DrawingOff:
+                case SkippedFrameReason::ContextIsStopped:
+                case SkippedFrameReason::NothingToDraw:
+                    // Do not report those as skipped frames as there was no frame expected to be
+                    // drawn
+                    break;
+            }
         }
     } else {
         mCurrentFrameInfo = mJankTracker.startFrame();
@@ -427,7 +441,7 @@
     info.damageAccumulator = &mDamageAccumulator;
     info.layerUpdateQueue = &mLayerUpdateQueue;
     info.damageGenerationId = mDamageId++;
-    info.out.canDrawThisFrame = true;
+    info.out.skippedFrameReason = std::nullopt;
 
     mAnimationContext->startFrame(info.mode);
     for (const sp<RenderNode>& node : mRenderNodes) {
@@ -447,8 +461,8 @@
     mIsDirty = true;
 
     if (CC_UNLIKELY(!hasOutputTarget())) {
-        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
-        info.out.canDrawThisFrame = false;
+        info.out.skippedFrameReason = SkippedFrameReason::NoOutputTarget;
+        mCurrentFrameInfo->setSkippedFrameReason(*info.out.skippedFrameReason);
         return;
     }
 
@@ -463,23 +477,23 @@
         if (vsyncDelta < 2_ms) {
             // Already drew for this vsync pulse, UI draw request missed
             // the deadline for RT animations
-            info.out.canDrawThisFrame = false;
+            info.out.skippedFrameReason = SkippedFrameReason::AlreadyDrawn;
         }
     } else {
-        info.out.canDrawThisFrame = true;
+        info.out.skippedFrameReason = std::nullopt;
     }
 
     // TODO: Do we need to abort out if the backdrop is added but not ready? Should that even
     // be an allowable combination?
     if (mRenderNodes.size() > 2 && !mRenderNodes[1]->isRenderable()) {
-        info.out.canDrawThisFrame = false;
+        info.out.skippedFrameReason = SkippedFrameReason::NothingToDraw;
     }
 
-    if (info.out.canDrawThisFrame) {
+    if (!info.out.skippedFrameReason) {
         int err = mNativeSurface->reserveNext();
         if (err != OK) {
-            mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
-            info.out.canDrawThisFrame = false;
+            info.out.skippedFrameReason = SkippedFrameReason::NoBuffer;
+            mCurrentFrameInfo->setSkippedFrameReason(*info.out.skippedFrameReason);
             ALOGW("reserveNext failed, error = %d (%s)", err, strerror(-err));
             if (err != TIMED_OUT) {
                 // A timed out surface can still recover, but assume others are permanently dead.
@@ -488,11 +502,11 @@
             }
         }
     } else {
-        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
+        mCurrentFrameInfo->setSkippedFrameReason(*info.out.skippedFrameReason);
     }
 
     bool postedFrameCallback = false;
-    if (info.out.hasAnimations || !info.out.canDrawThisFrame) {
+    if (info.out.hasAnimations || info.out.skippedFrameReason) {
         if (CC_UNLIKELY(!Properties::enableRTAnimations)) {
             info.out.requiresUiRedraw = true;
         }
@@ -558,9 +572,20 @@
     mSyncDelayDuration = 0;
     mIdleDuration = 0;
 
-    if (!Properties::isDrawingEnabled() ||
-        (dirty.isEmpty() && Properties::skipEmptyFrames && !surfaceRequiresRedraw())) {
-        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
+    const auto skippedFrameReason = [&]() -> std::optional<SkippedFrameReason> {
+        if (!Properties::isDrawingEnabled()) {
+            return SkippedFrameReason::DrawingOff;
+        }
+
+        if (dirty.isEmpty() && Properties::skipEmptyFrames && !surfaceRequiresRedraw()) {
+            return SkippedFrameReason::NothingToDraw;
+        }
+
+        return std::nullopt;
+    }();
+    if (skippedFrameReason) {
+        mCurrentFrameInfo->setSkippedFrameReason(*skippedFrameReason);
+
         if (auto grContext = getGrContext()) {
             // Submit to ensure that any texture uploads complete and Skia can
             // free its staging buffers.
@@ -904,7 +929,7 @@
 
     TreeInfo info(TreeInfo::MODE_RT_ONLY, *this);
     prepareTree(info, frameInfo, systemTime(SYSTEM_TIME_MONOTONIC), node);
-    if (info.out.canDrawThisFrame) {
+    if (!info.out.skippedFrameReason) {
         draw(info.out.solelyTextureViewUpdates);
     } else {
         // wait on fences so tasks don't overlap next frame
@@ -1107,6 +1132,12 @@
     return self->mColorMode != ColorMode::Default;
 }
 
+void CanvasContext::visitAllRenderNodes(std::function<void(const RenderNode&)> func) const {
+    for (auto node : mRenderNodes) {
+        node->visit(func);
+    }
+}
+
 } /* namespace renderthread */
 } /* namespace uirenderer */
 } /* namespace android */
diff --git a/libs/hwui/renderthread/CanvasContext.h b/libs/hwui/renderthread/CanvasContext.h
index 3f02674..241f8dd 100644
--- a/libs/hwui/renderthread/CanvasContext.h
+++ b/libs/hwui/renderthread/CanvasContext.h
@@ -238,6 +238,8 @@
 
     static bool shouldDither();
 
+    void visitAllRenderNodes(std::function<void(const RenderNode&)>) const;
+
 private:
     CanvasContext(RenderThread& thread, bool translucent, RenderNode* rootRenderNode,
                   IContextFactory* contextFactory, std::unique_ptr<IRenderPipeline> renderPipeline,
diff --git a/libs/hwui/renderthread/DrawFrameTask.cpp b/libs/hwui/renderthread/DrawFrameTask.cpp
index 53b43ba..1b333bf 100644
--- a/libs/hwui/renderthread/DrawFrameTask.cpp
+++ b/libs/hwui/renderthread/DrawFrameTask.cpp
@@ -104,7 +104,7 @@
         info.forceDrawFrame = mForceDrawFrame;
         mForceDrawFrame = false;
         canUnblockUiThread = syncFrameState(info);
-        canDrawThisFrame = info.out.canDrawThisFrame;
+        canDrawThisFrame = !info.out.skippedFrameReason.has_value();
         solelyTextureViewUpdates = info.out.solelyTextureViewUpdates;
 
         if (mFrameCommitCallback) {
@@ -192,11 +192,12 @@
     if (CC_UNLIKELY(!hasTarget || !canDraw)) {
         if (!hasTarget) {
             mSyncResult |= SyncResult::LostSurfaceRewardIfFound;
+            info.out.skippedFrameReason = SkippedFrameReason::NoOutputTarget;
         } else {
             // If we have a surface but can't draw we must be stopped
             mSyncResult |= SyncResult::ContextIsStopped;
+            info.out.skippedFrameReason = SkippedFrameReason::ContextIsStopped;
         }
-        info.out.canDrawThisFrame = false;
     }
 
     if (info.out.hasAnimations) {
@@ -204,7 +205,7 @@
             mSyncResult |= SyncResult::UIRedrawRequired;
         }
     }
-    if (!info.out.canDrawThisFrame) {
+    if (info.out.skippedFrameReason) {
         mSyncResult |= SyncResult::FrameDropped;
     }
     // If prepareTextures is false, we ran out of texture cache space
diff --git a/libs/hwui/renderthread/RenderThread.cpp b/libs/hwui/renderthread/RenderThread.cpp
index eb28c08..c740074 100644
--- a/libs/hwui/renderthread/RenderThread.cpp
+++ b/libs/hwui/renderthread/RenderThread.cpp
@@ -357,7 +357,15 @@
 
     String8 cachesOutput;
     mCacheManager->dumpMemoryUsage(cachesOutput, mRenderState);
-    dprintf(fd, "\nPipeline=%s\n%s\n", pipelineToString(), cachesOutput.string());
+    dprintf(fd, "\nPipeline=%s\n%s", pipelineToString(), cachesOutput.string());
+    for (auto&& context : mCacheManager->mCanvasContexts) {
+        context->visitAllRenderNodes([&](const RenderNode& node) {
+            if (node.isTextureView()) {
+                dprintf(fd, "TextureView: %dx%d\n", node.getWidth(), node.getHeight());
+            }
+        });
+    }
+    dprintf(fd, "\n");
 }
 
 void RenderThread::getMemoryUsage(size_t* cpuUsage, size_t* gpuUsage) {
diff --git a/libs/hwui/renderthread/VulkanManager.cpp b/libs/hwui/renderthread/VulkanManager.cpp
index f340945..a6e8c08f 100644
--- a/libs/hwui/renderthread/VulkanManager.cpp
+++ b/libs/hwui/renderthread/VulkanManager.cpp
@@ -34,9 +34,6 @@
 #include "pipeline/skia/ShaderCache.h"
 #include "renderstate/RenderState.h"
 
-#undef LOG_TAG
-#define LOG_TAG "VulkanManager"
-
 namespace android {
 namespace uirenderer {
 namespace renderthread {
diff --git a/libs/hwui/renderthread/VulkanSurface.cpp b/libs/hwui/renderthread/VulkanSurface.cpp
index b0ba619..20b743b 100644
--- a/libs/hwui/renderthread/VulkanSurface.cpp
+++ b/libs/hwui/renderthread/VulkanSurface.cpp
@@ -25,9 +25,6 @@
 #include "VulkanManager.h"
 #include "utils/Color.h"
 
-#undef LOG_TAG
-#define LOG_TAG "VulkanSurface"
-
 namespace android {
 namespace uirenderer {
 namespace renderthread {
diff --git a/libs/protoutil/Android.bp b/libs/protoutil/Android.bp
index 128be3c..28856c8 100644
--- a/libs/protoutil/Android.bp
+++ b/libs/protoutil/Android.bp
@@ -80,6 +80,10 @@
         "libgmock",
     ],
 
+    test_suites: [
+        "general-tests",
+    ],
+
     proto: {
         type: "full",
     },
diff --git a/libs/protoutil/AndroidTest.xml b/libs/protoutil/AndroidTest.xml
deleted file mode 100644
index 46d418e..0000000
--- a/libs/protoutil/AndroidTest.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2018 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<configuration description="Config for libprotoutil_test">
-    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
-        <option name="cleanup" value="true" />
-        <option name="push" value="libprotoutil_test->/data/nativetest/libprotoutil_test" />
-    </target_preparer>
-    <option name="test-suite-tag" value="apct" />
-    <test class="com.android.tradefed.testtype.GTest" >
-        <option name="native-test-device-path" value="/data/nativetest" />
-        <option name="module-name" value="libprotoutil_test" />
-    </test>
-</configuration>
diff --git a/libs/protoutil/TEST_MAPPING b/libs/protoutil/TEST_MAPPING
new file mode 100644
index 0000000..b10dd9b
--- /dev/null
+++ b/libs/protoutil/TEST_MAPPING
@@ -0,0 +1,12 @@
+{
+  "presubmit": [
+    {
+      "name": "libprotoutil_test"
+    }
+  ],
+  "hwasan-postsubmit": [
+    {
+      "name": "libprotoutil_test"
+    }
+  ]
+}
diff --git a/libs/protoutil/src/EncodedBuffer.cpp b/libs/protoutil/src/EncodedBuffer.cpp
index 96b54c6..afb54a6 100644
--- a/libs/protoutil/src/EncodedBuffer.cpp
+++ b/libs/protoutil/src/EncodedBuffer.cpp
@@ -17,6 +17,7 @@
 
 #include <stdlib.h>
 #include <sys/mman.h>
+#include <unistd.h>
 
 #include <android/util/EncodedBuffer.h>
 #include <android/util/protobuf.h>
@@ -25,7 +26,8 @@
 namespace android {
 namespace util {
 
-const size_t BUFFER_SIZE = 8 * 1024; // 8 KB
+constexpr size_t BUFFER_SIZE = 8 * 1024; // 8 KB
+const size_t kPageSize = getpagesize();
 
 EncodedBuffer::Pointer::Pointer() : Pointer(BUFFER_SIZE)
 {
@@ -92,7 +94,7 @@
 {
     // Align chunkSize to memory page size
     chunkSize = chunkSize == 0 ? BUFFER_SIZE : chunkSize;
-    mChunkSize = (chunkSize / PAGE_SIZE + ((chunkSize % PAGE_SIZE == 0) ? 0 : 1)) * PAGE_SIZE;
+    mChunkSize = (chunkSize + (kPageSize - 1)) & ~(kPageSize - 1);
     mWp = Pointer(mChunkSize);
     mEp = Pointer(mChunkSize);
 }
diff --git a/libs/protoutil/tests/EncodedBuffer_test.cpp b/libs/protoutil/tests/EncodedBuffer_test.cpp
index f895154..a0955854 100644
--- a/libs/protoutil/tests/EncodedBuffer_test.cpp
+++ b/libs/protoutil/tests/EncodedBuffer_test.cpp
@@ -15,12 +15,16 @@
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
 
+#include <unistd.h>
+
 using namespace android::util;
 using android::sp;
 
-constexpr size_t TEST_CHUNK_SIZE = 16UL;
-constexpr size_t TEST_CHUNK_HALF_SIZE = TEST_CHUNK_SIZE / 2;
-constexpr size_t TEST_CHUNK_3X_SIZE = 3 * TEST_CHUNK_SIZE;
+constexpr size_t __TEST_CHUNK_SIZE = 16UL;
+const size_t kPageSize = getpagesize();
+const size_t TEST_CHUNK_SIZE = (__TEST_CHUNK_SIZE + (kPageSize - 1)) & ~(kPageSize - 1);
+const size_t TEST_CHUNK_HALF_SIZE = TEST_CHUNK_SIZE / 2;
+const size_t TEST_CHUNK_3X_SIZE = 3 * TEST_CHUNK_SIZE;
 
 static void expectPointer(EncodedBuffer::Pointer* p, size_t pos) {
     EXPECT_EQ(p->pos(), pos);
@@ -34,13 +38,13 @@
     expectPointer(buffer->wp(), 0);
     EXPECT_EQ(buffer->currentToWrite(), TEST_CHUNK_SIZE);
     for (size_t i = 0; i < TEST_CHUNK_HALF_SIZE; i++) {
-        buffer->writeRawByte(50 + i);
+        buffer->writeRawByte(static_cast<uint8_t>(50 + i));
     }
     EXPECT_EQ(buffer->size(), TEST_CHUNK_HALF_SIZE);
     expectPointer(buffer->wp(), TEST_CHUNK_HALF_SIZE);
     EXPECT_EQ(buffer->currentToWrite(), TEST_CHUNK_HALF_SIZE);
     for (size_t i = 0; i < TEST_CHUNK_SIZE; i++) {
-        buffer->writeRawByte(80 + i);
+        buffer->writeRawByte(static_cast<uint8_t>(80 + i));
     }
     EXPECT_EQ(buffer->size(), TEST_CHUNK_SIZE + TEST_CHUNK_HALF_SIZE);
     expectPointer(buffer->wp(), TEST_CHUNK_SIZE + TEST_CHUNK_HALF_SIZE);
@@ -49,10 +53,10 @@
     // verifies the buffer's data
     expectPointer(buffer->ep(), 0);
     for (size_t i = 0; i < TEST_CHUNK_HALF_SIZE; i++) {
-        EXPECT_EQ(buffer->readRawByte(), 50 + i);
+        EXPECT_EQ(buffer->readRawByte(), static_cast<uint8_t>(50 + i));
     }
     for (size_t i = 0; i < TEST_CHUNK_SIZE; i++) {
-        EXPECT_EQ(buffer->readRawByte(), 80 + i);
+        EXPECT_EQ(buffer->readRawByte(), static_cast<uint8_t>(80 + i));
     }
 
     // clears the buffer
diff --git a/location/TEST_MAPPING b/location/TEST_MAPPING
index 214d2f3..f5deb2b 100644
--- a/location/TEST_MAPPING
+++ b/location/TEST_MAPPING
@@ -1,7 +1,13 @@
 {
   "presubmit": [
     {
-      "name": "CtsLocationFineTestCases"
+      "name": "CtsLocationFineTestCases",
+      "options": [
+          {
+             // TODO: Wait for test to deflake - b/293934372
+             "exclude-filter":"android.location.cts.fine.ScanningSettingsTest"
+          }
+      ]
     },
     {
       "name": "CtsLocationCoarseTestCases"
@@ -16,4 +22,4 @@
       }]
     }
   ]
-}
\ No newline at end of file
+}
diff --git a/location/java/android/location/GnssMeasurementRequest.java b/location/java/android/location/GnssMeasurementRequest.java
index 3f3ad75..65af392 100644
--- a/location/java/android/location/GnssMeasurementRequest.java
+++ b/location/java/android/location/GnssMeasurementRequest.java
@@ -16,11 +16,15 @@
 
 package android.location;
 
+import android.Manifest;
 import android.annotation.IntRange;
 import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.RequiresPermission;
 import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
+import android.os.WorkSource;
 import android.util.TimeUtils;
 
 import com.android.internal.util.Preconditions;
@@ -46,15 +50,16 @@
     private final boolean mCorrelationVectorOutputsEnabled;
     private final boolean mFullTracking;
     private final int mIntervalMillis;
-
+    private WorkSource mWorkSource;
     /**
      * Creates a {@link GnssMeasurementRequest} with a full list of parameters.
      */
     private GnssMeasurementRequest(boolean fullTracking, boolean correlationVectorOutputsEnabled,
-            int intervalMillis) {
+            int intervalMillis, WorkSource workSource) {
         mFullTracking = fullTracking;
         mCorrelationVectorOutputsEnabled = correlationVectorOutputsEnabled;
         mIntervalMillis = intervalMillis;
+        mWorkSource = Objects.requireNonNull(workSource);
     }
 
     /**
@@ -107,14 +112,31 @@
         return mIntervalMillis;
     }
 
+    /**
+     * Returns the work source used for power blame for this request. If empty (i.e.,
+     * {@link WorkSource#isEmpty()} is {@code true}, the system is free to assign power blame as it
+     * deems most appropriate.
+     *
+     * @return the work source used for power blame for this request
+     *
+     * @hide
+     */
+    @SystemApi
+    public @NonNull WorkSource getWorkSource() {
+        return mWorkSource;
+    }
+
     @NonNull
     public static final Creator<GnssMeasurementRequest> CREATOR =
             new Creator<GnssMeasurementRequest>() {
                 @Override
                 @NonNull
                 public GnssMeasurementRequest createFromParcel(@NonNull Parcel parcel) {
-                    return new GnssMeasurementRequest(parcel.readBoolean(), parcel.readBoolean(),
-                            parcel.readInt());
+                    return new GnssMeasurementRequest(
+                            /* fullTracking= */ parcel.readBoolean(),
+                            /* correlationVectorOutputsEnabled= */ parcel.readBoolean(),
+                            /* intervalMillis= */ parcel.readInt(),
+                            /* workSource= */ parcel.readTypedObject(WorkSource.CREATOR));
                 }
 
                 @Override
@@ -128,6 +150,7 @@
         parcel.writeBoolean(mFullTracking);
         parcel.writeBoolean(mCorrelationVectorOutputsEnabled);
         parcel.writeInt(mIntervalMillis);
+        parcel.writeTypedObject(mWorkSource, 0);
     }
 
     @NonNull
@@ -147,6 +170,9 @@
         if (mCorrelationVectorOutputsEnabled) {
             s.append(", CorrelationVectorOutputs");
         }
+        if (mWorkSource != null && !mWorkSource.isEmpty()) {
+            s.append(", ").append(mWorkSource);
+        }
         s.append(']');
         return s.toString();
     }
@@ -165,12 +191,16 @@
         if (mIntervalMillis != other.mIntervalMillis) {
             return false;
         }
+        if (!Objects.equals(mWorkSource, other.mWorkSource)) {
+            return false;
+        }
         return true;
     }
 
     @Override
     public int hashCode() {
-        return Objects.hash(mFullTracking, mCorrelationVectorOutputsEnabled, mIntervalMillis);
+        return Objects.hash(mFullTracking, mCorrelationVectorOutputsEnabled, mIntervalMillis,
+                mWorkSource);
     }
 
     @Override
@@ -183,6 +213,7 @@
         private boolean mCorrelationVectorOutputsEnabled;
         private boolean mFullTracking;
         private int mIntervalMillis;
+        private WorkSource mWorkSource;
 
         /**
          * Constructs a {@link Builder} instance.
@@ -197,6 +228,7 @@
             mCorrelationVectorOutputsEnabled = request.isCorrelationVectorOutputsEnabled();
             mFullTracking = request.isFullTracking();
             mIntervalMillis = request.getIntervalMillis();
+            mWorkSource = request.getWorkSource();
         }
 
         /**
@@ -255,11 +287,29 @@
             return this;
         }
 
+        /**
+         * Sets the work source to use for power blame for this request. Passing in null or leaving
+         * it unset will be an empty WorkSource, which implies the system is free to assign power
+         * blame as it determines best for this request (which usually means blaming the owner of
+         * the GnssMeasurement listener).
+         *
+         * <p>Permissions enforcement occurs when resulting request is actually used, not when this
+         * method is invoked.
+         *
+         * @hide
+         */
+        @SystemApi
+        @RequiresPermission(Manifest.permission.UPDATE_DEVICE_STATS)
+        public @NonNull Builder setWorkSource(@Nullable WorkSource workSource) {
+            mWorkSource = workSource;
+            return this;
+        }
+
         /** Builds a {@link GnssMeasurementRequest} instance as specified by this builder. */
         @NonNull
         public GnssMeasurementRequest build() {
             return new GnssMeasurementRequest(mFullTracking, mCorrelationVectorOutputsEnabled,
-                    mIntervalMillis);
+                    mIntervalMillis, new WorkSource(mWorkSource));
         }
     }
 }
diff --git a/location/java/android/location/LocationManagerInternal.java b/location/java/android/location/LocationManagerInternal.java
index d59756d..a48cc19 100644
--- a/location/java/android/location/LocationManagerInternal.java
+++ b/location/java/android/location/LocationManagerInternal.java
@@ -87,12 +87,6 @@
     public abstract boolean isProvider(@Nullable String provider, @NonNull CallerIdentity identity);
 
     /**
-     * Should only be used by GNSS code.
-     */
-    // TODO: there is no reason for this to exist as part of any API. move all the logic into gnss
-    public abstract void sendNiResponse(int notifId, int userResponse);
-
-    /**
      * Returns the GNSS provided time.
      *
      * @return LocationTime object that includes the current time, according to the GNSS location
diff --git a/location/java/com/android/internal/location/GpsNetInitiatedHandler.java b/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
index fba4249..ee2510f 100644
--- a/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
+++ b/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
@@ -18,28 +18,14 @@
 
 import android.Manifest;
 import android.annotation.RequiresPermission;
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.content.BroadcastReceiver;
 import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.location.INetInitiatedListener;
 import android.location.LocationManager;
-import android.os.RemoteException;
 import android.os.SystemClock;
-import android.os.UserHandle;
 import android.telephony.TelephonyCallback;
 import android.telephony.TelephonyManager;
 import android.telephony.emergency.EmergencyNumber;
 import android.util.Log;
 
-import com.android.internal.R;
-import com.android.internal.notification.SystemNotificationChannels;
-import com.android.internal.telephony.GsmAlphabet;
-
-import java.io.UnsupportedEncodingException;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -53,95 +39,20 @@
 
     private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
 
-    // string constants for defining data fields in NI Intent
-    public static final String NI_INTENT_KEY_NOTIF_ID = "notif_id";
-    public static final String NI_INTENT_KEY_TITLE = "title";
-    public static final String NI_INTENT_KEY_MESSAGE = "message";
-    public static final String NI_INTENT_KEY_TIMEOUT = "timeout";
-    public static final String NI_INTENT_KEY_DEFAULT_RESPONSE = "default_resp";
-
-    // the extra command to send NI response to GnssLocationProvider
-    public static final String NI_RESPONSE_EXTRA_CMD = "send_ni_response";
-
-    // the extra command parameter names in the Bundle
-    public static final String NI_EXTRA_CMD_NOTIF_ID = "notif_id";
-    public static final String NI_EXTRA_CMD_RESPONSE = "response";
-
-    // these need to match GpsNiType constants in gps_ni.h
-    public static final int GPS_NI_TYPE_VOICE = 1;
-    public static final int GPS_NI_TYPE_UMTS_SUPL = 2;
-    public static final int GPS_NI_TYPE_UMTS_CTRL_PLANE = 3;
-    public static final int GPS_NI_TYPE_EMERGENCY_SUPL = 4;
-
-    // these need to match GpsUserResponseType constants in gps_ni.h
-    public static final int GPS_NI_RESPONSE_ACCEPT = 1;
-    public static final int GPS_NI_RESPONSE_DENY = 2;
-    public static final int GPS_NI_RESPONSE_NORESP = 3;
-    public static final int GPS_NI_RESPONSE_IGNORE = 4;
-
-    // these need to match GpsNiNotifyFlags constants in gps_ni.h
-    public static final int GPS_NI_NEED_NOTIFY = 0x0001;
-    public static final int GPS_NI_NEED_VERIFY = 0x0002;
-    public static final int GPS_NI_PRIVACY_OVERRIDE = 0x0004;
-
-    // these need to match GpsNiEncodingType in gps_ni.h
-    public static final int GPS_ENC_NONE = 0;
-    public static final int GPS_ENC_SUPL_GSM_DEFAULT = 1;
-    public static final int GPS_ENC_SUPL_UTF8 = 2;
-    public static final int GPS_ENC_SUPL_UCS2 = 3;
-    public static final int GPS_ENC_UNKNOWN = -1;
-
     private final Context mContext;
     private final TelephonyManager mTelephonyManager;
 
     // parent gps location provider
     private final LocationManager mLocationManager;
 
-    // configuration of notificaiton behavior
-    private boolean mPlaySounds = false;
-    private boolean mPopupImmediately = true;
-
-    // read the SUPL_ES form gps.conf
-    private volatile boolean mIsSuplEsEnabled;
-
     // Set to true if the phone is having emergency call.
     private volatile boolean mIsInEmergencyCall;
 
-    // If Location function is enabled.
-    private volatile boolean mIsLocationEnabled = false;
-
-    private final INetInitiatedListener mNetInitiatedListener;
-
-    // Set to true if string from HAL is encoded as Hex, e.g., "3F0039"
-    @UnsupportedAppUsage
-    static private boolean mIsHexInput = true;
 
     // End time of emergency call, and extension, if set
     private volatile long mCallEndElapsedRealtimeMillis = 0;
     private volatile long mEmergencyExtensionMillis = 0;
 
-    public static class GpsNiNotification
-    {
-        @android.compat.annotation.UnsupportedAppUsage
-        public GpsNiNotification() {
-        }
-        public int notificationId;
-        public int niType;
-        public boolean needNotify;
-        public boolean needVerify;
-        public boolean privacyOverride;
-        public int timeout;
-        public int defaultResponse;
-        @UnsupportedAppUsage
-        public String requestorId;
-        @UnsupportedAppUsage
-        public String text;
-        @UnsupportedAppUsage
-        public int requestorIdEncoding;
-        @UnsupportedAppUsage
-        public int textEncoding;
-    }
-
     /** Callbacks for Emergency call events. */
     public interface EmergencyCallCallback {
         /** Callback invoked when an emergency call starts */
@@ -182,72 +93,20 @@
     // reference here.
     private final EmergencyCallListener mEmergencyCallListener = new EmergencyCallListener();
 
-    /**
-     * The notification that is shown when a network-initiated notification
-     * (and verification) event is received.
-     * <p>
-     * This is lazily created, so use {@link #setNINotification()}.
-     */
-    private Notification.Builder mNiNotificationBuilder;
-
     private final EmergencyCallCallback mEmergencyCallCallback;
 
     public GpsNetInitiatedHandler(Context context,
-                                  INetInitiatedListener netInitiatedListener,
                                   EmergencyCallCallback emergencyCallCallback,
                                   boolean isSuplEsEnabled) {
         mContext = context;
-
-        if (netInitiatedListener == null) {
-            throw new IllegalArgumentException("netInitiatedListener is null");
-        } else {
-            mNetInitiatedListener = netInitiatedListener;
-        }
         mEmergencyCallCallback = emergencyCallCallback;
 
-        setSuplEsEnabled(isSuplEsEnabled);
         mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
-        updateLocationMode();
         mTelephonyManager =
             (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
         mTelephonyManager.registerTelephonyCallback(mContext.getMainExecutor(),
                 mEmergencyCallListener);
 
-        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
-
-            @Override
-            public void onReceive(Context context, Intent intent) {
-                String action = intent.getAction();
-                if (action.equals(LocationManager.MODE_CHANGED_ACTION)) {
-                    updateLocationMode();
-                    if (DEBUG) Log.d(TAG, "location enabled :" + getLocationEnabled());
-                }
-            }
-        };
-        mContext.registerReceiver(broadcastReceiver,
-                new IntentFilter(LocationManager.MODE_CHANGED_ACTION));
-    }
-
-    public void setSuplEsEnabled(boolean isEnabled) {
-        mIsSuplEsEnabled = isEnabled;
-    }
-
-    public boolean getSuplEsEnabled() {
-        return mIsSuplEsEnabled;
-    }
-
-    /**
-     * Updates Location enabler based on location setting.
-     */
-    public void updateLocationMode() {
-        mIsLocationEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
-    }
-
-    /**
-     * Checks if user agreed to use location.
-     */
-    public boolean getLocationEnabled() {
-        return mIsLocationEnabled;
     }
 
     /**
@@ -289,346 +148,4 @@
     public void setEmergencyExtensionSeconds(int emergencyExtensionSeconds) {
         mEmergencyExtensionMillis = TimeUnit.SECONDS.toMillis(emergencyExtensionSeconds);
     }
-
-    // Handles NI events from HAL
-    @UnsupportedAppUsage
-    public void handleNiNotification(GpsNiNotification notif) {
-        if (DEBUG) Log.d(TAG, "in handleNiNotification () :"
-                        + " notificationId: " + notif.notificationId
-                        + " requestorId: " + notif.requestorId
-                        + " text: " + notif.text
-                        + " mIsSuplEsEnabled" + getSuplEsEnabled()
-                        + " mIsLocationEnabled" + getLocationEnabled());
-
-        if (getSuplEsEnabled()) {
-            handleNiInEs(notif);
-        } else {
-            handleNi(notif);
-        }
-
-        //////////////////////////////////////////////////////////////////////////
-        //   A note about timeout
-        //   According to the protocol, in the need_notify and need_verify case,
-        //   a default response should be sent when time out.
-        //
-        //   In some GPS hardware, the GPS driver (under HAL) can handle the timeout case
-        //   and this class GpsNetInitiatedHandler does not need to do anything.
-        //
-        //   However, the UI should at least close the dialog when timeout. Further,
-        //   for more general handling, timeout response should be added to the Handler here.
-        //
-    }
-
-    // handle NI form HAL when SUPL_ES is disabled.
-    private void handleNi(GpsNiNotification notif) {
-        if (DEBUG) Log.d(TAG, "in handleNi () :"
-                        + " needNotify: " + notif.needNotify
-                        + " needVerify: " + notif.needVerify
-                        + " privacyOverride: " + notif.privacyOverride
-                        + " mPopupImmediately: " + mPopupImmediately
-                        + " mInEmergency: " + getInEmergency());
-
-        if (!getLocationEnabled() && !getInEmergency()) {
-            // Location is currently disabled, ignore all NI requests.
-            try {
-                mNetInitiatedListener.sendNiResponse(notif.notificationId,
-                                                     GPS_NI_RESPONSE_IGNORE);
-            } catch (RemoteException e) {
-                Log.e(TAG, "RemoteException in sendNiResponse");
-            }
-        }
-        if (notif.needNotify) {
-        // If NI does not need verify or the dialog is not requested
-        // to pop up immediately, the dialog box will not pop up.
-            if (notif.needVerify && mPopupImmediately) {
-                // Popup the dialog box now
-                openNiDialog(notif);
-            } else {
-                // Show the notification
-                setNiNotification(notif);
-            }
-        }
-        // ACCEPT cases: 1. Notify, no verify; 2. no notify, no verify;
-        // 3. privacy override.
-        if (!notif.needVerify || notif.privacyOverride) {
-            try {
-                mNetInitiatedListener.sendNiResponse(notif.notificationId,
-                                                     GPS_NI_RESPONSE_ACCEPT);
-            } catch (RemoteException e) {
-                Log.e(TAG, "RemoteException in sendNiResponse");
-            }
-        }
-    }
-
-    // handle NI from HAL when the SUPL_ES is enabled
-    private void handleNiInEs(GpsNiNotification notif) {
-
-        if (DEBUG) Log.d(TAG, "in handleNiInEs () :"
-                    + " niType: " + notif.niType
-                    + " notificationId: " + notif.notificationId);
-
-        // UE is in emergency mode when in emergency call mode or in emergency call back mode
-        /*
-           1. When SUPL ES bit is off and UE is not in emergency mode:
-                  Call handleNi() to do legacy behaviour.
-           2. When SUPL ES bit is on and UE is in emergency mode:
-                  Call handleNi() to do acceptance behaviour.
-           3. When SUPL ES bit is off but UE is in emergency mode:
-                  Ignore the emergency SUPL INIT.
-           4. When SUPL ES bit is on but UE is not in emergency mode:
-                  Ignore the emergency SUPL INIT.
-        */
-        boolean isNiTypeES = (notif.niType == GPS_NI_TYPE_EMERGENCY_SUPL);
-        if (isNiTypeES != getInEmergency()) {
-            try {
-                mNetInitiatedListener.sendNiResponse(notif.notificationId,
-                                                     GPS_NI_RESPONSE_IGNORE);
-            } catch (RemoteException e) {
-                Log.e(TAG, "RemoteException in sendNiResponse");
-            }
-        } else {
-            handleNi(notif);
-        }
-    }
-
-    /**
-     * Posts a notification in the status bar using the contents in {@code notif} object.
-     */
-    private synchronized void setNiNotification(GpsNiNotification notif) {
-        NotificationManager notificationManager = (NotificationManager) mContext
-                .getSystemService(Context.NOTIFICATION_SERVICE);
-        if (notificationManager == null) {
-            return;
-        }
-
-        String title = getNotifTitle(notif, mContext);
-        String message = getNotifMessage(notif, mContext);
-
-        if (DEBUG) Log.d(TAG, "setNiNotification, notifyId: " + notif.notificationId +
-                ", title: " + title +
-                ", message: " + message);
-
-        // Construct Notification
-        if (mNiNotificationBuilder == null) {
-            mNiNotificationBuilder = new Notification.Builder(mContext,
-                SystemNotificationChannels.NETWORK_ALERTS)
-                    .setSmallIcon(com.android.internal.R.drawable.stat_sys_gps_on)
-                    .setWhen(0)
-                    .setOngoing(true)
-                    .setAutoCancel(true)
-                    .setColor(mContext.getColor(
-                            com.android.internal.R.color.system_notification_accent_color));
-        }
-
-        if (mPlaySounds) {
-            mNiNotificationBuilder.setDefaults(Notification.DEFAULT_SOUND);
-        } else {
-            mNiNotificationBuilder.setDefaults(0);
-        }
-
-        mNiNotificationBuilder.setTicker(getNotifTicker(notif, mContext))
-                .setContentTitle(title)
-                .setContentText(message);
-
-        notificationManager.notifyAsUser(null, notif.notificationId, mNiNotificationBuilder.build(),
-                UserHandle.ALL);
-    }
-
-    // Opens the notification dialog and waits for user input
-    private void openNiDialog(GpsNiNotification notif)
-    {
-        Intent intent = getDlgIntent(notif);
-
-        if (DEBUG) Log.d(TAG, "openNiDialog, notifyId: " + notif.notificationId +
-                ", requestorId: " + notif.requestorId +
-                ", text: " + notif.text);
-
-        mContext.startActivity(intent);
-    }
-
-    // Construct the intent for bringing up the dialog activity, which shows the
-    // notification and takes user input
-    private Intent getDlgIntent(GpsNiNotification notif)
-    {
-        Intent intent = new Intent();
-        String title = getDialogTitle(notif, mContext);
-        String message = getDialogMessage(notif, mContext);
-
-        // directly bring up the NI activity
-        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
-        intent.setClass(mContext, com.android.internal.app.NetInitiatedActivity.class);
-
-        // put data in the intent
-        intent.putExtra(NI_INTENT_KEY_NOTIF_ID, notif.notificationId);
-        intent.putExtra(NI_INTENT_KEY_TITLE, title);
-        intent.putExtra(NI_INTENT_KEY_MESSAGE, message);
-        intent.putExtra(NI_INTENT_KEY_TIMEOUT, notif.timeout);
-        intent.putExtra(NI_INTENT_KEY_DEFAULT_RESPONSE, notif.defaultResponse);
-
-        if (DEBUG) Log.d(TAG, "generateIntent, title: " + title + ", message: " + message +
-                ", timeout: " + notif.timeout);
-
-        return intent;
-    }
-
-    // Converts a string (or Hex string) to a char array
-    static byte[] stringToByteArray(String original, boolean isHex)
-    {
-        int length = isHex ? original.length() / 2 : original.length();
-        byte[] output = new byte[length];
-        int i;
-
-        if (isHex)
-        {
-            for (i = 0; i < length; i++)
-            {
-                output[i] = (byte) Integer.parseInt(original.substring(i*2, i*2+2), 16);
-            }
-        }
-        else {
-            for (i = 0; i < length; i++)
-            {
-                output[i] = (byte) original.charAt(i);
-            }
-        }
-
-        return output;
-    }
-
-    /**
-     * Unpacks an byte array containing 7-bit packed characters into a String.
-     *
-     * @param input a 7-bit packed char array
-     * @return the unpacked String
-     */
-    static String decodeGSMPackedString(byte[] input)
-    {
-        final char PADDING_CHAR = 0x00;
-        int lengthBytes = input.length;
-        int lengthSeptets = (lengthBytes * 8) / 7;
-        String decoded;
-
-        /* Special case where the last 7 bits in the last byte could hold a valid
-         * 7-bit character or a padding character. Drop the last 7-bit character
-         * if it is a padding character.
-         */
-        if (lengthBytes % 7 == 0) {
-            if (lengthBytes > 0) {
-                if ((input[lengthBytes - 1] >> 1) == PADDING_CHAR) {
-                    lengthSeptets = lengthSeptets - 1;
-                }
-            }
-        }
-
-        decoded = GsmAlphabet.gsm7BitPackedToString(input, 0, lengthSeptets);
-
-        // Return "" if decoding of GSM packed string fails
-        if (null == decoded) {
-            Log.e(TAG, "Decoding of GSM packed string failed");
-            decoded = "";
-        }
-
-        return decoded;
-    }
-
-    static String decodeUTF8String(byte[] input)
-    {
-        String decoded = "";
-        try {
-            decoded = new String(input, "UTF-8");
-        }
-        catch (UnsupportedEncodingException e)
-        {
-            throw new AssertionError();
-        }
-        return decoded;
-    }
-
-    static String decodeUCS2String(byte[] input)
-    {
-        String decoded = "";
-        try {
-            decoded = new String(input, "UTF-16");
-        }
-        catch (UnsupportedEncodingException e)
-        {
-            throw new AssertionError();
-        }
-        return decoded;
-    }
-
-    /** Decode NI string
-     *
-     * @param original   The text string to be decoded
-     * @param isHex      Specifies whether the content of the string has been encoded as a Hex string. Encoding
-     *                   a string as Hex can allow zeros inside the coded text.
-     * @param coding     Specifies the coding scheme of the string, such as GSM, UTF8, UCS2, etc. This coding scheme
-     *                      needs to match those used passed to HAL from the native GPS driver. Decoding is done according
-     *                   to the <code> coding </code>, after a Hex string is decoded. Generally, if the
-     *                   notification strings don't need further decoding, <code> coding </code> encoding can be
-     *                   set to -1, and <code> isHex </code> can be false.
-     * @return the decoded string
-     */
-    @UnsupportedAppUsage
-    static private String decodeString(String original, boolean isHex, int coding)
-    {
-        if (coding == GPS_ENC_NONE || coding == GPS_ENC_UNKNOWN) {
-            return original;
-        }
-
-        byte[] input = stringToByteArray(original, isHex);
-
-        switch (coding) {
-            case GPS_ENC_SUPL_GSM_DEFAULT:
-                return decodeGSMPackedString(input);
-
-            case GPS_ENC_SUPL_UTF8:
-                return decodeUTF8String(input);
-
-            case GPS_ENC_SUPL_UCS2:
-                return decodeUCS2String(input);
-
-            default:
-                Log.e(TAG, "Unknown encoding " + coding + " for NI text " + original);
-                return original;
-        }
-    }
-
-    // change this to configure notification display
-    static private String getNotifTicker(GpsNiNotification notif, Context context)
-    {
-        String ticker = String.format(context.getString(R.string.gpsNotifTicker),
-                decodeString(notif.requestorId, mIsHexInput, notif.requestorIdEncoding),
-                decodeString(notif.text, mIsHexInput, notif.textEncoding));
-        return ticker;
-    }
-
-    // change this to configure notification display
-    static private String getNotifTitle(GpsNiNotification notif, Context context)
-    {
-        String title = String.format(context.getString(R.string.gpsNotifTitle));
-        return title;
-    }
-
-    // change this to configure notification display
-    static private String getNotifMessage(GpsNiNotification notif, Context context)
-    {
-        String message = String.format(context.getString(R.string.gpsNotifMessage),
-                decodeString(notif.requestorId, mIsHexInput, notif.requestorIdEncoding),
-                decodeString(notif.text, mIsHexInput, notif.textEncoding));
-        return message;
-    }
-
-    // change this to configure dialog display (for verification)
-    static public String getDialogTitle(GpsNiNotification notif, Context context)
-    {
-        return getNotifTitle(notif, context);
-    }
-
-    // change this to configure dialog display (for verification)
-    static private String getDialogMessage(GpsNiNotification notif, Context context)
-    {
-        return getNotifMessage(notif, context);
-    }
-
 }
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index e8c9d0d..c3087bc 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -6915,7 +6915,10 @@
 
     /**
      * @hide
-     * Returns whether CSD is enabled and supported by the HAL on this device.
+     * Returns whether CSD is enabled and supported by the current active audio module HAL.
+     * This method will return {@code false) for setups in which CSD as a feature is available
+     * (see {@link AudioManager#isCsdAsAFeatureAvailable()}) and not enabled (see
+     * {@link AudioManager#isCsdAsAFeatureEnabled()}).
      */
     @TestApi
     @RequiresPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS_PRIVILEGED)
@@ -6929,6 +6932,49 @@
 
     /**
      * @hide
+     * Returns whether CSD as a feature can be manipulated by a client. This method
+     * returns {@code true} in countries where there isn't a safe hearing regulation
+     * enforced.
+     */
+    @RequiresPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS_PRIVILEGED)
+    public boolean isCsdAsAFeatureAvailable() {
+        try {
+            return getService().isCsdAsAFeatureAvailable();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * @hide
+     * Returns {@code true} if the client has enabled CSD. This function should only
+     * be called if {@link AudioManager#isCsdAsAFeatureAvailable()} returns {@code true}.
+     */
+    @RequiresPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS_PRIVILEGED)
+    public boolean isCsdAsAFeatureEnabled() {
+        try {
+            return getService().isCsdAsAFeatureEnabled();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * @hide
+     * Enables/disables the CSD feature. This function should only be called if
+     * {@link AudioManager#isCsdAsAFeatureAvailable()} returns {@code true}.
+     */
+    @RequiresPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS_PRIVILEGED)
+    public void setCsdAsAFeatureEnabled(boolean csdToggleValue) {
+        try {
+            getService().setCsdAsAFeatureEnabled(csdToggleValue);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * @hide
      * Describes an audio device that has not been categorized with a specific
      * audio type.
      */
diff --git a/media/java/android/media/IAudioService.aidl b/media/java/android/media/IAudioService.aidl
index b2466e9..5cbb4e5 100644
--- a/media/java/android/media/IAudioService.aidl
+++ b/media/java/android/media/IAudioService.aidl
@@ -325,6 +325,15 @@
     boolean isCsdEnabled();
 
     @EnforcePermission("MODIFY_AUDIO_SETTINGS_PRIVILEGED")
+    boolean isCsdAsAFeatureAvailable();
+
+    @EnforcePermission("MODIFY_AUDIO_SETTINGS_PRIVILEGED")
+    boolean isCsdAsAFeatureEnabled();
+
+    @EnforcePermission("MODIFY_AUDIO_SETTINGS_PRIVILEGED")
+    oneway void setCsdAsAFeatureEnabled(boolean csdToggleValue);
+
+    @EnforcePermission("MODIFY_AUDIO_SETTINGS_PRIVILEGED")
     oneway void setBluetoothAudioDeviceCategory(in String address, boolean isBle, int deviceType);
 
     @EnforcePermission("MODIFY_AUDIO_SETTINGS_PRIVILEGED")
diff --git a/media/java/android/media/MediaRouter2.java b/media/java/android/media/MediaRouter2.java
index 94a061a..d6921c8 100644
--- a/media/java/android/media/MediaRouter2.java
+++ b/media/java/android/media/MediaRouter2.java
@@ -985,6 +985,11 @@
 
     void onRequestCreateControllerByManagerOnHandler(
             RoutingSessionInfo oldSession, MediaRoute2Info route, long managerRequestId) {
+        Log.i(
+                TAG,
+                TextUtils.formatSimple(
+                        "requestCreateSessionByManager | requestId: %d, oldSession: %s, route: %s",
+                        managerRequestId, oldSession, route));
         RoutingController controller;
         if (oldSession.isSystemSession()) {
             controller = getSystemController();
diff --git a/media/java/android/media/RingtoneManager.java b/media/java/android/media/RingtoneManager.java
index 0ad8c24..0ff1b1e 100644
--- a/media/java/android/media/RingtoneManager.java
+++ b/media/java/android/media/RingtoneManager.java
@@ -42,7 +42,9 @@
 import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.os.UserManager;
+import android.provider.BaseColumns;
 import android.provider.MediaStore;
+import android.provider.MediaStore.Audio.AudioColumns;
 import android.provider.MediaStore.MediaColumns;
 import android.provider.Settings;
 import android.provider.Settings.System;
@@ -543,6 +545,95 @@
         return getUriFromCursor(mContext, mCursor);
     }
 
+    /**
+     * Gets the valid ringtone uri by a given uri string and ringtone type for the restore purpose.
+     *
+     * @param contentResolver ContentResolver to execute media query.
+     * @param value a canonicalized uri which refers to the ringtone.
+     * @param ringtoneType an integer representation of the kind of uri that is being restored, can
+     *     be RingtoneManager.TYPE_RINGTONE, RingtoneManager.TYPE_NOTIFICATION, or
+     *     RingtoneManager.TYPE_ALARM.
+     * @hide
+     */
+    public static @Nullable Uri getRingtoneUriForRestore(
+            @NonNull ContentResolver contentResolver, @Nullable String value, int ringtoneType)
+            throws FileNotFoundException, IllegalArgumentException {
+        if (value == null) {
+            // Return a valid null. It means the null value is intended instead of a failure.
+            return null;
+        }
+
+        Uri ringtoneUri;
+        final Uri canonicalUri = Uri.parse(value);
+
+        // Try to get the media uri via the regular uncanonicalize method first.
+        ringtoneUri = contentResolver.uncanonicalize(canonicalUri);
+        if (ringtoneUri != null) {
+            // Canonicalize it to make the result contain the right metadata of the media asset.
+            ringtoneUri = contentResolver.canonicalize(ringtoneUri);
+            return ringtoneUri;
+        }
+
+        // Query the media by title and ringtone type.
+        final String title = canonicalUri.getQueryParameter(AudioColumns.TITLE);
+        Uri baseUri = ContentUris.removeId(canonicalUri).buildUpon().clearQuery().build();
+        String ringtoneTypeSelection = "";
+        switch (ringtoneType) {
+            case RingtoneManager.TYPE_RINGTONE:
+                ringtoneTypeSelection = MediaStore.Audio.AudioColumns.IS_RINGTONE;
+                break;
+            case RingtoneManager.TYPE_NOTIFICATION:
+                ringtoneTypeSelection = MediaStore.Audio.AudioColumns.IS_NOTIFICATION;
+                break;
+            case RingtoneManager.TYPE_ALARM:
+                ringtoneTypeSelection = MediaStore.Audio.AudioColumns.IS_ALARM;
+                break;
+            default:
+                throw new IllegalArgumentException("Unknown ringtone type: " + ringtoneType);
+        }
+
+        final String selection = ringtoneTypeSelection + "=1 AND " + AudioColumns.TITLE + "=?";
+        Cursor cursor = null;
+        try {
+            cursor =
+                    contentResolver.query(
+                            baseUri,
+                            /* projection */ new String[] {BaseColumns._ID},
+                            /* selection */ selection,
+                            /* selectionArgs */ new String[] {title},
+                            /* sortOrder */ null,
+                            /* cancellationSignal */ null);
+
+        } catch (IllegalArgumentException e) {
+            throw new FileNotFoundException("Volume not found for " + baseUri);
+        }
+        if (cursor == null) {
+            throw new FileNotFoundException("Missing cursor for " + baseUri);
+        } else if (cursor.getCount() == 0) {
+            FileUtils.closeQuietly(cursor);
+            throw new FileNotFoundException("No item found for " + baseUri);
+        } else if (cursor.getCount() > 1) {
+            // Find more than 1 result.
+            // We are not sure which one is the right ringtone file so just abandon this case.
+            FileUtils.closeQuietly(cursor);
+            throw new FileNotFoundException(
+                    "Find multiple ringtone candidates by title+ringtone_type query: count: "
+                            + cursor.getCount());
+        }
+        if (cursor.moveToFirst()) {
+            ringtoneUri = ContentUris.withAppendedId(baseUri, cursor.getLong(0));
+            FileUtils.closeQuietly(cursor);
+        } else {
+            FileUtils.closeQuietly(cursor);
+            throw new FileNotFoundException("Failed to read row from the result.");
+        }
+
+        // Canonicalize it to make the result contain the right metadata of the media asset.
+        ringtoneUri = contentResolver.canonicalize(ringtoneUri);
+        Log.v(TAG, "Find a valid result: " + ringtoneUri);
+        return ringtoneUri;
+    }
+
     private static Uri getUriFromCursor(Context context, Cursor cursor) {
         final Uri uri = ContentUris.withAppendedId(Uri.parse(cursor.getString(URI_COLUMN_INDEX)),
                 cursor.getLong(ID_COLUMN_INDEX));
diff --git a/media/java/android/media/projection/MediaProjection.java b/media/java/android/media/projection/MediaProjection.java
index fb72c7b..223b432c 100644
--- a/media/java/android/media/projection/MediaProjection.java
+++ b/media/java/android/media/projection/MediaProjection.java
@@ -83,6 +83,7 @@
         try {
             mImpl.start(new MediaProjectionCallback());
         } catch (RemoteException e) {
+            Log.e(TAG, "Content Recording: Failed to start media projection", e);
             throw new RuntimeException("Failed to start media projection", e);
         }
         mDisplayManager = displayManager;
@@ -105,11 +106,18 @@
      * @see #unregisterCallback
      */
     public void registerCallback(@NonNull Callback callback, @Nullable Handler handler) {
-        final Callback c = Objects.requireNonNull(callback);
-        if (handler == null) {
-            handler = new Handler();
+        try {
+            final Callback c = Objects.requireNonNull(callback);
+            if (handler == null) {
+                handler = new Handler();
+            }
+            mCallbacks.put(c, new CallbackRecord(c, handler));
+        } catch (NullPointerException e) {
+            Log.e(TAG, "Content Recording: cannot register null Callback", e);
+            throw e;
+        } catch (RuntimeException e) {
+            Log.e(TAG, "Content Recording: failed to create new Handler to register Callback", e);
         }
-        mCallbacks.put(c, new CallbackRecord(c, handler));
     }
 
     /**
@@ -120,8 +128,13 @@
      * @see #registerCallback
      */
     public void unregisterCallback(@NonNull Callback callback) {
-        final Callback c = Objects.requireNonNull(callback);
-        mCallbacks.remove(c);
+        try {
+            final Callback c = Objects.requireNonNull(callback);
+            mCallbacks.remove(c);
+        } catch (NullPointerException e) {
+            Log.d(TAG, "Content Recording: cannot unregister null Callback", e);
+            throw e;
+        }
     }
 
     /**
@@ -203,9 +216,11 @@
             @Nullable VirtualDisplay.Callback callback, @Nullable Handler handler) {
         if (shouldMediaProjectionRequireCallback()) {
             if (mCallbacks.isEmpty()) {
-                throw new IllegalStateException(
+                final IllegalStateException e = new IllegalStateException(
                         "Must register a callback before starting capture, to manage resources in"
                                 + " response to MediaProjection states.");
+                Log.e(TAG, "Content Recording: no callback registered for virtual display", e);
+                throw e;
             }
         }
         final VirtualDisplayConfig.Builder builder = new VirtualDisplayConfig.Builder(name, width,
@@ -272,6 +287,7 @@
      */
     public void stop() {
         try {
+            Log.d(TAG, "Content Recording: stopping projection");
             mImpl.stop();
         } catch (RemoteException e) {
             Log.e(TAG, "Unable to stop projection", e);
diff --git a/media/java/android/media/projection/MediaProjectionManager.java b/media/java/android/media/projection/MediaProjectionManager.java
index 5a68c53..9790d02 100644
--- a/media/java/android/media/projection/MediaProjectionManager.java
+++ b/media/java/android/media/projection/MediaProjectionManager.java
@@ -256,6 +256,7 @@
      */
     public void stopActiveProjection() {
         try {
+            Log.d(TAG, "Content Recording: stopping active projection");
             mService.stopActiveProjection();
         } catch (RemoteException e) {
             Log.e(TAG, "Unable to stop the currently active media projection", e);
@@ -269,6 +270,7 @@
      */
     public void addCallback(@NonNull Callback callback, @Nullable Handler handler) {
         if (callback == null) {
+            Log.w(TAG, "Content Recording: cannot add null callback");
             throw new IllegalArgumentException("callback must not be null");
         }
         CallbackDelegate delegate = new CallbackDelegate(callback, handler);
@@ -286,6 +288,7 @@
      */
     public void removeCallback(@NonNull Callback callback) {
         if (callback == null) {
+            Log.w(TAG, "ContentRecording: cannot remove null callback");
             throw new IllegalArgumentException("callback must not be null");
         }
         CallbackDelegate delegate = mCallbacks.remove(callback);
diff --git a/media/java/android/media/session/MediaSession.java b/media/java/android/media/session/MediaSession.java
index f664fdc..1d6e38d 100644
--- a/media/java/android/media/session/MediaSession.java
+++ b/media/java/android/media/session/MediaSession.java
@@ -450,6 +450,7 @@
      * but it must be released if your activity or service is being destroyed.
      */
     public void release() {
+        setCallback(null);
         try {
             mBinder.destroySession();
         } catch (RemoteException e) {
diff --git a/media/java/android/media/tv/tuner/Tuner.java b/media/java/android/media/tv/tuner/Tuner.java
index d81843d..f87e47e 100644
--- a/media/java/android/media/tv/tuner/Tuner.java
+++ b/media/java/android/media/tv/tuner/Tuner.java
@@ -452,6 +452,12 @@
         acquireTRMSLock("shareFrontendFromTuner()");
         mFrontendLock.lock();
         try {
+            if (mFeOwnerTuner != null) {
+                // unregister self from the Frontend callback
+                mFeOwnerTuner.unregisterFrontendCallbackListener(this);
+                mFeOwnerTuner = null;
+                nativeUnshareFrontend();
+            }
             mTunerResourceManager.shareFrontend(mClientId, tuner.mClientId);
             mFeOwnerTuner = tuner;
             mFeOwnerTuner.registerFrontendCallbackListener(this);
diff --git a/media/java/android/media/tv/tuner/filter/Filter.java b/media/java/android/media/tv/tuner/filter/Filter.java
index c39a6db..d058600 100644
--- a/media/java/android/media/tv/tuner/filter/Filter.java
+++ b/media/java/android/media/tv/tuner/filter/Filter.java
@@ -32,7 +32,6 @@
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
-import java.lang.NullPointerException;
 import java.util.concurrent.Executor;
 
 /**
@@ -270,16 +269,20 @@
         synchronized (mCallbackLock) {
             if (mCallback != null && mExecutor != null) {
                 mExecutor.execute(() -> {
+                    FilterCallback callback;
                     synchronized (mCallbackLock) {
-                        if (mCallback != null) {
-                            try {
-                                mCallback.onFilterStatusChanged(this, status);
-                            }
-                            catch (NullPointerException e) {
-                                Log.d(TAG, "catch exception:" + e);
-                            }
+                        callback = mCallback;
+                    }
+                    if (callback != null) {
+                        try {
+                            callback.onFilterStatusChanged(this, status);
+                        } catch (NullPointerException e) {
+                            Log.d(TAG, "catch exception:" + e);
                         }
                     }
+                    if (callback != null) {
+                        callback.onFilterStatusChanged(this, status);
+                    }
                 });
             }
         }
@@ -289,19 +292,20 @@
         synchronized (mCallbackLock) {
             if (mCallback != null && mExecutor != null) {
                 mExecutor.execute(() -> {
+                    FilterCallback callback;
                     synchronized (mCallbackLock) {
-                        if (mCallback != null) {
-                            try {
-                                mCallback.onFilterEvent(this, events);
-                            }
-                            catch (NullPointerException e) {
-                                Log.d(TAG, "catch exception:" + e);
-                            }
-                        } else {
-                            for (FilterEvent event : events) {
-                                if (event instanceof MediaEvent) {
-                                    ((MediaEvent)event).release();
-                                }
+                        callback = mCallback;
+                    }
+                    if (callback != null) {
+                        try {
+                            callback.onFilterEvent(this, events);
+                        } catch (NullPointerException e) {
+                            Log.d(TAG, "catch exception:" + e);
+                        }
+                    } else {
+                        for (FilterEvent event : events) {
+                            if (event instanceof MediaEvent) {
+                                ((MediaEvent) event).release();
                             }
                         }
                     }
@@ -309,7 +313,7 @@
             } else {
                 for (FilterEvent event : events) {
                     if (event instanceof MediaEvent) {
-                        ((MediaEvent)event).release();
+                        ((MediaEvent) event).release();
                     }
                 }
             }
diff --git a/media/jni/android_media_MediaCodec.cpp b/media/jni/android_media_MediaCodec.cpp
index 5ea98c0c..b03a039 100644
--- a/media/jni/android_media_MediaCodec.cpp
+++ b/media/jni/android_media_MediaCodec.cpp
@@ -3450,7 +3450,8 @@
         JNIEnv *env, jobject thiz,
         jstring name, jboolean nameIsType, jboolean encoder, int pid, int uid) {
     if (name == NULL) {
-        jniThrowException(env, "java/lang/NullPointerException", NULL);
+        jniThrowException(env, "java/lang/NullPointerException",
+                          "No codec name specified");
         return;
     }
 
diff --git a/media/tests/mediatestutils/Android.bp b/media/tests/mediatestutils/Android.bp
index e50e69a..15bc177 100644
--- a/media/tests/mediatestutils/Android.bp
+++ b/media/tests/mediatestutils/Android.bp
@@ -24,9 +24,13 @@
 
 java_library {
     name: "mediatestutils",
+    srcs: [
+        "java/com/android/media/mediatestutils/TestUtils.java",
+    ],
     static_libs: [
+        "androidx.concurrent_concurrent-futures",
+        "guava",
         "mediatestutils_host",
-        "junit",
     ],
     visibility: [
         "//cts/tests/tests/media:__subpackages__",
diff --git a/media/tests/mediatestutils/TEST_MAPPING b/media/tests/mediatestutils/TEST_MAPPING
new file mode 100644
index 0000000..6dd09ae
--- /dev/null
+++ b/media/tests/mediatestutils/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "mediatestutilstests"
+    }
+  ]
+}
diff --git a/media/tests/mediatestutils/java/com/android/media/mediatestutils/TestUtils.java b/media/tests/mediatestutils/java/com/android/media/mediatestutils/TestUtils.java
new file mode 100644
index 0000000..69d836d
--- /dev/null
+++ b/media/tests/mediatestutils/java/com/android/media/mediatestutils/TestUtils.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.media.mediatestutils;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+
+import androidx.concurrent.futures.CallbackToFutureAdapter;
+
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
+
+import java.lang.ref.WeakReference;
+import java.util.Objects;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Predicate;
+
+/** Utils for audio tests. */
+public class TestUtils {
+    /**
+     * Return a future for an intent delivered by a broadcast receiver which matches an
+     * action and predicate.
+     * @param context - Context to register the receiver with
+     * @param action - String representing action to register receiver for
+     * @param pred - Predicate which sets the future if evaluates to true, otherwise, leaves
+     * the future unset. If the predicate throws, the future is set exceptionally
+     * @return - The future representing intent delivery matching predicate.
+     */
+    public static ListenableFuture<Intent> getFutureForIntent(
+            Context context, String action, Predicate<Intent> pred) {
+        // These are evaluated async
+        Objects.requireNonNull(action);
+        Objects.requireNonNull(pred);
+        return getFutureForListener(
+                (recv) ->
+                        context.registerReceiver(
+                                recv, new IntentFilter(action), Context.RECEIVER_NOT_EXPORTED),
+                (recv) -> {
+                    try {
+                        context.unregisterReceiver(recv);
+                    } catch (IllegalArgumentException e) {
+                        // Thrown when receiver is already unregistered, nothing to do
+                    }
+                },
+                (completer) ->
+                        new BroadcastReceiver() {
+                            @Override
+                            public void onReceive(Context context, Intent intent) {
+                                try {
+                                    if (action.equals(intent.getAction()) && pred.test(intent)) {
+                                        completer.set(intent);
+                                    }
+                                } catch (Exception e) {
+                                    completer.setException(e);
+                                }
+                            }
+                        },
+                "Intent receiver future for action: " + action);
+    }
+
+    /**
+     * Return a future for a callback registered to a listener interface.
+     * @param registerFunc - Function which consumes the callback object for registration
+     * @param unregisterFunc - Function which consumes the callback object for unregistration
+     * This function is called when the future is completed or cancelled
+     * @param instantiateCallback - Factory function for the callback object, provided a completer
+     * object (see {@code CallbackToFutureAdapter.Completer<T>}), which is a logical reference
+     * to the future returned by this function
+     * @param debug - Debug string contained in future {@code toString} representation.
+     */
+    public static <T, V> ListenableFuture<T> getFutureForListener(
+            Consumer<V> registerFunc,
+            Consumer<V> unregisterFunc,
+            Function<CallbackToFutureAdapter.Completer<T>, V> instantiateCallback,
+            String debug) {
+        // Doesn't need to be thread safe since the resolver is called inline
+        final WeakReference<V> wrapper[] = new WeakReference[1];
+        ListenableFuture<T> future =
+                CallbackToFutureAdapter.getFuture(
+                        completer -> {
+                            final var cb = instantiateCallback.apply(completer);
+                            wrapper[0] = new WeakReference(cb);
+                            registerFunc.accept(cb);
+                            return debug;
+                        });
+        if (wrapper[0] == null) {
+            throw new AssertionError("Resolver should be called inline");
+        }
+        final var weakref = wrapper[0];
+        future.addListener(
+                () -> {
+                    var cb = weakref.get();
+                    // If there is no reference left, the receiver has already been unregistered
+                    if (cb != null) {
+                        unregisterFunc.accept(cb);
+                        return;
+                    }
+                },
+                MoreExecutors.directExecutor()); // Direct executor is fine since lightweight
+        return future;
+    }
+}
diff --git a/media/tests/mediatestutils/tests/Android.bp b/media/tests/mediatestutils/tests/Android.bp
new file mode 100644
index 0000000..24a8360
--- /dev/null
+++ b/media/tests/mediatestutils/tests/Android.bp
@@ -0,0 +1,22 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_base_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_base_license"],
+}
+
+android_test {
+    name: "mediatestutilstests",
+    srcs: ["src/**/*.java"],
+    static_libs: [
+        "mockito-target-minus-junit4",
+        "androidx.test.runner",
+        "androidx.test.core",
+        "mediatestutils",
+        "junit",
+        "truth",
+    ],
+    test_suites: ["general-tests"],
+}
diff --git a/media/tests/mediatestutils/tests/AndroidManifest.xml b/media/tests/mediatestutils/tests/AndroidManifest.xml
new file mode 100644
index 0000000..662bc45
--- /dev/null
+++ b/media/tests/mediatestutils/tests/AndroidManifest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2023 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT 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.media.mediatestutils">
+
+    <application android:testOnly="false"
+                 android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation
+        android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="com.android.media.mediatestutils"
+        android:label="mediatestutils tests" />
+
+</manifest>
diff --git a/media/tests/mediatestutils/tests/src/java/com/android/media/mediatestutils/GetFutureForIntentTest.java b/media/tests/mediatestutils/tests/src/java/com/android/media/mediatestutils/GetFutureForIntentTest.java
new file mode 100644
index 0000000..a4266a3
--- /dev/null
+++ b/media/tests/mediatestutils/tests/src/java/com/android/media/mediatestutils/GetFutureForIntentTest.java
@@ -0,0 +1,156 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.media.mediatestutils;
+
+import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
+
+import static com.android.media.mediatestutils.TestUtils.getFutureForIntent;
+import static com.android.media.mediatestutils.TestUtils.getFutureForListener;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.fail;
+
+import android.content.Context;
+import android.content.Intent;
+import android.os.SystemClock;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.google.common.util.concurrent.ListenableFuture;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.ExecutionException;
+import java.util.function.Predicate;
+
+@RunWith(AndroidJUnit4.class)
+public class GetFutureForIntentTest {
+    public static final String INTENT_ACTION = "com.android.media.mediatestutils.TEST_ACTION";
+    public static final String INTENT_EXTRA = "com.android.media.mediatestutils.TEST_EXTRA";
+    public static final int MAGIC_VALUE = 7;
+
+    public final Context mContext = getApplicationContext();
+    public final Predicate<Intent> mPred =
+            i -> (i != null) && (i.getIntExtra(INTENT_EXTRA, -1) == MAGIC_VALUE);
+
+    @Test
+    public void futureCompletes_afterBroadcastFiresPredicatePasses() throws Exception {
+        final var future = getFutureForIntent(mContext, INTENT_ACTION, mPred);
+        sendIntent(true);
+        var intent = future.get();
+        assertThat(intent.getAction()).isEqualTo(INTENT_ACTION);
+        assertThat(intent.getIntExtra(INTENT_EXTRA, -1)).isEqualTo(MAGIC_VALUE);
+    }
+
+    @Test
+    public void futureDoesNotComplete_afterBroadcastFiresPredicateFails() throws Exception {
+        final var future = getFutureForIntent(mContext, INTENT_ACTION, mPred);
+        sendIntent(false);
+
+        // Wait a bit, and ensure the future hasn't completed
+        SystemClock.sleep(100);
+        assertThat(future.isDone()).isFalse();
+
+        // Future should still respond to subsequent passing intent
+        sendIntent(true);
+        var intent = future.get();
+        assertThat(intent.getAction()).isEqualTo(INTENT_ACTION);
+        assertThat(intent.getIntExtra(INTENT_EXTRA, -1)).isEqualTo(MAGIC_VALUE);
+    }
+
+    @Test
+    public void futureCompletesExceptionally_afterBroadcastFiresPredicateThrows() throws Exception {
+        final var future =
+                getFutureForIntent(
+                        mContext,
+                        INTENT_ACTION,
+                        i -> {
+                            throw new IllegalStateException();
+                        });
+
+        sendIntent(true);
+        try {
+            var intent = future.get();
+            fail("Exception expected if predicate throws");
+        } catch (ExecutionException e) {
+            assertThat(e.getCause().getClass()).isEqualTo(IllegalStateException.class);
+        }
+    }
+
+    @Test
+    public void doesNotThrow_whenDoubleSet() throws Exception {
+        final var future = getFutureForIntent(mContext, INTENT_ACTION, mPred);
+        sendIntent(true);
+        sendIntent(true);
+        var intent = future.get();
+        assertThat(intent.getAction()).isEqualTo(INTENT_ACTION);
+        assertThat(intent.getIntExtra(INTENT_EXTRA, -1)).isEqualTo(MAGIC_VALUE);
+    }
+
+    @Test
+    public void unregisterListener_whenComplete() throws Exception {
+        final var service = new FakeService();
+        final ListenableFuture<Void> future =
+                getFutureForListener(
+                        service::registerListener,
+                        service::unregisterListener,
+                        completer ->
+                                () -> {
+                                    completer.set(null);
+                                },
+                        "FakeService listener future");
+        service.mRunnable.run();
+        assertThat(service.mRunnable).isNull();
+    }
+
+    @Test
+    public void unregisterListener_whenCancel() throws Exception {
+        final var service = new FakeService();
+        final ListenableFuture<Void> future =
+                getFutureForListener(
+                        service::registerListener,
+                        service::unregisterListener,
+                        completer ->
+                                () -> {
+                                    completer.set(null);
+                                },
+                        "FakeService listener future");
+        future.cancel(false);
+        assertThat(service.mRunnable).isNull();
+    }
+
+    private static class FakeService {
+        Runnable mRunnable;
+
+        void registerListener(Runnable r) {
+            mRunnable = r;
+        }
+
+        void unregisterListener(Runnable r) {
+            assertThat(r).isEqualTo(mRunnable);
+            mRunnable = null;
+        }
+    }
+
+    private void sendIntent(boolean correctValue) {
+        final Intent intent = new Intent(INTENT_ACTION).setPackage(mContext.getPackageName());
+        intent.putExtra(INTENT_EXTRA, correctValue ? MAGIC_VALUE : MAGIC_VALUE + 1);
+        mContext.sendBroadcast(intent);
+    }
+}
diff --git a/native/android/Android.bp b/native/android/Android.bp
index 254eb44..7f3792d 100644
--- a/native/android/Android.bp
+++ b/native/android/Android.bp
@@ -46,7 +46,10 @@
 
 cc_library_shared {
     name: "libandroid",
-    defaults: ["libandroid_defaults"],
+    defaults: [
+        "libandroid_defaults",
+        "android.hardware.power-ndk_shared",
+    ],
 
     srcs: [
         "activity_manager.cpp",
@@ -95,7 +98,6 @@
         "libpowermanager",
         "android.hardware.configstore@1.0",
         "android.hardware.configstore-utils",
-        "android.hardware.power-V4-ndk",
         "libnativedisplay",
     ],
 
diff --git a/native/android/OWNERS b/native/android/OWNERS
index d41652f..0b86909 100644
--- a/native/android/OWNERS
+++ b/native/android/OWNERS
@@ -26,3 +26,6 @@
 
 # Input
 per-file input.cpp = file:/INPUT_OWNERS
+
+# PerformanceHint
+per-file performance_hint.cpp = file:/ADPF_OWNERS
diff --git a/native/android/configuration.cpp b/native/android/configuration.cpp
index 283445f..b50514d 100644
--- a/native/android/configuration.cpp
+++ b/native/android/configuration.cpp
@@ -36,7 +36,7 @@
 
 void AConfiguration_fromAssetManager(AConfiguration* out, AAssetManager* am) {
     ScopedLock<AssetManager2> locked_mgr(*AssetManagerForNdkAssetManager(am));
-    ResTable_config config = locked_mgr->GetConfigurations()[0];
+    ResTable_config config = locked_mgr->GetConfiguration();
 
     // AConfiguration is not a virtual subclass, so we can memcpy.
     memcpy(out, &config, sizeof(config));
diff --git a/native/android/libandroid.map.txt b/native/android/libandroid.map.txt
index d74f9b7..b0af09c 100644
--- a/native/android/libandroid.map.txt
+++ b/native/android/libandroid.map.txt
@@ -334,6 +334,7 @@
     APerformanceHint_reportActualWorkDuration; # introduced=Tiramisu
     APerformanceHint_closeSession; # introduced=Tiramisu
     APerformanceHint_setThreads; # introduced=UpsideDownCake
+    APerformanceHint_setPreferPowerEfficiency; # introduced=VanillaIceCream
   local:
     *;
 };
diff --git a/native/android/performance_hint.cpp b/native/android/performance_hint.cpp
index 6198f40..c25df6e 100644
--- a/native/android/performance_hint.cpp
+++ b/native/android/performance_hint.cpp
@@ -17,6 +17,7 @@
 #define LOG_TAG "perf_hint"
 
 #include <aidl/android/hardware/power/SessionHint.h>
+#include <aidl/android/hardware/power/SessionMode.h>
 #include <android/os/IHintManager.h>
 #include <android/os/IHintSession.h>
 #include <android/performance_hint.h>
@@ -36,6 +37,7 @@
 using namespace std::chrono_literals;
 
 using AidlSessionHint = aidl::android::hardware::power::SessionHint;
+using AidlSessionMode = aidl::android::hardware::power::SessionMode;
 
 struct APerformanceHintSession;
 
@@ -72,6 +74,7 @@
     int sendHint(SessionHint hint);
     int setThreads(const int32_t* threadIds, size_t size);
     int getThreadIds(int32_t* const threadIds, size_t* size);
+    int setPreferPowerEfficiency(bool enabled);
 
 private:
     friend struct APerformanceHintManager;
@@ -307,6 +310,18 @@
     return 0;
 }
 
+int APerformanceHintSession::setPreferPowerEfficiency(bool enabled) {
+    binder::Status ret =
+            mHintSession->setMode(static_cast<int32_t>(AidlSessionMode::POWER_EFFICIENCY), enabled);
+
+    if (!ret.isOk()) {
+        ALOGE("%s: HintSession setPreferPowerEfficiency failed: %s", __FUNCTION__,
+              ret.exceptionMessage().c_str());
+        return EPIPE;
+    }
+    return OK;
+}
+
 // ===================================== C API
 APerformanceHintManager* APerformanceHint_getManager() {
     return APerformanceHintManager::getInstance();
@@ -357,6 +372,10 @@
             ->getThreadIds(threadIds, size);
 }
 
+int APerformanceHint_setPreferPowerEfficiency(APerformanceHintSession* session, bool enabled) {
+    return session->setPreferPowerEfficiency(enabled);
+}
+
 void APerformanceHint_setIHintManagerForTesting(void* iManager) {
     delete gHintManagerForTesting;
     gHintManagerForTesting = nullptr;
diff --git a/native/android/tests/performance_hint/OWNERS b/native/android/tests/performance_hint/OWNERS
new file mode 100644
index 0000000..e3bbee92
--- /dev/null
+++ b/native/android/tests/performance_hint/OWNERS
@@ -0,0 +1 @@
+include /ADPF_OWNERS
diff --git a/native/android/tests/performance_hint/PerformanceHintNativeTest.cpp b/native/android/tests/performance_hint/PerformanceHintNativeTest.cpp
index 6f7562b..22d33b1 100644
--- a/native/android/tests/performance_hint/PerformanceHintNativeTest.cpp
+++ b/native/android/tests/performance_hint/PerformanceHintNativeTest.cpp
@@ -56,7 +56,8 @@
                 (const ::std::vector<int64_t>& actualDurationNanos,
                  const ::std::vector<int64_t>& timeStampNanos),
                 (override));
-    MOCK_METHOD(Status, sendHint, (int32_t hints), (override));
+    MOCK_METHOD(Status, sendHint, (int32_t hint), (override));
+    MOCK_METHOD(Status, setMode, (int32_t mode, bool enabled), (override));
     MOCK_METHOD(Status, close, (), (override));
     MOCK_METHOD(IBinder*, onAsBinder, (), (override));
 };
@@ -190,3 +191,51 @@
     result = APerformanceHint_setThreads(session, invalidTids.data(), invalidTids.size());
     EXPECT_EQ(EPERM, result);
 }
+
+TEST_F(PerformanceHintTest, SetPowerEfficient) {
+    APerformanceHintManager* manager = createManager();
+
+    std::vector<int32_t> tids;
+    tids.push_back(1);
+    tids.push_back(2);
+    int64_t targetDuration = 56789L;
+
+    StrictMock<MockIHintSession>* iSession = new StrictMock<MockIHintSession>();
+    sp<IHintSession> session_sp(iSession);
+
+    EXPECT_CALL(*mMockIHintManager, createHintSession(_, Eq(tids), Eq(targetDuration), _))
+            .Times(Exactly(1))
+            .WillRepeatedly(DoAll(SetArgPointee<3>(std::move(session_sp)), Return(Status())));
+
+    APerformanceHintSession* session =
+            APerformanceHint_createSession(manager, tids.data(), tids.size(), targetDuration);
+    ASSERT_TRUE(session);
+
+    EXPECT_CALL(*iSession, setMode(_, Eq(true))).Times(Exactly(1));
+    int result = APerformanceHint_setPreferPowerEfficiency(session, true);
+    EXPECT_EQ(0, result);
+
+    EXPECT_CALL(*iSession, setMode(_, Eq(false))).Times(Exactly(1));
+    result = APerformanceHint_setPreferPowerEfficiency(session, false);
+    EXPECT_EQ(0, result);
+}
+
+TEST_F(PerformanceHintTest, CreateZeroTargetDurationSession) {
+    APerformanceHintManager* manager = createManager();
+
+    std::vector<int32_t> tids;
+    tids.push_back(1);
+    tids.push_back(2);
+    int64_t targetDuration = 0;
+
+    StrictMock<MockIHintSession>* iSession = new StrictMock<MockIHintSession>();
+    sp<IHintSession> session_sp(iSession);
+
+    EXPECT_CALL(*mMockIHintManager, createHintSession(_, Eq(tids), Eq(targetDuration), _))
+            .Times(Exactly(1))
+            .WillRepeatedly(DoAll(SetArgPointee<3>(std::move(session_sp)), Return(Status())));
+
+    APerformanceHintSession* session =
+            APerformanceHint_createSession(manager, tids.data(), tids.size(), targetDuration);
+    ASSERT_TRUE(session);
+}
\ No newline at end of file
diff --git a/packages/CredentialManager/res/values-zh-rCN/strings.xml b/packages/CredentialManager/res/values-zh-rCN/strings.xml
index 42eaf00..15a668a 100644
--- a/packages/CredentialManager/res/values-zh-rCN/strings.xml
+++ b/packages/CredentialManager/res/values-zh-rCN/strings.xml
@@ -33,7 +33,7 @@
     <string name="passwordless_technology_detail" msgid="6853928846532955882">"借助通行密钥,您不必依赖密码就能登录。您只需使用指纹、人脸识别功能、PIN 码或滑动图案便可验证您的身份并创建通行密钥。"</string>
     <string name="public_key_cryptography_title" msgid="6751970819265298039">"公钥加密"</string>
     <string name="public_key_cryptography_detail" msgid="6937631710280562213">"根据 FIDO 联盟(成员包括 Google、Apple、Microsoft 等)和 W3C 的标准,通行密钥使用加密密钥对。不同于“用户名+密码字符串”的传统登录凭据,采用通行密钥时,系统会为应用或网站创建一个私钥-公钥对。私钥会安全地存储在您的设备上或密码管理工具中,用于证实您的身份。公钥会被共享给应用或网站服务器。您只要使用相应密钥,就能瞬间注册并登录。"</string>
-    <string name="improved_account_security_title" msgid="1069841917893513424">"提升了帐号安全性"</string>
+    <string name="improved_account_security_title" msgid="1069841917893513424">"提升了账号安全性"</string>
     <string name="improved_account_security_detail" msgid="9123750251551844860">"每个密钥都是专为特定应用或网站创建的,且仅与各自对应的网站或应用关联,因此您绝不会错误地登录任何欺诈性应用或网站。另外,由于服务器只保留公钥,黑客入侵的难度会大大增加。"</string>
     <string name="seamless_transition_title" msgid="5335622196351371961">"无缝转换"</string>
     <string name="seamless_transition_detail" msgid="4475509237171739843">"在我们向无密码未来迈进的过程中,密码仍会与通行密钥并行使用。"</string>
diff --git a/packages/EasterEgg/src/com/android/egg/quares/Quare.kt b/packages/EasterEgg/src/com/android/egg/quares/Quare.kt
index eb77362..f0cc2a1 100644
--- a/packages/EasterEgg/src/com/android/egg/quares/Quare.kt
+++ b/packages/EasterEgg/src/com/android/egg/quares/Quare.kt
@@ -137,14 +137,12 @@
         return 0
     }
 
-    override fun writeToParcel(p: Parcel?, flags: Int) {
-        p?.let {
-            p.writeInt(width)
-            p.writeInt(height)
-            p.writeInt(depth)
-            p.writeIntArray(data)
-            p.writeIntArray(user)
-        }
+    override fun writeToParcel(p: Parcel, flags: Int) {
+        p.writeInt(width)
+        p.writeInt(height)
+        p.writeInt(depth)
+        p.writeIntArray(data)
+        p.writeIntArray(user)
     }
 
     companion object CREATOR : Parcelable.Creator<Quare> {
diff --git a/packages/EasterEgg/src/com/android/egg/quares/QuaresActivity.kt b/packages/EasterEgg/src/com/android/egg/quares/QuaresActivity.kt
index 578de01..5fa6137 100644
--- a/packages/EasterEgg/src/com/android/egg/quares/QuaresActivity.kt
+++ b/packages/EasterEgg/src/com/android/egg/quares/QuaresActivity.kt
@@ -60,8 +60,8 @@
 
         setContentView(R.layout.activity_quares)
 
-        grid = findViewById(R.id.grid)
-        label = findViewById(R.id.label)
+        grid = requireViewById(R.id.grid)
+        label = requireViewById(R.id.label)
 
         if (savedInstanceState != null) {
             Log.v(TAG, "restoring puzzle from state")
@@ -135,7 +135,7 @@
         if (q.check()) {
             val dp = resources.displayMetrics.density
 
-            val label: Button = findViewById(R.id.label)
+            val label: Button = requireViewById(R.id.label)
             label.text = resName.replace(Regex("^.*/"), "")
             val drawable = icon?.loadDrawable(this)?.also {
                 it.setBounds(0, 0, (32 * dp).toInt(), (32 * dp).toInt())
diff --git a/packages/PackageInstaller/src/com/android/packageinstaller/InstallStart.java b/packages/PackageInstaller/src/com/android/packageinstaller/InstallStart.java
index f2f019d9..736e0ef 100644
--- a/packages/PackageInstaller/src/com/android/packageinstaller/InstallStart.java
+++ b/packages/PackageInstaller/src/com/android/packageinstaller/InstallStart.java
@@ -34,7 +34,6 @@
 import android.os.Bundle;
 import android.os.Process;
 import android.os.UserManager;
-import android.provider.Settings;
 import android.text.TextUtils;
 import android.util.EventLog;
 import android.util.Log;
@@ -51,12 +50,10 @@
 public class InstallStart extends Activity {
     private static final String TAG = InstallStart.class.getSimpleName();
 
-
-    private static final int DLG_INSTALL_APPS_RESTRICTED_FOR_USER = 1;
-    private static final int DLG_UNKNOWN_SOURCES_RESTRICTED_FOR_USER = 2;
     private PackageManager mPackageManager;
     private UserManager mUserManager;
     private boolean mAbortInstall = false;
+    private boolean mShouldFinish = true;
 
     private final boolean mLocalLOGV = false;
 
@@ -131,7 +128,7 @@
             mAbortInstall = true;
         }
 
-        checkDevicePolicyRestriction();
+        checkDevicePolicyRestrictions();
 
         final String installerPackageNameFromIntent = getIntent().getStringExtra(
                 Intent.EXTRA_INSTALLER_PACKAGE_NAME);
@@ -150,7 +147,9 @@
 
         if (mAbortInstall) {
             setResult(RESULT_CANCELED);
-            finish();
+            if (mShouldFinish) {
+                finish();
+            }
             return;
         }
 
@@ -281,58 +280,52 @@
         return originatingUid == installerUid;
     }
 
-    private void checkDevicePolicyRestriction() {
-        // Check for install apps user restriction first.
-        final int installAppsRestrictionSource = mUserManager.getUserRestrictionSource(
-                UserManager.DISALLOW_INSTALL_APPS, Process.myUserHandle());
-        if ((installAppsRestrictionSource & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) {
-            if (mLocalLOGV) Log.i(TAG, "install not allowed: " + UserManager.DISALLOW_INSTALL_APPS);
-            mAbortInstall = true;
-            showDialogInner(DLG_INSTALL_APPS_RESTRICTED_FOR_USER);
-            return;
-        } else if (installAppsRestrictionSource != UserManager.RESTRICTION_NOT_SET) {
-            if (mLocalLOGV) {
-                Log.i(TAG, "install not allowed by admin; showing "
-                        + Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
-            }
-            mAbortInstall = true;
-            startActivity(new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS));
-            return;
-        }
+    private void checkDevicePolicyRestrictions() {
+        final String[] restrictions = new String[] {
+            UserManager.DISALLOW_INSTALL_APPS,
+            UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
+            UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY
+        };
 
-        final int unknownSourcesRestrictionSource = mUserManager.getUserRestrictionSource(
-                UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, Process.myUserHandle());
-        final int unknownSourcesGlobalRestrictionSource = mUserManager.getUserRestrictionSource(
-                UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, Process.myUserHandle());
-        final int systemRestriction = UserManager.RESTRICTION_SOURCE_SYSTEM
-                & (unknownSourcesRestrictionSource | unknownSourcesGlobalRestrictionSource);
-        if (systemRestriction != 0) {
-            if (mLocalLOGV) Log.i(TAG, "Showing DLG_UNKNOWN_SOURCES_RESTRICTED_FOR_USER");
+        final DevicePolicyManager dpm = getSystemService(DevicePolicyManager.class);
+        for (String restriction : restrictions) {
+            if (!mUserManager.hasUserRestrictionForUser(restriction, Process.myUserHandle())) {
+                continue;
+            }
+
             mAbortInstall = true;
-            showDialogInner(DLG_UNKNOWN_SOURCES_RESTRICTED_FOR_USER);
-        } else if (unknownSourcesRestrictionSource != UserManager.RESTRICTION_NOT_SET) {
-            mAbortInstall = true;
-            startAdminSupportDetailsActivity(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
-        } else if (unknownSourcesGlobalRestrictionSource != UserManager.RESTRICTION_NOT_SET) {
-            mAbortInstall = true;
-            startAdminSupportDetailsActivity(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY);
+
+            // If the given restriction is set by an admin, display information about the
+            // admin enforcing the restriction for the affected user. If not enforced by the admin,
+            // show the system dialog.
+            final Intent showAdminSupportDetailsIntent = dpm.createAdminSupportIntent(restriction);
+            if (showAdminSupportDetailsIntent != null) {
+                if (mLocalLOGV) Log.i(TAG, "starting " + showAdminSupportDetailsIntent);
+                startActivity(showAdminSupportDetailsIntent);
+            } else {
+                if (mLocalLOGV) Log.i(TAG, "Restriction set by system: " + restriction);
+                mShouldFinish = false;
+                showDialogInner(restriction);
+            }
+            break;
         }
     }
 
     /**
-     * Replace any dialog shown by the dialog with the one for the given {@link #createDialog(int)}.
+     * Replace any dialog shown by the dialog with the one for the given
+     * {@link #createDialog(String)}.
      *
-     * @param id The dialog type to add
+     * @param restriction The restriction to create the dialog for
      */
-    private void showDialogInner(int id) {
-        if (mLocalLOGV) Log.i(TAG, "showDialogInner(" + id + ")");
+    private void showDialogInner(String restriction) {
+        if (mLocalLOGV) Log.i(TAG, "showDialogInner(" + restriction + ")");
         DialogFragment currentDialog =
                 (DialogFragment) getFragmentManager().findFragmentByTag("dialog");
         if (currentDialog != null) {
             currentDialog.dismissAllowingStateLoss();
         }
 
-        DialogFragment newDialog = createDialog(id);
+        DialogFragment newDialog = createDialog(restriction);
         if (newDialog != null) {
             getFragmentManager().beginTransaction()
                     .add(newDialog, "dialog").commitAllowingStateLoss();
@@ -342,34 +335,20 @@
     /**
      * Create a new dialog.
      *
-     * @param id The id of the dialog (determines dialog type)
+     * @param restriction The restriction to create the dialog for
      * @return The dialog
      */
-    private DialogFragment createDialog(int id) {
-        if (mLocalLOGV) Log.i(TAG, "createDialog(" + id + ")");
-        switch (id) {
-            case DLG_INSTALL_APPS_RESTRICTED_FOR_USER:
+    private DialogFragment createDialog(String restriction) {
+        if (mLocalLOGV) Log.i(TAG, "createDialog(" + restriction + ")");
+        switch (restriction) {
+            case UserManager.DISALLOW_INSTALL_APPS:
                 return PackageUtil.SimpleErrorDialog.newInstance(
                         R.string.install_apps_user_restriction_dlg_text);
-            case DLG_UNKNOWN_SOURCES_RESTRICTED_FOR_USER:
+            case UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES:
+            case UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY:
                 return PackageUtil.SimpleErrorDialog.newInstance(
                         R.string.unknown_apps_user_restriction_dlg_text);
         }
         return null;
     }
-
-    private void startAdminSupportDetailsActivity(String restriction) {
-        if (mLocalLOGV) Log.i(TAG, "startAdminSupportDetailsActivity(): " + restriction);
-
-        // If the given restriction is set by an admin, display information about the
-        // admin enforcing the restriction for the affected user.
-        final DevicePolicyManager dpm = getSystemService(DevicePolicyManager.class);
-        final Intent showAdminSupportDetailsIntent = dpm.createAdminSupportIntent(restriction);
-        if (showAdminSupportDetailsIntent != null) {
-            if (mLocalLOGV) Log.i(TAG, "starting " + showAdminSupportDetailsIntent);
-            startActivity(showAdminSupportDetailsIntent);
-        } else {
-            if (mLocalLOGV) Log.w(TAG, "not intent for " + restriction);
-        }
-    }
 }
diff --git a/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java b/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java
index 2d6cc69..df91d98 100644
--- a/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java
+++ b/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java
@@ -806,12 +806,12 @@
             }
             new Handler(Looper.getMainLooper()).postDelayed(() -> {
                 if (!isDestroyed()) {
+                    startActivity(getIntent());
                     // The start flag (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP) doesn't
                     // work for the multiple user case, i.e. the caller task user and started
                     // Activity user are not the same. To avoid having multiple PIAs in the task,
                     // finish the current PackageInstallerActivity
                     finish();
-                    startActivity(getIntent());
                 }
             }, 500);
 
diff --git a/packages/PrintSpooler/src/com/android/printspooler/ui/SelectPrinterActivity.java b/packages/PrintSpooler/src/com/android/printspooler/ui/SelectPrinterActivity.java
index 0c4cb8e..74acf67 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/ui/SelectPrinterActivity.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/ui/SelectPrinterActivity.java
@@ -19,6 +19,7 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.app.Activity;
+import android.app.ActivityOptions;
 import android.app.LoaderManager;
 import android.content.ComponentName;
 import android.content.Context;
@@ -714,8 +715,13 @@
 
                     try {
                         mPrinterForInfoIntent = printer;
+                        Bundle options = ActivityOptions.makeBasic()
+                                .setPendingIntentBackgroundActivityStartMode(
+                                        ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED)
+                                .toBundle();
                         startIntentSenderForResult(printer.getInfoIntent().getIntentSender(),
-                                INFO_INTENT_REQUEST_CODE, fillInIntent, 0, 0, 0);
+                                INFO_INTENT_REQUEST_CODE, fillInIntent, 0, 0, 0,
+                                options);
                     } catch (SendIntentException e) {
                         mPrinterForInfoIntent = null;
                         Log.e(LOG_TAG, "Could not execute pending info intent: %s", e);
diff --git a/packages/SettingsLib/Color/.gitignore b/packages/SettingsLib/Color/.gitignore
new file mode 100644
index 0000000..378eac2
--- /dev/null
+++ b/packages/SettingsLib/Color/.gitignore
@@ -0,0 +1 @@
+build
diff --git a/packages/SettingsLib/Color/Android.bp b/packages/SettingsLib/Color/Android.bp
new file mode 100644
index 0000000..713b7d9
--- /dev/null
+++ b/packages/SettingsLib/Color/Android.bp
@@ -0,0 +1,15 @@
+package {
+    default_applicable_licenses: ["frameworks_base_license"],
+}
+
+android_library {
+    name: "SettingsLibColor",
+    use_resource_processor: true,
+    sdk_version: "current",
+    min_sdk_version: "28",
+
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.permission",
+    ],
+}
diff --git a/packages/SettingsLib/Color/AndroidManifest.xml b/packages/SettingsLib/Color/AndroidManifest.xml
new file mode 100644
index 0000000..31e9d23
--- /dev/null
+++ b/packages/SettingsLib/Color/AndroidManifest.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright (C) 2023 The Android Open Source Project
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT 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 package="com.android.settingslib.color" />
diff --git a/packages/SystemUI/src/com/android/systemui/scene/shared/model/SceneTransitionModel.kt b/packages/SettingsLib/Color/build.gradle.kts
similarity index 68%
copy from packages/SystemUI/src/com/android/systemui/scene/shared/model/SceneTransitionModel.kt
copy to packages/SettingsLib/Color/build.gradle.kts
index c8f46a7..881bf14 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/shared/model/SceneTransitionModel.kt
+++ b/packages/SettingsLib/Color/build.gradle.kts
@@ -14,12 +14,17 @@
  * limitations under the License.
  */
 
-package com.android.systemui.scene.shared.model
+plugins {
+    alias(libs.plugins.android.library)
+}
 
-/** Models a transition between two scenes. */
-data class SceneTransitionModel(
-    /** The scene we transitioned away from. */
-    val from: SceneKey,
-    /** The scene we transitioned into. */
-    val to: SceneKey,
-)
+android {
+    namespace = "com.android.settingslib.color"
+
+    sourceSets {
+        sourceSets.getByName("main") {
+            res.setSrcDirs(listOf("res"))
+            manifest.srcFile("AndroidManifest.xml")
+        }
+    }
+}
diff --git a/packages/SettingsLib/Color/res/values/colors.xml b/packages/SettingsLib/Color/res/values/colors.xml
new file mode 100644
index 0000000..b0b9b10
--- /dev/null
+++ b/packages/SettingsLib/Color/res/values/colors.xml
@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright (C) 2023 The Android Open Source Project
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT 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>
+    <!-- Dynamic colors-->
+    <color name="settingslib_color_blue600">#1a73e8</color>
+    <color name="settingslib_color_blue400">#669df6</color>
+    <color name="settingslib_color_blue300">#8ab4f8</color>
+    <color name="settingslib_color_blue100">#d2e3fc</color>
+    <color name="settingslib_color_blue50">#e8f0fe</color>
+    <color name="settingslib_color_green600">#1e8e3e</color>
+    <color name="settingslib_color_green500">#34A853</color>
+    <color name="settingslib_color_green400">#5bb974</color>
+    <color name="settingslib_color_green100">#ceead6</color>
+    <color name="settingslib_color_green50">#e6f4ea</color>
+    <color name="settingslib_color_red600">#d93025</color>
+    <color name="settingslib_color_red500">#B3261E</color>
+    <color name="settingslib_color_red400">#ee675c</color>
+    <color name="settingslib_color_red100">#fad2cf</color>
+    <color name="settingslib_color_red50">#fce8e6</color>
+    <color name="settingslib_color_yellow600">#f9ab00</color>
+    <color name="settingslib_color_yellow400">#fcc934</color>
+    <color name="settingslib_color_yellow100">#feefc3</color>
+    <color name="settingslib_color_yellow50">#fef7e0</color>
+    <color name="settingslib_color_grey900">#202124</color>
+    <color name="settingslib_color_grey800">#3c4043</color>
+    <color name="settingslib_color_grey700">#5f6368</color>
+    <color name="settingslib_color_grey600">#80868b</color>
+    <color name="settingslib_color_grey500">#9AA0A6</color>
+    <color name="settingslib_color_grey400">#bdc1c6</color>
+    <color name="settingslib_color_grey300">#dadce0</color>
+    <color name="settingslib_color_grey200">#e8eaed</color>
+    <color name="settingslib_color_grey100">#f1f3f4</color>
+    <color name="settingslib_color_grey50">#f8f9fa</color>
+    <color name="settingslib_color_orange600">#e8710a</color>
+    <color name="settingslib_color_orange400">#fa903e</color>
+    <color name="settingslib_color_orange300">#fcad70</color>
+    <color name="settingslib_color_orange100">#fedfc8</color>
+    <color name="settingslib_color_pink600">#e52592</color>
+    <color name="settingslib_color_pink400">#ff63b8</color>
+    <color name="settingslib_color_pink300">#ff8bcb</color>
+    <color name="settingslib_color_pink100">#fdcfe8</color>
+    <color name="settingslib_color_purple600">#9334e6</color>
+    <color name="settingslib_color_purple400">#af5cf7</color>
+    <color name="settingslib_color_purple300">#c58af9</color>
+    <color name="settingslib_color_purple100">#e9d2fd</color>
+    <color name="settingslib_color_cyan600">#12b5c8</color>
+    <color name="settingslib_color_cyan400">#4ecde6</color>
+    <color name="settingslib_color_cyan300">#78d9ec</color>
+    <color name="settingslib_color_cyan100">#cbf0f8</color>
+</resources>
diff --git a/packages/SettingsLib/IllustrationPreference/Android.bp b/packages/SettingsLib/IllustrationPreference/Android.bp
index e80eb66..24ccab2 100644
--- a/packages/SettingsLib/IllustrationPreference/Android.bp
+++ b/packages/SettingsLib/IllustrationPreference/Android.bp
@@ -14,6 +14,7 @@
     resource_dirs: ["res"],
 
     static_libs: [
+        "SettingsLibColor",
         "androidx.preference_preference",
         "lottie",
     ],
diff --git a/packages/SettingsLib/IllustrationPreference/res/values/colors.xml b/packages/SettingsLib/IllustrationPreference/res/values/colors.xml
index accaa67..e53a43e 100644
--- a/packages/SettingsLib/IllustrationPreference/res/values/colors.xml
+++ b/packages/SettingsLib/IllustrationPreference/res/values/colors.xml
@@ -17,51 +17,4 @@
 
 <resources>
     <color name="settingslib_protection_color">@android:color/white</color>
-
-    <!-- Dynamic colors-->
-    <color name="settingslib_color_blue600">#1a73e8</color>
-    <color name="settingslib_color_blue400">#669df6</color>
-    <color name="settingslib_color_blue300">#8ab4f8</color>
-    <color name="settingslib_color_blue100">#d2e3fc</color>
-    <color name="settingslib_color_blue50">#e8f0fe</color>
-    <color name="settingslib_color_green600">#1e8e3e</color>
-    <color name="settingslib_color_green500">#34A853</color>
-    <color name="settingslib_color_green400">#5bb974</color>
-    <color name="settingslib_color_green100">#ceead6</color>
-    <color name="settingslib_color_green50">#e6f4ea</color>
-    <color name="settingslib_color_red600">#d93025</color>
-    <color name="settingslib_color_red500">#B3261E</color>
-    <color name="settingslib_color_red400">#ee675c</color>
-    <color name="settingslib_color_red100">#fad2cf</color>
-    <color name="settingslib_color_red50">#fce8e6</color>
-    <color name="settingslib_color_yellow600">#f9ab00</color>
-    <color name="settingslib_color_yellow400">#fcc934</color>
-    <color name="settingslib_color_yellow100">#feefc3</color>
-    <color name="settingslib_color_yellow50">#fef7e0</color>
-    <color name="settingslib_color_grey900">#202124</color>
-    <color name="settingslib_color_grey800">#3c4043</color>
-    <color name="settingslib_color_grey700">#5f6368</color>
-    <color name="settingslib_color_grey600">#80868b</color>
-    <color name="settingslib_color_grey500">#9AA0A6</color>
-    <color name="settingslib_color_grey400">#bdc1c6</color>
-    <color name="settingslib_color_grey300">#dadce0</color>
-    <color name="settingslib_color_grey200">#e8eaed</color>
-    <color name="settingslib_color_grey100">#f1f3f4</color>
-    <color name="settingslib_color_grey50">#f8f9fa</color>
-    <color name="settingslib_color_orange600">#e8710a</color>
-    <color name="settingslib_color_orange400">#fa903e</color>
-    <color name="settingslib_color_orange300">#fcad70</color>
-    <color name="settingslib_color_orange100">#fedfc8</color>
-    <color name="settingslib_color_pink600">#e52592</color>
-    <color name="settingslib_color_pink400">#ff63b8</color>
-    <color name="settingslib_color_pink300">#ff8bcb</color>
-    <color name="settingslib_color_pink100">#fdcfe8</color>
-    <color name="settingslib_color_purple600">#9334e6</color>
-    <color name="settingslib_color_purple400">#af5cf7</color>
-    <color name="settingslib_color_purple300">#c58af9</color>
-    <color name="settingslib_color_purple100">#e9d2fd</color>
-    <color name="settingslib_color_cyan600">#12b5c8</color>
-    <color name="settingslib_color_cyan400">#4ecde6</color>
-    <color name="settingslib_color_cyan300">#78d9ec</color>
-    <color name="settingslib_color_cyan100">#cbf0f8</color>
 </resources>
diff --git a/packages/SettingsLib/IllustrationPreference/src/com/android/settingslib/widget/ColorUtils.java b/packages/SettingsLib/IllustrationPreference/src/com/android/settingslib/widget/ColorUtils.java
index 07102d5..82b7e04 100644
--- a/packages/SettingsLib/IllustrationPreference/src/com/android/settingslib/widget/ColorUtils.java
+++ b/packages/SettingsLib/IllustrationPreference/src/com/android/settingslib/widget/ColorUtils.java
@@ -23,6 +23,8 @@
 import android.graphics.PorterDuffColorFilter;
 import android.util.Pair;
 
+import com.android.settingslib.color.R;
+
 import com.airbnb.lottie.LottieAnimationView;
 import com.airbnb.lottie.LottieProperty;
 import com.airbnb.lottie.model.KeyPath;
diff --git a/packages/SettingsLib/IllustrationPreference/src/com/android/settingslib/widget/LottieColorUtils.java b/packages/SettingsLib/IllustrationPreference/src/com/android/settingslib/widget/LottieColorUtils.java
index f166a18..0447ef8 100644
--- a/packages/SettingsLib/IllustrationPreference/src/com/android/settingslib/widget/LottieColorUtils.java
+++ b/packages/SettingsLib/IllustrationPreference/src/com/android/settingslib/widget/LottieColorUtils.java
@@ -21,6 +21,8 @@
 import android.graphics.PorterDuff;
 import android.graphics.PorterDuffColorFilter;
 
+import com.android.settingslib.color.R;
+
 import com.airbnb.lottie.LottieAnimationView;
 import com.airbnb.lottie.LottieProperty;
 import com.airbnb.lottie.model.KeyPath;
diff --git a/packages/SettingsLib/Spa/build.gradle.kts b/packages/SettingsLib/Spa/build.gradle.kts
index e76139f..1cc2867 100644
--- a/packages/SettingsLib/Spa/build.gradle.kts
+++ b/packages/SettingsLib/Spa/build.gradle.kts
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+import com.android.build.api.dsl.CommonExtension
 import com.android.build.gradle.BaseExtension
 import com.android.build.gradle.api.AndroidBasePlugin
 import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
@@ -25,7 +26,7 @@
 }
 
 allprojects {
-    extra["jetpackComposeVersion"] = "1.6.0-alpha01"
+    extra["jetpackComposeVersion"] = "1.6.0-alpha02"
 }
 
 subprojects {
@@ -47,10 +48,10 @@
 
     afterEvaluate {
         plugins.withType<AndroidBasePlugin> {
-            configure<BaseExtension> {
+            the(CommonExtension::class).apply {
                 if (buildFeatures.compose == true) {
                     composeOptions {
-                        kotlinCompilerExtensionVersion = "1.4.4"
+                        kotlinCompilerExtensionVersion = libs.versions.compose.compiler.get()
                     }
                 }
             }
diff --git a/packages/SettingsLib/Spa/gallery/res/values/strings.xml b/packages/SettingsLib/Spa/gallery/res/values/strings.xml
index 0d1a1fe..ec60f8c 100644
--- a/packages/SettingsLib/Spa/gallery/res/values/strings.xml
+++ b/packages/SettingsLib/Spa/gallery/res/values/strings.xml
@@ -24,4 +24,6 @@
     <string name="single_line_summary_preference_title" translatable="false">Preference (singleLineSummary = true)</string>
     <!-- Summary for single line summary preference. [DO NOT TRANSLATE] -->
     <string name="single_line_summary_preference_summary" translatable="false">A very long summary to show case a preference which only shows a single line summary.</string>
+    <!-- Footer text with two links. [DO NOT TRANSLATE] -->
+    <string name="footer_with_two_links" translatable="false">Annotated string with <a href="https://www.android.com/">link 1</a> and <a href="https://source.android.com/">link 2</a>.</string>
 </resources>
diff --git a/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/FooterPage.kt b/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/FooterPageProvider.kt
similarity index 92%
rename from packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/FooterPage.kt
rename to packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/FooterPageProvider.kt
index 9c7e0ce..50c0eb7 100644
--- a/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/FooterPage.kt
+++ b/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/FooterPageProvider.kt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2022 The Android Open Source Project
+ * Copyright (C) 2023 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -28,9 +28,11 @@
 import com.android.settingslib.spa.framework.compose.navigator
 import com.android.settingslib.spa.framework.compose.stateOf
 import com.android.settingslib.spa.framework.theme.SettingsTheme
+import com.android.settingslib.spa.gallery.R
 import com.android.settingslib.spa.widget.preference.Preference
 import com.android.settingslib.spa.widget.preference.PreferenceModel
 import com.android.settingslib.spa.widget.scaffold.RegularScaffold
+import com.android.settingslib.spa.widget.ui.AnnotatedText
 import com.android.settingslib.spa.widget.ui.Footer
 
 private const val TITLE = "Sample Footer"
@@ -78,6 +80,9 @@
                 entry.UiLayout()
             }
             Footer(footerText = "Footer text always at the end of page.")
+            Footer {
+                AnnotatedText(R.string.footer_with_two_links)
+            }
         }
     }
 }
diff --git a/packages/SettingsLib/Spa/gradle/libs.versions.toml b/packages/SettingsLib/Spa/gradle/libs.versions.toml
index ee40b02..0f467b9 100644
--- a/packages/SettingsLib/Spa/gradle/libs.versions.toml
+++ b/packages/SettingsLib/Spa/gradle/libs.versions.toml
@@ -16,8 +16,9 @@
 
 [versions]
 agp = "8.1.0"
+compose-compiler = "1.5.1"
 dexmaker-mockito = "2.28.3"
-kotlin = "1.8.10"
+kotlin = "1.9.0"
 truth = "1.1"
 
 [libraries]
diff --git a/packages/SettingsLib/Spa/settings.gradle.kts b/packages/SettingsLib/Spa/settings.gradle.kts
index 9909781..aac0fe9 100644
--- a/packages/SettingsLib/Spa/settings.gradle.kts
+++ b/packages/SettingsLib/Spa/settings.gradle.kts
@@ -40,3 +40,5 @@
 include(":spa")
 include(":gallery")
 include(":testutils")
+include(":SettingsLibColor")
+project(":SettingsLibColor").projectDir = File(rootDir, "../Color")
diff --git a/packages/SettingsLib/Spa/spa/Android.bp b/packages/SettingsLib/Spa/spa/Android.bp
index 7f5948c..6df0e99 100644
--- a/packages/SettingsLib/Spa/spa/Android.bp
+++ b/packages/SettingsLib/Spa/spa/Android.bp
@@ -24,6 +24,7 @@
     srcs: ["src/**/*.kt"],
     use_resource_processor: true,
     static_libs: [
+        "SettingsLibColor",
         "androidx.slice_slice-builders",
         "androidx.slice_slice-core",
         "androidx.slice_slice-view",
diff --git a/packages/SettingsLib/Spa/spa/build.gradle.kts b/packages/SettingsLib/Spa/spa/build.gradle.kts
index 377e72ed..84198de 100644
--- a/packages/SettingsLib/Spa/spa/build.gradle.kts
+++ b/packages/SettingsLib/Spa/spa/build.gradle.kts
@@ -52,6 +52,7 @@
 }
 
 dependencies {
+    api(project(":SettingsLibColor"))
     api("androidx.appcompat:appcompat:1.7.0-alpha03")
     api("androidx.slice:slice-builders:1.1.0-alpha02")
     api("androidx.slice:slice-core:1.1.0-alpha02")
@@ -62,7 +63,7 @@
     api("androidx.compose.ui:ui-tooling-preview:$jetpackComposeVersion")
     api("androidx.lifecycle:lifecycle-livedata-ktx")
     api("androidx.lifecycle:lifecycle-runtime-compose")
-    api("androidx.navigation:navigation-compose:2.7.0-beta01")
+    api("androidx.navigation:navigation-compose:2.7.0-rc01")
     api("com.github.PhilJay:MPAndroidChart:v3.1.0-alpha")
     api("com.google.android.material:material:1.7.0-alpha03")
     debugApi("androidx.compose.ui:ui-tooling:$jetpackComposeVersion")
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/AnnotatedStringResource.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/AnnotatedStringResource.kt
index 9ddd0c6..88ba4b0 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/AnnotatedStringResource.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/AnnotatedStringResource.kt
@@ -16,105 +16,93 @@
 
 package com.android.settingslib.spa.framework.util
 
-import android.content.res.Resources
 import android.graphics.Typeface
 import android.text.Spanned
 import android.text.style.StyleSpan
 import android.text.style.URLSpan
 import androidx.annotation.StringRes
+import androidx.compose.material3.MaterialTheme
 import androidx.compose.runtime.Composable
 import androidx.compose.runtime.remember
 import androidx.compose.ui.graphics.Color
 import androidx.compose.ui.platform.LocalContext
-import androidx.compose.ui.platform.LocalConfiguration
-import androidx.compose.ui.platform.LocalDensity
 import androidx.compose.ui.text.AnnotatedString
 import androidx.compose.ui.text.SpanStyle
 import androidx.compose.ui.text.buildAnnotatedString
 import androidx.compose.ui.text.font.FontStyle
 import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.unit.Density
+import androidx.compose.ui.text.style.TextDecoration
 
-const val URLSPAN_TAG = "URLSPAN_TAG"
+const val URL_SPAN_TAG = "URL_SPAN_TAG"
 
 @Composable
-fun annotatedStringResource(@StringRes id: Int, urlSpanColor: Color): AnnotatedString {
-    LocalConfiguration.current
+fun annotatedStringResource(@StringRes id: Int): AnnotatedString {
     val resources = LocalContext.current.resources
-    val density = LocalDensity.current
+    val urlSpanColor = MaterialTheme.colorScheme.primary
     return remember(id) {
         val text = resources.getText(id)
-        spannableStringToAnnotatedString(text, density, urlSpanColor)
+        spannableStringToAnnotatedString(text, urlSpanColor)
     }
 }
 
-private fun spannableStringToAnnotatedString(text: CharSequence, density: Density, urlSpanColor: Color): AnnotatedString {
-    return if (text is Spanned) {
-        with(density) {
-            buildAnnotatedString {
-                append((text.toString()))
-                text.getSpans(0, text.length, Any::class.java).forEach {
-                    val start = text.getSpanStart(it)
-                    val end = text.getSpanEnd(it)
-                    when (it) {
-                        is StyleSpan ->
-                            when (it.style) {
-                                Typeface.NORMAL -> addStyle(
-                                        SpanStyle(
-                                                fontWeight = FontWeight.Normal,
-                                                fontStyle = FontStyle.Normal
-                                        ),
-                                        start,
-                                        end
-                                )
-                                Typeface.BOLD -> addStyle(
-                                        SpanStyle(
-                                                fontWeight = FontWeight.Bold,
-                                                fontStyle = FontStyle.Normal
-                                        ),
-                                        start,
-                                        end
-                                )
-                                Typeface.ITALIC -> addStyle(
-                                        SpanStyle(
-                                                fontWeight = FontWeight.Normal,
-                                                fontStyle = FontStyle.Italic
-                                        ),
-                                        start,
-                                        end
-                                )
-                                Typeface.BOLD_ITALIC -> addStyle(
-                                        SpanStyle(
-                                                fontWeight = FontWeight.Bold,
-                                                fontStyle = FontStyle.Italic
-                                        ),
-                                        start,
-                                        end
-                                )
-                            }
-                        is URLSpan -> {
-                            addStyle(
-                                    SpanStyle(
-                                            color = urlSpanColor,
-                                    ),
-                                    start,
-                                    end
-                            )
-                            if (!it.url.isNullOrEmpty()) {
-                                addStringAnnotation(
-                                        URLSPAN_TAG,
-                                        it.url,
-                                        start,
-                                        end
-                                )
-                            }
-                        }
-                        else -> addStyle(SpanStyle(), start, end)
-                    }
+private fun spannableStringToAnnotatedString(text: CharSequence, urlSpanColor: Color) =
+    if (text is Spanned) {
+        buildAnnotatedString {
+            append((text.toString()))
+            for (span in text.getSpans(0, text.length, Any::class.java)) {
+                val start = text.getSpanStart(span)
+                val end = text.getSpanEnd(span)
+                when (span) {
+                    is StyleSpan -> addStyleSpan(span, start, end)
+                    is URLSpan -> addUrlSpan(span, urlSpanColor, start, end)
+                    else -> addStyle(SpanStyle(), start, end)
                 }
             }
         }
     } else {
         AnnotatedString(text.toString())
     }
+
+private fun AnnotatedString.Builder.addStyleSpan(styleSpan: StyleSpan, start: Int, end: Int) {
+    when (styleSpan.style) {
+        Typeface.NORMAL -> addStyle(
+            SpanStyle(fontWeight = FontWeight.Normal, fontStyle = FontStyle.Normal),
+            start,
+            end,
+        )
+
+        Typeface.BOLD -> addStyle(
+            SpanStyle(fontWeight = FontWeight.Bold, fontStyle = FontStyle.Normal),
+            start,
+            end,
+        )
+
+        Typeface.ITALIC -> addStyle(
+            SpanStyle(fontWeight = FontWeight.Normal, fontStyle = FontStyle.Italic),
+            start,
+            end,
+        )
+
+        Typeface.BOLD_ITALIC -> addStyle(
+            SpanStyle(fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic),
+            start,
+            end,
+        )
+    }
+}
+
+private fun AnnotatedString.Builder.addUrlSpan(
+    urlSpan: URLSpan,
+    urlSpanColor: Color,
+    start: Int,
+    end: Int,
+) {
+    addStyle(
+        SpanStyle(color = urlSpanColor, textDecoration = TextDecoration.Underline),
+        start,
+        end,
+    )
+    if (!urlSpan.url.isNullOrEmpty()) {
+        addStringAnnotation(URL_SPAN_TAG, urlSpan.url, start, end)
+    }
 }
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/illustration/Illustration.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/illustration/Illustration.kt
index 7cc9bf7..6a2163c 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/illustration/Illustration.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/illustration/Illustration.kt
@@ -22,11 +22,11 @@
 import androidx.compose.foundation.layout.padding
 import androidx.compose.foundation.layout.sizeIn
 import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.material3.MaterialTheme
 import androidx.compose.runtime.Composable
 import androidx.compose.ui.Alignment
 import androidx.compose.ui.Modifier
 import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
 import com.android.settingslib.spa.framework.theme.SettingsDimension
 import com.android.settingslib.spa.widget.ui.ImageBox
 import com.android.settingslib.spa.widget.ui.Lottie
@@ -81,7 +81,7 @@
                 maxHeight = SettingsDimension.illustrationMaxHeight,
             )
             .clip(RoundedCornerShape(SettingsDimension.illustrationCornerRadius))
-            .background(color = MaterialTheme.colorScheme.surface)
+            .background(color = Color.Transparent)
 
         when (resourceType) {
             ResourceType.LOTTIE -> {
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/AnnotatedText.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/AnnotatedText.kt
new file mode 100644
index 0000000..82ac7e3
--- /dev/null
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/AnnotatedText.kt
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.spa.widget.ui
+
+import androidx.annotation.StringRes
+import androidx.compose.foundation.text.ClickableText
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.platform.LocalUriHandler
+import com.android.settingslib.spa.framework.util.URL_SPAN_TAG
+import com.android.settingslib.spa.framework.util.annotatedStringResource
+
+@Composable
+fun AnnotatedText(@StringRes id: Int) {
+    val uriHandler = LocalUriHandler.current
+    val annotatedString = annotatedStringResource(id)
+    ClickableText(
+        text = annotatedString,
+        style = MaterialTheme.typography.bodyMedium.copy(
+            color = MaterialTheme.colorScheme.onSurfaceVariant,
+        ),
+    ) { offset ->
+        // Gets the url at the clicked position.
+        annotatedString.getStringAnnotations(URL_SPAN_TAG, offset, offset)
+            .firstOrNull()
+            ?.let { uriHandler.openUri(it.item) }
+    }
+}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Lottie.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Lottie.kt
index 915c6e2..a6cc3a9 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Lottie.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Lottie.kt
@@ -16,15 +16,24 @@
 
 package com.android.settingslib.spa.widget.ui
 
+import android.graphics.PorterDuff
+import android.graphics.PorterDuffColorFilter
+import androidx.compose.foundation.isSystemInDarkTheme
 import androidx.compose.foundation.layout.Box
 import androidx.compose.runtime.Composable
 import androidx.compose.runtime.getValue
 import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.res.colorResource
+import com.airbnb.lottie.LottieProperty
 import com.airbnb.lottie.compose.LottieAnimation
 import com.airbnb.lottie.compose.LottieCompositionSpec
 import com.airbnb.lottie.compose.LottieConstants
 import com.airbnb.lottie.compose.animateLottieCompositionAsState
 import com.airbnb.lottie.compose.rememberLottieComposition
+import com.airbnb.lottie.compose.rememberLottieDynamicProperties
+import com.airbnb.lottie.compose.rememberLottieDynamicProperty
+import com.android.settingslib.color.R
 
 @Composable
 fun Lottie(
@@ -38,6 +47,34 @@
     }
 }
 
+object LottieColorUtils {
+    private val DARK_TO_LIGHT_THEME_COLOR_MAP = mapOf(
+        ".grey600" to R.color.settingslib_color_grey400,
+        ".grey800" to R.color.settingslib_color_grey300,
+        ".grey900" to R.color.settingslib_color_grey50,
+        ".red400" to R.color.settingslib_color_red600,
+        ".black" to android.R.color.white,
+        ".blue400" to R.color.settingslib_color_blue600,
+        ".green400" to R.color.settingslib_color_green600,
+        ".green200" to R.color.settingslib_color_green500,
+        ".red200" to R.color.settingslib_color_red500,
+    )
+
+    @Composable
+    private fun getDefaultPropertiesList() =
+        DARK_TO_LIGHT_THEME_COLOR_MAP.map { (key, colorRes) ->
+            val color = colorResource(colorRes).toArgb()
+            rememberLottieDynamicProperty(
+                property = LottieProperty.COLOR_FILTER,
+                keyPath = arrayOf("**", key, "**")
+            ){ PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP) }
+        }
+
+    @Composable
+    fun getDefaultDynamicProperties() =
+        rememberLottieDynamicProperties(*getDefaultPropertiesList().toTypedArray())
+}
+
 @Composable
 private fun BaseLottie(resId: Int) {
     val composition by rememberLottieComposition(
@@ -47,8 +84,10 @@
         composition,
         iterations = LottieConstants.IterateForever,
     )
+    val isLightMode = !isSystemInDarkTheme()
     LottieAnimation(
         composition = composition,
+        dynamicProperties = LottieColorUtils.getDefaultDynamicProperties().takeIf { isLightMode },
         progress = { progress },
     )
 }
diff --git a/packages/SettingsLib/Spa/tests/res/values/strings.xml b/packages/SettingsLib/Spa/tests/res/values/strings.xml
index cbfea06..fb8f878 100644
--- a/packages/SettingsLib/Spa/tests/res/values/strings.xml
+++ b/packages/SettingsLib/Spa/tests/res/values/strings.xml
@@ -26,5 +26,7 @@
         other {There are # songs found in {place}.}
     }</string>
 
-    <string name="test_annotated_string_resource">Annotated string with <b>bold</b> and <a href="https://www.google.com/">link</a>.</string>
+    <string name="test_annotated_string_resource">Annotated string with <b>bold</b> and <a href="https://www.android.com/">link</a>.</string>
+
+    <string name="test_link"><a href="https://www.android.com/">link</a></string>
 </resources>
diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/compose/OverridableFlowTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/compose/OverridableFlowTest.kt
index c94572b..a47ccc1 100644
--- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/compose/OverridableFlowTest.kt
+++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/compose/OverridableFlowTest.kt
@@ -18,7 +18,6 @@
 
 import androidx.test.ext.junit.runners.AndroidJUnit4
 import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.flowOf
 import kotlinx.coroutines.flow.toList
@@ -28,7 +27,6 @@
 import org.junit.Test
 import org.junit.runner.RunWith
 
-@OptIn(ExperimentalCoroutinesApi::class)
 @RunWith(AndroidJUnit4::class)
 class OverridableFlowTest {
 
diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/AnnotatedStringResourceTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/AnnotatedStringResourceTest.kt
index b65be42..9928355 100644
--- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/AnnotatedStringResourceTest.kt
+++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/AnnotatedStringResourceTest.kt
@@ -16,14 +16,14 @@
 
 package com.android.settingslib.spa.framework.util
 
-import androidx.compose.ui.graphics.Color
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.compose.ui.text.AnnotatedString
 import androidx.compose.ui.text.SpanStyle
 import androidx.compose.ui.text.font.FontStyle
 import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.compose.ui.text.style.TextDecoration
 import androidx.test.ext.junit.runners.AndroidJUnit4
-import com.android.settingslib.spa.framework.util.URLSPAN_TAG
-import com.android.settingslib.spa.framework.util.annotatedStringResource
 import com.android.settingslib.spa.test.R
 import com.google.common.truth.Truth.assertThat
 import org.junit.Rule
@@ -38,24 +38,34 @@
     @Test
     fun testAnnotatedStringResource() {
         composeTestRule.setContent {
-            val annotatedString = annotatedStringResource(R.string.test_annotated_string_resource, Color.Blue)
+            val annotatedString =
+                annotatedStringResource(R.string.test_annotated_string_resource)
 
             val annotations = annotatedString.getStringAnnotations(0, annotatedString.length)
-            assertThat(annotations).hasSize(1)
-            assertThat(annotations[0].start).isEqualTo(31)
-            assertThat(annotations[0].end).isEqualTo(35)
-            assertThat(annotations[0].tag).isEqualTo(URLSPAN_TAG)
-            assertThat(annotations[0].item).isEqualTo("https://www.google.com/")
+            assertThat(annotations).containsExactly(
+                AnnotatedString.Range(
+                    item = "https://www.android.com/",
+                    start = 31,
+                    end = 35,
+                    tag = URL_SPAN_TAG,
+                )
+            )
 
-            assertThat(annotatedString.spanStyles).hasSize(2)
-            assertThat(annotatedString.spanStyles[0].start).isEqualTo(22)
-            assertThat(annotatedString.spanStyles[0].end).isEqualTo(26)
-            assertThat(annotatedString.spanStyles[0].item).isEqualTo(
-                    SpanStyle(fontWeight = FontWeight.Bold, fontStyle = FontStyle.Normal))
-
-            assertThat(annotatedString.spanStyles[1].start).isEqualTo(31)
-            assertThat(annotatedString.spanStyles[1].end).isEqualTo(35)
-            assertThat(annotatedString.spanStyles[1].item).isEqualTo(SpanStyle(color = Color.Blue))
+            assertThat(annotatedString.spanStyles).containsExactly(
+                AnnotatedString.Range(
+                    item = SpanStyle(fontWeight = FontWeight.Bold, fontStyle = FontStyle.Normal),
+                    start = 22,
+                    end = 26,
+                ),
+                AnnotatedString.Range(
+                    item = SpanStyle(
+                        color = MaterialTheme.colorScheme.primary,
+                        textDecoration = TextDecoration.Underline,
+                    ),
+                    start = 31,
+                    end = 35,
+                ),
+            )
         }
     }
 }
diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/AnnotatedTextTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/AnnotatedTextTest.kt
new file mode 100644
index 0000000..2c218e3
--- /dev/null
+++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/AnnotatedTextTest.kt
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.spa.framework.util
+
+import android.content.Context
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.platform.UriHandler
+import androidx.compose.ui.test.assertIsDisplayed
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.compose.ui.test.onNodeWithText
+import androidx.compose.ui.test.performClick
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.android.settingslib.spa.test.R
+import com.android.settingslib.spa.widget.ui.AnnotatedText
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mock
+import org.mockito.Mockito.verify
+import org.mockito.junit.MockitoJUnit
+import org.mockito.junit.MockitoRule
+
+@RunWith(AndroidJUnit4::class)
+class AnnotatedTextTest {
+    @get:Rule
+    val composeTestRule = createComposeRule()
+
+    @get:Rule
+    val mockito: MockitoRule = MockitoJUnit.rule()
+
+    @Mock
+    private lateinit var uriHandler: UriHandler
+
+    private val context: Context = ApplicationProvider.getApplicationContext()
+
+    @Test
+    fun text_isDisplayed() {
+        composeTestRule.setContent {
+            AnnotatedText(R.string.test_annotated_string_resource)
+        }
+
+        composeTestRule.onNodeWithText(context.getString(R.string.test_annotated_string_resource))
+            .assertIsDisplayed()
+    }
+
+    @Test
+    fun onUriClick_openUri() {
+        composeTestRule.setContent {
+            CompositionLocalProvider(LocalUriHandler provides uriHandler) {
+                AnnotatedText(R.string.test_link)
+            }
+        }
+
+        composeTestRule.onNodeWithText(context.getString(R.string.test_link)).performClick()
+
+        verify(uriHandler).openUri("https://www.android.com/")
+    }
+}
diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/CollectionsTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/CollectionsTest.kt
index 62f4707..693cd77 100644
--- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/CollectionsTest.kt
+++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/CollectionsTest.kt
@@ -18,12 +18,10 @@
 
 import androidx.test.ext.junit.runners.AndroidJUnit4
 import com.google.common.truth.Truth
-import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.test.runTest
 import org.junit.Test
 import org.junit.runner.RunWith
 
-@OptIn(ExperimentalCoroutinesApi::class)
 @RunWith(AndroidJUnit4::class)
 class CollectionsTest {
     @Test
diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/FlowsTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/FlowsTest.kt
index 4dcdea9..71d69b2 100644
--- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/FlowsTest.kt
+++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/FlowsTest.kt
@@ -18,7 +18,6 @@
 
 import androidx.test.ext.junit.runners.AndroidJUnit4
 import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.count
 import kotlinx.coroutines.flow.emptyFlow
 import kotlinx.coroutines.flow.first
@@ -28,7 +27,6 @@
 import org.junit.Test
 import org.junit.runner.RunWith
 
-@OptIn(ExperimentalCoroutinesApi::class)
 @RunWith(AndroidJUnit4::class)
 class FlowsTest {
     @Test
diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/StateFlowBridgeTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/StateFlowBridgeTest.kt
index e1d9a28..f0e57b9 100644
--- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/StateFlowBridgeTest.kt
+++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/StateFlowBridgeTest.kt
@@ -21,13 +21,11 @@
 import com.android.settingslib.spa.framework.compose.stateOf
 import com.android.settingslib.spa.testutils.firstWithTimeoutOrNull
 import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.test.runTest
 import org.junit.Rule
 import org.junit.Test
 import org.junit.runner.RunWith
 
-@OptIn(ExperimentalCoroutinesApi::class)
 @RunWith(AndroidJUnit4::class)
 class StateFlowBridgeTest {
     @get:Rule
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/enterprise/RestrictionsProvider.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/enterprise/RestrictionsProvider.kt
index e2ff7b0..a370ebf 100644
--- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/enterprise/RestrictionsProvider.kt
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/enterprise/RestrictionsProvider.kt
@@ -22,7 +22,6 @@
 import android.os.UserManager
 import androidx.compose.runtime.Composable
 import androidx.compose.runtime.State
-import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
 import androidx.lifecycle.compose.collectAsStateWithLifecycle
 import com.android.settingslib.RestrictedLockUtils
 import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin
@@ -90,7 +89,6 @@
         emit(getRestrictedMode())
     }.flowOn(Dispatchers.IO)
 
-    @OptIn(ExperimentalLifecycleComposeApi::class)
     @Composable
     override fun restrictedModeState() =
         restrictedMode.collectAsStateWithLifecycle(initialValue = null)
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt
index 21c9e34..945f2e2 100644
--- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt
@@ -28,8 +28,7 @@
     title: String,
     packageName: String,
     userId: Int,
-    footerText: String,
-    footerContent: (@Composable () -> Unit)?,
+    footerContent: @Composable () -> Unit,
     packageManagers: IPackageManagers,
     content: @Composable PackageInfo.() -> Unit,
 ) {
@@ -41,10 +40,6 @@
 
         packageInfo.content()
 
-        if (footerContent != null) {
-            Footer(footerContent)
-        } else {
-            Footer(footerText)
-        }
+        Footer(footerContent)
     }
 }
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppStorageSize.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppStorageSize.kt
index 5fc1972..626c913 100644
--- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppStorageSize.kt
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppStorageSize.kt
@@ -22,25 +22,27 @@
 import android.util.Log
 import androidx.compose.runtime.Composable
 import androidx.compose.runtime.State
-import androidx.compose.runtime.produceState
+import androidx.compose.runtime.remember
 import androidx.compose.ui.platform.LocalContext
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
 import com.android.settingslib.spaprivileged.framework.common.storageStatsManager
 import com.android.settingslib.spaprivileged.framework.compose.placeholder
 import com.android.settingslib.spaprivileged.model.app.userHandle
 import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.withContext
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.flowOn
 
 private const val TAG = "AppStorageSize"
 
 @Composable
 fun ApplicationInfo.getStorageSize(): State<String> {
     val context = LocalContext.current
-    return produceState(initialValue = placeholder()) {
-        withContext(Dispatchers.IO) {
+    return remember {
+        flow {
             val sizeBytes = calculateSizeBytes(context)
-            value = if (sizeBytes != null) Formatter.formatFileSize(context, sizeBytes) else ""
-        }
-    }
+            this.emit(if (sizeBytes != null) Formatter.formatFileSize(context, sizeBytes) else "")
+        }.flowOn(Dispatchers.IO)
+    }.collectAsStateWithLifecycle(initialValue = placeholder())
 }
 
 fun ApplicationInfo.calculateSizeBytes(context: Context): Long? {
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt
index 7c689c6..7f82be4 100644
--- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt
@@ -38,6 +38,7 @@
 import com.android.settingslib.spa.widget.preference.Preference
 import com.android.settingslib.spa.widget.preference.PreferenceModel
 import com.android.settingslib.spa.widget.preference.SwitchPreferenceModel
+import com.android.settingslib.spa.widget.ui.AnnotatedText
 import com.android.settingslib.spaprivileged.model.app.AppRecord
 import com.android.settingslib.spaprivileged.model.app.IPackageManagers
 import com.android.settingslib.spaprivileged.model.app.PackageManagers
@@ -140,8 +141,7 @@
         title = stringResource(pageTitleResId),
         packageName = packageName,
         userId = userId,
-        footerText = stringResource(footerResId),
-        footerContent = footerContent(),
+        footerContent = { AnnotatedText(footerResId) },
         packageManagers = packageManagers,
     ) {
         val model = createSwitchModel(applicationInfo)
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppList.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppList.kt
index f4b3204..1ab6230 100644
--- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppList.kt
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppList.kt
@@ -20,7 +20,6 @@
 import android.content.pm.ApplicationInfo
 import androidx.compose.runtime.Composable
 import androidx.compose.runtime.State
-import androidx.compose.ui.text.AnnotatedString
 import com.android.settingslib.spa.framework.common.SettingsEntryBuilder
 import com.android.settingslib.spa.framework.common.SettingsPageProvider
 import com.android.settingslib.spa.framework.compose.rememberContext
@@ -37,10 +36,7 @@
     val footerResId: Int
     val switchRestrictionKeys: List<String>
         get() = emptyList()
-    @Composable
-    fun footerContent(): (@Composable () -> Unit)? {
-        return null
-    }
+
     /**
      * Loads the extra info for the App List, and generates the [AppRecord] List.
      *
diff --git a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/model/app/AppListRepositoryTest.kt b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/model/app/AppListRepositoryTest.kt
index 375ed60..2281cd8 100644
--- a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/model/app/AppListRepositoryTest.kt
+++ b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/model/app/AppListRepositoryTest.kt
@@ -31,7 +31,6 @@
 import com.android.internal.R
 import com.android.settingslib.spaprivileged.framework.common.userManager
 import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.first
 import kotlinx.coroutines.flow.flowOf
 import kotlinx.coroutines.test.runTest
@@ -50,7 +49,6 @@
 import org.mockito.junit.MockitoRule
 import org.mockito.Mockito.`when` as whenever
 
-@OptIn(ExperimentalCoroutinesApi::class)
 @RunWith(AndroidJUnit4::class)
 class AppListRepositoryTest {
     @get:Rule
@@ -312,7 +310,12 @@
     fun getSystemPackageNames_returnExpectedValues() = runTest {
         mockInstalledApplications(
             apps = listOf(
-                NORMAL_APP, INSTANT_APP, SYSTEM_APP, UPDATED_SYSTEM_APP, HOME_APP, IN_LAUNCHER_APP
+                NORMAL_APP,
+                INSTANT_APP,
+                SYSTEM_APP,
+                UPDATED_SYSTEM_APP,
+                HOME_APP,
+                IN_LAUNCHER_APP,
             ),
             userId = ADMIN_USER_ID,
         )
@@ -329,7 +332,12 @@
     fun loadAndFilterApps_loadNonSystemApp_returnExpectedValues() = runTest {
         mockInstalledApplications(
             apps = listOf(
-                NORMAL_APP, INSTANT_APP, SYSTEM_APP, UPDATED_SYSTEM_APP, HOME_APP, IN_LAUNCHER_APP
+                NORMAL_APP,
+                INSTANT_APP,
+                SYSTEM_APP,
+                UPDATED_SYSTEM_APP,
+                HOME_APP,
+                IN_LAUNCHER_APP,
             ),
             userId = ADMIN_USER_ID,
         )
diff --git a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/model/app/AppListViewModelTest.kt b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/model/app/AppListViewModelTest.kt
index 9b22497..4d9d6da 100644
--- a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/model/app/AppListViewModelTest.kt
+++ b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/model/app/AppListViewModelTest.kt
@@ -25,7 +25,6 @@
 import com.android.settingslib.spa.testutils.waitUntil
 import com.android.settingslib.spaprivileged.template.app.AppListConfig
 import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.first
 import kotlinx.coroutines.flow.flowOf
@@ -37,7 +36,6 @@
 import org.mockito.junit.MockitoJUnit
 import org.mockito.junit.MockitoRule
 
-@OptIn(ExperimentalCoroutinesApi::class)
 @RunWith(AndroidJUnit4::class)
 class AppListViewModelTest {
     @get:Rule
diff --git a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppInfoTest.kt b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppInfoTest.kt
index 6831e56..ab34f68 100644
--- a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppInfoTest.kt
+++ b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppInfoTest.kt
@@ -23,10 +23,12 @@
 import androidx.compose.runtime.CompositionLocalProvider
 import androidx.compose.ui.platform.LocalContext
 import androidx.compose.ui.test.assertIsDisplayed
+import androidx.compose.ui.test.hasText
 import androidx.compose.ui.test.junit4.createComposeRule
 import androidx.compose.ui.test.onNodeWithText
 import androidx.test.core.app.ApplicationProvider
 import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.android.settingslib.spa.testutils.waitUntilExists
 import org.junit.Rule
 import org.junit.Test
 import org.junit.runner.RunWith
@@ -51,7 +53,7 @@
             }
         }
 
-        composeTestRule.onNodeWithText(LABEL).assertIsDisplayed()
+        composeTestRule.waitUntilExists(hasText(LABEL))
     }
 
     @Test
diff --git a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppListTest.kt b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppListTest.kt
index 241a134..124ced6 100644
--- a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppListTest.kt
+++ b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppListTest.kt
@@ -21,14 +21,16 @@
 import android.icu.text.CollationKey
 import androidx.compose.material3.Text
 import androidx.compose.runtime.Composable
+import androidx.compose.ui.test.ExperimentalTestApi
 import androidx.compose.ui.test.assertIsDisplayed
+import androidx.compose.ui.test.hasText
 import androidx.compose.ui.test.junit4.createComposeRule
 import androidx.compose.ui.test.onNodeWithText
 import androidx.compose.ui.test.performClick
 import androidx.compose.ui.unit.dp
 import androidx.test.core.app.ApplicationProvider
 import androidx.test.ext.junit.runners.AndroidJUnit4
-import com.android.settingslib.spa.framework.compose.toState
+import com.android.settingslib.spa.framework.compose.stateOf
 import com.android.settingslib.spa.widget.ui.SpinnerOption
 import com.android.settingslib.spaprivileged.R
 import com.android.settingslib.spaprivileged.model.app.AppEntry
@@ -42,6 +44,7 @@
 import org.junit.Test
 import org.junit.runner.RunWith
 
+@OptIn(ExperimentalTestApi::class)
 @RunWith(AndroidJUnit4::class)
 class AppListTest {
     @get:Rule
@@ -53,7 +56,10 @@
     fun whenHasOptions_firstOptionDisplayed() {
         setContent(options = listOf(OPTION_0, OPTION_1))
 
-        composeTestRule.onNodeWithText(OPTION_0).assertIsDisplayed()
+        composeTestRule.waitUntilExactlyOneExists(
+            matcher = hasText(OPTION_0),
+            timeoutMillis = 5_000,
+        )
         composeTestRule.onNodeWithText(OPTION_1).assertDoesNotExist()
     }
 
@@ -61,6 +67,10 @@
     fun whenHasOptions_couldSwitchOption() {
         setContent(options = listOf(OPTION_0, OPTION_1))
 
+        composeTestRule.waitUntilExactlyOneExists(
+            matcher = hasText(OPTION_0),
+            timeoutMillis = 5_000,
+        )
         composeTestRule.onNodeWithText(OPTION_0).performClick()
         composeTestRule.onNodeWithText(OPTION_1).performClick()
 
@@ -72,22 +82,30 @@
     fun whenNoApps() {
         setContent(appEntries = emptyList())
 
-        composeTestRule.onNodeWithText(context.getString(R.string.no_applications))
-            .assertIsDisplayed()
+        composeTestRule.waitUntilExactlyOneExists(
+            matcher = hasText(context.getString(R.string.no_applications)),
+            timeoutMillis = 5_000,
+        )
     }
 
     @Test
     fun couldShowAppItem() {
         setContent(appEntries = listOf(APP_ENTRY_A))
 
-        composeTestRule.onNodeWithText(APP_ENTRY_A.label).assertIsDisplayed()
+        composeTestRule.waitUntilExactlyOneExists(
+            matcher = hasText(APP_ENTRY_A.label),
+            timeoutMillis = 5_000,
+        )
     }
 
     @Test
     fun couldShowHeader() {
         setContent(appEntries = listOf(APP_ENTRY_A), header = { Text(HEADER) })
 
-        composeTestRule.onNodeWithText(HEADER).assertIsDisplayed()
+        composeTestRule.waitUntilExactlyOneExists(
+            matcher = hasText(HEADER),
+            timeoutMillis = 5_000,
+        )
     }
 
     @Test
@@ -102,7 +120,10 @@
     fun whenGrouped_groupTitleDisplayed() {
         setContent(appEntries = listOf(APP_ENTRY_A, APP_ENTRY_B), enableGrouping = true)
 
-        composeTestRule.onNodeWithText(GROUP_A).assertIsDisplayed()
+        composeTestRule.waitUntilExactlyOneExists(
+            matcher = hasText(GROUP_A),
+            timeoutMillis = 5_000,
+        )
         composeTestRule.onNodeWithText(GROUP_B).assertIsDisplayed()
     }
 
@@ -112,29 +133,26 @@
         header: @Composable () -> Unit = {},
         enableGrouping: Boolean = false,
     ) {
+        val appListInput = AppListInput(
+            config = AppListConfig(
+                userIds = listOf(USER_ID),
+                showInstantApps = false,
+                matchAnyUserForAdmin = false,
+            ),
+            listModel = TestAppListModel(enableGrouping = enableGrouping),
+            state = AppListState(showSystem = stateOf(false), searchQuery = stateOf("")),
+            header = header,
+            bottomPadding = 0.dp,
+        )
+        val listViewModel = object : IAppListViewModel<TestAppRecord> {
+            override val optionFlow = MutableStateFlow<Int?>(null)
+            override val spinnerOptionsFlow = flowOf(options.mapIndexed { index, option ->
+                SpinnerOption(id = index, text = option)
+            })
+            override val appListDataFlow = flowOf(AppListData(appEntries, option = 0))
+        }
         composeTestRule.setContent {
-            AppListInput(
-                config = AppListConfig(
-                    userIds = listOf(USER_ID),
-                    showInstantApps = false,
-                    matchAnyUserForAdmin = false,
-                ),
-                listModel = TestAppListModel(enableGrouping = enableGrouping),
-                state = AppListState(
-                    showSystem = false.toState(),
-                    searchQuery = "".toState(),
-                ),
-                header = header,
-                bottomPadding = 0.dp,
-            ).AppListImpl {
-                object : IAppListViewModel<TestAppRecord> {
-                    override val optionFlow: MutableStateFlow<Int?> = MutableStateFlow(null)
-                    override val spinnerOptionsFlow = flowOf(options.mapIndexed { index, option ->
-                        SpinnerOption(id = index, text = option)
-                    })
-                    override val appListDataFlow = flowOf(AppListData(appEntries, option = 0))
-                }
-            }
+            appListInput.AppListImpl { listViewModel }
         }
     }
 
diff --git a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppOpPermissionAppListTest.kt b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppOpPermissionAppListTest.kt
index c54f4f8..f4faa0a 100644
--- a/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppOpPermissionAppListTest.kt
+++ b/packages/SettingsLib/SpaPrivileged/tests/src/com/android/settingslib/spaprivileged/template/app/AppOpPermissionAppListTest.kt
@@ -31,7 +31,6 @@
 import com.android.settingslib.spaprivileged.model.app.IPackageManagers
 import com.android.settingslib.spaprivileged.test.R
 import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.flowOf
 import kotlinx.coroutines.test.runTest
 import org.junit.Before
@@ -44,12 +43,11 @@
 import org.mockito.Mockito.anyString
 import org.mockito.Mockito.doNothing
 import org.mockito.Mockito.verify
-import org.mockito.Mockito.`when` as whenever
 import org.mockito.Spy
 import org.mockito.junit.MockitoJUnit
 import org.mockito.junit.MockitoRule
+import org.mockito.Mockito.`when` as whenever
 
-@OptIn(ExperimentalCoroutinesApi::class)
 @RunWith(AndroidJUnit4::class)
 class AppOpPermissionAppListTest {
     @get:Rule val mockito: MockitoRule = MockitoJUnit.rule()
diff --git a/packages/SettingsLib/aconfig/settingslib_media_flag_declarations.aconfig b/packages/SettingsLib/aconfig/settingslib_media_flag_declarations.aconfig
index 0b74fa8..d1bcb57 100644
--- a/packages/SettingsLib/aconfig/settingslib_media_flag_declarations.aconfig
+++ b/packages/SettingsLib/aconfig/settingslib_media_flag_declarations.aconfig
@@ -2,7 +2,7 @@
 
 flag {
   name: "use_media_router2_for_info_media_manager"
-  namespace: "placeholder_namespace"
+  namespace: "media_solutions"
   description: "Gates whether to use a MediaRouter2-based implementation of InfoMediaManager, instead of the legacy MediaRouter2Manager-based implementation."
   bug: "192657812"
 }
\ No newline at end of file
diff --git a/packages/SettingsLib/res/values-af/strings.xml b/packages/SettingsLib/res/values-af/strings.xml
index ab07758..df32ef2 100644
--- a/packages/SettingsLib/res/values-af/strings.xml
+++ b/packages/SettingsLib/res/values-af/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Lêeroordrag"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Invoertoestel"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internettoegang"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Deling van kontakte en oproepgeskiedenis"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Gebruik vir deling van kontakte en oproepgeskiedenis"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Deling van internetverbinding"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Teksboodskappe"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM-toegang"</string>
diff --git a/packages/SettingsLib/res/values-am/strings.xml b/packages/SettingsLib/res/values-am/strings.xml
index 8d9bf8c..c20a9606 100644
--- a/packages/SettingsLib/res/values-am/strings.xml
+++ b/packages/SettingsLib/res/values-am/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ፋይል ማስተላለፍ"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ግቤት መሣሪያ"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"የበይነመረብ ድረስ"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"የእውቂያዎች እና የጥሪ ታሪክ ማጋራት"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"እውቂያዎችን እና የጥሪ ታሪክን ለማጋራት ይጠቀሙበት"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"የበይነ መረብ ተያያዥ ማጋሪያ"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"የጽሑፍ መልዕክቶች"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"የሲም መዳረሻ"</string>
diff --git a/packages/SettingsLib/res/values-ar/strings.xml b/packages/SettingsLib/res/values-ar/strings.xml
index 5a1a135..7337d73 100644
--- a/packages/SettingsLib/res/values-ar/strings.xml
+++ b/packages/SettingsLib/res/values-ar/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"نقل الملف"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"جهاز الإرسال"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"الوصول إلى الإنترنت"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"مشاركة جهات الاتصال وسجل المكالمات"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"استخدام إعدادات بلوتوث لمشاركة جهات الاتصال وسجل المكالمات"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"مشاركة اتصال الإنترنت"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"الرسائل النصية"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"‏الوصول إلى شريحة SIM"</string>
diff --git a/packages/SettingsLib/res/values-as/strings.xml b/packages/SettingsLib/res/values-as/strings.xml
index 6080dbf..dd3e5f4 100644
--- a/packages/SettingsLib/res/values-as/strings.xml
+++ b/packages/SettingsLib/res/values-as/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ফাইল স্থানান্তৰণ"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ইনপুট ডিভাইচ"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"ইণ্টাৰনেট সংযোগ"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"সম্পৰ্কসূচী আৰু কলৰ ইতিহাস শ্বেয়াৰ কৰা"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"সম্পৰ্কসূচী আৰু কলৰ ইতিহাস শ্বেয়াৰ কৰাৰ বাবে ব্যৱহাৰ কৰক"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"ইণ্টাৰনেট সংযোগ শ্বেয়াৰ"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"পাঠ বাৰ্তা"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"ছিমৰ এক্সেছ"</string>
diff --git a/packages/SettingsLib/res/values-az/strings.xml b/packages/SettingsLib/res/values-az/strings.xml
index 3cf8afa..05231ac 100644
--- a/packages/SettingsLib/res/values-az/strings.xml
+++ b/packages/SettingsLib/res/values-az/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Fayl transferi"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Daxiletmə cihazı"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"İnternetə giriş"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Kontaktlar və zəng tarixçəsi paylaşımı"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Kontaktlar və zəng tarixçəsi paylaşımı üçün istifadə edin"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"internet bağlantı paylaşımı"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Mətn Mesajları"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM-karta giriş"</string>
diff --git a/packages/SettingsLib/res/values-b+sr+Latn/strings.xml b/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
index 29d2f72..3cefd59 100644
--- a/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
+++ b/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Prenos datoteke"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Ulazni uređaj"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Pristup Internetu"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Deljenje kontakata i istorije poziva"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Koristite za deljenje kontakata i istorije poziva"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Deljenje internet veze"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS-ovi"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Pristup SIM kartici"</string>
diff --git a/packages/SettingsLib/res/values-be/arrays.xml b/packages/SettingsLib/res/values-be/arrays.xml
index b993eb6..e70d694 100644
--- a/packages/SettingsLib/res/values-be/arrays.xml
+++ b/packages/SettingsLib/res/values-be/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (бяспечны)"</item>
     <item msgid="7322156123728520872">"4K (шырокамаштабны)"</item>
     <item msgid="7735692090314849188">"4K (шырокамаштабны, бяспечны)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (два экраны)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"Няма"</item>
diff --git a/packages/SettingsLib/res/values-be/strings.xml b/packages/SettingsLib/res/values-be/strings.xml
index 6489255..47fa1db 100644
--- a/packages/SettingsLib/res/values-be/strings.xml
+++ b/packages/SettingsLib/res/values-be/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Перадача файлаў"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Прылада ўводу"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Доступ у інтэрнэт"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Абагульванне кантактаў і гісторыі выклікаў"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Ужываць для абагульвання кантактаў і гісторыі выклікаў"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Прадастаўленне доступу да Інтэрнэту"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Тэкставыя паведамленні"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Доступ да SIM-карты"</string>
diff --git a/packages/SettingsLib/res/values-bg/strings.xml b/packages/SettingsLib/res/values-bg/strings.xml
index 91dbb33..bd117b0 100644
--- a/packages/SettingsLib/res/values-bg/strings.xml
+++ b/packages/SettingsLib/res/values-bg/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Прехвърляне на файл"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Входно устройство"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Достъп до интернет"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Споделяне на контактите и ист. на обажд."</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Служи за споделяне на контактите и историята на обажданията"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Споделяне на връзката с интернет"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Текстови съобщения"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Достъп до SIM картата"</string>
diff --git a/packages/SettingsLib/res/values-bn/strings.xml b/packages/SettingsLib/res/values-bn/strings.xml
index fdbc9e4..d701894 100644
--- a/packages/SettingsLib/res/values-bn/strings.xml
+++ b/packages/SettingsLib/res/values-bn/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ফাইল স্থানান্তর"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ইনপুট ডিভাইস"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"ইন্টারনেট অ্যাক্সেস"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"পরিচিতি এবং কলের ইতিহাস শেয়ার করা"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"পরিচিতি ও কলের ইতিহাস শেয়ার করার জন্য ব্যবহার করুন"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"ইন্টারনেট কানেকশন শেয়ার করা হচ্ছে"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"এসএমএস"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"সিম অ্যাক্সেস"</string>
diff --git a/packages/SettingsLib/res/values-bs/strings.xml b/packages/SettingsLib/res/values-bs/strings.xml
index ec84dc63..99e160d 100644
--- a/packages/SettingsLib/res/values-bs/strings.xml
+++ b/packages/SettingsLib/res/values-bs/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Prenošenje fajla"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Ulazni uređaj"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Pristup internetu"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Dijeljenje kontakata i historije poziva"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Upotrijebite za dijeljenje kontakata i historije poziva"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Dijeljenje internet veze"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS-ovi"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Pristup SIM-u"</string>
diff --git a/packages/SettingsLib/res/values-ca/strings.xml b/packages/SettingsLib/res/values-ca/strings.xml
index 2901385..49358bd 100644
--- a/packages/SettingsLib/res/values-ca/strings.xml
+++ b/packages/SettingsLib/res/values-ca/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transferència de fitxers"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Dispositiu d\'entrada"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Accés a Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Compartició de contactes i historial de trucades"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Utilitza per compartir contactes i l\'historial de trucades"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Compartició de connexió d\'Internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Missatges de text"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Accés a la SIM"</string>
diff --git a/packages/SettingsLib/res/values-cs/strings.xml b/packages/SettingsLib/res/values-cs/strings.xml
index b52e7b7..dc2d456 100644
--- a/packages/SettingsLib/res/values-cs/strings.xml
+++ b/packages/SettingsLib/res/values-cs/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Přenos souborů"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Vstupní zařízení"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Přístup k internetu"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Sdílení kontaktů a historie volání"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Používat ke sdílení kontaktů a historie hovorů"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Sdílení internetového připojení"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Textové zprávy"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Přístup k SIM kartě"</string>
diff --git a/packages/SettingsLib/res/values-da/strings.xml b/packages/SettingsLib/res/values-da/strings.xml
index b96c28a..83a67c1 100644
--- a/packages/SettingsLib/res/values-da/strings.xml
+++ b/packages/SettingsLib/res/values-da/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Filoverførsel"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Inputenhed"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internetadgang"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Deling af kontakter og opkaldshistorik"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Brug til deling af kontakter og opkaldshistorik"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Deling af internetforbindelse"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Sms-beskeder"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Adgang til SIM-kort"</string>
diff --git a/packages/SettingsLib/res/values-de/strings.xml b/packages/SettingsLib/res/values-de/strings.xml
index d93baf1..6575f20 100644
--- a/packages/SettingsLib/res/values-de/strings.xml
+++ b/packages/SettingsLib/res/values-de/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Dateiübertragung"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Eingabegerät"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internetzugriff"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Teilen von Kontakten und der Anrufliste"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Zum Teilen von Kontakten und der Anrufliste verwenden"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Freigabe der Internetverbindung"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Zugriff auf SIM"</string>
diff --git a/packages/SettingsLib/res/values-el/strings.xml b/packages/SettingsLib/res/values-el/strings.xml
index e8edbff..1a36ef8 100644
--- a/packages/SettingsLib/res/values-el/strings.xml
+++ b/packages/SettingsLib/res/values-el/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Μεταφορά αρχείου"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Συσκευή εισόδου"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Πρόσβαση στο Διαδίκτυο"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Κοινοποίηση επαφών και ιστορικού κλήσεων"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Χρήση για την κοινοποίηση επαφών και του ιστορικού κλήσεων"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Κοινή χρήση σύνδεσης στο Διαδίκτυο"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Μηνύματα κειμένου"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Πρόσβαση SIM"</string>
diff --git a/packages/SettingsLib/res/values-en-rAU/strings.xml b/packages/SettingsLib/res/values-en-rAU/strings.xml
index 2a2e4ca..fa00776 100644
--- a/packages/SettingsLib/res/values-en-rAU/strings.xml
+++ b/packages/SettingsLib/res/values-en-rAU/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"File transfer"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Input device"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internet access"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Contacts and call history sharing"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Use for contacts and call history sharing"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Internet connection sharing"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Text messages"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM access"</string>
diff --git a/packages/SettingsLib/res/values-en-rCA/strings.xml b/packages/SettingsLib/res/values-en-rCA/strings.xml
index a9a95b1..5b1e86f 100644
--- a/packages/SettingsLib/res/values-en-rCA/strings.xml
+++ b/packages/SettingsLib/res/values-en-rCA/strings.xml
@@ -107,8 +107,8 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"File transfer"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Input device"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internet access"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Contacts and call history sharing"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Use for contacts and call history sharing"</string>
+    <string name="bluetooth_profile_pbap" msgid="2103406516858653017">"Allow access to contacts and call history"</string>
+    <string name="bluetooth_profile_pbap_summary" msgid="402819589201138227">"Info will be used for call announcements and more"</string>
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Internet connection sharing"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Text Messages"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM Access"</string>
diff --git a/packages/SettingsLib/res/values-en-rGB/strings.xml b/packages/SettingsLib/res/values-en-rGB/strings.xml
index 2a2e4ca..fa00776 100644
--- a/packages/SettingsLib/res/values-en-rGB/strings.xml
+++ b/packages/SettingsLib/res/values-en-rGB/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"File transfer"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Input device"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internet access"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Contacts and call history sharing"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Use for contacts and call history sharing"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Internet connection sharing"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Text messages"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM access"</string>
diff --git a/packages/SettingsLib/res/values-en-rIN/strings.xml b/packages/SettingsLib/res/values-en-rIN/strings.xml
index 2a2e4ca..fa00776 100644
--- a/packages/SettingsLib/res/values-en-rIN/strings.xml
+++ b/packages/SettingsLib/res/values-en-rIN/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"File transfer"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Input device"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internet access"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Contacts and call history sharing"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Use for contacts and call history sharing"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Internet connection sharing"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Text messages"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM access"</string>
diff --git a/packages/SettingsLib/res/values-en-rXC/strings.xml b/packages/SettingsLib/res/values-en-rXC/strings.xml
index af34e5b..8f4ba0e 100644
--- a/packages/SettingsLib/res/values-en-rXC/strings.xml
+++ b/packages/SettingsLib/res/values-en-rXC/strings.xml
@@ -107,8 +107,8 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‎‏‏‏‎‎‏‏‏‎‎‎‎‎‏‏‏‏‎‏‎‏‎‎‏‎‎‎‎‎‏‏‏‏‎‎‏‏‏‎‏‏‏‎‏‏‏‏‏‎‎‏‏‎‏‎‏‏‎‏‏‎‎File transfer‎‏‎‎‏‎"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‎‏‎‏‎‎‏‎‎‏‏‎‏‏‏‎‏‎‎‏‎‎‏‎‎‏‎‏‎‎‏‏‎‏‎‏‏‏‏‏‎‏‏‎‎‏‎‎‏‎‎‏‎‏‏‏‏‎‏‏‎‏‎‎Input device‎‏‎‎‏‎"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‎‎‏‏‎‏‏‏‏‏‎‏‏‎‏‏‎‏‏‏‎‏‏‎‎‎‎‏‏‏‎‎‏‎‎‏‏‎‏‏‏‏‏‏‎‎‏‏‏‎‏‏‎‏‏‏‏‎‏‏‎‎‎Internet access‎‏‎‎‏‎"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‎‏‏‏‎‏‏‎‎‏‎‎‏‏‎‏‎‏‏‏‏‏‎‎‏‎‏‏‎‎‏‎‏‎‎‎‏‏‎‎‎‎‎‏‏‎‏‎‏‏‏‎‎‎‏‏‏‎‏‏‎‏‏‎Contacts and call history sharing‎‏‎‎‏‎"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‎‏‏‎‎‏‏‎‏‏‏‏‎‏‎‏‏‏‏‎‎‎‎‎‏‏‎‎‎‎‏‏‏‎‎‏‎‎‎‎‎‏‏‏‎‎‏‏‎‏‎‏‏‏‏‏‎‏‏‏‎‎‎Use for contacts and call history sharing‎‏‎‎‏‎"</string>
+    <string name="bluetooth_profile_pbap" msgid="2103406516858653017">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‎‏‏‏‏‎‏‎‎‏‏‎‎‎‎‏‏‎‎‏‏‎‏‎‎‎‏‎‏‎‏‎‎‏‎‏‏‏‏‏‎‎‏‏‎‏‎‎‎‎‎‏‎‎‏‎‏‎‏‏‎‎‏‎Allow access to contacts and call history‎‏‎‎‏‎"</string>
+    <string name="bluetooth_profile_pbap_summary" msgid="402819589201138227">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‎‏‏‏‎‏‏‎‎‏‎‏‏‏‎‎‎‏‏‎‏‎‎‏‎‎‏‎‎‎‎‎‏‏‏‎‏‎‏‏‏‎‎‏‏‏‎‎‎‏‎‎‏‎‎‎‏‏‎‎‏‏‎Info will be used for call announcements and more‎‏‎‎‏‎"</string>
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‏‎‏‏‎‏‎‎‏‏‏‏‏‎‏‏‎‏‏‏‏‏‎‏‎‏‎‏‎‎‏‏‎‎‎‎‏‎‎‏‏‎‏‏‏‎‎‏‏‎‏‏‏‏‏‎‏‎‎‎‏‎‎Internet connection sharing‎‏‎‎‏‎"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‏‏‏‎‏‏‏‎‎‏‏‏‎‎‏‎‏‏‏‏‏‏‎‏‏‏‏‎‏‏‏‎‏‏‏‎‏‎‎‏‏‏‎‏‎‎‏‏‏‏‎‎‎‏‏‎‎‎‎‏‏‏‎Text Messages‎‏‎‎‏‎"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‏‏‎‎‏‏‎‎‏‏‏‏‏‎‎‏‎‏‎‏‏‏‎‏‏‏‏‎‏‏‎‏‏‎‎‏‏‏‏‎‎‏‎‎‎‏‎‎‏‎‏‎‏‏‏‎‏‏‎‎‏‎‎SIM Access‎‏‎‎‏‎"</string>
diff --git a/packages/SettingsLib/res/values-es-rUS/strings.xml b/packages/SettingsLib/res/values-es-rUS/strings.xml
index 52cd3fa..ec6e152 100644
--- a/packages/SettingsLib/res/values-es-rUS/strings.xml
+++ b/packages/SettingsLib/res/values-es-rUS/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transferencia de archivos"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Dispositivo de entrada"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Acceso a Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Compartir contactos e historial de llamadas"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Uso para compartir contactos e historial de llamadas"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Compartir conexión a Internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Mensajes de texto"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Acceso a SIM"</string>
diff --git a/packages/SettingsLib/res/values-es/strings.xml b/packages/SettingsLib/res/values-es/strings.xml
index dfad8d3..6934f8a 100644
--- a/packages/SettingsLib/res/values-es/strings.xml
+++ b/packages/SettingsLib/res/values-es/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transferencia de archivos"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Dispositivo de entrada"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Acceso a Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Compartir contactos e historial de llamadas"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Usar para compartir los contactos y el historial de llamadas"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Compartir conexión a Internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Mensajes de texto"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Acceso a tarjeta SIM"</string>
diff --git a/packages/SettingsLib/res/values-et/strings.xml b/packages/SettingsLib/res/values-et/strings.xml
index 53995ce..9979eda 100644
--- a/packages/SettingsLib/res/values-et/strings.xml
+++ b/packages/SettingsLib/res/values-et/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Failiedastus"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Sisendseade"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Juurdepääs internetile"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Kontaktide ja kõneajaloo jagamine"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Kasutage kontaktide ja kõneajaloo jagamiseks"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Interneti-ühenduse jagamine"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Tekstsõnumid"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Juurdepääs SIM-ile"</string>
diff --git a/packages/SettingsLib/res/values-eu/arrays.xml b/packages/SettingsLib/res/values-eu/arrays.xml
index 106dc89..95adf96 100644
--- a/packages/SettingsLib/res/values-eu/arrays.xml
+++ b/packages/SettingsLib/res/values-eu/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (segurua)"</item>
     <item msgid="7322156123728520872">"4K (hobetua)"</item>
     <item msgid="7735692090314849188">"4K (hobetua, segurua)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (bi pantaila)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"Bat ere ez"</item>
diff --git a/packages/SettingsLib/res/values-eu/strings.xml b/packages/SettingsLib/res/values-eu/strings.xml
index 06528e5..dacd8c6 100644
--- a/packages/SettingsLib/res/values-eu/strings.xml
+++ b/packages/SettingsLib/res/values-eu/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Fitxategi-transferentzia"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Sarrerako gailua"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Interneteko konexioa"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Kontaktuak eta deien historia partekatzeko aukera"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Erabili kontaktuetarako eta deien historia partekatzeko"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Interneteko konexioa partekatzea"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Testu-mezuak"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIMerako sarbidea"</string>
diff --git a/packages/SettingsLib/res/values-fa/strings.xml b/packages/SettingsLib/res/values-fa/strings.xml
index a46e327..b67b2d7 100644
--- a/packages/SettingsLib/res/values-fa/strings.xml
+++ b/packages/SettingsLib/res/values-fa/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"انتقال فایل"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"دستگاه ورودی"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"دسترسی به اینترنت"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"هم‌رسانی مخاطبین و سابقه تماس"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"استفاده برای هم‌رسانی مخاطبین و سابقه تماس"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"اشتراک‌گذاری اتصال اینترنت"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"پیام‌های نوشتاری"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"دسترسی سیم‌کارت"</string>
diff --git a/packages/SettingsLib/res/values-fi/strings.xml b/packages/SettingsLib/res/values-fi/strings.xml
index a5ce348..45d9784 100644
--- a/packages/SettingsLib/res/values-fi/strings.xml
+++ b/packages/SettingsLib/res/values-fi/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Tiedostonsiirto"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Syöttölaite"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internetyhteys"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Yhteystietojen ja soittohistorian jako"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Käytä yhteystiedoissa ja soittohistorian jakamiseen"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Internetyhteyden jakaminen"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Tekstiviestit"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM-kortin käyttö"</string>
diff --git a/packages/SettingsLib/res/values-fr-rCA/arrays.xml b/packages/SettingsLib/res/values-fr-rCA/arrays.xml
index 8bba20d..15cb17d 100644
--- a/packages/SettingsLib/res/values-fr-rCA/arrays.xml
+++ b/packages/SettingsLib/res/values-fr-rCA/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (sécurisé)"</item>
     <item msgid="7322156123728520872">"4K (adapté à la haute résolution)"</item>
     <item msgid="7735692090314849188">"4K (adapté haute rés., sécurisé)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (double écran)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"Aucun"</item>
diff --git a/packages/SettingsLib/res/values-fr-rCA/strings.xml b/packages/SettingsLib/res/values-fr-rCA/strings.xml
index fa565e6..c165acc5 100644
--- a/packages/SettingsLib/res/values-fr-rCA/strings.xml
+++ b/packages/SettingsLib/res/values-fr-rCA/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transfert de fichier"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Périphérique d\'entrée"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Accès Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Partage des contacts et des appels"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Sert à partager des contacts et l\'historique des appels"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Partage de connexion Internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Messages texte"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Accès à la carte SIM"</string>
diff --git a/packages/SettingsLib/res/values-fr/strings.xml b/packages/SettingsLib/res/values-fr/strings.xml
index 4972ebb..55658e7 100644
--- a/packages/SettingsLib/res/values-fr/strings.xml
+++ b/packages/SettingsLib/res/values-fr/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transfert de fichiers"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Périphérique d\'entrée"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Accès Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Partage contacts/historique des appels"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"À utiliser pour partage des contacts/historique des appels"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Partage de connexion Internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Accès à la SIM"</string>
diff --git a/packages/SettingsLib/res/values-gl/strings.xml b/packages/SettingsLib/res/values-gl/strings.xml
index fadaea5..f1d0ed1 100644
--- a/packages/SettingsLib/res/values-gl/strings.xml
+++ b/packages/SettingsLib/res/values-gl/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transferencia de ficheiros"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Dispositivo de entrada"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Acceso a Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Compartir contactos e hist. de chamadas"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Uso da opción de compartir contactos e historial de chamadas"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Uso compartido da conexión a Internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Mensaxes de texto"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Acceso á SIM"</string>
diff --git a/packages/SettingsLib/res/values-gu/arrays.xml b/packages/SettingsLib/res/values-gu/arrays.xml
index c4f90e4..4f7cbd2 100644
--- a/packages/SettingsLib/res/values-gu/arrays.xml
+++ b/packages/SettingsLib/res/values-gu/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (સુરક્ષિત)"</item>
     <item msgid="7322156123728520872">"4K (ઉચ્ચ સ્તરીય)"</item>
     <item msgid="7735692090314849188">"4K (ઉચ્ચ સ્તરીય, સુરક્ષિત)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (દ્વિ સ્ક્રીન)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"કોઈ નહીં"</item>
diff --git a/packages/SettingsLib/res/values-gu/strings.xml b/packages/SettingsLib/res/values-gu/strings.xml
index 11bd628..9f84dd4 100644
--- a/packages/SettingsLib/res/values-gu/strings.xml
+++ b/packages/SettingsLib/res/values-gu/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ફાઇલ સ્થાનાંતરણ"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ઇનપુટ ડિવાઇસ"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"ઇન્ટરનેટ ઍક્સેસ"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"સંપર્કો અને કૉલ ઇતિહાસની શેરિંગ"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"સંપર્કો અને કૉલ ઇતિહાસની શેરિંગ માટે ઉપયોગ કરો"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"ઇન્ટરનેટ કનેક્શન શેરિંગ"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"ટેક્સ્ટ સંદેશા"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"સિમ ઍક્સેસ"</string>
diff --git a/packages/SettingsLib/res/values-hi/strings.xml b/packages/SettingsLib/res/values-hi/strings.xml
index 828fb60..f417f8e 100644
--- a/packages/SettingsLib/res/values-hi/strings.xml
+++ b/packages/SettingsLib/res/values-hi/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"फ़ाइल स्थानांतरण"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"इनपुट डिवाइस"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"इंटरनेट ऐक्सेस"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"संपर्क और कॉल का इतिहास शेयर करें"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"इसका इस्तेमाल संपर्क और कॉल का इतिहास शेयर करने के लिए करें"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"इंटरनेट कनेक्शन साझाकरण"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"लेख संदेश"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"सिम ऐक्सेस"</string>
diff --git a/packages/SettingsLib/res/values-hr/strings.xml b/packages/SettingsLib/res/values-hr/strings.xml
index 4c2f89a..0da7d1d 100644
--- a/packages/SettingsLib/res/values-hr/strings.xml
+++ b/packages/SettingsLib/res/values-hr/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Prijenos datoteke"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Ulazni uređaj"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Pristup internetu"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Dijeljenje kontakata i povijesti poziva"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Upotreba za dijeljenje kontakata i povijesti poziva"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Dijeljenje internetske veze"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS-ovi"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Pristup SIM-u"</string>
diff --git a/packages/SettingsLib/res/values-hu/strings.xml b/packages/SettingsLib/res/values-hu/strings.xml
index 136afb1..1bca6a0 100644
--- a/packages/SettingsLib/res/values-hu/strings.xml
+++ b/packages/SettingsLib/res/values-hu/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Fájlátvitel"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Beviteli eszköz"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internetelérés"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Névjegyek és hívásnapló megosztása"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Névjegyek és hívásnapló megosztásához használható"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Internetkapcsolat megosztása"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Szöveges üzenetek"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM-elérés"</string>
diff --git a/packages/SettingsLib/res/values-hy/strings.xml b/packages/SettingsLib/res/values-hy/strings.xml
index 58b2df54..a5bccea 100644
--- a/packages/SettingsLib/res/values-hy/strings.xml
+++ b/packages/SettingsLib/res/values-hy/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Ֆայլերի փոխանցում"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Ներմուծման սարք"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Ինտերնետի հասանելիություն"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Կիսվել կոնտակտներով/զանգերի պատմությամբ"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Օգտագործել՝ կոնտակտներով/զանգերի պատմությամբ կիսվելու համար"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Ինտերնետ կապի տարածում"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS հաղորդագրություններ"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM քարտի հասանելիություն"</string>
diff --git a/packages/SettingsLib/res/values-in/arrays.xml b/packages/SettingsLib/res/values-in/arrays.xml
index e309af7..038800c 100644
--- a/packages/SettingsLib/res/values-in/arrays.xml
+++ b/packages/SettingsLib/res/values-in/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (aman)"</item>
     <item msgid="7322156123728520872">"4K (ditingkatkan)"</item>
     <item msgid="7735692090314849188">"4K (ditingkatkan, aman)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (layar ganda)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"Tidak ada"</item>
diff --git a/packages/SettingsLib/res/values-in/strings.xml b/packages/SettingsLib/res/values-in/strings.xml
index 71ecc34..d9c0a06 100644
--- a/packages/SettingsLib/res/values-in/strings.xml
+++ b/packages/SettingsLib/res/values-in/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transfer file"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Perangkat masukan"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Akses Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Berbagi kontak dan histori panggilan"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Gunakan untuk berbagi kontak dan histori panggilan"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Berbagi koneksi internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Akses SIM"</string>
diff --git a/packages/SettingsLib/res/values-is/strings.xml b/packages/SettingsLib/res/values-is/strings.xml
index d78bd13..7e746ff 100644
--- a/packages/SettingsLib/res/values-is/strings.xml
+++ b/packages/SettingsLib/res/values-is/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Skráaflutningur"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Inntakstæki"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internetaðgangur"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Deiling tengiliða og símtalaferils"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Nota til að deila tengiliðum og símtalaferli"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Deiling nettengingar"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Textaskilaboð"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Aðgangur að SIM-korti"</string>
diff --git a/packages/SettingsLib/res/values-it/strings.xml b/packages/SettingsLib/res/values-it/strings.xml
index becf59e0..1e4b981 100644
--- a/packages/SettingsLib/res/values-it/strings.xml
+++ b/packages/SettingsLib/res/values-it/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Trasferimento file"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Dispositivo di input"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Accesso a Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Condivisione contatti e cronologia chiamate"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Usa per condivisione di contatti e cronologia chiamate"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Condivisione connessione Internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Accesso alla SIM"</string>
@@ -545,12 +547,12 @@
     <string name="zen_mode_duration_always_prompt_title" msgid="3212996860498119555">"Chiedi ogni volta"</string>
     <string name="zen_mode_forever" msgid="3339224497605461291">"Fino alla disattivazione"</string>
     <string name="time_unit_just_now" msgid="3006134267292728099">"Adesso"</string>
-    <string name="media_transfer_this_device_name" product="default" msgid="2357329267148436433">"Questo telefono"</string>
+    <string name="media_transfer_this_device_name" product="default" msgid="2357329267148436433">"Questo smartphone"</string>
     <string name="media_transfer_this_device_name" product="tablet" msgid="3714653244000242800">"Questo tablet"</string>
     <string name="media_transfer_dock_speaker_device_name" msgid="2856219597113881950">"Base con altoparlante"</string>
     <string name="media_transfer_external_device_name" msgid="2588672258721846418">"Dispositivo esterno"</string>
     <string name="media_transfer_default_device_name" msgid="4315604017399871828">"Dispositivo connesso"</string>
-    <string name="media_transfer_this_phone" msgid="7194341457812151531">"Questo telefono"</string>
+    <string name="media_transfer_this_phone" msgid="7194341457812151531">"Questo smartphone"</string>
     <string name="media_output_status_unknown_error" msgid="5098565887497902222">"Impossibile riprodurre su questo dispositivo"</string>
     <string name="media_output_status_require_premium" msgid="8411255800047014822">"Esegui l\'upgrade dell\'account per cambiare"</string>
     <string name="media_output_status_not_support_downloads" msgid="4523828729240373315">"Qui non è possibile riprodurre i download"</string>
diff --git a/packages/SettingsLib/res/values-iw/strings.xml b/packages/SettingsLib/res/values-iw/strings.xml
index 77787dc..328cc82 100644
--- a/packages/SettingsLib/res/values-iw/strings.xml
+++ b/packages/SettingsLib/res/values-iw/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"העברת קבצים"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"מכשיר קלט"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"גישה לאינטרנט"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"שיתוף אנשי הקשר והיסטוריית השיחות"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"ההגדרה משמשת לשיתוף של אנשי הקשר והיסטוריית השיחות"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"שיתוף חיבור לאינטרנט"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"הודעות טקסט"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"‏גישה ל-SIM"</string>
@@ -316,7 +318,7 @@
     <string name="select_usb_configuration_dialog_title" msgid="3579567144722589237">"‏יש לבחור תצורת USB"</string>
     <string name="allow_mock_location" msgid="2102650981552527884">"אפשרות של מיקומים מדומים"</string>
     <string name="allow_mock_location_summary" msgid="179780881081354579">"אפשרות של מיקומים מדומים"</string>
-    <string name="debug_view_attributes" msgid="3539609843984208216">"לאפשר בדיקת תכונת תצוגה"</string>
+    <string name="debug_view_attributes" msgid="3539609843984208216">"‏לאפשר את הבדיקה של מאפיינים של ה-View"</string>
     <string name="mobile_data_always_on_summary" msgid="1112156365594371019">"‏השארת חבילת הגלישה פעילה תמיד, גם כש-Wi‑Fi פעיל (למעבר מהיר בין רשתות)."</string>
     <string name="tethering_hardware_offload_summary" msgid="7801345335142803029">"אם השירות זמין, יש להשתמש בשיפור מהירות באמצעות חומרה לצורך שיתוף אינטרנט בין ניידים"</string>
     <string name="adb_warning_title" msgid="7708653449506485728">"‏לאפשר ניפוי באגים של USB?"</string>
@@ -343,7 +345,7 @@
     <string name="select_application" msgid="2543228890535466325">"בחירת אפליקציה"</string>
     <string name="no_application" msgid="9038334538870247690">"אף אחת"</string>
     <string name="wait_for_debugger" msgid="7461199843335409809">"יש להמתין לכלי לניפוי באגים"</string>
-    <string name="wait_for_debugger_summary" msgid="6846330006113363286">"אפליקציה שנוקו בה הבאגים ממתינה למנקה הבאגים לצירוף לפני ביצוע"</string>
+    <string name="wait_for_debugger_summary" msgid="6846330006113363286">"האפליקציה שמתבצע בה ניקוי באגים ממתינה שהכלי לניפוי באגים יתחבר אליה לפני הריצה"</string>
     <string name="debug_input_category" msgid="7349460906970849771">"קלט"</string>
     <string name="debug_drawing_category" msgid="5066171112313666619">"שרטוט"</string>
     <string name="debug_hw_drawing_category" msgid="5830815169336975162">"עיבוד מואץ של חומרה"</string>
diff --git a/packages/SettingsLib/res/values-ja/strings.xml b/packages/SettingsLib/res/values-ja/strings.xml
index deaba35..46bb17e 100644
--- a/packages/SettingsLib/res/values-ja/strings.xml
+++ b/packages/SettingsLib/res/values-ja/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ファイル転送"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"入力デバイス"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"インターネットアクセス"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"連絡先と通話履歴の共有"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"連絡先と通話履歴の共有に使用します"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"インターネット接続の共有"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"テキスト メッセージ"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIMアクセス"</string>
diff --git a/packages/SettingsLib/res/values-ka/strings.xml b/packages/SettingsLib/res/values-ka/strings.xml
index fb7bada..a0205bb 100644
--- a/packages/SettingsLib/res/values-ka/strings.xml
+++ b/packages/SettingsLib/res/values-ka/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ფაილების გადაცემა"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"შეყვანის მოწყობილობა"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"ინტერნეტზე წვდომა"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"კონტაქტ. და საუბრის ისტორიის გაზიარება"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"გამოიყენეთ კონტაქტებისა და საუბრის ისტორიის გასაზიარებლად"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"ინტერნეტ კავშირის გაზიარება"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"ტექსტური შეტყობინებები"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM წვდომა"</string>
diff --git a/packages/SettingsLib/res/values-kk/strings.xml b/packages/SettingsLib/res/values-kk/strings.xml
index 0c55c2d..3b240d4 100644
--- a/packages/SettingsLib/res/values-kk/strings.xml
+++ b/packages/SettingsLib/res/values-kk/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Файл жіберу"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Кіріс құрылғысы"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Интернетке қосылу"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Контактілер мен қоңыраулар тарихын бөлісу"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Контактілер мен қоңыраулар тарихын бөлісу үшін пайдалану"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Интернет байланысын ортақ қолдану"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Мәтіндік хабарлар"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM картасына кіру"</string>
diff --git a/packages/SettingsLib/res/values-km/strings.xml b/packages/SettingsLib/res/values-km/strings.xml
index f9f964f..36c25a9 100644
--- a/packages/SettingsLib/res/values-km/strings.xml
+++ b/packages/SettingsLib/res/values-km/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ផ្ទេរ​ឯកសារ"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ឧបករណ៍​បញ្ចូល"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"ការចូលប្រើ​អ៊ីនធឺណិត"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"ការចែករំលែកទំនាក់ទំនង និងប្រវត្តិហៅទូរសព្ទ"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"ការប្រើសម្រាប់ការចែករំលែកទំនាក់ទំនង និងប្រវត្តិហៅទូរសព្ទ"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"ចែករំលែក​ការ​តភ្ជាប់​អ៊ីនធឺណិត"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"សារ​ជាអក្សរ"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"ការចូលដំណើរការស៊ីម"</string>
diff --git a/packages/SettingsLib/res/values-kn/strings.xml b/packages/SettingsLib/res/values-kn/strings.xml
index e17121a..aa93942 100644
--- a/packages/SettingsLib/res/values-kn/strings.xml
+++ b/packages/SettingsLib/res/values-kn/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ಫೈಲ್ ವರ್ಗಾವಣೆ"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ಇನ್‌ಪುಟ್‌ ಸಾಧನ"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"ಇಂಟರ್ನೆಟ್ ಆ್ಯಕ್ಸೆಸ್"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"ಸಂಪರ್ಕಗಳು ಹಾಗೂ ಕರೆ ಇತಿಹಾಸ ಹಂಚಿಕೊಳ್ಳುವಿಕೆ"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"ಸಂಪರ್ಕಗಳು ಮತ್ತು ಕರೆ ಇತಿಹಾಸ ಹಂಚಿಕೆಗಾಗಿ ಬಳಸಿ"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"ಇಂಟರ್ನೆಟ್ ಸಂಪರ್ಕ ಹಂಚಿಕೊಳ್ಳುವಿಕೆ"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"ಪಠ್ಯ ಸಂದೇಶಗಳು"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"ಸಿಮ್ ಆ್ಯಕ್ಸೆಸ್"</string>
diff --git a/packages/SettingsLib/res/values-ko/strings.xml b/packages/SettingsLib/res/values-ko/strings.xml
index 148e81d..2b2a09f 100644
--- a/packages/SettingsLib/res/values-ko/strings.xml
+++ b/packages/SettingsLib/res/values-ko/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"파일 전송"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"입력 장치"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"인터넷 액세스"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"연락처 및 통화 기록 공유"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"연락처 및 통화 기록 공유에 사용"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"인터넷 연결 공유"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"문자 메시지"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM 액세스"</string>
diff --git a/packages/SettingsLib/res/values-ky/strings.xml b/packages/SettingsLib/res/values-ky/strings.xml
index b3b5abd..92df614 100644
--- a/packages/SettingsLib/res/values-ky/strings.xml
+++ b/packages/SettingsLib/res/values-ky/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Файл алмашуу"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Киргизүү түзмөгү"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Интернетке мүмкүнчүлүк алуу"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Байланыштарды жана чалуу таржымалын бөлүшүү"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Байланыштарды жана чалуу таржымалын бөлүшүү үчүн колдонуу"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Интернет байланышын бөлүшүү"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS билдирүүлөрү"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM картаны пайдалануу мүмкүнчүлүгү"</string>
diff --git a/packages/SettingsLib/res/values-lo/strings.xml b/packages/SettingsLib/res/values-lo/strings.xml
index 3963518..fdd393d 100644
--- a/packages/SettingsLib/res/values-lo/strings.xml
+++ b/packages/SettingsLib/res/values-lo/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ການໂອນຍ້າຍໄຟລ໌"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ອຸປະກອນປ້ອນຂໍ້ມູນ"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"ການເຂົ້າເຖິງອິນເຕີເນັດ"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"ແບ່ງປັນລາຍຊື່ຜູ້ຕິດຕໍ່ ແລະ ປະຫວັດການໂທ"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"ໃຊ້ສໍາລັບແບ່ງປັນລາຍຊື່ຜູ້ຕິດຕໍ່ ແລະ ປະຫວັດການໂທ"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"ການແບ່ງປັນການເຊື່ອມຕໍ່ອິນເຕີເນັດ"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"ຂໍ້ຄວາມ"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"ການ​ເຂົ້າ​ເຖິງ SIM"</string>
diff --git a/packages/SettingsLib/res/values-lt/strings.xml b/packages/SettingsLib/res/values-lt/strings.xml
index 9ede534..7376c11 100644
--- a/packages/SettingsLib/res/values-lt/strings.xml
+++ b/packages/SettingsLib/res/values-lt/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Failo perkėlimas"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Įvesties įrenginys"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Prieiga prie interneto"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Kontaktų ir skambučių istorijos bendrinimas"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Naudoti kontaktams ir skambučių istorijai bendrinti"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Interneto ryšio bendrinimas"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Teksto pranešimai"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM prieiga"</string>
diff --git a/packages/SettingsLib/res/values-lv/arrays.xml b/packages/SettingsLib/res/values-lv/arrays.xml
index c9161d9..7626c66 100644
--- a/packages/SettingsLib/res/values-lv/arrays.xml
+++ b/packages/SettingsLib/res/values-lv/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4 KB (drošs)"</item>
     <item msgid="7322156123728520872">"4 KB (mērogots)"</item>
     <item msgid="7735692090314849188">"4 KB (mērogots, drošs)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (dubults ekrāns)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"Nav"</item>
diff --git a/packages/SettingsLib/res/values-lv/strings.xml b/packages/SettingsLib/res/values-lv/strings.xml
index c33243b..85ca364 100644
--- a/packages/SettingsLib/res/values-lv/strings.xml
+++ b/packages/SettingsLib/res/values-lv/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Failu pārsūtīšana"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Ievades ierīce"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Piekļuve internetam"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Kontaktpersonu un zvanu vēst. kopīgošana"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Paredzēts kontaktpersonu un zvanu vēstures kopīgošanai"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Interneta savienojuma koplietošana"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Īsziņas"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Piekļuve SIM kartei"</string>
diff --git a/packages/SettingsLib/res/values-mk/strings.xml b/packages/SettingsLib/res/values-mk/strings.xml
index a3d9e96..cdc0831 100644
--- a/packages/SettingsLib/res/values-mk/strings.xml
+++ b/packages/SettingsLib/res/values-mk/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Пренос на датотека"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Влезен уред"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Пристап до интернет"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Споделување контакти и историја на повици"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Користење на споделувањето контакти и историја на повици"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Споделување конекција на интернет"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Текстуални пораки"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Пристап до SIM"</string>
diff --git a/packages/SettingsLib/res/values-ml/strings.xml b/packages/SettingsLib/res/values-ml/strings.xml
index 8b3caae..fe7a375 100644
--- a/packages/SettingsLib/res/values-ml/strings.xml
+++ b/packages/SettingsLib/res/values-ml/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ഫയൽ കൈമാറൽ"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ഇൻപുട്ട് ഉപകരണം"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"ഇന്‍റർനെറ്റ് ആക്‌സസ്"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"കോ‌ൺടാക്‌റ്റുകളും കോൾ ചരിത്രം പങ്കിടലും"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"കോൺടാക്‌റ്റുകളുടെയും കോൾ ചരിത്രം പങ്കിടലിന്റെയും ഉപയോഗം"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"ഇന്റർനെറ്റ് കണക്ഷൻ പങ്കിടൽ"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"അക്ഷര സന്ദേശങ്ങൾ"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"സിം ആക്സസ്"</string>
diff --git a/packages/SettingsLib/res/values-mn/strings.xml b/packages/SettingsLib/res/values-mn/strings.xml
index a2447d26..23b3c2e 100644
--- a/packages/SettingsLib/res/values-mn/strings.xml
+++ b/packages/SettingsLib/res/values-mn/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Файл дамжуулалт"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Оруулах төхөөрөмж"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Интернэт хандалт"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Харилцагчид ба дуудлагын түүх хуваалцах"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Харилцагчид ба дуудлагын түүх хуваалцахад ашиглах"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Интернэт холболтыг хуваалцах"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Мессеж"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM Хандалт"</string>
diff --git a/packages/SettingsLib/res/values-mr/strings.xml b/packages/SettingsLib/res/values-mr/strings.xml
index e76c708..8e10da7 100644
--- a/packages/SettingsLib/res/values-mr/strings.xml
+++ b/packages/SettingsLib/res/values-mr/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"फाइल स्थानांतरण"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"इनपुट डिव्हाइस"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"इंटरनेट अ‍ॅक्सेस"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"संपर्क आणि कॉल इतिहास शेअरिंग"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"संपर्क आणि कॉल इतिहास शेअरिंगसाठी वापरा"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"इंटरनेट कनेक्शन शेअररण"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"मजकूर मेसेज"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"सिम अ‍ॅक्सेस"</string>
diff --git a/packages/SettingsLib/res/values-ms/strings.xml b/packages/SettingsLib/res/values-ms/strings.xml
index 3f35079..70d99a1 100644
--- a/packages/SettingsLib/res/values-ms/strings.xml
+++ b/packages/SettingsLib/res/values-ms/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Pemindahan fail"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Peranti input"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Akses Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Perkongsian kenalan &amp; sejarah panggilan"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Digunakan untuk perkongsian kenalan dan sejarah panggilan"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Perkongsian sambungan Internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Mesej Teks"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Akses SIM"</string>
diff --git a/packages/SettingsLib/res/values-my/strings.xml b/packages/SettingsLib/res/values-my/strings.xml
index 9cc6051..8c596ad 100644
--- a/packages/SettingsLib/res/values-my/strings.xml
+++ b/packages/SettingsLib/res/values-my/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ဖိုင်လွဲပြောင်းခြင်း"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ထည့်သွင်းသော စက်"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"အင်တာနက်ချိတ်ဆက်ခြင်း"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"အဆက်အသွယ်၊ ခေါ်ဆိုမှုမှတ်တမ်း မျှဝေခြင်း"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"အဆက်အသွယ်နှင့် ခေါ်ဆိုမှုမှတ်တမ်း မျှဝေရန် သုံးသည်"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"အင်တာနက်ဆက်သွယ်မှု မျှဝေခြင်း"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"မိုဘိုင်းမက်ဆေ့ဂျ်များ"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM အသုံးပြုခြင်း"</string>
diff --git a/packages/SettingsLib/res/values-nb/arrays.xml b/packages/SettingsLib/res/values-nb/arrays.xml
index 0ab39ee..c456ae1 100644
--- a/packages/SettingsLib/res/values-nb/arrays.xml
+++ b/packages/SettingsLib/res/values-nb/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (sikker)"</item>
     <item msgid="7322156123728520872">"4K (oppskalert)"</item>
     <item msgid="7735692090314849188">"4K (oppskalert, sikker)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (dobbel skjerm)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"Ingen"</item>
diff --git a/packages/SettingsLib/res/values-nb/strings.xml b/packages/SettingsLib/res/values-nb/strings.xml
index 9d35068..f5b607d 100644
--- a/packages/SettingsLib/res/values-nb/strings.xml
+++ b/packages/SettingsLib/res/values-nb/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Filoverføring"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Inndataenhet"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internett-tilgang"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Deling av kontakter og anropslogg"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Bruk for deling av kontakter og anropslogg"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Deling av internettilkobling"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Tekstmeldinger"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Tilgang til SIM-kortet"</string>
@@ -556,7 +558,7 @@
     <string name="media_output_status_not_support_downloads" msgid="4523828729240373315">"Kan ikke spille av nedlastinger her"</string>
     <string name="media_output_status_try_after_ad" msgid="8312579066856015441">"Prøv igjen etter annonsen"</string>
     <string name="media_output_status_device_in_low_power_mode" msgid="8184631698321758451">"Vekk enheten for å spille her"</string>
-    <string name="media_output_status_unauthorized" msgid="5880222828273853838">"Enheten er ikke godkjent"</string>
+    <string name="media_output_status_unauthorized" msgid="5880222828273853838">"Enheten er ikke godkjent til å spille av"</string>
     <string name="media_output_status_track_unsupported" msgid="5576313219317709664">"Kan ikke spille av dette her"</string>
     <string name="profile_connect_timeout_subtext" msgid="4043408193005851761">"Tilkoblingsproblemer. Slå enheten av og på igjen"</string>
     <string name="media_transfer_wired_device_name" msgid="4447880899964056007">"Lydenhet med kabel"</string>
diff --git a/packages/SettingsLib/res/values-ne/strings.xml b/packages/SettingsLib/res/values-ne/strings.xml
index e536c16..a3c121a 100644
--- a/packages/SettingsLib/res/values-ne/strings.xml
+++ b/packages/SettingsLib/res/values-ne/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"फाइल स्थानान्तरण"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"इनपुट उपकरण"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"इन्टरनेट एक्सेस"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"कन्ट्याक्ट र कल हिस्ट्री सेयर गर्ने"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"कन्ट्याक्ट र कल हिस्ट्री सेयर गर्न प्रयोग गरियोस्"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"इन्टरनेट जडान साझेदारी गर्दै"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"टेक्स्ट म्यासेजहरू"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM एक्सेस"</string>
diff --git a/packages/SettingsLib/res/values-nl/arrays.xml b/packages/SettingsLib/res/values-nl/arrays.xml
index 6898086..4451c93 100644
--- a/packages/SettingsLib/res/values-nl/arrays.xml
+++ b/packages/SettingsLib/res/values-nl/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (veilig)"</item>
     <item msgid="7322156123728520872">"4K (opgeschaald)"</item>
     <item msgid="7735692090314849188">"4K (opgeschaald, veilig)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (dubbel scherm)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (dual screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"Geen"</item>
diff --git a/packages/SettingsLib/res/values-nl/strings.xml b/packages/SettingsLib/res/values-nl/strings.xml
index c73abb4..aa7e7a0 100644
--- a/packages/SettingsLib/res/values-nl/strings.xml
+++ b/packages/SettingsLib/res/values-nl/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Bestandsoverdracht"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Invoerapparaat"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internettoegang"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Contacten en gespreksgeschiedenis delen"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Gebruiken om contacten en gespreksgeschiedenis te delen"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Internetverbinding delen"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Sms-berichten"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Sim-toegang"</string>
diff --git a/packages/SettingsLib/res/values-or/strings.xml b/packages/SettingsLib/res/values-or/strings.xml
index 89d3636..6154db1 100644
--- a/packages/SettingsLib/res/values-or/strings.xml
+++ b/packages/SettingsLib/res/values-or/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ଫାଇଲ୍‌ ଟ୍ରାନ୍ସଫର୍‌"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ଇନ୍‌ପୁଟ୍‌ ଡିଭାଇସ୍"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"ଇଣ୍ଟରନେଟ ଆକ୍ସେସ"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"କଣ୍ଟାକ୍ଟ ଏବଂ କଲ ଇତିହାସ ସେୟାରିଂ"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"କଣ୍ଟାକ୍ଟ ଏବଂ କଲ ଇତିହାସ ସେୟାରିଂ ପାଇଁ ବ୍ୟବହାର କରନ୍ତୁ"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"ଇଣ୍ଟର୍‌ନେଟ୍‌ ସଂଯୋଗ ଶେୟାରିଙ୍ଗ"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"ଟେକ୍ସଟ୍ ମେସେଜ୍"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM ଆକ୍ସେସ"</string>
diff --git a/packages/SettingsLib/res/values-pa/arrays.xml b/packages/SettingsLib/res/values-pa/arrays.xml
index 0ac6bb5..3cb0f50 100644
--- a/packages/SettingsLib/res/values-pa/arrays.xml
+++ b/packages/SettingsLib/res/values-pa/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (ਸੁਰੱਖਿਅਤ)"</item>
     <item msgid="7322156123728520872">"4K (ਪੂਰਾ ਕੀਤਾ)"</item>
     <item msgid="7735692090314849188">"4K (ਪੂਰਾ ਕੀਤਾ, ਸੁਰੱਖਿਅਤ)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (ਦੂਹਰੀ ਸਕ੍ਰੀਨ)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"ਕੋਈ ਨਹੀਂ"</item>
diff --git a/packages/SettingsLib/res/values-pa/strings.xml b/packages/SettingsLib/res/values-pa/strings.xml
index 8ba9e78..1ab9dda 100644
--- a/packages/SettingsLib/res/values-pa/strings.xml
+++ b/packages/SettingsLib/res/values-pa/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ਫਾਈਲ ਟ੍ਰਾਂਸਫਰ"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ਇਨਪੁੱਟ ਡੀਵਾਈਸ"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"ਇੰਟਰਨੈੱਟ ਪਹੁੰਚ"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"ਸੰਪਰਕ ਅਤੇ ਕਾਲ ਇਤਿਹਾਸ ਸਾਂਝਾ ਕਰਨਾ"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"ਸੰਪਰਕ ਅਤੇ ਕਾਲ ਇਤਿਹਾਸ ਸਾਂਝਾ ਕਰਨ ਲਈ ਵਰਤੋਂ ਕਰੋ"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"ਇੰਟਰਨੈੱਟ ਕਨੈਕਸ਼ਨ ਸਾਂਝਾਕਰਨ"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"ਲਿਖਤ ਸੁਨੇਹੇ"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"ਸਿਮ ਪਹੁੰਚ"</string>
diff --git a/packages/SettingsLib/res/values-pl/strings.xml b/packages/SettingsLib/res/values-pl/strings.xml
index e75ea77..c0dce8d 100644
--- a/packages/SettingsLib/res/values-pl/strings.xml
+++ b/packages/SettingsLib/res/values-pl/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Przesyłanie pliku"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Urządzenie wejściowe"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Dostęp do internetu"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Udostępnianie kontaktów i historii połączeń"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Używaj w przypadku udostępniania kontaktów i historii połączeń"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Udostępnianie połączenia internetowego"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS-y"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Dostęp do karty SIM"</string>
diff --git a/packages/SettingsLib/res/values-pt-rBR/strings.xml b/packages/SettingsLib/res/values-pt-rBR/strings.xml
index 1507e5b..9493e20 100644
--- a/packages/SettingsLib/res/values-pt-rBR/strings.xml
+++ b/packages/SettingsLib/res/values-pt-rBR/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transferência de arquivo"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Dispositivo de entrada"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Acesso à Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Compartilhar contatos e histórico de chamadas"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Use para compartilhar contatos e o histórico de chamadas"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Compartilhamento de conexão à Internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Mensagens de texto"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Acesso ao chip"</string>
diff --git a/packages/SettingsLib/res/values-pt-rPT/strings.xml b/packages/SettingsLib/res/values-pt-rPT/strings.xml
index a40cd2a..12d37d2 100644
--- a/packages/SettingsLib/res/values-pt-rPT/strings.xml
+++ b/packages/SettingsLib/res/values-pt-rPT/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transferência do ficheiro"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Dispositivo de entrada"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Acesso à internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Part. histórico de chamadas e contactos"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Usar para partilha do histórico de chamadas e dos contactos"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Partilha da ligação à internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Mensagens de texto"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Acesso ao SIM"</string>
diff --git a/packages/SettingsLib/res/values-pt/strings.xml b/packages/SettingsLib/res/values-pt/strings.xml
index 1507e5b..9493e20 100644
--- a/packages/SettingsLib/res/values-pt/strings.xml
+++ b/packages/SettingsLib/res/values-pt/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transferência de arquivo"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Dispositivo de entrada"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Acesso à Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Compartilhar contatos e histórico de chamadas"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Use para compartilhar contatos e o histórico de chamadas"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Compartilhamento de conexão à Internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Mensagens de texto"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Acesso ao chip"</string>
diff --git a/packages/SettingsLib/res/values-ro/strings.xml b/packages/SettingsLib/res/values-ro/strings.xml
index 6fda8d2..0f68d27 100644
--- a/packages/SettingsLib/res/values-ro/strings.xml
+++ b/packages/SettingsLib/res/values-ro/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transfer de fișiere"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Dispozitiv de intrare"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Acces la internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Acces la agendă și istoricul apelurilor"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Folosește pentru accesul la agendă și istoricul apelurilor"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Distribuirea conexiunii la internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Mesaje text"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Acces la SIM"</string>
diff --git a/packages/SettingsLib/res/values-ru/arrays.xml b/packages/SettingsLib/res/values-ru/arrays.xml
index 3e3b21c..e26b1a6 100644
--- a/packages/SettingsLib/res/values-ru/arrays.xml
+++ b/packages/SettingsLib/res/values-ru/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (защита)"</item>
     <item msgid="7322156123728520872">"4K (масштабирование)"</item>
     <item msgid="7735692090314849188">"4K (масштабирование, защита)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (два экрана)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"Нет"</item>
diff --git a/packages/SettingsLib/res/values-ru/strings.xml b/packages/SettingsLib/res/values-ru/strings.xml
index 8127ef2..2a390aa 100644
--- a/packages/SettingsLib/res/values-ru/strings.xml
+++ b/packages/SettingsLib/res/values-ru/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Профиль OPP"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Профиль HID"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Доступ к интернету"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Доступ к контактам и журналу звонков"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Использовать для доступа к контактам и журналу звонков"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Профиль PAN"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Текстовые сообщения"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Доступ к SIM-карте"</string>
diff --git a/packages/SettingsLib/res/values-si/strings.xml b/packages/SettingsLib/res/values-si/strings.xml
index 277125d..15e00c9 100644
--- a/packages/SettingsLib/res/values-si/strings.xml
+++ b/packages/SettingsLib/res/values-si/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ගොනු හුවමාරුව"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ආදාන උපාංගය"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"අන්තර්ජාල ප්‍රවේශය"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"සම්බන්ධතා සහ ඇමතුම් ඉතිහාසය බෙදා ගැනීම"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"සම්බන්ධතා සහ ඇමතුම් ඉතිහාසය බෙදා ගැනීම සඳහා භාවිතා කරන්න"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"අන්තර්ජාල සම්බන්ධතා බෙදාගැනීම"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"පෙළ පණිවිඩ"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM ප්‍රවේශය"</string>
diff --git a/packages/SettingsLib/res/values-sk/strings.xml b/packages/SettingsLib/res/values-sk/strings.xml
index 52b0f0b..5be4d1b 100644
--- a/packages/SettingsLib/res/values-sk/strings.xml
+++ b/packages/SettingsLib/res/values-sk/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Prenos súborov"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Vstupné zariadenie"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Prístup na internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Zdieľať kontakty a históriu hovorov"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Používané pri zdieľaní kontaktov a histórie hovorov"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Zdieľanie pripojenia na Internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Textové správy"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Prístup k SIM karte"</string>
diff --git a/packages/SettingsLib/res/values-sl/strings.xml b/packages/SettingsLib/res/values-sl/strings.xml
index fdd0a22..ecef697 100644
--- a/packages/SettingsLib/res/values-sl/strings.xml
+++ b/packages/SettingsLib/res/values-sl/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Prenos datoteke"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Vnosna naprava"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internetni dostop"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Deljenje stikov in zgodovine klicev"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Uporabite za deljenje stikov in zgodovine klicev."</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Deljenje internetne povezave"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Sporočila SMS"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Dostop do kartice SIM"</string>
diff --git a/packages/SettingsLib/res/values-sq/strings.xml b/packages/SettingsLib/res/values-sq/strings.xml
index 1622ff7..e4d402d6 100644
--- a/packages/SettingsLib/res/values-sq/strings.xml
+++ b/packages/SettingsLib/res/values-sq/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Transferimi i skedarëve"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Pajisja e hyrjes"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Qasje në internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Ndarje: kontakte e historik telefonatash"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Përdor për ndarje kontaktesh e të historikut të telefonatave"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Ndarja e lidhjes së internetit"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Mesazhet me tekst"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Qasje në kartën SIM"</string>
diff --git a/packages/SettingsLib/res/values-sr/strings.xml b/packages/SettingsLib/res/values-sr/strings.xml
index d1b3289..2f5ebdd 100644
--- a/packages/SettingsLib/res/values-sr/strings.xml
+++ b/packages/SettingsLib/res/values-sr/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Пренос датотеке"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Улазни уређај"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Приступ Интернету"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Дељење контаката и историје позива"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Користите за дељење контаката и историје позива"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Дељење интернет везе"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS-ови"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Приступ SIM картици"</string>
diff --git a/packages/SettingsLib/res/values-sv/arrays.xml b/packages/SettingsLib/res/values-sv/arrays.xml
index dfe491d..3a344ce 100644
--- a/packages/SettingsLib/res/values-sv/arrays.xml
+++ b/packages/SettingsLib/res/values-sv/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (säkert)"</item>
     <item msgid="7322156123728520872">"4K (uppskalat)"</item>
     <item msgid="7735692090314849188">"4K (uppskalat, säkert)"</item>
-    <item msgid="7346816300608639624">"720 p, 1080 p (dubbla skärmar)"</item>
+    <item msgid="7346816300608639624">"720 p, 1080 p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"Inga"</item>
diff --git a/packages/SettingsLib/res/values-sv/strings.xml b/packages/SettingsLib/res/values-sv/strings.xml
index 2c7c736..3cc2dc4 100644
--- a/packages/SettingsLib/res/values-sv/strings.xml
+++ b/packages/SettingsLib/res/values-sv/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Filöverföring"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Indataenhet"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internetåtkomst"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Delning av kontakter och samtalshistorik"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Använd för delning av kontakter och samtalshistorik"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Delning av Internetanslutning"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Sms"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM-åtkomst"</string>
diff --git a/packages/SettingsLib/res/values-sw/strings.xml b/packages/SettingsLib/res/values-sw/strings.xml
index 60d9186..67ab4d3 100644
--- a/packages/SettingsLib/res/values-sw/strings.xml
+++ b/packages/SettingsLib/res/values-sw/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Uhamishaji wa faili"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Kifaa cha kuingiza"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Ufikiaji wa intaneti"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Kushiriki anwani na rekodi ya simu zilizopigwa"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Tumia kushiriki anwani na rekodi ya simu zilizopigwa"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Kushiriki muunganisho wa tovuti"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Ufikiaji wa SIM"</string>
diff --git a/packages/SettingsLib/res/values-ta/strings.xml b/packages/SettingsLib/res/values-ta/strings.xml
index ce10e21..b99a0c5 100644
--- a/packages/SettingsLib/res/values-ta/strings.xml
+++ b/packages/SettingsLib/res/values-ta/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ஃபைல் இடமாற்றம்"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"உள்ளீட்டுச் சாதனம்"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"இணைய அணுகல்"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"தொடர்புகள் &amp; அழைப்புப் பதிவைப் பகிர்தல்"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"தொடர்புகளையும் அழைப்புப் பதிவையும் பகிர்வதற்குப் பயன்படுத்து"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"இணைய இணைப்பு பகிர்தல்"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"உரைச் செய்திகள்"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"சிம் அணுகல்"</string>
diff --git a/packages/SettingsLib/res/values-te/strings.xml b/packages/SettingsLib/res/values-te/strings.xml
index 567bffb..3c12cdc 100644
--- a/packages/SettingsLib/res/values-te/strings.xml
+++ b/packages/SettingsLib/res/values-te/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"ఫైల్ బదిలీ"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ఇన్‌పుట్ పరికరం"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"ఇంటర్నెట్ యాక్సెస్"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"కాంటాక్ట్‌లు, కాల్ హిస్టరీ షేరింగ్"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"కాంటాక్ట్‌లు, కాల్ హిస్టరీ షేరింగ్ కోసం ఉపయోగించండి"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"ఇంటర్నెట్ కనెక్షన్ షేరింగ్"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"టెక్స్ట్ మెసేజ్‌లు"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM యాక్సెస్"</string>
diff --git a/packages/SettingsLib/res/values-th/arrays.xml b/packages/SettingsLib/res/values-th/arrays.xml
index 23d5f60..480aee4 100644
--- a/packages/SettingsLib/res/values-th/arrays.xml
+++ b/packages/SettingsLib/res/values-th/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (ปลอดภัย)"</item>
     <item msgid="7322156123728520872">"4K (เพิ่มความละเอียด)"</item>
     <item msgid="7735692090314849188">"4K (เพิ่มความละเอียด ปลอดภัย)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (หน้าจอคู่)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"ไม่มี"</item>
diff --git a/packages/SettingsLib/res/values-th/strings.xml b/packages/SettingsLib/res/values-th/strings.xml
index 69324d1..f3d08ba 100644
--- a/packages/SettingsLib/res/values-th/strings.xml
+++ b/packages/SettingsLib/res/values-th/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"การถ่ายโอนไฟล์"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"อุปกรณ์อินพุต"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"การเข้าถึงอินเทอร์เน็ต"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"การแชร์รายชื่อติดต่อและประวัติการโทร"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"ใช้สำหรับการแชร์รายชื่อติดต่อและประวัติการโทร"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"การแชร์การเชื่อมต่ออินเทอร์เน็ต"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"ข้อความ"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"การเข้าถึงซิม"</string>
diff --git a/packages/SettingsLib/res/values-tl/strings.xml b/packages/SettingsLib/res/values-tl/strings.xml
index 889e396..9159ca4 100644
--- a/packages/SettingsLib/res/values-tl/strings.xml
+++ b/packages/SettingsLib/res/values-tl/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Paglilipat ng file"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Device sa pag-input"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Access sa internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Contacts at pagbabahagi ng call history"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Gamitin para sa contacts at pagbabahagi ng call history"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Pagbabahagi ng koneksyon sa internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Mga Text Message"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Access sa SIM"</string>
diff --git a/packages/SettingsLib/res/values-tr/arrays.xml b/packages/SettingsLib/res/values-tr/arrays.xml
index ed3755a..27591be 100644
--- a/packages/SettingsLib/res/values-tr/arrays.xml
+++ b/packages/SettingsLib/res/values-tr/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (güvenli)"</item>
     <item msgid="7322156123728520872">"4K (yukarı ölçeklenmiş)"</item>
     <item msgid="7735692090314849188">"4K (yukarı ölçeklenmiş, güvenli)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (çift ekran)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"Hiçbiri"</item>
diff --git a/packages/SettingsLib/res/values-tr/strings.xml b/packages/SettingsLib/res/values-tr/strings.xml
index 495bcd9..0f8df02 100644
--- a/packages/SettingsLib/res/values-tr/strings.xml
+++ b/packages/SettingsLib/res/values-tr/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Dosya aktarımı"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Giriş cihazı"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"İnternet erişimi"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Kişi ve çağrı geçmişi paylaşımı"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Kişi ve çağrı geçmişi paylaşımı için kullanın"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"İnternet bağlantısı paylaşımı"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Kısa Mesajlar"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM Erişimi"</string>
diff --git a/packages/SettingsLib/res/values-uk/arrays.xml b/packages/SettingsLib/res/values-uk/arrays.xml
index 83336d5..6032efb 100644
--- a/packages/SettingsLib/res/values-uk/arrays.xml
+++ b/packages/SettingsLib/res/values-uk/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K (захист)"</item>
     <item msgid="7322156123728520872">"4K (масштабування)"</item>
     <item msgid="7735692090314849188">"4K (масштабування, захист)"</item>
-    <item msgid="7346816300608639624">"720p, 1080p (два екрани)"</item>
+    <item msgid="7346816300608639624">"720p, 1080p (Dual Screen)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"Нічого"</item>
diff --git a/packages/SettingsLib/res/values-uk/strings.xml b/packages/SettingsLib/res/values-uk/strings.xml
index 2158ec1..8c24312 100644
--- a/packages/SettingsLib/res/values-uk/strings.xml
+++ b/packages/SettingsLib/res/values-uk/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Передавання файлів"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Пристрій введення"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Доступ до Інтернету"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Доступ до контактів і історії викликів"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Використовуйте, щоб надсилати контакти й історію викликів"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Надання доступу до Інтернету"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Текстові повідомлення"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Доступ до SIM-карти"</string>
diff --git a/packages/SettingsLib/res/values-ur/strings.xml b/packages/SettingsLib/res/values-ur/strings.xml
index 5dc7332..5967add 100644
--- a/packages/SettingsLib/res/values-ur/strings.xml
+++ b/packages/SettingsLib/res/values-ur/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"فائل کی منتقلی"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"ان پٹ آلہ"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"انٹرنیٹ تک رسائی"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"رابطے اور کال کی سرگزشت کا اشتراک"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"رابطے اور کال کی سرگزشت کے اشتراک کے لیے استعمال کریں"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"انٹرنیٹ کنکشن کا اشتراک کرنا"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"ٹیکسٹ پیغامات"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"‏SIM رسائی"</string>
diff --git a/packages/SettingsLib/res/values-uz/strings.xml b/packages/SettingsLib/res/values-uz/strings.xml
index cdc7e1c..b9c17fc 100644
--- a/packages/SettingsLib/res/values-uz/strings.xml
+++ b/packages/SettingsLib/res/values-uz/strings.xml
@@ -107,8 +107,8 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Fayl uzatish"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Kiritish qurilmasi"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Internetga ulanish"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Kontakt va chaqiruvlar tarixiga kirish"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Kontaktlar va chaqiruvlar tarixiga kirish uchun foydalaning"</string>
+    <string name="bluetooth_profile_pbap" msgid="2103406516858653017">"Chaqiruv va kontaktlarga ruxsat berilsinmi?"</string>
+    <string name="bluetooth_profile_pbap_summary" msgid="402819589201138227">"Maʼlumotlar chaqiruvlar haqida xabar berish uchun ishlatiladi"</string>
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Internet aloqasi ulashmasi"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS xabarlari"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM kartaga kirish"</string>
diff --git a/packages/SettingsLib/res/values-vi/strings.xml b/packages/SettingsLib/res/values-vi/strings.xml
index 8ed63e9..cc8dacd 100644
--- a/packages/SettingsLib/res/values-vi/strings.xml
+++ b/packages/SettingsLib/res/values-vi/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Chuyển tệp"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Thiết bị đầu vào"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Truy cập Internet"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Chia sẻ danh bạ và nhật ký cuộc gọi"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Dùng để chia sẻ danh bạ và nhật ký cuộc gọi"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Chia sẻ kết nối internet"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Tin nhắn văn bản"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Truy cập SIM"</string>
diff --git a/packages/SettingsLib/res/values-zh-rCN/arrays.xml b/packages/SettingsLib/res/values-zh-rCN/arrays.xml
index 1ae55e4..432dd5f 100644
--- a/packages/SettingsLib/res/values-zh-rCN/arrays.xml
+++ b/packages/SettingsLib/res/values-zh-rCN/arrays.xml
@@ -243,7 +243,7 @@
     <item msgid="8612549335720461635">"4K(安全)"</item>
     <item msgid="7322156123728520872">"4K(画质提升)"</item>
     <item msgid="7735692090314849188">"4K(画质提升、安全)"</item>
-    <item msgid="7346816300608639624">"720p,1080p(双屏)"</item>
+    <item msgid="7346816300608639624">"720p、1080p(双屏幕)"</item>
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="4433736508877934305">"无"</item>
diff --git a/packages/SettingsLib/res/values-zh-rCN/strings.xml b/packages/SettingsLib/res/values-zh-rCN/strings.xml
index 0f0b9c4..84af4b5 100644
--- a/packages/SettingsLib/res/values-zh-rCN/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rCN/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"文件传输"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"输入设备"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"互联网连接"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"联系人信息和通话记录分享"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"用于联系人信息和通话记录分享"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"共享互联网连接"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"短信"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM 卡访问权限"</string>
@@ -552,7 +554,7 @@
     <string name="media_transfer_default_device_name" msgid="4315604017399871828">"连接的设备"</string>
     <string name="media_transfer_this_phone" msgid="7194341457812151531">"这部手机"</string>
     <string name="media_output_status_unknown_error" msgid="5098565887497902222">"无法在此设备上播放"</string>
-    <string name="media_output_status_require_premium" msgid="8411255800047014822">"升级帐号后才能切换"</string>
+    <string name="media_output_status_require_premium" msgid="8411255800047014822">"升级账号后才能切换"</string>
     <string name="media_output_status_not_support_downloads" msgid="4523828729240373315">"无法在此设备上播放下载的内容"</string>
     <string name="media_output_status_try_after_ad" msgid="8312579066856015441">"广告之后重试"</string>
     <string name="media_output_status_device_in_low_power_mode" msgid="8184631698321758451">"若要在此设备上播放,请唤醒设备"</string>
@@ -576,7 +578,7 @@
     <string name="delete_blob_text" msgid="2819192607255625697">"删除共享数据"</string>
     <string name="delete_blob_confirmation_text" msgid="7807446938920827280">"确定要删除这些共享数据吗?"</string>
     <string name="user_add_user_item_summary" msgid="5748424612724703400">"用户拥有个人专属的应用和内容"</string>
-    <string name="user_add_profile_item_summary" msgid="5418602404308968028">"您可以限制其他人使用来自您的帐号的应用和内容"</string>
+    <string name="user_add_profile_item_summary" msgid="5418602404308968028">"您可以限制其他人使用来自您的账号的应用和内容"</string>
     <string name="user_add_user_item_title" msgid="2394272381086965029">"用户"</string>
     <string name="user_add_profile_item_title" msgid="3111051717414643029">"受限个人资料"</string>
     <string name="user_add_user_title" msgid="5457079143694924885">"要添加新用户吗?"</string>
diff --git a/packages/SettingsLib/res/values-zh-rHK/strings.xml b/packages/SettingsLib/res/values-zh-rHK/strings.xml
index 57718d8..dfde69f 100644
--- a/packages/SettingsLib/res/values-zh-rHK/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rHK/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"檔案傳輸"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"輸入裝置"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"互聯網連線"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"分享通訊錄及通話記錄"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"用於分享通訊錄及通話記錄"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"互聯網連線分享"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"短訊"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM 卡存取"</string>
diff --git a/packages/SettingsLib/res/values-zh-rTW/strings.xml b/packages/SettingsLib/res/values-zh-rTW/strings.xml
index 18317da..0257527 100644
--- a/packages/SettingsLib/res/values-zh-rTW/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rTW/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"檔案傳輸"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"輸入裝置"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"網際網路連線"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"分享聯絡人和通話記錄"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"用於分享聯絡人和通話記錄"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"網際網路連線分享"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"簡訊"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM 卡存取權"</string>
diff --git a/packages/SettingsLib/res/values-zu/strings.xml b/packages/SettingsLib/res/values-zu/strings.xml
index edf5f3c..27bad75 100644
--- a/packages/SettingsLib/res/values-zu/strings.xml
+++ b/packages/SettingsLib/res/values-zu/strings.xml
@@ -107,8 +107,10 @@
     <string name="bluetooth_profile_opp" msgid="6692618568149493430">"Dlulisa ifayela"</string>
     <string name="bluetooth_profile_hid" msgid="2969922922664315866">"Idivaysi yokufakwayo"</string>
     <string name="bluetooth_profile_pan" msgid="1006235139308318188">"Ukufinyelela i-Inthanethi"</string>
-    <string name="bluetooth_profile_pbap" msgid="4262303387989406171">"Ukwabelana ngoxhumana nabo nomlando wekholi"</string>
-    <string name="bluetooth_profile_pbap_summary" msgid="6466456791354759132">"Ukusetshenziswa kokwabelana ngoxhumana nabo nomlando wekholi"</string>
+    <!-- no translation found for bluetooth_profile_pbap (2103406516858653017) -->
+    <skip />
+    <!-- no translation found for bluetooth_profile_pbap_summary (402819589201138227) -->
+    <skip />
     <string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Ukwabelana ngoxhumano lwe-Inthanethi"</string>
     <string name="bluetooth_profile_map" msgid="8907204701162107271">"Imilayezo yombhalo"</string>
     <string name="bluetooth_profile_sap" msgid="8304170950447934386">"Ukufinyelela kwe-SIM"</string>
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index dab3bcb..0acce03 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -225,9 +225,9 @@
     <!-- Bluetooth settings. The user-visible string that is used whenever referring to the PAN profile (accessing Internet through remote device). [CHAR LIMIT=40] -->
     <string name="bluetooth_profile_pan">Internet access</string>
     <!-- Bluetooth settings. The user-visible string that is used whenever referring to the PBAP profile. [CHAR LIMIT=40] -->
-    <string name="bluetooth_profile_pbap">Contacts and call history sharing</string>
+    <string name="bluetooth_profile_pbap">Allow access to contacts and call history</string>
     <!-- Bluetooth settings. The user-visible summary string that is used whenever referring to the PBAP profile (sharing contacts). [CHAR LIMIT=60] -->
-    <string name="bluetooth_profile_pbap_summary">Use for contacts and call history sharing</string>
+    <string name="bluetooth_profile_pbap_summary">Info will be used for call announcements and more</string>
     <!-- Bluetooth settings. The user-visible string that is used whenever referring to the PAN profile (sharing this device's Internet connection). [CHAR LIMIT=40] -->
     <string name="bluetooth_profile_pan_nap">Internet connection sharing</string>
     <!-- Bluetooth settings. The user-visible string that is used whenever referring to the map profile. -->
diff --git a/packages/SettingsLib/src/com/android/settingslib/fuelgauge/BatteryStatus.java b/packages/SettingsLib/src/com/android/settingslib/fuelgauge/BatteryStatus.java
index 1251b0d..f90a17a 100644
--- a/packages/SettingsLib/src/com/android/settingslib/fuelgauge/BatteryStatus.java
+++ b/packages/SettingsLib/src/com/android/settingslib/fuelgauge/BatteryStatus.java
@@ -26,6 +26,7 @@
 import static android.os.BatteryManager.EXTRA_PLUGGED;
 import static android.os.BatteryManager.EXTRA_PRESENT;
 import static android.os.BatteryManager.EXTRA_STATUS;
+import static android.os.OsProtoEnums.BATTERY_PLUGGED_NONE;
 
 import android.content.Context;
 import android.content.Intent;
@@ -40,8 +41,11 @@
  */
 public class BatteryStatus {
     private static final int LOW_BATTERY_THRESHOLD = 20;
+    private static final int SEVERE_LOW_BATTERY_THRESHOLD = 10;
+    private static final int EXTREME_LOW_BATTERY_THRESHOLD = 3;
     private static final int DEFAULT_CHARGING_VOLTAGE_MICRO_VOLT = 5000000;
 
+    public static final int BATTERY_LEVEL_UNKNOWN = -1;
     public static final int CHARGING_UNKNOWN = -1;
     public static final int CHARGING_SLOWLY = 0;
     public static final int CHARGING_REGULAR = 1;
@@ -90,21 +94,7 @@
         present = batteryChangedIntent.getBooleanExtra(EXTRA_PRESENT, true);
         this.incompatibleCharger = incompatibleCharger;
 
-        final int maxChargingMicroAmp = batteryChangedIntent.getIntExtra(EXTRA_MAX_CHARGING_CURRENT,
-                -1);
-        int maxChargingMicroVolt = batteryChangedIntent.getIntExtra(EXTRA_MAX_CHARGING_VOLTAGE, -1);
-
-        if (maxChargingMicroVolt <= 0) {
-            maxChargingMicroVolt = DEFAULT_CHARGING_VOLTAGE_MICRO_VOLT;
-        }
-        if (maxChargingMicroAmp > 0) {
-            // Calculating muW = muA * muV / (10^6 mu^2 / mu); splitting up the divisor
-            // to maintain precision equally on both factors.
-            maxChargingWattage = (maxChargingMicroAmp / 1000)
-                    * (maxChargingMicroVolt / 1000);
-        } else {
-            maxChargingWattage = -1;
-        }
+        maxChargingWattage = calculateMaxChargingMicroWatt(batteryChangedIntent);
     }
 
     /** Determine whether the device is plugged. */
@@ -126,7 +116,7 @@
 
     /** Determine whether the device is plugged in dock. */
     public boolean isPluggedInDock() {
-        return plugged == BatteryManager.BATTERY_PLUGGED_DOCK;
+        return isPluggedInDock(plugged);
     }
 
     /**
@@ -140,15 +130,15 @@
 
     /** Whether battery is low and needs to be charged. */
     public boolean isBatteryLow() {
-        return level < LOW_BATTERY_THRESHOLD;
+        return isLowBattery(level);
     }
 
     /** Whether battery defender is enabled. */
     public boolean isBatteryDefender() {
-        return chargingStatus == CHARGING_POLICY_ADAPTIVE_LONGLIFE;
+        return isBatteryDefender(chargingStatus);
     }
 
-    /** Return current chargin speed is fast, slow or normal. */
+    /** Return current charging speed is fast, slow or normal. */
     public final int getChargingSpeed(Context context) {
         final int slowThreshold = context.getResources().getInteger(
                 R.integer.config_chargingSlowlyThreshold);
@@ -197,12 +187,13 @@
     /** Gets the battery level from the intent. */
     public static int getBatteryLevel(Intent batteryChangedIntent) {
         if (batteryChangedIntent == null) {
-            return -1; /*invalid battery level*/
+            return BATTERY_LEVEL_UNKNOWN;
         }
-        final int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
+        final int level =
+                batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, BATTERY_LEVEL_UNKNOWN);
         final int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
         return scale == 0
-                ? -1 /*invalid battery level*/
+                ? BATTERY_LEVEL_UNKNOWN
                 : Math.round((level / (float) scale) * 100f);
     }
 
@@ -218,4 +209,126 @@
                 || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS
                 || plugged == BatteryManager.BATTERY_PLUGGED_DOCK;
     }
+
+    /** Determine whether the device is plugged in dock. */
+    public static boolean isPluggedInDock(Intent batteryChangedIntent) {
+        return isPluggedInDock(
+                batteryChangedIntent.getIntExtra(EXTRA_PLUGGED, BATTERY_PLUGGED_NONE));
+    }
+
+    /** Determine whether the device is plugged in dock. */
+    public static boolean isPluggedInDock(int plugged) {
+        return plugged == BatteryManager.BATTERY_PLUGGED_DOCK;
+    }
+
+    /**
+     * Whether the battery is low or not.
+     *
+     * @param batteryChangedIntent the {@link ACTION_BATTERY_CHANGED} intent
+     * @return {@code true} if the battery level is less or equal to {@link LOW_BATTERY_THRESHOLD}
+     */
+    public static boolean isLowBattery(Intent batteryChangedIntent) {
+        int level = getBatteryLevel(batteryChangedIntent);
+        return isLowBattery(level);
+    }
+
+    /**
+     * Whether the battery is low or not.
+     *
+     * @param batteryLevel the battery level
+     * @return {@code true} if the battery level is less or equal to {@link LOW_BATTERY_THRESHOLD}
+     */
+    public static boolean isLowBattery(int batteryLevel) {
+        return batteryLevel <= LOW_BATTERY_THRESHOLD;
+    }
+
+    /**
+     * Whether the battery is severe low or not.
+     *
+     * @param batteryChangedIntent the ACTION_BATTERY_CHANGED intent
+     * @return {@code true} if the battery level is less or equal to {@link
+     *     SEVERE_LOW_BATTERY_THRESHOLD}
+     */
+    public static boolean isSevereLowBattery(Intent batteryChangedIntent) {
+        int level = getBatteryLevel(batteryChangedIntent);
+        return level <= SEVERE_LOW_BATTERY_THRESHOLD;
+    }
+
+    /**
+     * Whether the battery is extreme low or not.
+     *
+     * @param batteryChangedIntent the ACTION_BATTERY_CHANGED intent
+     * @return {@code true} if the battery level is less or equal to {@link
+     *     EXTREME_LOW_BATTERY_THRESHOLD}
+     */
+    public static boolean isExtremeLowBattery(Intent batteryChangedIntent) {
+        int level = getBatteryLevel(batteryChangedIntent);
+        return level <= EXTREME_LOW_BATTERY_THRESHOLD;
+    }
+
+    /**
+     * Whether the battery defender is enabled or not.
+     *
+     * @param batteryChangedIntent the ACTION_BATTERY_CHANGED intent
+     * @return {@code true} if the battery defender is enabled. It could be dock defend, dwell
+     *     defend, or temp defend
+     */
+    public static boolean isBatteryDefender(Intent batteryChangedIntent) {
+        int chargingStatus =
+                batteryChangedIntent.getIntExtra(EXTRA_CHARGING_STATUS, CHARGING_POLICY_DEFAULT);
+        return isBatteryDefender(chargingStatus);
+    }
+
+    /**
+     * Whether the battery defender is enabled or not.
+     *
+     * @param chargingStatus for {@link EXTRA_CHARGING_STATUS} field in the ACTION_BATTERY_CHANGED
+     *     intent
+     * @return {@code true} if the battery defender is enabled. It could be dock defend, dwell
+     *     defend, or temp defend
+     */
+    public static boolean isBatteryDefender(int chargingStatus) {
+        return chargingStatus == CHARGING_POLICY_ADAPTIVE_LONGLIFE;
+    }
+
+    /**
+     * Gets the max charging current and max charging voltage form {@link
+     * Intent.ACTION_BATTERY_CHANGED} and calculates the charging speed based on the {@link
+     * R.integer.config_chargingSlowlyThreshold} and {@link R.integer.config_chargingFastThreshold}.
+     *
+     * @param context the application context
+     * @param batteryChangedIntent the intent from {@link Intent.ACTION_BATTERY_CHANGED}
+     * @return the charging speed. {@link CHARGING_REGULAR}, {@link CHARGING_FAST}, {@link
+     *     CHARGING_SLOWLY} or {@link CHARGING_UNKNOWN}
+     */
+    public static int getChargingSpeed(Context context, Intent batteryChangedIntent) {
+        final int maxChargingMicroWatt = calculateMaxChargingMicroWatt(batteryChangedIntent);
+        if (maxChargingMicroWatt <= 0) {
+            return CHARGING_UNKNOWN;
+        } else if (maxChargingMicroWatt
+                < context.getResources().getInteger(R.integer.config_chargingSlowlyThreshold)) {
+            return CHARGING_SLOWLY;
+        } else if (maxChargingMicroWatt
+                > context.getResources().getInteger(R.integer.config_chargingFastThreshold)) {
+            return CHARGING_FAST;
+        } else {
+            return CHARGING_REGULAR;
+        }
+    }
+
+    private static int calculateMaxChargingMicroWatt(Intent batteryChangedIntent) {
+        final int maxChargingMicroAmp =
+                batteryChangedIntent.getIntExtra(EXTRA_MAX_CHARGING_CURRENT, -1);
+        int maxChargingMicroVolt = batteryChangedIntent.getIntExtra(EXTRA_MAX_CHARGING_VOLTAGE, -1);
+        if (maxChargingMicroVolt <= 0) {
+            maxChargingMicroVolt = DEFAULT_CHARGING_VOLTAGE_MICRO_VOLT;
+        }
+
+        if (maxChargingMicroAmp > 0) {
+            // Calculating µW = mA * mV
+            return (int) Math.round(maxChargingMicroAmp * 0.001 * maxChargingMicroVolt * 0.001);
+        } else {
+            return -1;
+        }
+    }
 }
diff --git a/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt b/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt
index a03acc3..73f6db6 100644
--- a/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt
+++ b/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt
@@ -325,7 +325,7 @@
         return batteryLevel
     }
 
-    override fun onBoundsChange(bounds: Rect?) {
+    override fun onBoundsChange(bounds: Rect) {
         super.onBoundsChange(bounds)
         updateSize()
     }
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java
index fe3ef5d..dbc3bf7 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java
@@ -22,6 +22,7 @@
 import android.bluetooth.BluetoothDevice;
 import android.content.ComponentName;
 import android.content.Context;
+import android.content.pm.PackageManager;
 import android.graphics.drawable.Drawable;
 import android.media.AudioDeviceAttributes;
 import android.media.AudioManager;
@@ -520,9 +521,13 @@
                     if (type == MediaDevice.MediaDeviceType.TYPE_USB_C_AUDIO_DEVICE
                             || type == MediaDevice.MediaDeviceType.TYPE_3POINT5_MM_AUDIO_DEVICE
                             || type == MediaDevice.MediaDeviceType.TYPE_PHONE_DEVICE) {
-                        MediaDevice mutingExpectedDevice = getMutingExpectedDevice();
-                        if (mutingExpectedDevice != null) {
-                            mMediaDevices.add(mutingExpectedDevice);
+                        if (isTv()) {
+                            mMediaDevices.addAll(buildDisconnectedBluetoothDevice());
+                        } else {
+                            MediaDevice mutingExpectedDevice = getMutingExpectedDevice();
+                            if (mutingExpectedDevice != null) {
+                                mMediaDevices.add(mutingExpectedDevice);
+                            }
                         }
                         break;
                     }
@@ -542,6 +547,12 @@
             }
         }
 
+        private boolean isTv() {
+            PackageManager pm = mContext.getPackageManager();
+            return pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)
+                    || pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK);
+        }
+
         private MediaDevice getMutingExpectedDevice() {
             if (mBluetoothAdapter == null
                     || mAudioManager.getMutingExpectedDevice() == null) {
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/MediaDevice.java b/packages/SettingsLib/src/com/android/settingslib/media/MediaDevice.java
index 9234d37..147412d 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/MediaDevice.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/MediaDevice.java
@@ -22,6 +22,7 @@
 import static android.media.MediaRoute2Info.TYPE_GROUP;
 import static android.media.MediaRoute2Info.TYPE_HDMI;
 import static android.media.MediaRoute2Info.TYPE_HEARING_AID;
+import static android.media.MediaRoute2Info.TYPE_REMOTE_AUDIO_VIDEO_RECEIVER;
 import static android.media.MediaRoute2Info.TYPE_REMOTE_SPEAKER;
 import static android.media.MediaRoute2Info.TYPE_REMOTE_TV;
 import static android.media.MediaRoute2Info.TYPE_UNKNOWN;
@@ -82,7 +83,8 @@
             MediaDeviceType.TYPE_FAST_PAIR_BLUETOOTH_DEVICE,
             MediaDeviceType.TYPE_BLUETOOTH_DEVICE,
             MediaDeviceType.TYPE_CAST_DEVICE,
-            MediaDeviceType.TYPE_CAST_GROUP_DEVICE})
+            MediaDeviceType.TYPE_CAST_GROUP_DEVICE,
+            MediaDeviceType.TYPE_REMOTE_AUDIO_VIDEO_RECEIVER})
     public @interface MediaDeviceType {
         int TYPE_UNKNOWN = 0;
         int TYPE_PHONE_DEVICE = 1;
@@ -92,6 +94,7 @@
         int TYPE_BLUETOOTH_DEVICE = 5;
         int TYPE_CAST_DEVICE = 6;
         int TYPE_CAST_GROUP_DEVICE = 7;
+        int TYPE_REMOTE_AUDIO_VIDEO_RECEIVER = 8;
     }
 
     @Retention(RetentionPolicy.SOURCE)
@@ -161,6 +164,9 @@
             case TYPE_BLE_HEADSET:
                 mType = MediaDeviceType.TYPE_BLUETOOTH_DEVICE;
                 break;
+            case TYPE_REMOTE_AUDIO_VIDEO_RECEIVER:
+                mType = MediaDeviceType.TYPE_REMOTE_AUDIO_VIDEO_RECEIVER;
+                break;
             case TYPE_UNKNOWN:
             case TYPE_REMOTE_TV:
             case TYPE_REMOTE_SPEAKER:
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/dpp/WifiDppIntentHelper.java b/packages/SettingsLib/src/com/android/settingslib/wifi/dpp/WifiDppIntentHelper.java
new file mode 100644
index 0000000..1134d13
--- /dev/null
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/dpp/WifiDppIntentHelper.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.wifi.dpp;
+
+import android.content.Intent;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiManager;
+import android.text.TextUtils;
+
+import java.util.List;
+
+
+/**
+ * Wifi dpp intent helper functions to share between the Settings App and SystemUI.
+ */
+public class WifiDppIntentHelper {
+    static final String EXTRA_WIFI_SECURITY = "security";
+
+    /** The data corresponding to {@code WifiConfiguration} SSID */
+    static final String EXTRA_WIFI_SSID = "ssid";
+
+    /** The data corresponding to {@code WifiConfiguration} preSharedKey */
+    static final String EXTRA_WIFI_PRE_SHARED_KEY = "preSharedKey";
+
+    /** The data corresponding to {@code WifiConfiguration} hiddenSSID */
+    static final String EXTRA_WIFI_HIDDEN_SSID = "hiddenSsid";
+    static final String SECURITY_NO_PASSWORD = "nopass"; //open network or OWE
+    static final String SECURITY_WEP = "WEP";
+    static final String SECURITY_WPA_PSK = "WPA";
+    static final String SECURITY_SAE = "SAE";
+
+    /**
+     * Set all extra except {@code EXTRA_WIFI_NETWORK_ID} for the intent to
+     * launch configurator activity later.
+     *
+     * @param intent the target to set extra
+     * @param wifiManager an instance of {@code WifiManager}
+     * @param wifiConfiguration the Wi-Fi network for launching configurator activity
+     */
+    public static void setConfiguratorIntentExtra(Intent intent, WifiManager wifiManager,
+            WifiConfiguration wifiConfiguration) {
+        String ssid = removeFirstAndLastDoubleQuotes(wifiConfiguration.SSID);
+        String security = getSecurityString(wifiConfiguration);
+
+        // When the value of this key is read, the actual key is not returned, just a "*".
+        // Call privileged system API to obtain actual key.
+        String preSharedKey = removeFirstAndLastDoubleQuotes(getPresharedKey(wifiManager,
+                wifiConfiguration));
+
+        if (!TextUtils.isEmpty(ssid)) {
+            intent.putExtra(EXTRA_WIFI_SSID, ssid);
+        }
+        if (!TextUtils.isEmpty(security)) {
+            intent.putExtra(EXTRA_WIFI_SECURITY, security);
+        }
+        if (!TextUtils.isEmpty(preSharedKey)) {
+            intent.putExtra(EXTRA_WIFI_PRE_SHARED_KEY, preSharedKey);
+        }
+        intent.putExtra(EXTRA_WIFI_HIDDEN_SSID, wifiConfiguration.hiddenSSID);
+    }
+
+    private static String getSecurityString(WifiConfiguration config) {
+        if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.SAE)) {
+            return SECURITY_SAE;
+        }
+        if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.OWE)) {
+            return SECURITY_NO_PASSWORD;
+        }
+        if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)
+                || config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA2_PSK)) {
+            return SECURITY_WPA_PSK;
+        }
+        return (config.wepKeys[0] == null) ? SECURITY_NO_PASSWORD : SECURITY_WEP;
+    }
+
+    private static String removeFirstAndLastDoubleQuotes(String str) {
+        if (TextUtils.isEmpty(str)) {
+            return str;
+        }
+
+        int begin = 0;
+        int end = str.length() - 1;
+        if (str.charAt(begin) == '\"') {
+            begin++;
+        }
+        if (str.charAt(end) == '\"') {
+            end--;
+        }
+        return str.substring(begin, end + 1);
+    }
+
+    private static String getPresharedKey(WifiManager wifiManager,
+            WifiConfiguration wifiConfiguration) {
+        List<WifiConfiguration> privilegedWifiConfigurations =
+                wifiManager.getPrivilegedConfiguredNetworks();
+
+        for (WifiConfiguration privilegedWifiConfiguration : privilegedWifiConfigurations) {
+            if (privilegedWifiConfiguration.networkId == wifiConfiguration.networkId) {
+                // WEP uses a shared key hence the AuthAlgorithm.SHARED is used
+                // to identify it.
+                if (wifiConfiguration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)
+                        && wifiConfiguration.allowedAuthAlgorithms.get(
+                        WifiConfiguration.AuthAlgorithm.SHARED)) {
+                    return privilegedWifiConfiguration
+                            .wepKeys[privilegedWifiConfiguration.wepTxKeyIndex];
+                } else {
+                    return privilegedWifiConfiguration.preSharedKey;
+                }
+            }
+        }
+        return wifiConfiguration.preSharedKey;
+    }
+}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/dpp/WifiDppIntentHelperTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/dpp/WifiDppIntentHelperTest.java
new file mode 100644
index 0000000..d73df2d
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/dpp/WifiDppIntentHelperTest.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.wifi.dpp;
+
+import static com.android.settingslib.wifi.dpp.WifiDppIntentHelper.EXTRA_WIFI_HIDDEN_SSID;
+import static com.android.settingslib.wifi.dpp.WifiDppIntentHelper.EXTRA_WIFI_PRE_SHARED_KEY;
+import static com.android.settingslib.wifi.dpp.WifiDppIntentHelper.EXTRA_WIFI_SECURITY;
+import static com.android.settingslib.wifi.dpp.WifiDppIntentHelper.EXTRA_WIFI_SSID;
+import static com.android.settingslib.wifi.dpp.WifiDppIntentHelper.SECURITY_NO_PASSWORD;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.when;
+
+import android.content.Intent;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiManager;
+
+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.util.ArrayList;
+
+@RunWith(RobolectricTestRunner.class)
+public class WifiDppIntentHelperTest {
+    @Mock
+    private WifiManager mWifiManager;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        when(mWifiManager.getPrivilegedConfiguredNetworks()).thenReturn(new ArrayList<>());
+    }
+
+    @Test
+    public void setConfiguratorIntentExtra_returnsCorrectValues() {
+        WifiConfiguration wifiConfiguration = new WifiConfiguration();
+        wifiConfiguration.SSID = EXTRA_WIFI_SSID;
+        wifiConfiguration.preSharedKey = EXTRA_WIFI_PRE_SHARED_KEY;
+        wifiConfiguration.hiddenSSID = true;
+
+        Intent expected = new Intent();
+        WifiDppIntentHelper.setConfiguratorIntentExtra(expected, mWifiManager, wifiConfiguration);
+
+        assertThat(expected.getStringExtra(EXTRA_WIFI_SSID)).isEqualTo(EXTRA_WIFI_SSID);
+        assertThat(expected.getStringExtra(EXTRA_WIFI_SECURITY)).isEqualTo(SECURITY_NO_PASSWORD);
+        assertThat(expected.getStringExtra(EXTRA_WIFI_PRE_SHARED_KEY)).isEqualTo(
+                EXTRA_WIFI_PRE_SHARED_KEY);
+        assertThat(expected.getBooleanExtra(EXTRA_WIFI_HIDDEN_SSID, false))
+                .isEqualTo(true);
+    }
+}
diff --git a/packages/SettingsLib/tests/unit/src/com/android/settingslib/fuelgague/BatteryStatusTest.kt b/packages/SettingsLib/tests/unit/src/com/android/settingslib/fuelgague/BatteryStatusTest.kt
new file mode 100644
index 0000000..6c0c1a7
--- /dev/null
+++ b/packages/SettingsLib/tests/unit/src/com/android/settingslib/fuelgague/BatteryStatusTest.kt
@@ -0,0 +1,330 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.fuelgague
+
+import android.content.Context
+import android.content.Intent
+import android.os.BatteryManager
+import android.os.BatteryManager.BATTERY_PLUGGED_AC
+import android.os.BatteryManager.BATTERY_PLUGGED_DOCK
+import android.os.BatteryManager.BATTERY_PLUGGED_USB
+import android.os.BatteryManager.BATTERY_PLUGGED_WIRELESS
+import android.os.BatteryManager.BATTERY_STATUS_FULL
+import android.os.BatteryManager.BATTERY_STATUS_UNKNOWN
+import android.os.BatteryManager.CHARGING_POLICY_ADAPTIVE_LONGLIFE
+import android.os.BatteryManager.CHARGING_POLICY_DEFAULT
+import android.os.BatteryManager.EXTRA_MAX_CHARGING_CURRENT
+import android.os.BatteryManager.EXTRA_MAX_CHARGING_VOLTAGE
+import android.os.OsProtoEnums.BATTERY_PLUGGED_NONE
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.android.settingslib.fuelgauge.BatteryStatus
+import com.android.settingslib.fuelgauge.BatteryStatus.CHARGING_FAST
+import com.android.settingslib.fuelgauge.BatteryStatus.CHARGING_REGULAR
+import com.android.settingslib.fuelgauge.BatteryStatus.CHARGING_SLOWLY
+import com.android.settingslib.fuelgauge.BatteryStatus.CHARGING_UNKNOWN
+import com.android.settingslib.fuelgauge.BatteryStatus.isBatteryDefender
+import com.google.common.truth.Truth.assertThat
+import com.google.common.truth.Truth.assertWithMessage
+import java.util.Optional
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+import org.junit.runners.Suite
+import org.junit.runners.Suite.SuiteClasses
+
+@RunWith(Suite::class)
+@SuiteClasses(
+    BatteryStatusTest.NonParameterizedTest::class,
+    BatteryStatusTest.IsPluggedInTest::class,
+    BatteryStatusTest.IsChargedTest::class,
+    BatteryStatusTest.GetChargingSpeedTest::class,
+    BatteryStatusTest.IsPluggedInDockTest::class,
+)
+open class BatteryStatusTest {
+
+    @RunWith(AndroidJUnit4::class)
+    class NonParameterizedTest : BatteryStatusTest() {
+        @Test
+        fun isLowBattery_20Percent_returnsTrue() {
+            val level = 20
+            val intent = createIntent(batteryLevel = level)
+
+            assertWithMessage("failed by isLowBattery(Intent), level=$level")
+                .that(BatteryStatus.isLowBattery(intent))
+                .isTrue()
+            assertWithMessage("failed by isLowBattery($level)")
+                .that(BatteryStatus.isLowBattery(level))
+                .isTrue()
+        }
+
+        @Test
+        fun isLowBattery_21Percent_returnsFalse() {
+            val level = 21
+            val intent = createIntent(batteryLevel = level)
+
+            assertWithMessage("failed by isLowBattery(intent), level=$level")
+                .that(BatteryStatus.isLowBattery(intent))
+                .isFalse()
+            assertWithMessage("failed by isLowBattery($level)")
+                .that(BatteryStatus.isLowBattery(intent))
+                .isFalse()
+        }
+
+        @Test
+        fun isSevereLowBattery_10Percent_returnsTrue() {
+            val batteryChangedIntent = createIntent(batteryLevel = 10)
+
+            assertThat(BatteryStatus.isSevereLowBattery(batteryChangedIntent)).isTrue()
+        }
+
+        @Test
+        fun isSevereLowBattery_11Percent_returnFalse() {
+            val batteryChangedIntent = createIntent(batteryLevel = 11)
+
+            assertThat(BatteryStatus.isSevereLowBattery(batteryChangedIntent)).isFalse()
+        }
+
+        @Test
+        fun isExtremeLowBattery_3Percent_returnsTrue() {
+            val batteryChangedIntent = createIntent(batteryLevel = 3)
+
+            assertThat(BatteryStatus.isExtremeLowBattery(batteryChangedIntent)).isTrue()
+        }
+
+        @Test
+        fun isExtremeLowBattery_4Percent_returnsFalse() {
+            val batteryChangedIntent = createIntent(batteryLevel = 4)
+
+            assertThat(BatteryStatus.isExtremeLowBattery(batteryChangedIntent)).isFalse()
+        }
+
+        @Test
+        fun isBatteryDefender_chargingLongLife_returnsTrue() {
+            val chargingStatus = CHARGING_POLICY_ADAPTIVE_LONGLIFE
+            val batteryChangedIntent = createIntent(chargingStatus = chargingStatus)
+
+            assertIsBatteryDefender(chargingStatus, batteryChangedIntent).isTrue()
+        }
+
+        @Test
+        fun isBatteryDefender_nonChargingLongLife_returnsFalse() {
+            val chargingStatus = CHARGING_POLICY_DEFAULT
+            val batteryChangedIntent = createIntent(chargingStatus = chargingStatus)
+
+            assertIsBatteryDefender(chargingStatus, batteryChangedIntent).isFalse()
+        }
+
+        private fun assertIsBatteryDefender(chargingStatus: Int, batteryChangedIntent: Intent) =
+            object {
+                val assertions =
+                    listOf(
+                        "failed by isBatteryDefender(Intent), chargingStatus=$chargingStatus".let {
+                            assertWithMessage(it).that(isBatteryDefender(batteryChangedIntent))
+                        },
+                        "failed by isBatteryDefender($chargingStatus)".let {
+                            assertWithMessage(it).that(isBatteryDefender(chargingStatus))
+                        },
+                    )
+
+                fun isTrue() = assertions.forEach { it.isTrue() }
+
+                fun isFalse() = assertions.forEach { it.isFalse() }
+            }
+    }
+
+    @RunWith(Parameterized::class)
+    class IsPluggedInTest(
+        private val name: String,
+        private val plugged: Int,
+        val expected: Boolean
+    ) : BatteryStatusTest() {
+
+        @Test
+        fun isPluggedIn_() {
+            val batteryChangedIntent = createIntent(plugged = plugged)
+
+            assertWithMessage("failed by isPluggedIn(plugged=$plugged)")
+                .that(BatteryStatus.isPluggedIn(plugged))
+                .isEqualTo(expected)
+            assertWithMessage("failed by isPlugged(Intent), which plugged=$plugged")
+                .that(BatteryStatus.isPluggedIn(batteryChangedIntent))
+                .isEqualTo(expected)
+        }
+
+        companion object {
+            @Parameterized.Parameters(name = "{0}")
+            @JvmStatic
+            fun parameters() =
+                arrayListOf(
+                    arrayOf("withAC_returnsTrue", BATTERY_PLUGGED_AC, true),
+                    arrayOf("withDock_returnsTrue", BATTERY_PLUGGED_DOCK, true),
+                    arrayOf("withUSB_returnsTrue", BATTERY_PLUGGED_USB, true),
+                    arrayOf("withWireless_returnsTrue", BATTERY_PLUGGED_WIRELESS, true),
+                    arrayOf("pluggedNone_returnsTrue", BATTERY_PLUGGED_NONE, false),
+                )
+        }
+    }
+
+    @RunWith(Parameterized::class)
+    class IsPluggedInDockTest(
+        private val name: String,
+        private val plugged: Int,
+        val expected: Boolean
+    ) : BatteryStatusTest() {
+
+        @Test
+        fun isPluggedDockIn_() {
+            val batteryChangedIntent = createIntent(plugged = plugged)
+
+            assertWithMessage("failed by isPluggedInDock(plugged=$plugged)")
+                .that(BatteryStatus.isPluggedInDock(plugged))
+                .isEqualTo(expected)
+            assertWithMessage("failed by isPluggedInDock(Intent), which plugged=$plugged")
+                .that(BatteryStatus.isPluggedInDock(batteryChangedIntent))
+                .isEqualTo(expected)
+        }
+
+        companion object {
+            @Parameterized.Parameters(name = "{0}")
+            @JvmStatic
+            fun parameters() =
+                arrayListOf(
+                    arrayOf("withAC_returnsTrue", BATTERY_PLUGGED_AC, false),
+                    arrayOf("withDock_returnsTrue", BATTERY_PLUGGED_DOCK, true),
+                    arrayOf("withUSB_returnsTrue", BATTERY_PLUGGED_USB, false),
+                    arrayOf("withWireless_returnsTrue", BATTERY_PLUGGED_WIRELESS, false),
+                    arrayOf("pluggedNone_returnsTrue", BATTERY_PLUGGED_NONE, false),
+                )
+        }
+    }
+
+    @RunWith(Parameterized::class)
+    class IsChargedTest(
+        private val status: Int,
+        private val batteryLevel: Int,
+        private val expected: Boolean
+    ) : BatteryStatusTest() {
+
+        @Test
+        fun isCharged_() {
+            val batteryChangedIntent = createIntent(batteryLevel = batteryLevel, status = status)
+
+            assertWithMessage(
+                    "failed by isCharged(Intent), status=$status, batteryLevel=$batteryLevel"
+                )
+                .that(BatteryStatus.isCharged(batteryChangedIntent))
+                .isEqualTo(expected)
+            assertWithMessage("failed by isCharged($status, $batteryLevel)")
+                .that(BatteryStatus.isCharged(status, batteryLevel))
+                .isEqualTo(expected)
+        }
+
+        companion object {
+            @Parameterized.Parameters(name = "status{0}_level{1}_returns-{2}")
+            @JvmStatic
+            fun parameters() =
+                arrayListOf(
+                    arrayOf(BATTERY_STATUS_FULL, 99, true),
+                    arrayOf(BATTERY_STATUS_UNKNOWN, 100, true),
+                    arrayOf(BATTERY_STATUS_FULL, 100, true),
+                    arrayOf(BATTERY_STATUS_UNKNOWN, 99, false),
+                )
+        }
+    }
+
+    @RunWith(Parameterized::class)
+    class GetChargingSpeedTest(
+        private val name: String,
+        private val maxChargingCurrent: Optional<Int>,
+        private val maxChargingVoltage: Optional<Int>,
+        private val expectedChargingSpeed: Int,
+    ) {
+
+        val context: Context = ApplicationProvider.getApplicationContext()
+
+        @Test
+        fun getChargingSpeed_() {
+            val batteryChangedIntent =
+                Intent(Intent.ACTION_BATTERY_CHANGED).apply {
+                    maxChargingCurrent.ifPresent { putExtra(EXTRA_MAX_CHARGING_CURRENT, it) }
+                    maxChargingVoltage.ifPresent { putExtra(EXTRA_MAX_CHARGING_VOLTAGE, it) }
+                }
+
+            assertThat(BatteryStatus.getChargingSpeed(context, batteryChangedIntent))
+                .isEqualTo(expectedChargingSpeed)
+        }
+
+        companion object {
+            @Parameterized.Parameters(name = "{0}")
+            @JvmStatic
+            fun parameters() =
+                arrayListOf(
+                    arrayOf(
+                        "maxCurrent=n/a, maxVoltage=n/a -> UNKNOWN",
+                        Optional.empty<Int>(),
+                        Optional.empty<Int>(),
+                        CHARGING_UNKNOWN
+                    ),
+                    arrayOf(
+                        "maxCurrent=0, maxVoltage=9000000 -> UNKNOWN",
+                        Optional.of(0),
+                        Optional.of(0),
+                        CHARGING_UNKNOWN
+                    ),
+                    arrayOf(
+                        "maxCurrent=1500000, maxVoltage=5000000 -> CHARGING_REGULAR",
+                        Optional.of(1500000),
+                        Optional.of(5000000),
+                        CHARGING_REGULAR
+                    ),
+                    arrayOf(
+                        "maxCurrent=1000000, maxVoltage=5000000 -> CHARGING_REGULAR",
+                        Optional.of(1000000),
+                        Optional.of(5000000),
+                        CHARGING_REGULAR
+                    ),
+                    arrayOf(
+                        "maxCurrent=1500001, maxVoltage=5000000 -> CHARGING_FAST",
+                        Optional.of(1501000),
+                        Optional.of(5000000),
+                        CHARGING_FAST
+                    ),
+                    arrayOf(
+                        "maxCurrent=999999, maxVoltage=5000000 -> CHARGING_SLOWLY",
+                        Optional.of(999999),
+                        Optional.of(5000000),
+                        CHARGING_SLOWLY
+                    ),
+                )
+        }
+    }
+
+    protected fun createIntent(
+        batteryLevel: Int = 50,
+        chargingStatus: Int = CHARGING_POLICY_DEFAULT,
+        plugged: Int = BATTERY_PLUGGED_NONE,
+        status: Int = BatteryManager.BATTERY_STATUS_CHARGING,
+    ): Intent =
+        Intent(Intent.ACTION_BATTERY_CHANGED).apply {
+            putExtra(BatteryManager.EXTRA_STATUS, status)
+            putExtra(BatteryManager.EXTRA_LEVEL, batteryLevel)
+            putExtra(BatteryManager.EXTRA_SCALE, 100)
+            putExtra(BatteryManager.EXTRA_CHARGING_STATUS, chargingStatus)
+            putExtra(BatteryManager.EXTRA_PLUGGED, plugged)
+        }
+}
diff --git a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
index 423c8a3..2d62e2a 100644
--- a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
+++ b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
@@ -242,6 +242,7 @@
         Settings.Secure.HEARING_AID_CALL_ROUTING,
         Settings.Secure.HEARING_AID_MEDIA_ROUTING,
         Settings.Secure.HEARING_AID_SYSTEM_SOUNDS_ROUTING,
-        Settings.Secure.ACCESSIBILITY_FONT_SCALING_HAS_BEEN_CHANGED
+        Settings.Secure.ACCESSIBILITY_FONT_SCALING_HAS_BEEN_CHANGED,
+        Settings.Secure.SEARCH_PRESS_HOLD_NAV_HANDLE_ENABLED
     };
 }
diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java
index 46e73d0..bb67bbc3 100644
--- a/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java
+++ b/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java
@@ -441,6 +441,7 @@
                                 String.valueOf(Global.Wearable.TETHERED_CONFIG_TETHERED)
                         }));
         VALIDATORS.put(Global.Wearable.PHONE_SWITCHING_SUPPORTED, BOOLEAN_VALIDATOR);
-        VALIDATORS.put(Global.Wearable.WEAR_LAUNCHER_UI_MODE, NON_NEGATIVE_INTEGER_VALIDATOR);
+        VALIDATORS.put(Global.Wearable.WEAR_LAUNCHER_UI_MODE, ANY_INTEGER_VALIDATOR);
+        VALIDATORS.put(Global.Wearable.WEAR_POWER_ANOMALY_SERVICE_ENABLED, BOOLEAN_VALIDATOR);
     }
 }
diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
index f1efe9e..4494765 100644
--- a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
+++ b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
@@ -200,6 +200,7 @@
         VALIDATORS.put(Secure.ASSIST_GESTURE_WAKE_ENABLED, BOOLEAN_VALIDATOR);
         VALIDATORS.put(Secure.ASSIST_TOUCH_GESTURE_ENABLED, BOOLEAN_VALIDATOR);
         VALIDATORS.put(Secure.ASSIST_LONG_PRESS_HOME_ENABLED, BOOLEAN_VALIDATOR);
+        VALIDATORS.put(Secure.SEARCH_PRESS_HOLD_NAV_HANDLE_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_DISMISS_RTL, BOOLEAN_VALIDATOR);
@@ -261,6 +262,8 @@
         VALIDATORS.put(Secure.NAV_BAR_KIDS_MODE, BOOLEAN_VALIDATOR);
         VALIDATORS.put(
                 Secure.NAVIGATION_MODE, new DiscreteValueValidator(new String[] {"0", "1", "2"}));
+        VALIDATORS.put(Secure.NAVIGATION_MODE_RESTORE,
+                new DiscreteValueValidator(new String[] {"-1", "0", "1", "2"}));
         VALIDATORS.put(Secure.BACK_GESTURE_INSET_SCALE_LEFT,
                 new InclusiveFloatRangeValidator(0.0f, Float.MAX_VALUE));
         VALIDATORS.put(Secure.BACK_GESTURE_INSET_SCALE_RIGHT,
@@ -385,5 +388,6 @@
         VALIDATORS.put(Secure.ACCESSIBILITY_FONT_SCALING_HAS_BEEN_CHANGED, BOOLEAN_VALIDATOR);
         VALIDATORS.put(Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_EDGE_HAPTIC_ENABLED,
                 BOOLEAN_VALIDATOR);
+        VALIDATORS.put(Secure.DND_CONFIGS_MIGRATED, BOOLEAN_VALIDATOR);
     }
 }
diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/SystemSettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/SystemSettingsValidators.java
index 0dd8569..80cf6c3 100644
--- a/packages/SettingsProvider/src/android/provider/settings/validators/SystemSettingsValidators.java
+++ b/packages/SettingsProvider/src/android/provider/settings/validators/SystemSettingsValidators.java
@@ -184,6 +184,7 @@
         VALIDATORS.put(System.POINTER_LOCATION, BOOLEAN_VALIDATOR);
         VALIDATORS.put(System.SHOW_TOUCHES, BOOLEAN_VALIDATOR);
         VALIDATORS.put(System.SHOW_KEY_PRESSES, BOOLEAN_VALIDATOR);
+        VALIDATORS.put(System.SHOW_ROTARY_INPUT, BOOLEAN_VALIDATOR);
         VALIDATORS.put(System.WINDOW_ORIENTATION_LISTENER_LOG, BOOLEAN_VALIDATOR);
         VALIDATORS.put(System.LOCKSCREEN_SOUNDS_ENABLED, BOOLEAN_VALIDATOR);
         VALIDATORS.put(System.LOCKSCREEN_DISABLED, BOOLEAN_VALIDATOR);
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
index 99a00e4..c830d6b 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
@@ -835,7 +835,11 @@
                 continue;
             }
 
-            if (settingsToPreserve.contains(getQualifiedKeyForSetting(key, contentUri))) {
+            // Filter out Settings.Secure.NAVIGATION_MODE from modified preserve settings.
+            // Let it take part in restore process. See also b/244532342.
+            boolean isSettingPreserved = settingsToPreserve.contains(
+                    getQualifiedKeyForSetting(key, contentUri));
+            if (isSettingPreserved && !Settings.Secure.NAVIGATION_MODE.equals(key)) {
                 Log.i(TAG, "Skipping restore for setting " + key + " as it is marked as "
                         + "preserved");
                 continue;
@@ -896,6 +900,23 @@
             } else {
                 destination = contentUri;
             }
+
+            // Value is written to NAVIGATION_MODE_RESTORE to mark navigation mode
+            // has been set before on source device.
+            // See also: b/244532342.
+            if (Settings.Secure.NAVIGATION_MODE.equals(key)) {
+                contentValues.clear();
+                contentValues.put(Settings.NameValueTable.NAME,
+                        Settings.Secure.NAVIGATION_MODE_RESTORE);
+                contentValues.put(Settings.NameValueTable.VALUE, value);
+                cr.insert(destination, contentValues);
+                // Avoid restore original setting if it has been preserved.
+                if (isSettingPreserved) {
+                    Log.i(TAG, "Skipping restore for setting navigation_mode "
+                        + "as it is marked as preserved");
+                    continue;
+                }
+            }
             settingsHelper.restoreValue(this, cr, contentValues, destination, key, value,
                     mRestoredFromSdkInt);
 
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
index 9da1ab8..27a45df 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
@@ -44,6 +44,7 @@
 import com.android.internal.app.LocalePicker;
 import com.android.settingslib.devicestate.DeviceStateRotationLockSettingsManager;
 
+import java.io.FileNotFoundException;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Locale;
@@ -332,21 +333,30 @@
      * @param value can be a canonicalized uri or "_silent" to indicate a silent (null) ringtone.
      */
     private void setRingtone(String name, String value) {
-        // If it's null, don't change the default
-        if (value == null) return;
-        final Uri ringtoneUri;
-        if (SILENT_RINGTONE.equals(value)) {
-            ringtoneUri = null;
-        } else {
-            Uri canonicalUri = Uri.parse(value);
-            ringtoneUri = mContext.getContentResolver().uncanonicalize(canonicalUri);
-            if (ringtoneUri == null) {
-                // Unrecognized or invalid Uri, don't restore
-                return;
-            }
-        }
-        final int ringtoneType = getRingtoneType(name);
+        Log.v(TAG, "Set ringtone for name: " + name + " value: " + value);
 
+        // If it's null, don't change the default.
+        if (value == null) return;
+        final int ringtoneType = getRingtoneType(name);
+        if (SILENT_RINGTONE.equals(value)) {
+            // SILENT_RINGTONE is a special constant generated by onBackupValue in the source
+            // device.
+            RingtoneManager.setActualDefaultRingtoneUri(mContext, ringtoneType, null);
+            return;
+        }
+
+        Uri ringtoneUri = null;
+        try {
+            ringtoneUri =
+                    RingtoneManager.getRingtoneUriForRestore(
+                            mContext.getContentResolver(), value, ringtoneType);
+        } catch (FileNotFoundException | IllegalArgumentException e) {
+            Log.w(TAG, "Failed to resolve " + value + ": " + e);
+            // Unrecognized or invalid Uri, don't restore
+            return;
+        }
+
+        Log.v(TAG, "setActualDefaultRingtoneUri type: " + ringtoneType + ", uri: " + ringtoneUri);
         RingtoneManager.setActualDefaultRingtoneUri(mContext, ringtoneType, ringtoneUri);
     }
 
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index 1192e00..d2b444b 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -1926,6 +1926,9 @@
         dumpSetting(s, p,
                 Settings.Secure.ASSIST_LONG_PRESS_HOME_ENABLED,
                 SecureSettingsProto.Assist.LONG_PRESS_HOME_ENABLED);
+        dumpSetting(s, p,
+                Settings.Secure.SEARCH_PRESS_HOLD_NAV_HANDLE_ENABLED,
+                SecureSettingsProto.Assist.SEARCH_PRESS_HOLD_NAV_HANDLE_ENABLED);
         p.end(assistToken);
 
         final long assistHandlesToken = p.start(SecureSettingsProto.ASSIST_HANDLES);
diff --git a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
index 9c9dd8a..c697c1f 100644
--- a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
+++ b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
@@ -79,6 +79,7 @@
                     Settings.System.SHOW_GTALK_SERVICE_STATUS, // candidate for backup?
                     Settings.System.SHOW_TOUCHES,
                     Settings.System.SHOW_KEY_PRESSES,
+                    Settings.System.SHOW_ROTARY_INPUT,
                     Settings.System.SIP_ADDRESS_ONLY, // value, not a setting
                     Settings.System.SIP_ALWAYS, // value, not a setting
                     Settings.System.SYSTEM_LOCALES, // bug?
@@ -689,7 +690,8 @@
                     Settings.Global.Wearable.TETHER_CONFIG_STATE,
                     Settings.Global.Wearable.PHONE_SWITCHING_SUPPORTED,
                     Settings.Global.Wearable.WEAR_MEDIA_CONTROLS_PACKAGE,
-                    Settings.Global.Wearable.WEAR_MEDIA_SESSIONS_PACKAGE);
+                    Settings.Global.Wearable.WEAR_MEDIA_SESSIONS_PACKAGE,
+                    Settings.Global.Wearable.WEAR_POWER_ANOMALY_SERVICE_ENABLED);
 
     private static final Set<String> BACKUP_DENY_LIST_SECURE_SETTINGS =
              newHashSet(
@@ -722,7 +724,8 @@
                  Settings.Secure.AUTOMATIC_STORAGE_MANAGER_ENABLED,
                  Settings.Secure.AUTOMATIC_STORAGE_MANAGER_LAST_RUN,
                  Settings.Secure.AUTOMATIC_STORAGE_MANAGER_TURNED_OFF_BY_POLICY,
-                 Settings.Secure.AUDIO_DEVICE_INVENTORY, // setting not controllable by user
+                 Settings.Secure.AUDIO_DEVICE_INVENTORY, // not controllable by user
+                 Settings.Secure.AUDIO_SAFE_CSD_AS_A_FEATURE_ENABLED, // not controllable by user
                  Settings.Secure.BACKUP_AUTO_RESTORE,
                  Settings.Secure.BACKUP_ENABLED,
                  Settings.Secure.BACKUP_PROVISIONED,
@@ -857,7 +860,9 @@
                  Settings.Secure.UI_TRANSLATION_ENABLED,
                  Settings.Secure.CREDENTIAL_SERVICE,
                  Settings.Secure.CREDENTIAL_SERVICE_PRIMARY,
-                 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_EDGE_HAPTIC_ENABLED);
+                 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_EDGE_HAPTIC_ENABLED,
+                 Settings.Secure.DND_CONFIGS_MIGRATED,
+                 Settings.Secure.NAVIGATION_MODE_RESTORE);
 
     @Test
     public void systemSettingsBackedUpOrDenied() {
diff --git a/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java b/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java
index bc81c44..4b10b56 100644
--- a/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java
+++ b/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java
@@ -23,20 +23,31 @@
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verifyZeroInteractions;
+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.ContentResolver;
+import android.content.ContentProvider;
 import android.content.ContentValues;
 import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.res.AssetFileDescriptor;
 import android.content.res.Resources;
+import android.database.Cursor;
+import android.database.MatrixCursor;
 import android.media.AudioManager;
 import android.net.Uri;
+import android.os.Bundle;
 import android.os.LocaleList;
+import android.provider.BaseColumns;
+import android.provider.MediaStore;
 import android.provider.Settings;
 import android.telephony.TelephonyManager;
+import android.test.mock.MockContentProvider;
+import android.test.mock.MockContentResolver;
+import android.util.ArrayMap;
 
-import androidx.test.platform.app.InstrumentationRegistry;
 import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.R;
@@ -57,31 +68,46 @@
     private static final String SETTING_VALUE = "setting_value";
     private static final String SETTING_REAL_VALUE = "setting_real_value";
 
+    private static final String DEFAULT_RINGTONE_VALUE =
+            "content://media/internal/audio/media/10?title=DefaultRingtone&canonical=1";
+    private static final String DEFAULT_NOTIFICATION_VALUE =
+            "content://media/internal/audio/media/20?title=DefaultNotification&canonical=1";
+    private static final String DEFAULT_ALARM_VALUE =
+            "content://media/internal/audio/media/30?title=DefaultAlarm&canonical=1";
+
     private SettingsHelper mSettingsHelper;
 
     @Mock private Context mContext;
     @Mock private Resources mResources;
-    @Mock private ContentResolver mContentResolver;
     @Mock private AudioManager mAudioManager;
     @Mock private TelephonyManager mTelephonyManager;
 
+    @Mock private MockContentResolver mContentResolver;
+    private MockSettingsProvider mSettingsProvider;
+
     @Before
     public void setUp() {
-        clearLongPressPowerValues();
         MockitoAnnotations.initMocks(this);
         when(mContext.getSystemService(eq(Context.AUDIO_SERVICE))).thenReturn(mAudioManager);
         when(mContext.getSystemService(eq(Context.TELEPHONY_SERVICE))).thenReturn(
                 mTelephonyManager);
         when(mContext.getResources()).thenReturn(mResources);
         when(mContext.getApplicationContext()).thenReturn(mContext);
-        when(mContext.getContentResolver()).thenReturn(getContentResolver());
+        when(mContext.getApplicationInfo()).thenReturn(new ApplicationInfo());
 
         mSettingsHelper = spy(new SettingsHelper(mContext));
+        mContentResolver = spy(new MockContentResolver());
+        when(mContext.getContentResolver()).thenReturn(mContentResolver);
+        mSettingsProvider = new MockSettingsProvider(mContext);
+        mContentResolver.addProvider(Settings.AUTHORITY, mSettingsProvider);
     }
 
     @After
     public void tearDown() {
-        clearLongPressPowerValues();
+        Settings.Global.putString(mContentResolver, Settings.Global.POWER_BUTTON_LONG_PRESS,
+                null);
+        Settings.Global.putString(mContentResolver, Settings.Global.KEY_CHORD_POWER_VOLUME_UP,
+                null);
     }
 
     @Test
@@ -106,33 +132,30 @@
         mSettingsHelper.restoreValue(mContext, mContentResolver, new ContentValues(), Uri.EMPTY,
                 SETTING_KEY, SETTING_VALUE, /* restoredFromSdkInt */ 0);
 
-        verifyZeroInteractions(mContentResolver);
+        // The only time of interaction happened during setUp()
+        verify(mContentResolver, times(1))
+                .addProvider(Settings.AUTHORITY, mSettingsProvider);
+
+        verifyNoMoreInteractions(mContentResolver);
     }
 
     @Test
     public void testRestoreValue_lppForAssistantEnabled_updatesValue() {
-        ContentResolver cr =
-                InstrumentationRegistry.getInstrumentation().getTargetContext()
-                        .getContentResolver();
         when(mResources.getBoolean(
                 R.bool.config_longPressOnPowerForAssistantSettingAvailable)).thenReturn(
                 true);
 
-        mSettingsHelper.restoreValue(mContext, cr, new ContentValues(), Uri.EMPTY,
+        mSettingsHelper.restoreValue(mContext, mContentResolver, new ContentValues(), Uri.EMPTY,
                 Settings.Global.POWER_BUTTON_LONG_PRESS, "5", 0);
 
-        assertThat(
-                Settings.Global.getInt(cr, Settings.Global.POWER_BUTTON_LONG_PRESS, -1))
-                    .isEqualTo(5);
-        assertThat(Settings.Global.getInt(cr, Settings.Global.KEY_CHORD_POWER_VOLUME_UP,
-                -1)).isEqualTo(2);
+        assertThat(Settings.Global.getInt(
+                mContentResolver, Settings.Global.POWER_BUTTON_LONG_PRESS, -1)).isEqualTo(5);
+        assertThat(Settings.Global.getInt(
+                mContentResolver, Settings.Global.KEY_CHORD_POWER_VOLUME_UP, -1)).isEqualTo(2);
     }
 
     @Test
     public void testRestoreValue_lppForAssistantNotEnabled_updatesValueToDefaultConfig() {
-        ContentResolver cr =
-                InstrumentationRegistry.getInstrumentation().getTargetContext()
-                        .getContentResolver();
         when(mResources.getBoolean(
                 R.bool.config_longPressOnPowerForAssistantSettingAvailable)).thenReturn(
                 true);
@@ -144,21 +167,17 @@
                 R.integer.config_keyChordPowerVolumeUp)).thenReturn(
                 1);
 
-        mSettingsHelper.restoreValue(mContext, cr, new ContentValues(), Uri.EMPTY,
+        mSettingsHelper.restoreValue(mContext, mContentResolver, new ContentValues(), Uri.EMPTY,
                 Settings.Global.POWER_BUTTON_LONG_PRESS, "2", 0);
 
-        assertThat(
-                Settings.Global.getInt(cr, Settings.Global.POWER_BUTTON_LONG_PRESS, -1))
-                .isEqualTo(1);
-        assertThat(Settings.Global.getInt(cr, Settings.Global.KEY_CHORD_POWER_VOLUME_UP,
-                -1)).isEqualTo(1);
+        assertThat(Settings.Global.getInt(
+                mContentResolver, Settings.Global.POWER_BUTTON_LONG_PRESS, -1)).isEqualTo(1);
+        assertThat(Settings.Global.getInt(
+                mContentResolver, Settings.Global.KEY_CHORD_POWER_VOLUME_UP, -1)).isEqualTo(1);
     }
 
     @Test
     public void testRestoreValue_lppForAssistantNotEnabledDefaultConfig_updatesValue() {
-        ContentResolver cr =
-                InstrumentationRegistry.getInstrumentation().getTargetContext()
-                        .getContentResolver();
         when(mResources.getBoolean(
                 R.bool.config_longPressOnPowerForAssistantSettingAvailable)).thenReturn(
                 true);
@@ -170,47 +189,39 @@
                 R.integer.config_keyChordPowerVolumeUp)).thenReturn(
                 1);
 
-        mSettingsHelper.restoreValue(mContext, cr, new ContentValues(), Uri.EMPTY,
+        mSettingsHelper.restoreValue(mContext, mContentResolver, new ContentValues(), Uri.EMPTY,
                 Settings.Global.POWER_BUTTON_LONG_PRESS, "2", 0);
 
-        assertThat(
-                Settings.Global.getInt(cr, Settings.Global.POWER_BUTTON_LONG_PRESS, -1))
-                    .isEqualTo(1);
-        assertThat(Settings.Global.getInt(cr, Settings.Global.KEY_CHORD_POWER_VOLUME_UP,
-                -1)).isEqualTo(1);
+        assertThat(Settings.Global.getInt(
+                mContentResolver, Settings.Global.POWER_BUTTON_LONG_PRESS, -1)).isEqualTo(1);
+        assertThat(Settings.Global.getInt(
+                mContentResolver, Settings.Global.KEY_CHORD_POWER_VOLUME_UP, -1)).isEqualTo(1);
     }
 
     @Test
     public void testRestoreValue_lppForAssistantNotAvailable_doesNotRestore() {
-        ContentResolver cr =
-                InstrumentationRegistry.getInstrumentation().getTargetContext()
-                        .getContentResolver();
-        when(mResources.getBoolean(
-                R.bool.config_longPressOnPowerForAssistantSettingAvailable)).thenReturn(
-                false);
+        when(mResources.getBoolean(R.bool.config_longPressOnPowerForAssistantSettingAvailable))
+                .thenReturn(false);
 
-        mSettingsHelper.restoreValue(mContext, cr, new ContentValues(), Uri.EMPTY,
-                Settings.Global.POWER_BUTTON_LONG_PRESS, "5", 0);
+        mSettingsHelper.restoreValue(mContext, mContentResolver, new ContentValues(), Uri.EMPTY,
+                Settings.Global.POWER_BUTTON_LONG_PRESS, "500", 0);
 
-        assertThat((Settings.Global.getInt(cr, Settings.Global.POWER_BUTTON_LONG_PRESS,
-                -1))).isEqualTo(-1);
+        assertThat((Settings.Global.getInt(
+                mContentResolver, Settings.Global.POWER_BUTTON_LONG_PRESS, -1))).isEqualTo(-1);
     }
 
 
     @Test
     public void testRestoreValue_lppForAssistantInvalid_doesNotRestore() {
-        ContentResolver cr =
-                InstrumentationRegistry.getInstrumentation().getTargetContext()
-                        .getContentResolver();
         when(mResources.getBoolean(
                 R.bool.config_longPressOnPowerForAssistantSettingAvailable)).thenReturn(
                 false);
 
-        mSettingsHelper.restoreValue(mContext, cr, new ContentValues(), Uri.EMPTY,
+        mSettingsHelper.restoreValue(mContext, mContentResolver, new ContentValues(), Uri.EMPTY,
                 Settings.Global.POWER_BUTTON_LONG_PRESS, "trees", 0);
 
-        assertThat((Settings.Global.getInt(cr, Settings.Global.POWER_BUTTON_LONG_PRESS,
-                -1))).isEqualTo(-1);
+        assertThat((Settings.Global.getInt(
+                mContentResolver, Settings.Global.POWER_BUTTON_LONG_PRESS, -1))).isEqualTo(-1);
     }
 
     @Test
@@ -338,6 +349,359 @@
     }
 
     @Test
+    public void testRestoreValue_customRingtone_regularUncanonicalize_Success() {
+        final String sourceRingtoneValue =
+                "content://media/internal/audio/media/1?title=Song&canonical=1";
+        final String newRingtoneValueUncanonicalized =
+                "content://media/internal/audio/media/100";
+        final String newRingtoneValueCanonicalized =
+                "content://media/internal/audio/media/100?title=Song&canonical=1";
+
+        ContentProvider mockMediaContentProvider =
+                new MockContentProvider(mContext) {
+                    @Override
+                    public Uri uncanonicalize(Uri url) {
+                        assertThat(url).isEqualTo(Uri.parse(sourceRingtoneValue));
+                        return Uri.parse(newRingtoneValueUncanonicalized);
+                    }
+
+                    @Override
+                    public Uri canonicalize(Uri url) {
+                        assertThat(url).isEqualTo(Uri.parse(newRingtoneValueUncanonicalized));
+                        return Uri.parse(newRingtoneValueCanonicalized);
+                    }
+
+                    @Override
+                    public String getType(Uri url) {
+                        return "audio/ogg";
+                    }
+                };
+
+        mContentResolver.addProvider(MediaStore.AUTHORITY, mockMediaContentProvider);
+
+        resetRingtoneSettingsToDefault();
+        assertThat(Settings.System.getString(mContentResolver, Settings.System.RINGTONE))
+                .isEqualTo(DEFAULT_RINGTONE_VALUE);
+
+        mSettingsHelper.restoreValue(
+                mContext,
+                mContentResolver,
+                new ContentValues(),
+                Uri.EMPTY,
+                Settings.System.RINGTONE,
+                sourceRingtoneValue,
+                0);
+
+        assertThat(Settings.System.getString(mContentResolver, Settings.System.RINGTONE))
+                .isEqualTo(newRingtoneValueCanonicalized);
+    }
+
+    @Test
+    public void testRestoreValue_customRingtone_useCustomLookup_success() {
+        final String sourceRingtoneValue =
+                "content://0@media/external/audio/media/1?title=Song&canonical=1";
+        final String newRingtoneValueUncanonicalized =
+                "content://0@media/external/audio/media/100";
+        final String newRingtoneValueCanonicalized =
+                "content://0@media/external/audio/media/100?title=Song&canonical=1";
+
+        MatrixCursor cursor = new MatrixCursor(new String[] {BaseColumns._ID});
+        cursor.addRow(new Object[] {100L});
+
+        ContentProvider mockMediaContentProvider =
+                new MockContentProvider(mContext) {
+                    @Override
+                    public Uri uncanonicalize(Uri url) {
+                        // mock the lookup failure in regular MediaProvider.uncanonicalize.
+                        return null;
+                    }
+
+                    @Override
+                    public Uri canonicalize(Uri url) {
+                        assertThat(url).isEqualTo(Uri.parse(newRingtoneValueUncanonicalized));
+                        return Uri.parse(newRingtoneValueCanonicalized);
+                    }
+
+                    @Override
+                    public String getType(Uri url) {
+                        return "audio/ogg";
+                    }
+
+                    @Override
+                    public Cursor query(
+                            Uri uri,
+                            String[] projection,
+                            String selection,
+                            String[] selectionArgs,
+                            String sortOrder) {
+                        assertThat(uri)
+                                .isEqualTo(Uri.parse("content://0@media/external/audio/media"));
+                        assertThat(projection).isEqualTo(new String[] {"_id"});
+                        assertThat(selection).isEqualTo("is_ringtone=1 AND title=?");
+                        assertThat(selectionArgs).isEqualTo(new String[] {"Song"});
+                        return cursor;
+                    }
+                };
+
+        mContentResolver.addProvider(MediaStore.AUTHORITY, mockMediaContentProvider);
+        mContentResolver.addProvider("0@" + MediaStore.AUTHORITY, mockMediaContentProvider);
+
+        resetRingtoneSettingsToDefault();
+
+        mSettingsHelper.restoreValue(
+                mContext,
+                mContentResolver,
+                new ContentValues(),
+                Uri.EMPTY,
+                Settings.System.RINGTONE,
+                sourceRingtoneValue,
+                0);
+
+        assertThat(Settings.System.getString(mContentResolver, Settings.System.RINGTONE))
+                .isEqualTo(newRingtoneValueCanonicalized);
+    }
+
+    @Test
+    public void testRestoreValue_customRingtone_notificationSound_useCustomLookup_success() {
+        final String sourceRingtoneValue =
+                "content://0@media/external/audio/media/2?title=notificationPing&canonical=1";
+        final String newRingtoneValueUncanonicalized =
+                "content://0@media/external/audio/media/200";
+        final String newRingtoneValueCanonicalized =
+                "content://0@media/external/audio/media/200?title=notificationPing&canonicalize=1";
+
+        MatrixCursor cursor = new MatrixCursor(new String[] {BaseColumns._ID});
+        cursor.addRow(new Object[] {200L});
+
+        ContentProvider mockMediaContentProvider =
+                new MockContentProvider(mContext) {
+                    @Override
+                    public Uri uncanonicalize(Uri url) {
+                        // mock the lookup failure in regular MediaProvider.uncanonicalize.
+                        return null;
+                    }
+
+                    @Override
+                    public Uri canonicalize(Uri url) {
+                        assertThat(url).isEqualTo(Uri.parse(newRingtoneValueUncanonicalized));
+                        return Uri.parse(newRingtoneValueCanonicalized);
+                    }
+
+                    @Override
+                    public String getType(Uri url) {
+                        return "audio/ogg";
+                    }
+
+                    @Override
+                    public Cursor query(
+                            Uri uri,
+                            String[] projection,
+                            String selection,
+                            String[] selectionArgs,
+                            String sortOrder) {
+                        assertThat(uri)
+                                .isEqualTo(Uri.parse("content://0@media/external/audio/media"));
+                        assertThat(projection).isEqualTo(new String[] {"_id"});
+                        assertThat(selection).isEqualTo("is_notification=1 AND title=?");
+                        assertThat(selectionArgs).isEqualTo(new String[] {"notificationPing"});
+                        return cursor;
+                    }
+                };
+
+        mContentResolver.addProvider(MediaStore.AUTHORITY, mockMediaContentProvider);
+        mContentResolver.addProvider("0@" + MediaStore.AUTHORITY, mockMediaContentProvider);
+
+        resetRingtoneSettingsToDefault();
+
+        mSettingsHelper.restoreValue(
+                mContext,
+                mContentResolver,
+                new ContentValues(),
+                Uri.EMPTY,
+                Settings.System.NOTIFICATION_SOUND,
+                sourceRingtoneValue,
+                0);
+
+        assertThat(
+                        Settings.System.getString(
+                                mContentResolver, Settings.System.NOTIFICATION_SOUND))
+                .isEqualTo(newRingtoneValueCanonicalized);
+    }
+
+    @Test
+    public void testRestoreValue_customRingtone_alarmSound_useCustomLookup_success() {
+        final String sourceRingtoneValue =
+                "content://0@media/external/audio/media/3?title=alarmSound&canonical=1";
+        final String newRingtoneValueUncanonicalized =
+                "content://0@media/external/audio/media/300";
+        final String newRingtoneValueCanonicalized =
+                "content://0@media/external/audio/media/300?title=alarmSound&canonical=1";
+
+        MatrixCursor cursor = new MatrixCursor(new String[] {BaseColumns._ID});
+        cursor.addRow(new Object[] {300L});
+
+        ContentProvider mockMediaContentProvider =
+                new MockContentProvider(mContext) {
+                    @Override
+                    public Uri uncanonicalize(Uri url) {
+                        // mock the lookup failure in regular MediaProvider.uncanonicalize.
+                        return null;
+                    }
+
+                    @Override
+                    public Uri canonicalize(Uri url) {
+                        assertThat(url).isEqualTo(Uri.parse(newRingtoneValueUncanonicalized));
+                        return Uri.parse(newRingtoneValueCanonicalized);
+                    }
+
+                    @Override
+                    public String getType(Uri url) {
+                        return "audio/ogg";
+                    }
+
+                    @Override
+                    public Cursor query(
+                            Uri uri,
+                            String[] projection,
+                            String selection,
+                            String[] selectionArgs,
+                            String sortOrder) {
+                        assertThat(uri)
+                                .isEqualTo(Uri.parse("content://0@media/external/audio/media"));
+                        assertThat(projection).isEqualTo(new String[] {"_id"});
+                        assertThat(selection).isEqualTo("is_alarm=1 AND title=?");
+                        assertThat(selectionArgs).isEqualTo(new String[] {"alarmSound"});
+                        return cursor;
+                    }
+
+                    @Override
+                    public AssetFileDescriptor openTypedAssetFile(Uri url, String mimeType,
+                            Bundle opts) {
+                        return null;
+                    }
+                };
+
+        mContentResolver.addProvider(MediaStore.AUTHORITY, mockMediaContentProvider);
+        mContentResolver.addProvider("0@" + MediaStore.AUTHORITY, mockMediaContentProvider);
+
+        resetRingtoneSettingsToDefault();
+
+        mSettingsHelper.restoreValue(
+                mContext,
+                mContentResolver,
+                new ContentValues(),
+                Uri.EMPTY,
+                Settings.System.ALARM_ALERT,
+                sourceRingtoneValue,
+                0);
+
+        assertThat(Settings.System.getString(mContentResolver, Settings.System.ALARM_ALERT))
+                .isEqualTo(newRingtoneValueCanonicalized);
+    }
+
+    @Test
+    public void testRestoreValue_customRingtone_useCustomLookup_multipleResults_notRestore() {
+        final String sourceRingtoneValue =
+                "content://0@media/external/audio/media/1?title=Song&canonical=1";
+
+        // This is to mock the case that there are multiple results by querying title +
+        // ringtone_type.
+        MatrixCursor cursor = new MatrixCursor(new String[] {BaseColumns._ID});
+        cursor.addRow(new Object[] {100L});
+        cursor.addRow(new Object[] {110L});
+
+        ContentProvider mockMediaContentProvider =
+                new MockContentProvider(mContext) {
+                    @Override
+                    public Uri uncanonicalize(Uri url) {
+                        // mock the lookup failure in regular MediaProvider.uncanonicalize.
+                        return null;
+                    }
+
+                    @Override
+                    public String getType(Uri url) {
+                        return "audio/ogg";
+                    }
+                };
+
+        mContentResolver.addProvider(MediaStore.AUTHORITY, mockMediaContentProvider);
+        mContentResolver.addProvider("0@" + MediaStore.AUTHORITY, mockMediaContentProvider);
+
+        resetRingtoneSettingsToDefault();
+
+        mSettingsHelper.restoreValue(
+                mContext,
+                mContentResolver,
+                new ContentValues(),
+                Uri.EMPTY,
+                Settings.System.RINGTONE,
+                sourceRingtoneValue,
+                0);
+
+        assertThat(Settings.System.getString(mContentResolver, Settings.System.RINGTONE))
+                .isEqualTo(DEFAULT_RINGTONE_VALUE);
+    }
+
+    @Test
+    public void testRestoreValue_customRingtone_restoreSilentValue() {
+        ContentProvider mockMediaContentProvider =
+                new MockContentProvider(mContext) {
+                    @Override
+                    public Uri uncanonicalize(Uri url) {
+                        // mock the lookup failure in regular MediaProvider.uncanonicalize.
+                        return null;
+                    }
+
+                    @Override
+                    public String getType(Uri url) {
+                        return "audio/ogg";
+                    }
+                };
+
+        mContentResolver.addProvider(MediaStore.AUTHORITY, mockMediaContentProvider);
+
+        resetRingtoneSettingsToDefault();
+
+        mSettingsHelper.restoreValue(
+                mContext,
+                mContentResolver,
+                new ContentValues(),
+                Uri.EMPTY,
+                Settings.System.RINGTONE,
+                "_silent",
+                0);
+
+        assertThat(Settings.System.getString(mContentResolver, Settings.System.RINGTONE))
+                .isEqualTo(null);
+    }
+
+    private static class MockSettingsProvider extends MockContentProvider {
+        private final ArrayMap<String, String> mKeyValueStore = new ArrayMap<>();
+        MockSettingsProvider(Context context) {
+            super(context);
+        }
+
+        @Override
+        public Bundle call(String method, String request, Bundle args) {
+            if (method.startsWith("PUT_")) {
+                mKeyValueStore.put(request, args.getString("value"));
+                return null;
+            } else if (method.startsWith("GET_")) {
+                return Bundle.forPair("value", mKeyValueStore.getOrDefault(request, ""));
+            }
+            return null;
+        }
+
+        @Override
+        public Uri insert(Uri uri, ContentValues values) {
+            String name = values.getAsString("name");
+            String value = values.getAsString("value");
+            mKeyValueStore.put(name, value);
+            return null;
+        }
+    }
+
+    @Test
     public void restoreValue_autoRotation_deviceStateAutoRotationDisabled_restoresValue() {
         when(mResources.getStringArray(R.array.config_perDeviceStateRotationLockDefaults))
                 .thenReturn(new String[]{});
@@ -364,15 +728,13 @@
     }
 
     private int getAutoRotationSettingValue() {
-        return Settings.System.getInt(
-                getContentResolver(),
+        return Settings.System.getInt(mContentResolver,
                 Settings.System.ACCELEROMETER_ROTATION,
                 /* default= */ -1);
     }
 
     private void setAutoRotationSettingValue(int value) {
-        Settings.System.putInt(
-                getContentResolver(),
+        Settings.System.putInt(mContentResolver,
                 Settings.System.ACCELEROMETER_ROTATION,
                 value
         );
@@ -381,7 +743,7 @@
     private void restoreAutoRotationSetting(int newValue) {
         mSettingsHelper.restoreValue(
                 mContext,
-                getContentResolver(),
+                mContentResolver,
                 new ContentValues(),
                 /* destination= */ Settings.System.CONTENT_URI,
                 /* name= */ Settings.System.ACCELEROMETER_ROTATION,
@@ -389,15 +751,19 @@
                 /* restoredFromSdkInt= */ 0);
     }
 
-    private ContentResolver getContentResolver() {
-        return InstrumentationRegistry.getInstrumentation().getTargetContext()
-                .getContentResolver();
-    }
+    private void resetRingtoneSettingsToDefault() {
+        Settings.System.putString(
+                mContentResolver, Settings.System.RINGTONE, DEFAULT_RINGTONE_VALUE);
+        Settings.System.putString(
+                mContentResolver, Settings.System.NOTIFICATION_SOUND, DEFAULT_NOTIFICATION_VALUE);
+        Settings.System.putString(
+                mContentResolver, Settings.System.ALARM_ALERT, DEFAULT_ALARM_VALUE);
 
-    private void clearLongPressPowerValues() {
-        ContentResolver cr = InstrumentationRegistry.getInstrumentation().getTargetContext()
-                .getContentResolver();
-        Settings.Global.putString(cr, Settings.Global.POWER_BUTTON_LONG_PRESS, null);
-        Settings.Global.putString(cr, Settings.Global.KEY_CHORD_POWER_VOLUME_UP, null);
+        assertThat(Settings.System.getString(mContentResolver, Settings.System.RINGTONE))
+                .isEqualTo(DEFAULT_RINGTONE_VALUE);
+        assertThat(Settings.System.getString(mContentResolver, Settings.System.NOTIFICATION_SOUND))
+                .isEqualTo(DEFAULT_NOTIFICATION_VALUE);
+        assertThat(Settings.System.getString(mContentResolver, Settings.System.ALARM_ALERT))
+                .isEqualTo(DEFAULT_ALARM_VALUE);
     }
 }
diff --git a/packages/SystemUI/Android.bp b/packages/SystemUI/Android.bp
index 29999c2..b472982 100644
--- a/packages/SystemUI/Android.bp
+++ b/packages/SystemUI/Android.bp
@@ -423,6 +423,7 @@
         "mockito-target-extended-minus-junit4",
         "androidx.test.ext.junit",
         "androidx.test.ext.truth",
+        "kotlin-test",
     ],
     libs: [
         "android.test.runner",
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index 58c9f77..6778d5a 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -562,7 +562,7 @@
                   android:exported="true"
                   android:launchMode="singleTop"
                   android:permission="android.permission.MANAGE_SENSOR_PRIVACY"
-                  android:theme="@style/Theme.SystemUI.Dialog.Alert"
+                  android:theme="@style/Theme.SystemUI.Dialog.Alert.SensorPrivacy"
                   android:finishOnCloseSystemDialogs="true"
                   android:showForAllUsers="true">
         </activity>
diff --git a/packages/SystemUI/OWNERS b/packages/SystemUI/OWNERS
index 0f1f168..a892269 100644
--- a/packages/SystemUI/OWNERS
+++ b/packages/SystemUI/OWNERS
@@ -98,7 +98,6 @@
 yuandizhou@google.com
 yurilin@google.com
 zakcohen@google.com
-zoepage@google.com
 
 #Android TV
 rgl@google.com
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/DialogLaunchAnimator.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/DialogLaunchAnimator.kt
index 37b1ee5..187d073 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/DialogLaunchAnimator.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/DialogLaunchAnimator.kt
@@ -249,7 +249,7 @@
         // intent is to launch a dialog from another dialog.
         val animatedParent =
             openedDialogs.firstOrNull {
-                it.dialog.window.decorView.viewRootImpl == controller.viewRoot
+                it.dialog.window?.decorView?.viewRootImpl == controller.viewRoot
             }
         val controller =
             animatedParent?.dialogContentWithBackground?.let {
@@ -336,7 +336,7 @@
     ): ActivityLaunchAnimator.Controller? {
         val animatedDialog =
             openedDialogs.firstOrNull {
-                it.dialog.window.decorView.viewRootImpl == view.viewRootImpl
+                it.dialog.window?.decorView?.viewRootImpl == view.viewRootImpl
             }
                 ?: return null
         return createActivityLaunchController(animatedDialog, cujType)
@@ -417,7 +417,7 @@
                 animatedDialog.prepareForStackDismiss()
 
                 // Remove the dim.
-                dialog.window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
+                dialog.window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
             }
 
             override fun onLaunchAnimationEnd(isExpandingFullyAbove: Boolean) {
@@ -783,7 +783,7 @@
         }
 
         // Show the background dim.
-        dialog.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
+        dialog.window?.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
 
         startAnimation(
             isLaunching = true,
@@ -863,7 +863,7 @@
             isLaunching = false,
             onLaunchAnimationStart = {
                 // Remove the dim background as soon as we start the animation.
-                dialog.window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
+                dialog.window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
             },
             onLaunchAnimationEnd = {
                 val dialogContentWithBackground = this.dialogContentWithBackground!!
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/GhostedViewLaunchAnimatorController.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/GhostedViewLaunchAnimatorController.kt
index 1a03ede..6c4b695 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/GhostedViewLaunchAnimatorController.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/GhostedViewLaunchAnimatorController.kt
@@ -206,8 +206,9 @@
             return
         }
 
-        backgroundView = FrameLayout(launchContainer.context)
-        launchContainerOverlay.add(backgroundView)
+        backgroundView = FrameLayout(launchContainer.context).also {
+            launchContainerOverlay.add(it)
+        }
 
         // We wrap the ghosted view background and use it to draw the expandable background. Its
         // alpha will be set to 0 as soon as we start drawing the expanding background.
@@ -319,7 +320,7 @@
         backgroundDrawable?.wrapped?.alpha = startBackgroundAlpha
 
         GhostView.removeGhost(ghostedView)
-        launchContainerOverlay.remove(backgroundView)
+        backgroundView?.let { launchContainerOverlay.remove(it) }
 
         if (ghostedView is LaunchableView) {
             // Restore the ghosted view visibility.
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/LaunchAnimator.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/LaunchAnimator.kt
index 142fd21..d6eba2e 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/LaunchAnimator.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/LaunchAnimator.kt
@@ -283,7 +283,7 @@
 
         animator.addListener(
             object : AnimatorListenerAdapter() {
-                override fun onAnimationStart(animation: Animator?, isReverse: Boolean) {
+                override fun onAnimationStart(animation: Animator, isReverse: Boolean) {
                     if (DEBUG) {
                         Log.d(TAG, "Animation started")
                     }
@@ -295,7 +295,7 @@
                     launchContainerOverlay.add(windowBackgroundLayer)
                 }
 
-                override fun onAnimationEnd(animation: Animator?) {
+                override fun onAnimationEnd(animation: Animator) {
                     if (DEBUG) {
                         Log.d(TAG, "Animation ended")
                     }
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt
index b555fa5..8dc7495 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt
@@ -42,7 +42,9 @@
                 return baseTypeface
             }
 
-            val axes = FontVariationAxis.fromFontVariationSettings(fVar).toMutableList()
+            val axes = FontVariationAxis.fromFontVariationSettings(fVar)
+                ?.toMutableList()
+                ?: mutableListOf()
             axes.removeIf { !baseTypeface.isSupportedAxes(it.getOpenTypeTagValue()) }
             if (axes.isEmpty()) {
                 return baseTypeface
@@ -120,8 +122,8 @@
             }
             addListener(
                 object : AnimatorListenerAdapter() {
-                    override fun onAnimationEnd(animation: Animator?) = textInterpolator.rebase()
-                    override fun onAnimationCancel(animation: Animator?) = textInterpolator.rebase()
+                    override fun onAnimationEnd(animation: Animator) = textInterpolator.rebase()
+                    override fun onAnimationCancel(animation: Animator) = textInterpolator.rebase()
                 }
             )
         }
@@ -302,11 +304,11 @@
             if (onAnimationEnd != null) {
                 val listener =
                     object : AnimatorListenerAdapter() {
-                        override fun onAnimationEnd(animation: Animator?) {
+                        override fun onAnimationEnd(animation: Animator) {
                             onAnimationEnd.run()
                             animator.removeListener(this)
                         }
-                        override fun onAnimationCancel(animation: Animator?) {
+                        override fun onAnimationCancel(animation: Animator) {
                             animator.removeListener(this)
                         }
                     }
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/ViewHierarchyAnimator.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/ViewHierarchyAnimator.kt
index 38b99cc..bd3706e 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/ViewHierarchyAnimator.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/ViewHierarchyAnimator.kt
@@ -1046,7 +1046,7 @@
                         }
                     }
 
-                    override fun onAnimationCancel(animation: Animator?) {
+                    override fun onAnimationCancel(animation: Animator) {
                         cancelled = true
                     }
                 }
diff --git a/packages/SystemUI/compose/core/OWNERS b/packages/SystemUI/compose/core/OWNERS
new file mode 100644
index 0000000..7e37f4f
--- /dev/null
+++ b/packages/SystemUI/compose/core/OWNERS
@@ -0,0 +1,12 @@
+set noparent
+
+# Bug component: 1184816
+
+jdemeulenaere@google.com
+nijamkin@google.com
+
+# Don't send reviews here.
+dsandler@android.com
+cinek@google.com
+juliacr@google.com
+pixel@google.com
diff --git a/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/Key.kt b/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/Key.kt
index c3f44f8..f7ebe2f 100644
--- a/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/Key.kt
+++ b/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/Key.kt
@@ -37,7 +37,14 @@
 }
 
 /** Key for a scene. */
-class SceneKey(name: String, identity: Any = Object()) : Key(name, identity) {
+class SceneKey(
+    name: String,
+    identity: Any = Object(),
+) : Key(name, identity) {
+
+    /** The unique [ElementKey] identifying this scene's root element. */
+    val rootElementKey = ElementKey(name, identity)
+
     override fun toString(): String {
         return "SceneKey(name=$name)"
     }
diff --git a/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/SceneTransitions.kt b/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/SceneTransitions.kt
index 9752f53..f4e3902 100644
--- a/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/SceneTransitions.kt
+++ b/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/SceneTransitions.kt
@@ -35,7 +35,7 @@
 
 /** The transitions configuration of a [SceneTransitionLayout]. */
 class SceneTransitions(
-    val transitionSpecs: List<TransitionSpec>,
+    private val transitionSpecs: List<TransitionSpec>,
 ) {
     private val cache = mutableMapOf<SceneKey, MutableMap<SceneKey, TransitionSpec>>()
 
diff --git a/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/TransitionDslImpl.kt b/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/TransitionDslImpl.kt
index afd49b4..48d5638e8b 100644
--- a/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/TransitionDslImpl.kt
+++ b/packages/SystemUI/compose/core/src/com/android/compose/animation/scene/TransitionDslImpl.kt
@@ -75,7 +75,7 @@
     }
 }
 
-private class TransitionBuilderImpl : TransitionBuilder {
+internal class TransitionBuilderImpl : TransitionBuilder {
     val transformations = mutableListOf<Transformation>()
     override var spec: AnimationSpec<Float> = spring(stiffness = Spring.StiffnessLow)
 
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/ExampleFeature.kt b/packages/SystemUI/compose/features/src/com/android/systemui/ExampleFeature.kt
deleted file mode 100644
index c58c162..0000000
--- a/packages/SystemUI/compose/features/src/com/android/systemui/ExampleFeature.kt
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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 androidx.compose.foundation.clickable
-import androidx.compose.foundation.layout.BoxWithConstraints
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.Row
-import androidx.compose.foundation.layout.Spacer
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.size
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.Surface
-import androidx.compose.material3.Text
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.getValue
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.remember
-import androidx.compose.runtime.setValue
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.unit.Dp
-import androidx.compose.ui.unit.dp
-import kotlin.math.roundToInt
-
-/**
- * This is an example Compose feature, which shows a text and a count that is incremented when
- * clicked. We also show the max width available to this component, which is displayed either next
- * to or below the text depending on that max width.
- */
-@Composable
-fun ExampleFeature(text: String, modifier: Modifier = Modifier) {
-    BoxWithConstraints(modifier) {
-        val maxWidth = maxWidth
-        if (maxWidth < 600.dp) {
-            Column {
-                CounterTile(text)
-                Spacer(Modifier.size(16.dp))
-                MaxWidthTile(maxWidth)
-            }
-        } else {
-            Row {
-                CounterTile(text)
-                Spacer(Modifier.size(16.dp))
-                MaxWidthTile(maxWidth)
-            }
-        }
-    }
-}
-
-@Composable
-private fun CounterTile(text: String, modifier: Modifier = Modifier) {
-    Surface(
-        modifier,
-        color = MaterialTheme.colorScheme.primaryContainer,
-        shape = RoundedCornerShape(28.dp),
-    ) {
-        var count by remember { mutableStateOf(0) }
-        Column(
-            Modifier.clickable { count++ }.padding(16.dp),
-        ) {
-            Text(text)
-            Text("I was clicked $count times.")
-        }
-    }
-}
-
-@Composable
-private fun MaxWidthTile(maxWidth: Dp, modifier: Modifier = Modifier) {
-    Surface(
-        modifier,
-        color = MaterialTheme.colorScheme.tertiaryContainer,
-        shape = RoundedCornerShape(28.dp),
-    ) {
-        Text(
-            "The max available width to me is: ${maxWidth.value.roundToInt()}dp",
-            Modifier.padding(16.dp)
-        )
-    }
-}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/bouncer/ui/composable/BouncerScene.kt b/packages/SystemUI/compose/features/src/com/android/systemui/bouncer/ui/composable/BouncerScene.kt
index b9baa793..81b9eb0 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/bouncer/ui/composable/BouncerScene.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/bouncer/ui/composable/BouncerScene.kt
@@ -24,7 +24,7 @@
 import androidx.compose.animation.Crossfade
 import androidx.compose.animation.core.snap
 import androidx.compose.animation.core.tween
-import androidx.compose.foundation.background
+import androidx.compose.foundation.Canvas
 import androidx.compose.foundation.layout.Arrangement
 import androidx.compose.foundation.layout.Box
 import androidx.compose.foundation.layout.Column
@@ -46,6 +46,7 @@
 import androidx.compose.ui.Modifier
 import androidx.compose.ui.res.stringResource
 import androidx.compose.ui.unit.dp
+import com.android.compose.animation.scene.ElementKey
 import com.android.compose.animation.scene.SceneScope
 import com.android.systemui.R
 import com.android.systemui.bouncer.ui.viewmodel.AuthMethodBouncerViewModel
@@ -63,6 +64,13 @@
 import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.flow.asStateFlow
 
+object Bouncer {
+    object Elements {
+        val Background = ElementKey("BouncerBackground")
+        val Content = ElementKey("BouncerContent")
+    }
+}
+
 /** The bouncer scene displays authentication challenges like PIN, password, or pattern. */
 @SysUISingleton
 class BouncerScene
@@ -88,7 +96,7 @@
 }
 
 @Composable
-private fun BouncerScene(
+private fun SceneScope.BouncerScene(
     viewModel: BouncerViewModel,
     dialogFactory: BouncerSceneDialogFactory,
     modifier: Modifier = Modifier,
@@ -97,84 +105,90 @@
     val authMethodViewModel: AuthMethodBouncerViewModel? by viewModel.authMethod.collectAsState()
     val dialogMessage: String? by viewModel.throttlingDialogMessage.collectAsState()
     var dialog: Dialog? by remember { mutableStateOf(null) }
+    val backgroundColor = MaterialTheme.colorScheme.surface
 
-    Column(
-        horizontalAlignment = Alignment.CenterHorizontally,
-        verticalArrangement = Arrangement.spacedBy(60.dp),
-        modifier =
-            modifier
-                .fillMaxSize()
-                .background(MaterialTheme.colorScheme.surface)
-                .padding(start = 32.dp, top = 92.dp, end = 32.dp, bottom = 32.dp)
-    ) {
-        Crossfade(
-            targetState = message,
-            label = "Bouncer message",
-            animationSpec = if (message.isUpdateAnimated) tween() else snap(),
-        ) { message ->
-            Text(
-                text = message.text,
-                color = MaterialTheme.colorScheme.onSurface,
-                style = MaterialTheme.typography.bodyLarge,
-            )
+    Box(modifier) {
+        Canvas(Modifier.element(Bouncer.Elements.Background).fillMaxSize()) {
+            drawRect(color = backgroundColor)
         }
 
-        Box(Modifier.weight(1f)) {
-            when (val nonNullViewModel = authMethodViewModel) {
-                is PinBouncerViewModel ->
-                    PinBouncer(
-                        viewModel = nonNullViewModel,
-                        modifier = Modifier.align(Alignment.Center),
-                    )
-                is PasswordBouncerViewModel ->
-                    PasswordBouncer(
-                        viewModel = nonNullViewModel,
-                        modifier = Modifier.align(Alignment.Center),
-                    )
-                is PatternBouncerViewModel ->
-                    PatternBouncer(
-                        viewModel = nonNullViewModel,
-                        modifier =
-                            Modifier.aspectRatio(1f, matchHeightConstraintsFirst = false)
-                                .align(Alignment.BottomCenter),
-                    )
-                else -> Unit
-            }
-        }
-
-        Button(
-            onClick = viewModel::onEmergencyServicesButtonClicked,
-            colors =
-                ButtonDefaults.buttonColors(
-                    containerColor = MaterialTheme.colorScheme.tertiaryContainer,
-                    contentColor = MaterialTheme.colorScheme.onTertiaryContainer,
-                ),
+        Column(
+            horizontalAlignment = Alignment.CenterHorizontally,
+            verticalArrangement = Arrangement.spacedBy(60.dp),
+            modifier =
+                Modifier.element(Bouncer.Elements.Content)
+                    .fillMaxSize()
+                    .padding(start = 32.dp, top = 92.dp, end = 32.dp, bottom = 32.dp)
         ) {
-            Text(
-                text = stringResource(com.android.internal.R.string.lockscreen_emergency_call),
-                style = MaterialTheme.typography.bodyMedium,
-            )
-        }
-
-        if (dialogMessage != null) {
-            if (dialog == null) {
-                dialog =
-                    dialogFactory().apply {
-                        setMessage(dialogMessage)
-                        setButton(
-                            DialogInterface.BUTTON_NEUTRAL,
-                            context.getString(R.string.ok),
-                        ) { _, _ ->
-                            viewModel.onThrottlingDialogDismissed()
-                        }
-                        setCancelable(false)
-                        setCanceledOnTouchOutside(false)
-                        show()
-                    }
+            Crossfade(
+                targetState = message,
+                label = "Bouncer message",
+                animationSpec = if (message.isUpdateAnimated) tween() else snap(),
+            ) { message ->
+                Text(
+                    text = message.text,
+                    color = MaterialTheme.colorScheme.onSurface,
+                    style = MaterialTheme.typography.bodyLarge,
+                )
             }
-        } else {
-            dialog?.dismiss()
-            dialog = null
+
+            Box(Modifier.weight(1f)) {
+                when (val nonNullViewModel = authMethodViewModel) {
+                    is PinBouncerViewModel ->
+                        PinBouncer(
+                            viewModel = nonNullViewModel,
+                            modifier = Modifier.align(Alignment.Center),
+                        )
+                    is PasswordBouncerViewModel ->
+                        PasswordBouncer(
+                            viewModel = nonNullViewModel,
+                            modifier = Modifier.align(Alignment.Center),
+                        )
+                    is PatternBouncerViewModel ->
+                        PatternBouncer(
+                            viewModel = nonNullViewModel,
+                            modifier =
+                                Modifier.aspectRatio(1f, matchHeightConstraintsFirst = false)
+                                    .align(Alignment.BottomCenter),
+                        )
+                    else -> Unit
+                }
+            }
+
+            Button(
+                onClick = viewModel::onEmergencyServicesButtonClicked,
+                colors =
+                    ButtonDefaults.buttonColors(
+                        containerColor = MaterialTheme.colorScheme.tertiaryContainer,
+                        contentColor = MaterialTheme.colorScheme.onTertiaryContainer,
+                    ),
+            ) {
+                Text(
+                    text = stringResource(com.android.internal.R.string.lockscreen_emergency_call),
+                    style = MaterialTheme.typography.bodyMedium,
+                )
+            }
+
+            if (dialogMessage != null) {
+                if (dialog == null) {
+                    dialog =
+                        dialogFactory().apply {
+                            setMessage(dialogMessage)
+                            setButton(
+                                DialogInterface.BUTTON_NEUTRAL,
+                                context.getString(R.string.ok),
+                            ) { _, _ ->
+                                viewModel.onThrottlingDialogDismissed()
+                            }
+                            setCancelable(false)
+                            setCanceledOnTouchOutside(false)
+                            show()
+                        }
+                }
+            } else {
+                dialog?.dismiss()
+                dialog = null
+            }
         }
     }
 }
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenScene.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenScene.kt
index ca7352e..da48762 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenScene.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/LockscreenScene.kt
@@ -63,7 +63,7 @@
             .stateIn(
                 scope = applicationScope,
                 started = SharingStarted.Eagerly,
-                initialValue = destinationScenes(up = viewModel.upDestinationSceneKey.value)
+                initialValue = destinationScenes(up = null)
             )
 
     @Composable
@@ -77,12 +77,12 @@
     }
 
     private fun destinationScenes(
-        up: SceneKey,
+        up: SceneKey?,
     ): Map<UserAction, SceneModel> {
-        return mapOf(
-            UserAction.Swipe(Direction.UP) to SceneModel(up),
-            UserAction.Swipe(Direction.DOWN) to SceneModel(SceneKey.Shade)
-        )
+        return buildMap {
+            up?.let { this[UserAction.Swipe(Direction.UP)] = SceneModel(up) }
+            this[UserAction.Swipe(Direction.DOWN)] = SceneModel(SceneKey.Shade)
+        }
     }
 }
 
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/notifications/ui/composable/Notifications.kt b/packages/SystemUI/compose/features/src/com/android/systemui/notifications/ui/composable/Notifications.kt
index 38b751c..dd71dfa 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/notifications/ui/composable/Notifications.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/notifications/ui/composable/Notifications.kt
@@ -31,15 +31,24 @@
 import androidx.compose.ui.Modifier
 import androidx.compose.ui.draw.clip
 import androidx.compose.ui.unit.dp
+import com.android.compose.animation.scene.ElementKey
+import com.android.compose.animation.scene.SceneScope
+
+object Notifications {
+    object Elements {
+        val Notifications = ElementKey("Notifications")
+    }
+}
 
 @Composable
-fun Notifications(
+fun SceneScope.Notifications(
     modifier: Modifier = Modifier,
 ) {
     // TODO(b/272779828): implement.
     Column(
         modifier =
             modifier
+                .element(key = Notifications.Elements.Notifications)
                 .fillMaxWidth()
                 .defaultMinSize(minHeight = 300.dp)
                 .clip(RoundedCornerShape(32.dp))
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/people/ui/compose/PeopleScreen.kt b/packages/SystemUI/compose/features/src/com/android/systemui/people/ui/compose/PeopleScreen.kt
index d84e676..68f010e 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/people/ui/compose/PeopleScreen.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/people/ui/compose/PeopleScreen.kt
@@ -42,13 +42,10 @@
 import androidx.compose.ui.Alignment
 import androidx.compose.ui.Modifier
 import androidx.compose.ui.graphics.asImageBitmap
-import androidx.compose.ui.platform.LocalLifecycleOwner
 import androidx.compose.ui.res.dimensionResource
 import androidx.compose.ui.res.stringResource
 import androidx.compose.ui.text.style.TextAlign
 import androidx.compose.ui.unit.dp
-import androidx.lifecycle.Lifecycle
-import androidx.lifecycle.repeatOnLifecycle
 import com.android.compose.theme.LocalAndroidColorScheme
 import com.android.systemui.R
 import com.android.systemui.compose.modifiers.sysuiResTag
@@ -70,15 +67,6 @@
     val priorityTiles by viewModel.priorityTiles.collectAsState()
     val recentTiles by viewModel.recentTiles.collectAsState()
 
-    // Make sure to refresh the tiles/conversations when the lifecycle is resumed, so that it
-    // updates them when going back to the Activity after leaving it.
-    val lifecycleOwner = LocalLifecycleOwner.current
-    LaunchedEffect(lifecycleOwner, viewModel) {
-        lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
-            viewModel.onTileRefreshRequested()
-        }
-    }
-
     // Call [onResult] this activity when the ViewModel tells us so.
     LaunchedEffect(viewModel.result) {
         viewModel.result.collect { result ->
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/qs/footer/ui/compose/QuickSettings.kt b/packages/SystemUI/compose/features/src/com/android/systemui/qs/footer/ui/compose/QuickSettings.kt
index 1bb341c..c84a5e9 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/qs/footer/ui/compose/QuickSettings.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/qs/footer/ui/compose/QuickSettings.kt
@@ -31,15 +31,27 @@
 import androidx.compose.ui.Modifier
 import androidx.compose.ui.draw.clip
 import androidx.compose.ui.unit.dp
+import com.android.compose.animation.scene.ElementKey
+import com.android.compose.animation.scene.SceneScope
+
+object QuickSettings {
+    object Elements {
+        // TODO RENAME
+        val Content = ElementKey("QuickSettingsContent")
+        val CollapsedGrid = ElementKey("QuickSettingsCollapsedGrid")
+        val FooterActions = ElementKey("QuickSettingsFooterActions")
+    }
+}
 
 @Composable
-fun QuickSettings(
+fun SceneScope.QuickSettings(
     modifier: Modifier = Modifier,
 ) {
     // TODO(b/272780058): implement.
     Column(
         modifier =
             modifier
+                .element(QuickSettings.Elements.Content)
                 .fillMaxWidth()
                 .defaultMinSize(minHeight = 300.dp)
                 .clip(RoundedCornerShape(32.dp))
@@ -47,15 +59,19 @@
                 .padding(16.dp),
     ) {
         Text(
-            text = "Quick settings",
-            modifier = Modifier.align(Alignment.CenterHorizontally),
+            text = "Quick settings grid",
+            modifier =
+                Modifier.element(QuickSettings.Elements.CollapsedGrid)
+                    .align(Alignment.CenterHorizontally),
             style = MaterialTheme.typography.titleLarge,
             color = MaterialTheme.colorScheme.onPrimary,
         )
         Spacer(modifier = Modifier.weight(1f))
         Text(
             text = "QS footer actions",
-            modifier = Modifier.align(Alignment.CenterHorizontally),
+            modifier =
+                Modifier.element(QuickSettings.Elements.FooterActions)
+                    .align(Alignment.CenterHorizontally),
             style = MaterialTheme.typography.titleSmall,
             color = MaterialTheme.colorScheme.onPrimary,
         )
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/qs/ui/composable/QuickSettingsScene.kt b/packages/SystemUI/compose/features/src/com/android/systemui/qs/ui/composable/QuickSettingsScene.kt
index 29763c2..e5cd439 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/qs/ui/composable/QuickSettingsScene.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/qs/ui/composable/QuickSettingsScene.kt
@@ -16,19 +16,17 @@
 
 package com.android.systemui.qs.ui.composable
 
-import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.clickable
 import androidx.compose.foundation.layout.Box
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.Row
-import androidx.compose.material3.Button
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.Text
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
 import androidx.compose.runtime.Composable
-import androidx.compose.ui.Alignment
 import androidx.compose.ui.Modifier
 import androidx.compose.ui.unit.dp
 import com.android.compose.animation.scene.SceneScope
 import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.qs.footer.ui.compose.QuickSettings
 import com.android.systemui.qs.ui.viewmodel.QuickSettingsSceneViewModel
 import com.android.systemui.scene.shared.model.Direction
 import com.android.systemui.scene.shared.model.SceneKey
@@ -69,23 +67,18 @@
 }
 
 @Composable
-private fun QuickSettingsScene(
+private fun SceneScope.QuickSettingsScene(
     viewModel: QuickSettingsSceneViewModel,
     modifier: Modifier = Modifier,
 ) {
     // TODO(b/280887232): implement the real UI.
 
-    Box(modifier = modifier) {
-        Column(
-            horizontalAlignment = Alignment.CenterHorizontally,
-            modifier = Modifier.align(Alignment.Center)
-        ) {
-            Text("Quick settings", style = MaterialTheme.typography.headlineMedium)
-            Row(
-                horizontalArrangement = Arrangement.spacedBy(8.dp),
-            ) {
-                Button(onClick = { viewModel.onContentClicked() }) { Text("Open some content") }
-            }
-        }
+    Box(
+        modifier
+            .fillMaxSize()
+            .clickable(onClick = { viewModel.onContentClicked() })
+            .padding(horizontal = 16.dp, vertical = 48.dp)
+    ) {
+        QuickSettings(modifier = Modifier.fillMaxHeight())
     }
 }
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/SceneContainer.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/SceneContainer.kt
index 3dfdbba..c865070 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/SceneContainer.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/SceneContainer.kt
@@ -31,7 +31,6 @@
 import com.android.compose.animation.scene.Swipe
 import com.android.compose.animation.scene.UserAction as SceneTransitionUserAction
 import com.android.compose.animation.scene.observableTransitionState
-import com.android.compose.animation.scene.transitions
 import com.android.systemui.scene.shared.model.Direction
 import com.android.systemui.scene.shared.model.ObservableTransitionState
 import com.android.systemui.scene.shared.model.SceneKey
@@ -77,8 +76,8 @@
 
     SceneTransitionLayout(
         currentScene = currentSceneKey.toTransitionSceneKey(),
-        onChangeScene = { sceneKey -> viewModel.setCurrentScene(sceneKey.toModel()) },
-        transitions = transitions {},
+        onChangeScene = viewModel::onSceneChanged,
+        transitions = SceneContainerTransitions,
         state = state,
         modifier = modifier.fillMaxSize(),
     ) {
@@ -98,7 +97,9 @@
             ) {
                 with(composableScene) {
                     this@scene.Content(
-                        modifier = Modifier.fillMaxSize(),
+                        modifier =
+                            Modifier.element(sceneKey.toTransitionSceneKey().rootElementKey)
+                                .fillMaxSize(),
                     )
                 }
             }
@@ -129,14 +130,6 @@
 }
 
 // TODO(b/293899074): remove this once we can use the one from SceneTransitionLayout.
-private fun SceneKey.toTransitionSceneKey(): SceneTransitionSceneKey {
-    return SceneTransitionSceneKey(
-        name = toString(),
-        identity = this,
-    )
-}
-
-// TODO(b/293899074): remove this once we can use the one from SceneTransitionLayout.
 private fun SceneTransitionSceneKey.toModel(): SceneModel {
     return SceneModel(key = identity as SceneKey)
 }
@@ -154,3 +147,7 @@
         is UserAction.Back -> Back
     }
 }
+
+private fun SceneContainerViewModel.onSceneChanged(sceneKey: SceneTransitionSceneKey) {
+    onSceneChanged(sceneKey.toModel())
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/SceneContainerTransitions.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/SceneContainerTransitions.kt
new file mode 100644
index 0000000..404bf81
--- /dev/null
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/SceneContainerTransitions.kt
@@ -0,0 +1,34 @@
+package com.android.systemui.scene.ui.composable
+
+import com.android.compose.animation.scene.transitions
+import com.android.systemui.scene.ui.composable.transitions.bouncerToGoneTransition
+import com.android.systemui.scene.ui.composable.transitions.goneToQuickSettingsTransition
+import com.android.systemui.scene.ui.composable.transitions.goneToShadeTransition
+import com.android.systemui.scene.ui.composable.transitions.lockscreenToBouncerTransition
+import com.android.systemui.scene.ui.composable.transitions.lockscreenToGoneTransition
+import com.android.systemui.scene.ui.composable.transitions.lockscreenToQuickSettingsTransition
+import com.android.systemui.scene.ui.composable.transitions.lockscreenToShadeTransition
+import com.android.systemui.scene.ui.composable.transitions.shadeToQuickSettingsTransition
+
+/**
+ * Comprehensive definition of all transitions between scenes in [SceneContainer].
+ *
+ * Transitions are automatically reversible, so define only one transition per scene pair. By
+ * convention, use the more common transition direction when defining the pair order, e.g.
+ * Lockscreen to Bouncer rather than Bouncer to Lockscreen.
+ *
+ * The actual transition DSL must be placed in a separate file under the package
+ * [com.android.systemui.scene.ui.composable.transitions].
+ *
+ * Please keep the list sorted alphabetically.
+ */
+val SceneContainerTransitions = transitions {
+    from(Bouncer, to = Gone) { bouncerToGoneTransition() }
+    from(Gone, to = Shade) { goneToShadeTransition() }
+    from(Gone, to = QuickSettings) { goneToQuickSettingsTransition() }
+    from(Lockscreen, to = Bouncer) { lockscreenToBouncerTransition() }
+    from(Lockscreen, to = Shade) { lockscreenToShadeTransition() }
+    from(Lockscreen, to = QuickSettings) { lockscreenToQuickSettingsTransition() }
+    from(Lockscreen, to = Gone) { lockscreenToGoneTransition() }
+    from(Shade, to = QuickSettings) { shadeToQuickSettingsTransition() }
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/TransitionSceneKeys.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/TransitionSceneKeys.kt
new file mode 100644
index 0000000..8d0d705
--- /dev/null
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/TransitionSceneKeys.kt
@@ -0,0 +1,15 @@
+package com.android.systemui.scene.ui.composable
+
+import com.android.compose.animation.scene.SceneKey as SceneTransitionSceneKey
+import com.android.systemui.scene.shared.model.SceneKey
+
+val Lockscreen = SceneKey.Lockscreen.toTransitionSceneKey()
+val Bouncer = SceneKey.Bouncer.toTransitionSceneKey()
+val Shade = SceneKey.Shade.toTransitionSceneKey()
+val QuickSettings = SceneKey.QuickSettings.toTransitionSceneKey()
+val Gone = SceneKey.Gone.toTransitionSceneKey()
+
+// TODO(b/293899074): Remove this file once we can use the scene keys from SceneTransitionLayout.
+fun SceneKey.toTransitionSceneKey(): SceneTransitionSceneKey {
+    return SceneTransitionSceneKey(name = toString(), identity = this)
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromBouncerToGoneTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromBouncerToGoneTransition.kt
new file mode 100644
index 0000000..1a9face
--- /dev/null
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromBouncerToGoneTransition.kt
@@ -0,0 +1,11 @@
+package com.android.systemui.scene.ui.composable.transitions
+
+import androidx.compose.animation.core.tween
+import com.android.compose.animation.scene.TransitionBuilder
+import com.android.systemui.scene.ui.composable.Bouncer
+
+fun TransitionBuilder.bouncerToGoneTransition() {
+    spec = tween(durationMillis = 500)
+
+    fade(Bouncer.rootElementKey)
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromGoneToQuickSettingsTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromGoneToQuickSettingsTransition.kt
new file mode 100644
index 0000000..291617f
--- /dev/null
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromGoneToQuickSettingsTransition.kt
@@ -0,0 +1,12 @@
+package com.android.systemui.scene.ui.composable.transitions
+
+import androidx.compose.animation.core.tween
+import com.android.compose.animation.scene.Edge
+import com.android.compose.animation.scene.TransitionBuilder
+import com.android.systemui.scene.ui.composable.QuickSettings
+
+fun TransitionBuilder.goneToQuickSettingsTransition() {
+    spec = tween(durationMillis = 500)
+
+    translate(QuickSettings.rootElementKey, Edge.Top, true)
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromGoneToShadeTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromGoneToShadeTransition.kt
new file mode 100644
index 0000000..45df2b1
--- /dev/null
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromGoneToShadeTransition.kt
@@ -0,0 +1,12 @@
+package com.android.systemui.scene.ui.composable.transitions
+
+import androidx.compose.animation.core.tween
+import com.android.compose.animation.scene.Edge
+import com.android.compose.animation.scene.TransitionBuilder
+import com.android.systemui.scene.ui.composable.Shade
+
+fun TransitionBuilder.goneToShadeTransition() {
+    spec = tween(durationMillis = 500)
+
+    translate(Shade.rootElementKey, Edge.Top, true)
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToBouncerTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToBouncerTransition.kt
new file mode 100644
index 0000000..1fee874
--- /dev/null
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToBouncerTransition.kt
@@ -0,0 +1,14 @@
+package com.android.systemui.scene.ui.composable.transitions
+
+import androidx.compose.animation.core.tween
+import androidx.compose.ui.unit.dp
+import com.android.compose.animation.scene.TransitionBuilder
+import com.android.systemui.bouncer.ui.composable.Bouncer
+
+fun TransitionBuilder.lockscreenToBouncerTransition() {
+    spec = tween(durationMillis = 500)
+
+    translate(Bouncer.Elements.Content, y = 300.dp)
+    fractionRange(end = 0.5f) { fade(Bouncer.Elements.Background) }
+    fractionRange(start = 0.5f) { fade(Bouncer.Elements.Content) }
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToGoneTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToGoneTransition.kt
new file mode 100644
index 0000000..da6306d
--- /dev/null
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToGoneTransition.kt
@@ -0,0 +1,11 @@
+package com.android.systemui.scene.ui.composable.transitions
+
+import androidx.compose.animation.core.tween
+import com.android.compose.animation.scene.TransitionBuilder
+import com.android.systemui.scene.ui.composable.Lockscreen
+
+fun TransitionBuilder.lockscreenToGoneTransition() {
+    spec = tween(durationMillis = 500)
+
+    fade(Lockscreen.rootElementKey)
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToQuickSettingsTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToQuickSettingsTransition.kt
new file mode 100644
index 0000000..e63bc4e
--- /dev/null
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToQuickSettingsTransition.kt
@@ -0,0 +1,12 @@
+package com.android.systemui.scene.ui.composable.transitions
+
+import androidx.compose.animation.core.tween
+import com.android.compose.animation.scene.Edge
+import com.android.compose.animation.scene.TransitionBuilder
+import com.android.systemui.scene.ui.composable.QuickSettings
+
+fun TransitionBuilder.lockscreenToQuickSettingsTransition() {
+    spec = tween(durationMillis = 500)
+
+    translate(QuickSettings.rootElementKey, Edge.Top, true)
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToShadeTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToShadeTransition.kt
new file mode 100644
index 0000000..7ecfb62
--- /dev/null
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromLockscreenToShadeTransition.kt
@@ -0,0 +1,24 @@
+package com.android.systemui.scene.ui.composable.transitions
+
+import androidx.compose.animation.core.tween
+import com.android.compose.animation.scene.Edge
+import com.android.compose.animation.scene.TransitionBuilder
+import com.android.systemui.notifications.ui.composable.Notifications
+import com.android.systemui.qs.footer.ui.compose.QuickSettings
+import com.android.systemui.shade.ui.composable.Shade
+
+fun TransitionBuilder.lockscreenToShadeTransition() {
+    spec = tween(durationMillis = 500)
+
+    punchHole(Shade.Elements.QuickSettings, bounds = Shade.Elements.Scrim, Shade.Shapes.Scrim)
+    translate(Shade.Elements.Scrim, Edge.Top, startsOutsideLayoutBounds = false)
+    fractionRange(end = 0.5f) {
+        fade(Shade.Elements.ScrimBackground)
+        translate(
+            QuickSettings.Elements.CollapsedGrid,
+            Edge.Top,
+            startsOutsideLayoutBounds = false,
+        )
+    }
+    fractionRange(start = 0.5f) { fade(Notifications.Elements.Notifications) }
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromShadeToQuickSettingsTransition.kt b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromShadeToQuickSettingsTransition.kt
new file mode 100644
index 0000000..21a10b1
--- /dev/null
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/scene/ui/composable/transitions/FromShadeToQuickSettingsTransition.kt
@@ -0,0 +1,14 @@
+package com.android.systemui.scene.ui.composable.transitions
+
+import androidx.compose.animation.core.tween
+import com.android.compose.animation.scene.Edge
+import com.android.compose.animation.scene.TransitionBuilder
+import com.android.systemui.notifications.ui.composable.Notifications
+import com.android.systemui.qs.footer.ui.compose.QuickSettings
+
+fun TransitionBuilder.shadeToQuickSettingsTransition() {
+    spec = tween(durationMillis = 500)
+
+    translate(Notifications.Elements.Notifications, Edge.Bottom)
+    timestampRange(endMillis = 83) { fade(QuickSettings.Elements.FooterActions) }
+}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/shade/ui/composable/ShadeScene.kt b/packages/SystemUI/compose/features/src/com/android/systemui/shade/ui/composable/ShadeScene.kt
index ff1cb5f..f985aa2 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/shade/ui/composable/ShadeScene.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/shade/ui/composable/ShadeScene.kt
@@ -16,16 +16,22 @@
 
 package com.android.systemui.shade.ui.composable
 
+import androidx.compose.foundation.background
 import androidx.compose.foundation.clickable
 import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
 import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
 import androidx.compose.foundation.layout.fillMaxSize
 import androidx.compose.foundation.layout.height
 import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.MaterialTheme
 import androidx.compose.runtime.Composable
 import androidx.compose.ui.Alignment
 import androidx.compose.ui.Modifier
 import androidx.compose.ui.unit.dp
+import com.android.compose.animation.scene.ElementKey
 import com.android.compose.animation.scene.SceneScope
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
@@ -44,6 +50,26 @@
 import kotlinx.coroutines.flow.map
 import kotlinx.coroutines.flow.stateIn
 
+object Shade {
+    object Elements {
+        val QuickSettings = ElementKey("ShadeQuickSettings")
+        val Scrim = ElementKey("ShadeScrim")
+        val ScrimBackground = ElementKey("ShadeScrimBackground")
+    }
+
+    object Dimensions {
+        val ScrimCornerSize = 32.dp
+    }
+
+    object Shapes {
+        val Scrim =
+            RoundedCornerShape(
+                topStart = Dimensions.ScrimCornerSize,
+                topEnd = Dimensions.ScrimCornerSize,
+            )
+    }
+}
+
 /** The shade scene shows scrolling list of notifications and some of the quick setting tiles. */
 @SysUISingleton
 class ShadeScene
@@ -79,20 +105,28 @@
 }
 
 @Composable
-private fun ShadeScene(
+private fun SceneScope.ShadeScene(
     viewModel: ShadeSceneViewModel,
     modifier: Modifier = Modifier,
 ) {
-    Column(
-        horizontalAlignment = Alignment.CenterHorizontally,
-        verticalArrangement = Arrangement.spacedBy(16.dp),
-        modifier =
-            modifier
-                .fillMaxSize()
-                .clickable(onClick = { viewModel.onContentClicked() })
-                .padding(horizontal = 16.dp, vertical = 48.dp)
-    ) {
-        QuickSettings(modifier = Modifier.height(160.dp))
-        Notifications(modifier = Modifier.weight(1f))
+    Box(modifier.element(Shade.Elements.Scrim)) {
+        Spacer(
+            modifier =
+                Modifier.element(Shade.Elements.ScrimBackground)
+                    .fillMaxSize()
+                    .background(MaterialTheme.colorScheme.scrim, shape = Shade.Shapes.Scrim)
+        )
+
+        Column(
+            horizontalAlignment = Alignment.CenterHorizontally,
+            verticalArrangement = Arrangement.spacedBy(16.dp),
+            modifier =
+                Modifier.fillMaxSize()
+                    .clickable(onClick = { viewModel.onContentClicked() })
+                    .padding(horizontal = 16.dp, vertical = 48.dp)
+        ) {
+            QuickSettings(modifier = Modifier.height(160.dp))
+            Notifications(modifier = Modifier.weight(1f))
+        }
     }
 }
diff --git a/packages/SystemUI/compose/features/tests/src/com/android/systemui/ExampleFeatureTest.kt b/packages/SystemUI/compose/features/tests/src/com/android/systemui/ExampleFeatureTest.kt
deleted file mode 100644
index 1c2e8fa..0000000
--- a/packages/SystemUI/compose/features/tests/src/com/android/systemui/ExampleFeatureTest.kt
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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 androidx.compose.ui.test.assertIsDisplayed
-import androidx.compose.ui.test.junit4.createComposeRule
-import androidx.compose.ui.test.onNodeWithText
-import androidx.compose.ui.test.performClick
-import androidx.test.ext.junit.runners.AndroidJUnit4
-import org.junit.Rule
-import org.junit.Test
-import org.junit.runner.RunWith
-
-@RunWith(AndroidJUnit4::class)
-class ExampleFeatureTest {
-    @get:Rule val composeRule = createComposeRule()
-
-    @Test
-    fun testProvidedTextIsDisplayed() {
-        composeRule.setContent { ExampleFeature("foo") }
-
-        composeRule.onNodeWithText("foo").assertIsDisplayed()
-    }
-
-    @Test
-    fun testCountIsIncreasedWhenClicking() {
-        composeRule.setContent { ExampleFeature("foo") }
-
-        composeRule.onNodeWithText("I was clicked 0 times.").assertIsDisplayed().performClick()
-        composeRule.onNodeWithText("I was clicked 1 times.").assertIsDisplayed()
-    }
-}
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ClockRegistry.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ClockRegistry.kt
index 798bdec4..ab0225d 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ClockRegistry.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/ClockRegistry.kt
@@ -409,6 +409,18 @@
             scope.launch(bgDispatcher) { mutateSetting { it.copy(seedColor = value) } }
         }
 
+    // Returns currentClockId if clock is connected, otherwise DEFAULT_CLOCK_ID. Since this
+    // is dependent on which clocks are connected, it may change when a clock is installed or
+    // removed from the device (unlike currentClockId).
+    // TODO: Merge w/ CurrentClockId when we convert to a flow. We shouldn't need both behaviors.
+    val activeClockId: String
+        get() {
+            if (!availableClocks.containsKey(currentClockId)) {
+                return DEFAULT_CLOCK_ID
+            }
+            return currentClockId
+        }
+
     init {
         // Register default clock designs
         for (clock in defaultClockProvider.getClocks()) {
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockController.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockController.kt
index e539c95..b28920c 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockController.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/clocks/DefaultClockController.kt
@@ -62,9 +62,10 @@
     private val burmeseLineSpacing =
         resources.getFloat(R.dimen.keyguard_clock_line_spacing_scale_burmese)
     private val defaultLineSpacing = resources.getFloat(R.dimen.keyguard_clock_line_spacing_scale)
+    protected var onSecondaryDisplay: Boolean = false
 
     override val events: DefaultClockEvents
-    override val config = ClockConfig()
+    override val config = ClockConfig(DEFAULT_CLOCK_ID)
 
     init {
         val parent = FrameLayout(ctx)
@@ -142,6 +143,11 @@
                     view.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSizePx)
                     recomputePadding(targetRegion)
                 }
+
+                override fun onSecondaryDisplayChanged(onSecondaryDisplay: Boolean) {
+                    this@DefaultClockController.onSecondaryDisplay = onSecondaryDisplay
+                    recomputePadding(null)
+                }
             }
 
         open fun recomputePadding(targetRegion: Rect?) {}
@@ -182,13 +188,19 @@
         override fun recomputePadding(targetRegion: Rect?) {
             // We center the view within the targetRegion instead of within the parent
             // view by computing the difference and adding that to the padding.
-            val parent = view.parent
-            val yDiff =
-                if (targetRegion != null && parent is View && parent.isLaidOut())
-                    targetRegion.centerY() - parent.height / 2f
-                else 0f
             val lp = view.getLayoutParams() as FrameLayout.LayoutParams
-            lp.topMargin = (-0.5f * view.bottom + yDiff).toInt()
+            lp.topMargin =
+                if (onSecondaryDisplay) {
+                    // On the secondary display we don't want any additional top/bottom margin.
+                    0
+                } else {
+                    val parent = view.parent
+                    val yDiff =
+                        if (targetRegion != null && parent is View && parent.isLaidOut())
+                            targetRegion.centerY() - parent.height / 2f
+                        else 0f
+                    (-0.5f * view.bottom + yDiff).toInt()
+                }
             view.setLayoutParams(lp)
         }
 
diff --git a/packages/SystemUI/customization/src/com/android/systemui/shared/customization/data/content/CustomizationProviderContract.kt b/packages/SystemUI/customization/src/com/android/systemui/shared/customization/data/content/CustomizationProviderContract.kt
index 46f5971..92d2bd2 100644
--- a/packages/SystemUI/customization/src/com/android/systemui/shared/customization/data/content/CustomizationProviderContract.kt
+++ b/packages/SystemUI/customization/src/com/android/systemui/shared/customization/data/content/CustomizationProviderContract.kt
@@ -190,6 +190,9 @@
         /** Flag denoting transit clock are enabled in wallpaper picker. */
         const val FLAG_NAME_PAGE_TRANSITIONS = "wallpaper_picker_page_transitions"
 
+        /** Flag denoting adding apply button to wallpaper picker's grid preview page. */
+        const val FLAG_NAME_GRID_APPLY_BUTTON = "wallpaper_picker_grid_apply_button"
+
         /** Flag denoting whether preview loading animation is enabled. */
         const val FLAG_NAME_WALLPAPER_PICKER_PREVIEW_ANIMATION =
             "wallpaper_picker_preview_animation"
diff --git a/packages/SystemUI/ktfmt_includes.txt b/packages/SystemUI/ktfmt_includes.txt
index 006fc09..92083b0 100644
--- a/packages/SystemUI/ktfmt_includes.txt
+++ b/packages/SystemUI/ktfmt_includes.txt
@@ -438,7 +438,6 @@
 -packages/SystemUI/src/com/android/systemui/statusbar/policy/WalletControllerImpl.kt
 -packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/RemoteInput.kt
 -packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/SmartRepliesInflationModule.kt
--packages/SystemUI/src/com/android/systemui/statusbar/tv/VpnStatusObserver.kt
 -packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowModule.kt
 -packages/SystemUI/src/com/android/systemui/statusbar/window/StatusBarWindowStateController.kt
 -packages/SystemUI/src/com/android/systemui/temporarydisplay/TemporaryViewDisplayController.kt
@@ -446,7 +445,6 @@
 -packages/SystemUI/src/com/android/systemui/temporarydisplay/chipbar/ChipbarRootView.kt
 -packages/SystemUI/src/com/android/systemui/toast/ToastDefaultAnimation.kt
 -packages/SystemUI/src/com/android/systemui/toast/ToastLogger.kt
--packages/SystemUI/src/com/android/systemui/tv/TVSystemUICoreStartableModule.kt
 -packages/SystemUI/src/com/android/systemui/unfold/FoldAodAnimationController.kt
 -packages/SystemUI/src/com/android/systemui/unfold/FoldStateLogger.kt
 -packages/SystemUI/src/com/android/systemui/unfold/SysUIUnfoldModule.kt
diff --git a/packages/SystemUI/plugin/src/com/android/systemui/plugins/ClockProviderPlugin.kt b/packages/SystemUI/plugin/src/com/android/systemui/plugins/ClockProviderPlugin.kt
index d962732..e2f4793 100644
--- a/packages/SystemUI/plugin/src/com/android/systemui/plugins/ClockProviderPlugin.kt
+++ b/packages/SystemUI/plugin/src/com/android/systemui/plugins/ClockProviderPlugin.kt
@@ -177,6 +177,9 @@
      * targetRegion is relative to the parent view.
      */
     fun onTargetRegionChanged(targetRegion: Rect?)
+
+    /** Called to notify the clock about its display. */
+    fun onSecondaryDisplayChanged(onSecondaryDisplay: Boolean)
 }
 
 /** Tick rates for clocks */
@@ -196,6 +199,8 @@
 
 /** Render configuration for the full clock. Modifies the way systemUI behaves with this clock. */
 data class ClockConfig(
+    val id: String,
+
     /** Transition to AOD should move smartspace like large clock instead of small clock */
     val useAlternateSmartspaceAODTransition: Boolean = false,
 
diff --git a/packages/SystemUI/plugin/src/com/android/systemui/plugins/VolumeDialogController.java b/packages/SystemUI/plugin/src/com/android/systemui/plugins/VolumeDialogController.java
index cf7d2c5..3d9645a 100644
--- a/packages/SystemUI/plugin/src/com/android/systemui/plugins/VolumeDialogController.java
+++ b/packages/SystemUI/plugin/src/com/android/systemui/plugins/VolumeDialogController.java
@@ -58,9 +58,26 @@
     void userActivity();
     void getState();
 
-    boolean areCaptionsEnabled();
-    void setCaptionsEnabled(boolean isEnabled);
+    /**
+     * Get Captions enabled state
+     *
+     * @param checkForSwitchState set true when we'd like to switch captions enabled state after
+     *                            getting the latest captions state.
+     */
+    void getCaptionsEnabledState(boolean checkForSwitchState);
 
+    /**
+     * Set Captions enabled state
+     *
+     * @param enabled the captions enabled state we'd like to update.
+     */
+    void setCaptionsEnabledState(boolean enabled);
+
+    /**
+     * Get Captions component state
+     *
+     * @param fromTooltip if it's triggered from tooltip.
+     */
     void getCaptionsComponentState(boolean fromTooltip);
 
     @ProvidesInterface(version = StreamState.VERSION)
@@ -192,7 +209,22 @@
         void onScreenOff();
         void onShowSafetyWarning(int flags);
         void onAccessibilityModeChanged(Boolean showA11yStream);
+
+        /**
+         * Callback function for captions component state changed event
+         *
+         * @param isComponentEnabled the lateset captions component state.
+         * @param fromTooltip if it's triggered from tooltip.
+         */
         void onCaptionComponentStateChanged(Boolean isComponentEnabled, Boolean fromTooltip);
+
+        /**
+         * Callback function for captions enabled state changed event
+         *
+         * @param isEnabled the lateset captions enabled state.
+         * @param checkBeforeSwitch intend to switch captions enabled state after the callback.
+         */
+        void onCaptionEnabledStateChanged(Boolean isEnabled, Boolean checkBeforeSwitch);
         // requires version 2
         void onShowCsdWarning(@AudioManager.CsdWarning int csdWarning, int durationMs);
     }
diff --git a/packages/SystemUI/plugin/src/com/android/systemui/plugins/WeatherData.kt b/packages/SystemUI/plugin/src/com/android/systemui/plugins/WeatherData.kt
index f83fa33..affb76b 100644
--- a/packages/SystemUI/plugin/src/com/android/systemui/plugins/WeatherData.kt
+++ b/packages/SystemUI/plugin/src/com/android/systemui/plugins/WeatherData.kt
@@ -57,7 +57,7 @@
 
         private fun readIntFromBundle(extras: Bundle, key: String): Int? =
             try {
-                extras.getString(key).toInt()
+                extras.getString(key)?.toInt()
             } catch (e: Exception) {
                 null
             }
diff --git a/packages/SystemUI/res-keyguard/layout-land/keyguard_pin_view.xml b/packages/SystemUI/res-keyguard/layout-land/keyguard_pin_view.xml
new file mode 100644
index 0000000..cd7ab98
--- /dev/null
+++ b/packages/SystemUI/res-keyguard/layout-land/keyguard_pin_view.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+**
+** Copyright 2023, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License")
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT 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">
+
+    <include layout="@layout/keyguard_pin_view_landscape" />
+
+</FrameLayout>
diff --git a/packages/SystemUI/res-keyguard/layout-sw600dp-land/keyguard_pin_view.xml b/packages/SystemUI/res-keyguard/layout-sw600dp-land/keyguard_pin_view.xml
new file mode 100644
index 0000000..80cc8c0
--- /dev/null
+++ b/packages/SystemUI/res-keyguard/layout-sw600dp-land/keyguard_pin_view.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+**
+** Copyright 2023, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License")
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT 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">
+
+    <include layout="@layout/keyguard_pin_view_portrait" />
+
+</FrameLayout>
diff --git a/packages/SystemUI/res-keyguard/layout/keyguard_clock_presentation.xml b/packages/SystemUI/res-keyguard/layout/keyguard_clock_presentation.xml
new file mode 100644
index 0000000..593f507f
--- /dev/null
+++ b/packages/SystemUI/res-keyguard/layout/keyguard_clock_presentation.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+**
+** Copyright 2023, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License")
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT 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:id="@+id/presentation"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+    <com.android.keyguard.KeyguardStatusView
+        android:id="@+id/clock"
+        android:layout_width="410dp"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center"
+        android:orientation="vertical">
+
+        <include
+            android:id="@+id/keyguard_clock_container"
+            layout="@layout/keyguard_clock_switch"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content" />
+    </com.android.keyguard.KeyguardStatusView>
+
+</FrameLayout>
diff --git a/packages/SystemUI/res-keyguard/layout/keyguard_pin_view_landscape.xml b/packages/SystemUI/res-keyguard/layout/keyguard_pin_view_landscape.xml
new file mode 100644
index 0000000..e00742d
--- /dev/null
+++ b/packages/SystemUI/res-keyguard/layout/keyguard_pin_view_landscape.xml
@@ -0,0 +1,231 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+**
+** Copyright 2023, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License")
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT 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.keyguard.KeyguardPINView xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:androidprv="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:id="@+id/keyguard_pin_view"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:layout_gravity="center_horizontal|bottom"
+    android:clipChildren="false"
+    android:clipToPadding="false"
+    android:orientation="horizontal">
+
+    <androidx.constraintlayout.widget.ConstraintLayout
+        android:layout_width="0dp"
+        android:layout_height="match_parent"
+        android:layout_weight="2"
+        android:clipChildren="false"
+        android:clipToPadding="false"
+        android:layoutDirection="ltr"
+        android:orientation="vertical">
+
+        <include layout="@layout/keyguard_bouncer_message_area" />
+
+        <com.android.systemui.bouncer.ui.BouncerMessageView
+            android:id="@+id/bouncer_message_view"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:orientation="vertical"
+            androidprv:layout_constraintBottom_toTopOf="@+id/row0"
+            androidprv:layout_constraintTop_toTopOf="parent"
+            androidprv:layout_constraintVertical_chainStyle="packed" />
+
+        <!-- Set this to be just above key1. It would be better to introduce a barrier above
+         key1/key2/key3, then place this View above that. Sadly, that doesn't work (the Barrier
+         drops to the bottom of the page, and key1/2/3 all shoot up to the top-left). In any
+         case, the Flow should ensure that key1/2/3 all have the same top, so this should be
+         fine. -->
+        <com.android.keyguard.AlphaOptimizedRelativeLayout
+            android:id="@+id/row0"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:paddingBottom="@dimen/num_pad_entry_row_margin_bottom"
+            androidprv:layout_constraintBottom_toTopOf="@+id/keyguard_selector_fade_container"
+            androidprv:layout_constraintTop_toBottomOf="@+id/bouncer_message_view"
+            tools:layout_editor_absoluteX="-16dp">
+
+            <com.android.keyguard.PasswordTextView
+                android:id="@+id/pinEntry"
+                style="@style/Widget.TextView.Password"
+                android:layout_width="@dimen/keyguard_security_width"
+                android:layout_height="@dimen/keyguard_password_height"
+                android:layout_centerHorizontal="true"
+                android:layout_marginRight="72dp"
+                android:contentDescription="@string/keyguard_accessibility_pin_area"
+                androidprv:scaledTextSize="@integer/scaled_password_text_size" />
+        </com.android.keyguard.AlphaOptimizedRelativeLayout>
+
+        <include
+            android:id="@+id/keyguard_selector_fade_container"
+            layout="@layout/keyguard_eca"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_gravity="bottom|center_horizontal"
+            android:layout_marginBottom="@dimen/keyguard_eca_bottom_margin"
+            android:layout_marginTop="@dimen/keyguard_eca_top_margin"
+            android:gravity="center_horizontal"
+            android:orientation="vertical"
+            androidprv:layout_constraintBottom_toBottomOf="parent" />
+
+    </androidx.constraintlayout.widget.ConstraintLayout>
+
+    <androidx.constraintlayout.widget.ConstraintLayout
+        android:id="@+id/pin_container"
+        android:layout_width="0dp"
+        android:layout_height="match_parent"
+        android:layout_weight="3"
+        android:clipChildren="false"
+        android:clipToPadding="false"
+        android:layoutDirection="ltr"
+        android:orientation="vertical">
+
+        <!-- Guideline used to place the top row of keys relative to the screen height. This will be
+        updated in KeyguardPINView to reduce the height of the PIN pad. -->
+        <androidx.constraintlayout.widget.Guideline
+            android:id="@+id/pin_pad_top_guideline"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:orientation="horizontal"
+            androidprv:layout_constraintGuide_percent="0" />
+
+        <com.android.keyguard.KeyguardPinFlowView
+            android:id="@+id/flow1"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:clipChildren="false"
+            android:clipToPadding="false"
+            android:orientation="horizontal"
+
+            androidprv:constraint_referenced_ids="key1,key2,key3,key4,key5,key6,key7,key8,key9,delete_button,key0,key_enter"
+
+            androidprv:flow_horizontalGap="@dimen/num_pad_key_margin_end"
+
+            androidprv:flow_horizontalStyle="packed"
+            androidprv:flow_maxElementsWrap="3"
+
+            androidprv:flow_verticalBias="0.5"
+            androidprv:flow_verticalGap="@dimen/num_pad_entry_row_margin_bottom"
+            androidprv:flow_verticalStyle="packed"
+
+            androidprv:flow_wrapMode="aligned"
+            androidprv:layout_constraintBottom_toBottomOf="parent"
+            androidprv:layout_constraintEnd_toEndOf="parent"
+            androidprv:layout_constraintStart_toStartOf="parent"
+            androidprv:layout_constraintTop_toBottomOf="@id/pin_pad_top_guideline" />
+
+        <com.android.keyguard.NumPadButton
+            android:id="@+id/delete_button"
+            style="@style/NumPadKey.Delete"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:accessibilityTraversalBefore="@id/key0"
+            android:contentDescription="@string/keyboardview_keycode_delete" />
+
+        <com.android.keyguard.NumPadButton
+            android:id="@+id/key_enter"
+            style="@style/NumPadKey.Enter"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:contentDescription="@string/keyboardview_keycode_enter" />
+
+        <com.android.keyguard.NumPadKey
+            android:id="@+id/key1"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:accessibilityTraversalBefore="@id/key2"
+            androidprv:digit="1"
+            androidprv:textView="@+id/pinEntry" />
+
+        <com.android.keyguard.NumPadKey
+            android:id="@+id/key2"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:accessibilityTraversalBefore="@id/key3"
+            androidprv:digit="2"
+            androidprv:textView="@+id/pinEntry" />
+
+        <com.android.keyguard.NumPadKey
+            android:id="@+id/key3"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:accessibilityTraversalBefore="@id/key4"
+            androidprv:digit="3"
+            androidprv:textView="@+id/pinEntry" />
+
+        <com.android.keyguard.NumPadKey
+            android:id="@+id/key4"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:accessibilityTraversalBefore="@id/key5"
+            androidprv:digit="4"
+            androidprv:textView="@+id/pinEntry" />
+
+        <com.android.keyguard.NumPadKey
+            android:id="@+id/key5"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:accessibilityTraversalBefore="@id/key6"
+            androidprv:digit="5"
+            androidprv:textView="@+id/pinEntry" />
+
+
+        <com.android.keyguard.NumPadKey
+            android:id="@+id/key6"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:accessibilityTraversalBefore="@id/key7"
+            androidprv:digit="6"
+            androidprv:textView="@+id/pinEntry" />
+
+        <com.android.keyguard.NumPadKey
+            android:id="@+id/key7"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:accessibilityTraversalBefore="@id/key8"
+            androidprv:digit="7"
+            androidprv:textView="@+id/pinEntry" />
+
+        <com.android.keyguard.NumPadKey
+            android:id="@+id/key8"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:accessibilityTraversalBefore="@id/key9"
+            androidprv:digit="8"
+            androidprv:textView="@+id/pinEntry" />
+
+        <com.android.keyguard.NumPadKey
+            android:id="@+id/key9"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:accessibilityTraversalBefore="@id/delete_button"
+            androidprv:digit="9"
+            androidprv:textView="@+id/pinEntry" />
+
+        <com.android.keyguard.NumPadKey
+            android:id="@+id/key0"
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:accessibilityTraversalBefore="@id/key_enter"
+            androidprv:digit="0"
+            androidprv:textView="@+id/pinEntry" />
+
+    </androidx.constraintlayout.widget.ConstraintLayout>
+
+</com.android.keyguard.KeyguardPINView>
diff --git a/packages/SystemUI/res-keyguard/values-af/strings.xml b/packages/SystemUI/res-keyguard/values-af/strings.xml
index fc92e01..2eb1bb5 100644
--- a/packages/SystemUI/res-keyguard/values-af/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-af/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN word vereis ná vassluit"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Wagwoord word vereis ná vassluit"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Patroon word vereis ná vassluit"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Die opdatering sal installeer wanneer die toestel nie gebruik word nie"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Meer sekuriteit vereis. PIN ruk lank nie gebruik nie."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Meer sekuriteit vereis. Wagwoord ruk lank nie gebruik nie."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Meer sekuriteit vereis. Patroon ruk lank nie gebruik nie."</string>
diff --git a/packages/SystemUI/res-keyguard/values-am/strings.xml b/packages/SystemUI/res-keyguard/values-am/strings.xml
index 88670cd..5fd946b 100644
--- a/packages/SystemUI/res-keyguard/values-am/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-am/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"ከመቆለፊያ በኋላ ፒን ያስፈልጋል"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"ከመቆለፊያ በኋላ የይለፍ ቃል ያስፈልጋል"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"ከመቆለፊያ በኋላ ስርዓተ ጥለት ያስፈልጋል"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"መሣሪያው ጥቅም ላይ በማይውልበት ጊዜ ዝማኔ ይጫናል"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"ተጨማሪ የደህንነት ጥበቃ ያስፈልጋል። ፒን ለተወሰነ ጊዜ ጥቅም ላይ አልዋለም።"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"ተጨማሪ የደህንነት ጥበቃ ያስፈልጋል። የይለፍ ቃል ለተወሰነ ጊዜ ጥቅም ላይ አልዋለም።"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"ተጨማሪ የደህንነት ጥበቃ ያስፈልጋል። ስርዓተ ጥለት ለተወሰነ ጊዜ ጥቅም ላይ አልዋለም።"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ar/strings.xml b/packages/SystemUI/res-keyguard/values-ar/strings.xml
index b66f6fd..b6479f4 100644
--- a/packages/SystemUI/res-keyguard/values-ar/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ar/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"يجب إدخال رقم التعريف الشخصي بعد إلغاء التأمين."</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"يجب إدخال كلمة المرور بعد إلغاء التأمين."</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"يجب رسم النقش بعد إلغاء التأمين."</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"سيتم تثبيت التحديث عندما لا يكون الجهاز قيد الاستخدام."</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"‏يجب تعزيز الأمان. لم يُستخدَم رقم PIN لبعض الوقت."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"يجب تعزيز الأمان. لم تستخدَم كلمة المرور لبعض الوقت."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"يجب تعزيز الأمان. لم يُستخدَم النقش لبعض الوقت."</string>
diff --git a/packages/SystemUI/res-keyguard/values-as/strings.xml b/packages/SystemUI/res-keyguard/values-as/strings.xml
index 6796756..a41a704 100644
--- a/packages/SystemUI/res-keyguard/values-as/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-as/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"লকডাউনৰ পাছত পিন দিয়াৰ আৱশ্যক"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"লকডাউনৰ পাছত পাছৱৰ্ড দিয়াৰ আৱশ্যক"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"লকডাউনৰ পাছত আৰ্হি দিয়াৰ আৱশ্যক"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"ডিভাইচটো ব্যৱহাৰ হৈ নাথাকোঁতে আপডে’ট ইনষ্টল হ’ব"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"অতিৰিক্ত সুৰক্ষাৰ আৱশ্যক। কিছু সময় ধৰি আৰ্হি ব্যৱহাৰ কৰা হোৱা নাই।"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"অতিৰিক্ত সুৰক্ষাৰ আৱশ্যক। কিছু সময় ধৰি পাছৱৰ্ড ব্যৱহাৰ কৰা হোৱা নাই।"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"অতিৰিক্ত সুৰক্ষাৰ আৱশ্যক। কিছু সময় ধৰি আৰ্হি ব্যৱহাৰ কৰা হোৱা নাই।"</string>
diff --git a/packages/SystemUI/res-keyguard/values-az/strings.xml b/packages/SystemUI/res-keyguard/values-az/strings.xml
index d8cf6c0..f66fb3c 100644
--- a/packages/SystemUI/res-keyguard/values-az/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-az/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Kilidləmədən sonra PIN tələb edilir"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Kilidləmədən sonra parol tələb edilir"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Kilidləmədən sonra model tələb edilir"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Cihaz istifadə edilmədikdə güncəllənmə quraşdırılacaq"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Qoruma lazımdır. PIN bir müddət işlənməyib."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Qoruma lazımdır. Parol bir müddət işlənməyib."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Qoruma lazımdır. Model bir müddət işlənməyib."</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 72067e7..b0a6471 100644
--- a/packages/SystemUI/res-keyguard/values-b+sr+Latn/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-b+sr+Latn/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN je obavezan posle zaključavanja"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Lozinka je obavezna posle zaključavanja"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Šablon je obavezan posle zaključavanja"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Ažuriranje će se instalirati kada se uređaj ne koristi"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Potrebna je dodatna zaštita. PIN dugo nije korišćen."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Potrebna je dodatna zaštita. Lozinka dugo nije korišćena."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Potrebna je dodatna zaštita. Šablon dugo nije korišćen."</string>
diff --git a/packages/SystemUI/res-keyguard/values-be/strings.xml b/packages/SystemUI/res-keyguard/values-be/strings.xml
index 12c693f..11cc77d 100644
--- a/packages/SystemUI/res-keyguard/values-be/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-be/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Пасля блакіроўкі неабходна ўвесці PIN-код"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Пасля блакіроўкі неабходна ўвесці пароль"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Пасля блакіроўкі неабходна ўвесці ўзор разблакіроўкі"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Абнаўленне будзе ўсталявана, калі прылада не выкарыстоўваецца"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Патрабуецца дадатковая праверка. Даўно не выкарыстоўваўся PIN-код."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Патрабуецца дадатковая праверка. Даўно не выкарыстоўваўся пароль."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Патрабуецца дадатковая праверка. Даўно не выкарыстоўваўся ўзор разблакіроўкі."</string>
diff --git a/packages/SystemUI/res-keyguard/values-bg/strings.xml b/packages/SystemUI/res-keyguard/values-bg/strings.xml
index 6726d42..c554a27 100644
--- a/packages/SystemUI/res-keyguard/values-bg/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-bg/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"След заключването се изисква ПИН код"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"След заключването се изисква парола"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"След заключването се изисква фигура"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Актуализацията ще се инсталира, когато устройството не се използва"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Изисква се допъл. защита. ПИН кодът не е ползван скоро."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Изисква се допъл. защита. Паролата не е ползвана скоро."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Изисква се допъл. защита. Фигурата не е ползвана скоро."</string>
diff --git a/packages/SystemUI/res-keyguard/values-bn/strings.xml b/packages/SystemUI/res-keyguard/values-bn/strings.xml
index 457f85d..69f533c 100644
--- a/packages/SystemUI/res-keyguard/values-bn/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-bn/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"লকডাউন হওয়ার পরে পিন দিতে হবে"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"লকডাউন হওয়ার পরে পাসওয়ার্ড দিতে হবে"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"লকডাউন হওয়ার পরে প্যাটার্ন দিতে হবে"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"ডিভাইস ব্যবহার না করাকালীন আপডেট ইনস্টল করা হবে"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"অতিরিক্ত সুরক্ষা দরকার। পিন কিছুক্ষণ ব্যবহার করা হয়নি।"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"অতিরিক্ত সুরক্ষা দরকার। পাসওয়ার্ড কিছুক্ষণ ব্যবহার করা হয়নি।"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"অতিরিক্ত সুরক্ষা দরকার। প্যাটার্ন কিছুক্ষণ ব্যবহার করা হয়নি।"</string>
diff --git a/packages/SystemUI/res-keyguard/values-bs/strings.xml b/packages/SystemUI/res-keyguard/values-bs/strings.xml
index 6dc147f..4c519c8 100644
--- a/packages/SystemUI/res-keyguard/values-bs/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-bs/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN je potreban nakon zaključavanja"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Lozinka je potrebna nakon zaključavanja"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Uzorak je potreban nakon zaključavanja"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Ažuriranje će se instalirati dok se uređaj ne koristi"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Potrebna je dodatna zaštita. PIN dugo nije unošen."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Potrebna je dodatna zaštita. Lozinka dugo nije unošena."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Potrebna je dodatna zaštita. Uzorak dugo nije unošen."</string>
diff --git a/packages/SystemUI/res-keyguard/values-ca/strings.xml b/packages/SystemUI/res-keyguard/values-ca/strings.xml
index 8b901c0..3bd6508 100644
--- a/packages/SystemUI/res-keyguard/values-ca/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ca/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Cal el PIN després del bloqueig de seguretat"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Cal la contrasenya després del bloqueig de seguretat"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Cal el patró després del bloqueig de seguretat"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"L\'actualització s\'instal·larà quan el dispositiu no estigui en ús"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Cal més seguretat. Fa temps que no utilitzes el PIN."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Cal més seguretat. Contrasenya no utilitzada fa temps."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Cal més seguretat. Fa temps que no utilitzes el patró."</string>
diff --git a/packages/SystemUI/res-keyguard/values-cs/strings.xml b/packages/SystemUI/res-keyguard/values-cs/strings.xml
index b4c0343..e075d85 100644
--- a/packages/SystemUI/res-keyguard/values-cs/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-cs/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Po uzamčení je třeba zadat PIN"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Po uzamčení je třeba zadat heslo"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Po uzamčení je třeba zadat gesto"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Aktualizace se nainstaluje, až zařízení nebudete používat"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Je potřeba další krok. PIN dlouho nepoužit."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Je potřeba další krok. Heslo dlouho nepoužito."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Je potřeba další krok. Gesto dlouho nepoužito."</string>
diff --git a/packages/SystemUI/res-keyguard/values-da/strings.xml b/packages/SystemUI/res-keyguard/values-da/strings.xml
index 3840785..027166f 100644
--- a/packages/SystemUI/res-keyguard/values-da/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-da/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Pinkode er påkrævet efter brug af låsning"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Adgangskode er påkrævet efter brug af låsning"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Mønster er påkrævet efter brug af låsning"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Opdateringen installeres, når enheden ikke er i brug"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Mere sikkerhed er påkrævet. Pinkoden er ikke blevet brugt i et stykke tid."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Mere sikkerhed er påkrævet. Adgangskoden er ikke blevet brugt i et stykke tid."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Mere sikkerhed er påkrævet. Mønsteret er ikke blevet brugt i et stykke tid."</string>
diff --git a/packages/SystemUI/res-keyguard/values-de/strings.xml b/packages/SystemUI/res-keyguard/values-de/strings.xml
index 5d069ff..117f7a9 100644
--- a/packages/SystemUI/res-keyguard/values-de/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-de/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Nach einer Sperre muss die PIN eingegeben werden"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Nach einer Sperre muss das Passwort eingegeben werden"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Nach einer Sperre muss das Muster gezeichnet werden"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Update wird installiert, wenn das Gerät nicht verwendet wird"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Zusätzliche Sicherheitsmaßnahme erforderlich. Die PIN wurde länger nicht genutzt."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Zusätzliche Sicherheitsmaßnahme erforderlich. Passwort wurde länger nicht genutzt."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Zusätzliche Sicherheitsmaßnahme erforderlich. Muster wurde länger nicht genutzt."</string>
diff --git a/packages/SystemUI/res-keyguard/values-el/strings.xml b/packages/SystemUI/res-keyguard/values-el/strings.xml
index f02be89..cd7637c 100644
--- a/packages/SystemUI/res-keyguard/values-el/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-el/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Απαιτείται PIN μετά από κλείδωμα"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Απαιτείται κωδικός πρόσβασης μετά από κλείδωμα"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Απαιτείται μοτίβο μετά από κλείδωμα"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Η ενημέρωση θα εγκατασταθεί όταν δεν χρησιμοποιείται η συσκευή"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Απαιτ. πρόσθ. ασφάλ. Το PIN έχει καιρό να χρησιμοπ."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Απαιτ. πρόσθ. ασφάλ. Ο κωδ. πρ. έχει καιρό να χρησ."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Απαιτ. πρόσθ. ασφάλ. Το μοτίβο έχει καιρό να χρησιμ."</string>
diff --git a/packages/SystemUI/res-keyguard/values-en-rAU/strings.xml b/packages/SystemUI/res-keyguard/values-en-rAU/strings.xml
index ab7208b..0ace8a7 100644
--- a/packages/SystemUI/res-keyguard/values-en-rAU/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-en-rAU/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN is required after lockdown"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Password is required after lockdown"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Pattern is required after lockdown"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Update will be installed when the device is not in use"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Added security required. PIN not used for a while."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Added security required. Password not used for a while."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Added security required. Pattern not used for a while."</string>
diff --git a/packages/SystemUI/res-keyguard/values-en-rGB/strings.xml b/packages/SystemUI/res-keyguard/values-en-rGB/strings.xml
index ab7208b..0ace8a7 100644
--- a/packages/SystemUI/res-keyguard/values-en-rGB/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-en-rGB/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN is required after lockdown"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Password is required after lockdown"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Pattern is required after lockdown"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Update will be installed when the device is not in use"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Added security required. PIN not used for a while."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Added security required. Password not used for a while."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Added security required. Pattern not used for a while."</string>
diff --git a/packages/SystemUI/res-keyguard/values-en-rIN/strings.xml b/packages/SystemUI/res-keyguard/values-en-rIN/strings.xml
index ab7208b..0ace8a7 100644
--- a/packages/SystemUI/res-keyguard/values-en-rIN/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-en-rIN/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN is required after lockdown"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Password is required after lockdown"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Pattern is required after lockdown"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Update will be installed when the device is not in use"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Added security required. PIN not used for a while."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Added security required. Password not used for a while."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Added security required. Pattern not used for a while."</string>
diff --git a/packages/SystemUI/res-keyguard/values-es-rUS/strings.xml b/packages/SystemUI/res-keyguard/values-es-rUS/strings.xml
index 2aa9c04..debbeb1 100644
--- a/packages/SystemUI/res-keyguard/values-es-rUS/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-es-rUS/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Se requiere el PIN después del bloqueo"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Se requiere la contraseña después del bloqueo"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Se requiere el patrón después del bloqueo"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Se instalará la actualización cuando el dispositivo esté en desuso"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Reforzar seguridad. PIN sin uso mucho tiempo."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Reforzar seguridad. Contraseña sin uso mucho tiempo."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Reforzar seguridad. Patrón sin uso mucho tiempo."</string>
diff --git a/packages/SystemUI/res-keyguard/values-es/strings.xml b/packages/SystemUI/res-keyguard/values-es/strings.xml
index 78ecc85..0ea98a8 100644
--- a/packages/SystemUI/res-keyguard/values-es/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-es/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Se necesita el PIN después del bloqueo"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Se necesita la contraseña después del bloqueo"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Se necesita el patrón después del bloqueo"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"La actualización se instalará cuando el dispositivo no esté en uso"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Se debe reforzar la seguridad. PIN no usado en mucho tiempo."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Se debe reforzar la seguridad. Contraseña no usada en mucho tiempo."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Se debe reforzar la seguridad. Patrón no usado en mucho tiempo."</string>
diff --git a/packages/SystemUI/res-keyguard/values-et/strings.xml b/packages/SystemUI/res-keyguard/values-et/strings.xml
index 26ead1f..722a022 100644
--- a/packages/SystemUI/res-keyguard/values-et/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-et/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Pärast lukustamist on PIN-kood nõutav"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Pärast lukustamist on parool nõutav"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Pärast lukustamist on muster nõutav"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Värskendus installitakse, kui seadet ei kasutata"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Turvalisuse suurendamine on nõutav. PIN-koodi ei ole mõnda aega kasutatud."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Turvalisuse suurendamine on nõutav. Parooli ei ole mõnda aega kasutatud."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Turvalisuse suurendamine on nõutav. Mustrit ei ole mõnda aega kasutatud."</string>
diff --git a/packages/SystemUI/res-keyguard/values-eu/strings.xml b/packages/SystemUI/res-keyguard/values-eu/strings.xml
index 52d2336..d329369 100644
--- a/packages/SystemUI/res-keyguard/values-eu/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-eu/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PINa behar da blokeoa desgaitu ostean"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Pasahitza behar da blokeoa desgaitu ostean"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Eredua behar da blokeoa desgaitu ostean"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Gailua erabiltzen ari ez zarenean instalatuko da eguneratzea"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Segurtasuna areagotu behar da. PINa ez da erabili aldi batez."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Segurtasuna areagotu behar da. Pasahitza ez da erabili aldi batez."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Segurtasuna areagotu behar da. Eredua ez da erabili aldi batez."</string>
diff --git a/packages/SystemUI/res-keyguard/values-fa/strings.xml b/packages/SystemUI/res-keyguard/values-fa/strings.xml
index 1e7978e..4815815 100644
--- a/packages/SystemUI/res-keyguard/values-fa/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-fa/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"بعداز قفل همه باید از پین استفاده کرد"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"بعداز قفل همه باید از گذرواژه استفاده کرد"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"بعداز قفل همه باید از الگو استفاده کرد"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"به‌روزرسانی وقتی دستگاه درحال استفاده نیست نصب خواهد شد"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"امنیت بیشتر لازم است. مدتی از پین استفاده نشده است."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"امنیت بیشتر لازم است. گذرواژه مدتی استفاده نشده است."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"امنیت بیشتر لازم است. مدتی از الگو استفاده نشده است."</string>
diff --git a/packages/SystemUI/res-keyguard/values-fi/strings.xml b/packages/SystemUI/res-keyguard/values-fi/strings.xml
index 2ec0c99..02d41d8 100644
--- a/packages/SystemUI/res-keyguard/values-fi/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-fi/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN-koodi tarvitaan lukitustilan jälkeen"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Salasana tarvitaan lukitustilan jälkeen"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Kuvio tarvitaan lukitustilan jälkeen"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Päivitys asennetaan, kun laite ei ole käytössä"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Lisäsuojausta tarvitaan. PIN-koodia ei ole käytetty."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Lisäsuojausta tarvitaan. Salasanaa ei ole käytetty."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Lisäsuojausta tarvitaan. Kuviota ei ole käytetty."</string>
diff --git a/packages/SystemUI/res-keyguard/values-fr-rCA/strings.xml b/packages/SystemUI/res-keyguard/values-fr-rCA/strings.xml
index b0bfa33..fa1a191 100644
--- a/packages/SystemUI/res-keyguard/values-fr-rCA/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-fr-rCA/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Le NIP est requis après le verrouillage"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Le mot de passe est requis après le verrouillage"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Le schéma est requis après le verrouillage"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"La mise à jour sera installée lorsque l\'appareil n\'est pas utilisé"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Plus de sécurité requise. NIP non utilisé pour un temps."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Plus de sécurité requise. MDP non utilisé pour un temps."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Plus de sécurité requise. Schéma non utilisé pour un temps."</string>
diff --git a/packages/SystemUI/res-keyguard/values-fr/strings.xml b/packages/SystemUI/res-keyguard/values-fr/strings.xml
index 5161832..d687a1d 100644
--- a/packages/SystemUI/res-keyguard/values-fr/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-fr/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Code requis après un blocage"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Mot de passe requis après un blocage"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Schéma requis après un blocage"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"La mise à jour aura lieu lorsque votre appareil n\'est pas utilisé"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Code inutilisé depuis un moment. Renforcez la sécurité."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Mot de passe inutilisé depuis un moment. Renforcez la sécurité."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Schéma inutilisé depuis un moment. Renforcez la sécurité."</string>
diff --git a/packages/SystemUI/res-keyguard/values-gl/strings.xml b/packages/SystemUI/res-keyguard/values-gl/strings.xml
index e33a899..3faa7ca 100644
--- a/packages/SystemUI/res-keyguard/values-gl/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-gl/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Requírese o PIN tras o bloqueo"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Requírese o contrasinal tras o bloqueo"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Requírese o padrón tras o bloqueo"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"A actualización instalarase cando o dispositivo non se estea usando"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Requírese seguranza adicional. O PIN non se usou desde hai tempo."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Requírese seguranza adicional. O contrasinal non se usou desde hai tempo."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Requírese seguranza adicional. O padrón non se usou desde hai tempo."</string>
diff --git a/packages/SystemUI/res-keyguard/values-gu/strings.xml b/packages/SystemUI/res-keyguard/values-gu/strings.xml
index 1d806ca..99c9883 100644
--- a/packages/SystemUI/res-keyguard/values-gu/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-gu/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"પિન પછી પાસવર્ડ આવશ્યક છે"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"લૉકડાઉન પછી પાસવર્ડ આવશ્યક છે"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"પૅટર્ન પછી પાસવર્ડ આવશ્યક છે"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"જ્યારે ડિવાઇસ ઉપયોગમાં ન હોય ત્યારે અપડેટ ઇન્સ્ટૉલ કરવામાં આવશે"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"વધારાની સુરક્ષા આવશ્યક છે. થોડા સમય માટે પિનનો ઉપયોગ થયો નથી."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"વધારાની સુરક્ષા આવશ્યક છે. થોડા સમય માટે પાસવર્ડનો ઉપયોગ થયો નથી."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"વધારાની સુરક્ષા આવશ્યક છે. થોડા સમય માટે પૅટર્નનો ઉપયોગ થયો નથી."</string>
diff --git a/packages/SystemUI/res-keyguard/values-hi/strings.xml b/packages/SystemUI/res-keyguard/values-hi/strings.xml
index 808950e..9d32f04 100644
--- a/packages/SystemUI/res-keyguard/values-hi/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-hi/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"लॉकडाउन के बाद, पिन डालना ज़रूरी है"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"लॉकडाउन के बाद, पासवर्ड डालना ज़रूरी है"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"लॉकडाउन के बाद, पैटर्न ड्रॉ करना ज़रूरी है"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"अपडेट तब इंस्टॉल किया जाएगा, जब डिवाइस का इस्तेमाल न किया जा रहा हो"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"अतिरिक्त सुरक्षा ज़रूरी है. कुछ समय से पिन नहीं डाला गया."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"अतिरिक्त सुरक्षा ज़रूरी है. कुछ समय से पासवर्ड नहीं डाला गया."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"अतिरिक्त सुरक्षा ज़रूरी है. कुछ समय से पैटर्न ड्रॉ नहीं किया गया."</string>
diff --git a/packages/SystemUI/res-keyguard/values-hr/strings.xml b/packages/SystemUI/res-keyguard/values-hr/strings.xml
index 970ae5c..b4224bf 100644
--- a/packages/SystemUI/res-keyguard/values-hr/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-hr/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN je obavezan nakon zaključavanja"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Zaporka je obavezna nakon zaključavanja"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Uzorak je obavezan nakon zaključavanja"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Ažuriranje će se instalirati kad uređaj nije u upotrebi"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Potrebna je dodatna sigurnost. PIN nije upotrijebljen duže vrijeme."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Potrebna je dodatna sigurnost. Zaporka nije upotrijebljena duže vrijeme."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Potrebna je dodatna sigurnost. Uzorak nije upotrijebljen duže vrijeme."</string>
diff --git a/packages/SystemUI/res-keyguard/values-hu/strings.xml b/packages/SystemUI/res-keyguard/values-hu/strings.xml
index bc0a98d..bc712c7 100644
--- a/packages/SystemUI/res-keyguard/values-hu/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-hu/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN-kód megadása szükséges a zárolás után"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Jelszó megadása szükséges a zárolás után"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Minta megadása szükséges a zárolás után"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"A frissítést telepíti a rendszer, amikor nincs használatban az eszköz"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Fokozott biztonság szükséges. Régóta nem használta a PIN-t."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Fokozott biztonság szükséges. Régóta nem használta jelszavát."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Fokozott biztonság szükséges. Régóta nem használta a mintát."</string>
diff --git a/packages/SystemUI/res-keyguard/values-hy/strings.xml b/packages/SystemUI/res-keyguard/values-hy/strings.xml
index 230c6ba..4d7bbbe 100644
--- a/packages/SystemUI/res-keyguard/values-hy/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-hy/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Արգելափակումից հետո հարկավոր է մուտքագրել PIN կոդը"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Արգելափակումից հետո հարկավոր է մուտքագրել գաղտնաբառը"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Արգելափակումից հետո հարկավոր է գծել նախշը"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Թարմացումը կտեղադրվի, երբ սարքն օգտագործվելիս չլինի"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"PIN կոդը որոշ ժամանակ չի օգտագործվել։"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Գաղտնաբառը որոշ ժամանակ չի օգտագործվել։"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Նախշը որոշ ժամանակ չի օգտագործվել։"</string>
diff --git a/packages/SystemUI/res-keyguard/values-in/strings.xml b/packages/SystemUI/res-keyguard/values-in/strings.xml
index cf01634..aa766e9 100644
--- a/packages/SystemUI/res-keyguard/values-in/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-in/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN diperlukan setelah kunci total"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Sandi diperlukan setelah kunci total"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Pola diperlukan setelah kunci total"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Update akan diinstal saat perangkat sedang tidak digunakan"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Perlu keamanan tambahan. PIN tidak digunakan selama beberapa waktu."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Perlu keamanan tambahan. Sandi tidak digunakan selama beberapa waktu."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Perlu keamanan tambahan. Pola tidak digunakan selama beberapa waktu."</string>
diff --git a/packages/SystemUI/res-keyguard/values-is/strings.xml b/packages/SystemUI/res-keyguard/values-is/strings.xml
index ca36400..99f1779 100644
--- a/packages/SystemUI/res-keyguard/values-is/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-is/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN-númers er krafist eftir læsingu"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Aðgangsorðs er krafist eftir læsingu"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Mynsturs er krafist eftir læsingu"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Uppfærslan verður sett upp þegar tækið er ekki í notkun"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Viðbótaröryggis krafist. PIN-númer var ekki notað um hríð."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Viðbótaröryggis krafist. Aðgangsorð var ekki notað um hríð."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Viðbótaröryggis krafist. Mynstur var ekki notað um hríð."</string>
diff --git a/packages/SystemUI/res-keyguard/values-it/strings.xml b/packages/SystemUI/res-keyguard/values-it/strings.xml
index e46ae37..e5079c7 100644
--- a/packages/SystemUI/res-keyguard/values-it/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-it/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN richiesto dopo il blocco"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Password richiesta dopo il blocco"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Sequenza richiesta dopo il blocco"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"L\'aggiornamento verrà installato quando il dispositivo non sarà in uso"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Occorre maggiore sicurezza. PIN non usato per un po\' di tempo."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Occorre maggiore sicurezza. Password non usata per un po\' di tempo."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Occorre maggiore sicurezza. Sequenza non usata per un po\' di tempo."</string>
diff --git a/packages/SystemUI/res-keyguard/values-iw/strings.xml b/packages/SystemUI/res-keyguard/values-iw/strings.xml
index 667bf9b..bc66355 100644
--- a/packages/SystemUI/res-keyguard/values-iw/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-iw/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"נדרש קוד אימות לאחר הפעלת \'ללא \'ביטול נעילה בטביעת אצבע\'\'"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"נדרשת סיסמה לאחר הפעלת \'ללא \'ביטול נעילה בטביעת אצבע\'\'"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"נדרש קו ביטול נעילה לאחר הפעלת \'ללא \'ביטול נעילה בטביעת אצבע\'\'"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"העדכון יותקן כשהמכשיר לא יהיה בשימוש"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"נדרשת אבטחה מוגברת. לא השתמשת בקוד אימות זמן מה."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"נדרשת אבטחה מוגברת. לא השתמשת בסיסמה זמן מה."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"נדרשת אבטחה מוגברת. לא השתמשת בקו ביטול נעילה זמן מה."</string>
diff --git a/packages/SystemUI/res-keyguard/values-ja/strings.xml b/packages/SystemUI/res-keyguard/values-ja/strings.xml
index 5230984..1d59a63 100644
--- a/packages/SystemUI/res-keyguard/values-ja/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ja/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"ロックダウン後は PIN の入力が必要になります"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"ロックダウン後はパスワードの入力が必要になります"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"ロックダウン後はパターンの入力が必要になります"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"アップデートは、デバイスを使用していないときにインストールされます"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"セキュリティ強化が必要: PIN がしばらく未使用です。"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"セキュリティ強化が必要: パスワードがしばらく未使用です。"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"セキュリティ強化が必要: パターンがしばらく未使用です。"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ka/strings.xml b/packages/SystemUI/res-keyguard/values-ka/strings.xml
index 04a7b0d..5bd6b2e 100644
--- a/packages/SystemUI/res-keyguard/values-ka/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ka/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"დაბლოკვის შემდეგ საჭიროა PIN-კოდი"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"დაბლოკვის შემდეგ საჭიროა პაროლი"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"დაბლოკვის შემდეგ საჭიროა ნიმუში"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"განახლება დაინსტალირდება, როცა მოწყობილობა არ გამოიყენება"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"საჭიროა დამ. უსაფრთ. PIN-კოდი ერთხანს არ გამოიყენ."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"საჭ. დამ. უსაფრთ. პაროლი ერთხანს არ გამოიყენება."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"საჭიროა დამ. უსაფრთ. ნიმუში ერთხანს არ გამოიყენება."</string>
diff --git a/packages/SystemUI/res-keyguard/values-kk/strings.xml b/packages/SystemUI/res-keyguard/values-kk/strings.xml
index deab7b8..83d270d 100644
--- a/packages/SystemUI/res-keyguard/values-kk/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-kk/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Құлыпталғаннан кейін PIN кодын енгізу қажет."</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Құлыпталғаннан кейін құпия сөз енгізу қажет."</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Құлыпталғаннан кейін өрнек енгізу қажет."</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Құрылғы қолданылмағанда жаңартылады."</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Қауіпсіздікті күшейту қажет. PIN коды біраз уақыт қолданылмаған."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Қауіпсіздікті күшейту қажет. Құпия сөз біраз уақыт қолданылмаған."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Қауіпсіздікті күшейту қажет. Өрнек біраз уақыт қолданылмаған."</string>
diff --git a/packages/SystemUI/res-keyguard/values-km/strings.xml b/packages/SystemUI/res-keyguard/values-km/strings.xml
index 1325151..5306cb1 100644
--- a/packages/SystemUI/res-keyguard/values-km/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-km/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"ត្រូវការកូដ PIN បន្ទាប់ពីការចាក់សោ"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"ត្រូវការពាក្យសម្ងាត់បន្ទាប់ពីការចាក់សោ"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"ត្រូវការលំនាំបន្ទាប់ពីការចាក់សោ"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"កំណែថ្មីនឹងត្រូវបានដំឡើង នៅពេលឧបករណ៍មិនជាប់ប្រើ"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"ត្រូវការសុវត្ថិភាពបន្ថែម។ មិនបានប្រើកូដ PIN មួយរយៈ។"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"ត្រូវការសុវត្ថិភាពបន្ថែម។ មិនបានប្រើពាក្យសម្ងាត់មួយរយៈ។"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"ត្រូវការសុវត្ថិភាពបន្ថែម។ មិនបានប្រើលំនាំមួយរយៈ។"</string>
diff --git a/packages/SystemUI/res-keyguard/values-kn/strings.xml b/packages/SystemUI/res-keyguard/values-kn/strings.xml
index 749ebb6..d609a23 100644
--- a/packages/SystemUI/res-keyguard/values-kn/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-kn/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"ಲಾಕ್‌ಡೌನ್ ಮಾಡಿದ ನಂತರ ಪಿನ್ ಬಳಸುವ ಅಗತ್ಯವಿದೆ"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"ಲಾಕ್‌ಡೌನ್‌ನ ನಂತರ ಪಾಸ್‌ವರ್ಡ್‌ನ ಅಗತ್ಯವಿದೆ"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"ಲಾಕ್‌ಡೌನ್ ಮಾಡಿದ ನಂತರ ಪ್ಯಾಟರ್ನ್‌ ಬಳಸುವ ಅಗತ್ಯವಿದೆ"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"ಸಾಧನವನ್ನು ಬಳಕೆ ಮಾಡದ ಸಮಯದಲ್ಲಿ ಅಪ್‌ಡೇಟ್ ಅನ್ನು ಇನ್‌ಸ್ಟಾಲ್ ಮಾಡಲಾಗುತ್ತದೆ"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"ಹೆಚ್ಚುವರಿ ಸುರಕ್ಷತೆಯ ಅಗತ್ಯವಿದೆ. ಪಿನ್ ಅನ್ನು ಸ್ವಲ್ಪ ಕಾಲದಿಂದ ಬಳಸಿಲ್ಲ."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"ಹೆಚ್ಚುವರಿ ಸುರಕ್ಷತೆಯ ಅಗತ್ಯವಿದೆ. ಪಾಸ್‌ವರ್ಡ್ ಅನ್ನು ಸ್ವಲ್ಪ ಕಾಲದಿಂದ ಬಳಸಿಲ್ಲ."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"ಹೆಚ್ಚುವರಿ ಸುರಕ್ಷತೆಯ ಅಗತ್ಯವಿದೆ. ಪ್ಯಾಟರ್ನ್ ಅನ್ನು ಸ್ವಲ್ಪ ಕಾಲದಿಂದ ಬಳಸಿಲ್ಲ."</string>
diff --git a/packages/SystemUI/res-keyguard/values-ko/strings.xml b/packages/SystemUI/res-keyguard/values-ko/strings.xml
index ae75286..532253e 100644
--- a/packages/SystemUI/res-keyguard/values-ko/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ko/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"기기가 잠겨 PIN을 입력해야 합니다."</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"기기가 잠겨 비밀번호를 입력해야 합니다."</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"기기가 잠겨 패턴을 입력해야 합니다."</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"기기를 사용하지 않을 때 업데이트가 설치됩니다."</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"보안을 강화해야 합니다. 한동안 PIN이 사용되지 않았습니다."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"보안을 강화해야 합니다. 한동안 비밀번호가 사용되지 않았습니다."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"보안을 강화해야 합니다. 한동안 패턴이 사용되지 않았습니다."</string>
diff --git a/packages/SystemUI/res-keyguard/values-ky/strings.xml b/packages/SystemUI/res-keyguard/values-ky/strings.xml
index 638fd98..9ad9d56 100644
--- a/packages/SystemUI/res-keyguard/values-ky/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ky/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Бекем кулпулангандан кийин PIN код талап кылынат"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Бекем кулпулангандан кийин сырсөз талап кылынат"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Бекем кулпулангандан кийн грфикалык ачкыч талп клынт"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Жаңыртуу түзмөк колдонулбай турганда орнотулат"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Кошмча кпсуздук тлап клнат. PIN код бир нче убкыт бою клднулгн эмeс."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Кошмча кпсуздук тлап клнат. Сырсз бир нче убкыт бою клднулгн эмeс."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Кошмча кпсуздук тлап клнат. Грфиклык ачкч бир нче убкыт бою клднулгн эмeс."</string>
diff --git a/packages/SystemUI/res-keyguard/values-lo/strings.xml b/packages/SystemUI/res-keyguard/values-lo/strings.xml
index efe5377..0059d7f 100644
--- a/packages/SystemUI/res-keyguard/values-lo/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-lo/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"ຕ້ອງໃສ່ PIN ຫຼັງຈາກທີ່ລັອກໄວ້"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"ຕ້ອງໃສ່ລະຫັດຜ່ານຫຼັງຈາກທີ່ລັອກໄວ້"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"ຕ້ອງແຕ້ມຮູບແບບຫຼັງຈາກທີ່ລັອກໄວ້"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"ລະບົບຈະຕິດຕັ້ງການອັບເດດເມື່ອບໍ່ມີການນຳໃຊ້ອຸປະກອນ"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"ຕ້ອງເພີ່ມຄວາມປອດໄພ. ບໍ່ໄດ້ໃຊ້ PIN ມາໄລຍະໜຶ່ງແລ້ວ."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"ຕ້ອງເພີ່ມຄວາມປອດໄພ. ບໍ່ໄດ້ໃຊ້ລະຫັດຜ່ານມາໄລຍະໜຶ່ງແລ້ວ."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"ຕ້ອງເພີ່ມຄວາມປອດໄພ. ບໍ່ໄດ້ໃຊ້ຮູບແບບມາໄລຍະໜຶ່ງແລ້ວ."</string>
diff --git a/packages/SystemUI/res-keyguard/values-lt/strings.xml b/packages/SystemUI/res-keyguard/values-lt/strings.xml
index 59f0aa3..01e2f88 100644
--- a/packages/SystemUI/res-keyguard/values-lt/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-lt/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Po užrakinimo reikalingas PIN kodas"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Po užrakinimo reikalingas slaptažodis"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Po užrakinimo reikalingas atrakinimo piešinys"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Naujinys bus įdiegtas, kai įrenginys nebus naudojamas"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Reikalinga papildoma sauga. PIN kodas nebuvo naudojamas kurį laiką."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Reikalinga papildoma sauga. Slaptažodis nebuvo naudojamas kurį laiką."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Reikalinga papildoma sauga. Atrakinimo piešinys nebuvo naudojamas kurį laiką."</string>
diff --git a/packages/SystemUI/res-keyguard/values-lv/strings.xml b/packages/SystemUI/res-keyguard/values-lv/strings.xml
index ee9e8c2..2133694 100644
--- a/packages/SystemUI/res-keyguard/values-lv/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-lv/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Pēc bloķēšanas ir jāievada PIN"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Pēc bloķēšanas ir jāievada parole"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Pēc bloķēšanas ir jāzīmē kombinācija"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Atjauninājums tiks instalēts, kad ierīce netiks izmantota."</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Jāveic papildu drošības darbība. PIN ilgu laiku nav lietots."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Jāveic papildu drošības darbība. Parole ilgu laiku nav lietota."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Jāveic papildu drošības darbība. Kombinācija ilgu laiku nav lietota."</string>
diff --git a/packages/SystemUI/res-keyguard/values-mk/strings.xml b/packages/SystemUI/res-keyguard/values-mk/strings.xml
index a869d60..2771c7f 100644
--- a/packages/SystemUI/res-keyguard/values-mk/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-mk/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Потребен е PIN-код по заклучување"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Потребна е лозинка по заклучување"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Потребна е шема по заклучување"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Ажурирањето ќе се инсталира кога нема да се користи уредот"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Потребна е дополнителна безбедност. PIN-кодот не бил користен некое време."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Потребна е дополнителна безбедност. Лозинката не била користена некое време."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Потребна е дополнителна безбедност. Шемата не била користена некое време."</string>
diff --git a/packages/SystemUI/res-keyguard/values-ml/strings.xml b/packages/SystemUI/res-keyguard/values-ml/strings.xml
index e247cc7..02ee66f 100644
--- a/packages/SystemUI/res-keyguard/values-ml/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ml/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"ലോക്ക്‌ഡൗണിന് ശേഷം പിൻ നൽകേണ്ടതുണ്ട്"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"ലോക്ക്‌ഡൗണിന് ശേഷം പാസ്‌വേഡ് നൽകേണ്ടതുണ്ട്"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"ലോക്ക്‌ഡൗണിന് ശേഷം പാറ്റേൺ വരയ്‌ക്കേണ്ടതുണ്ട്"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"ഉപകരണം ഉപയോഗിക്കാതിരിക്കുമ്പോൾ അപ്ഡേറ്റ് ഇൻസ്റ്റാൾ ആകും"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"അധിക സുരക്ഷ വേണം. അൽപകാലം പിൻ ഉപയോഗിച്ചില്ല."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"അധിക സുരക്ഷ വേണം. അൽപകാലം പാസ്‌വേഡ് ഉപയോഗിച്ചില്ല."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"അധിക സുരക്ഷ വേണം. അൽപകാലം പാറ്റേൺ ഉപയോഗിച്ചില്ല."</string>
diff --git a/packages/SystemUI/res-keyguard/values-mn/strings.xml b/packages/SystemUI/res-keyguard/values-mn/strings.xml
index 7b555fb64..2b9f81e 100644
--- a/packages/SystemUI/res-keyguard/values-mn/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-mn/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Түгжсэний дараа ПИН шаардлагатай"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Түгжсэний дараа нууц үг шаардлагатай"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Түгжсэний дараа хээ шаардлагатай"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Төхөөрөмжийг ашиглаагүй үед шинэчлэлтийг суулгана"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Нэмэлт аюулгүй байдал шаардлагатай. ПИН-г хэсэг хугацаанд ашиглаагүй."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Нэмэлт аюулгүй байдал шаардлагатай. Нууц үгийг хэсэг хугацаанд ашиглаагүй."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Нэмэлт аюулгүй байдал шаардлагатай. Хээг хэсэг хугацаанд ашиглаагүй."</string>
diff --git a/packages/SystemUI/res-keyguard/values-mr/strings.xml b/packages/SystemUI/res-keyguard/values-mr/strings.xml
index ada2f11..7aa7bdd 100644
--- a/packages/SystemUI/res-keyguard/values-mr/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-mr/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"लॉकडाउननंतर पिन आवश्यक आहे"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"लॉकडाउननंतर पासवर्ड आवश्यक आहे"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"लॉकडाउननंतर पॅटर्न आवश्यक आहे"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"डिव्हाइस वापरात नसताना अपडेट इंस्टॉल केले जाईल"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"अतिरिक्त सुरक्षा आवश्‍यक आहे. काही वेळेसाठी पिन अनलॉक केला गेला नव्हता."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"अतिरिक्त सुरक्षा आवश्‍यक आहे. काही वेळेसाठी पासवर्ड अनलॉक केला गेला नव्हता."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"अतिरिक्त सुरक्षा आवश्‍यक आहे. काही वेळेसाठी पॅटर्न अनलॉक केला गेला नव्हता."</string>
diff --git a/packages/SystemUI/res-keyguard/values-ms/strings.xml b/packages/SystemUI/res-keyguard/values-ms/strings.xml
index 60c4531..bdfa4a7 100644
--- a/packages/SystemUI/res-keyguard/values-ms/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ms/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN diperlukan selepas kunci semua"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Kata laluan diperlukan selepas kunci semua"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Corak diperlukan selepas kunci semua"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Kemaskinian akan dipasang apabila peranti tidak digunakan"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Keselamatan tambahan diperlukan. PIN tidak digunakan."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Keselamatan tambahan diperlukan. Kata laluan tidak digunakan."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Keselamatan tambahan diperlukan. Corak tidak digunakan."</string>
diff --git a/packages/SystemUI/res-keyguard/values-my/strings.xml b/packages/SystemUI/res-keyguard/values-my/strings.xml
index 4092c9a..e85cf8a 100644
--- a/packages/SystemUI/res-keyguard/values-my/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-my/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"လော့ခ်ဒေါင်းလုပ်ပြီးနောက် ပင်နံပါတ်လိုအပ်သည်"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"လော့ခ်ဒေါင်းလုပ်ပြီးနောက် စကားဝှက်လိုအပ်သည်"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"လော့ခ်ဒေါင်းလုပ်ပြီးနောက် ပုံဖော်ခြင်းလိုအပ်သည်"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"စက်သုံးနေခြင်း မရှိချိန်တွင် အပ်ဒိတ် ထည့်သွင်းပါမည်"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"ထပ်ဆောင်းလုံခြုံရေး လိုအပ်သည်။ ပင်နံပါတ်မသုံးသည်မှာ အနည်းငယ်ကြာပြီ။"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"ထပ်ဆောင်းလုံခြုံရေး လိုအပ်သည်။ စကားဝှက်မသုံးသည်မှာ အနည်းငယ်ကြာပြီ။"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"ထပ်ဆောင်းလုံခြုံရေး လိုအပ်သည်။ ပုံဖော်ခြင်းမသုံးသည်မှာ အနည်းငယ်ကြာပြီ။"</string>
diff --git a/packages/SystemUI/res-keyguard/values-nb/strings.xml b/packages/SystemUI/res-keyguard/values-nb/strings.xml
index deb1421..455d086 100644
--- a/packages/SystemUI/res-keyguard/values-nb/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-nb/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN-koden kreves etter låsing"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Passordet kreves etter låsing"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Mønsteret kreves etter låsing"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Oppdateringen installeres når enheten ikke brukes"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Økt sikkerhet kreves. Har ikke brukt PIN-koden nylig"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Økt sikkerhet kreves. Har ikke brukt passordet nylig"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Økt sikkerhet kreves. Har ikke brukt mønsteret nylig"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ne/strings.xml b/packages/SystemUI/res-keyguard/values-ne/strings.xml
index 4cc238d..f0094a3 100644
--- a/packages/SystemUI/res-keyguard/values-ne/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ne/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"लकडाउन गरेपछि PIN हाल्नु पर्ने हुन्छ"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"लकडाउन गरेपछि पासवर्ड हाल्नु पर्ने हुन्छ"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"लकडाउन गरेपछि प्याटर्न कोर्नु पर्ने हुन्छ"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"डिभाइस नचलाइएका बेला अपडेट इन्स्टल हुने छ"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"थप सुरक्षित बनाउनु पर्ने हुन्छ। केही समयदेखि PIN प्रयोग गरिएको छैन।"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"थप सुरक्षित बनाउनु पर्ने हुन्छ। केही समयदेखि पासवर्ड प्रयोग गरिएको छैन।"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"थप सुरक्षित बनाउनु पर्ने हुन्छ। केही समयदेखि प्याटर्न प्रयोग गरिएको छैन।"</string>
diff --git a/packages/SystemUI/res-keyguard/values-nl/strings.xml b/packages/SystemUI/res-keyguard/values-nl/strings.xml
index 60578fa..a236639 100644
--- a/packages/SystemUI/res-keyguard/values-nl/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-nl/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Na lockdown is de pincode vereist"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Na lockdown is het wachtwoord vereist"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Na lockdown is het patroon vereist"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Update wordt geïnstalleerd als het apparaat niet wordt gebruikt"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Extra beveiliging. Pincode is lang niet gebruikt."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Extra beveiliging. Wachtwoord is lang niet gebruikt."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Extra beveiliging. Patroon is lang niet gebruikt."</string>
diff --git a/packages/SystemUI/res-keyguard/values-or/strings.xml b/packages/SystemUI/res-keyguard/values-or/strings.xml
index 4baae48..b31c9c0 100644
--- a/packages/SystemUI/res-keyguard/values-or/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-or/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"ଲକଡାଉନ ହେବା ପରେ PIN ଆବଶ୍ୟକ"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"ଲକଡାଉନ ହେବା ପରେ ପାସୱାର୍ଡ ଆବଶ୍ୟକ"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"ଲକଡାଉନ ହେବା ପରେ ପାଟର୍ନ ଆବଶ୍ୟକ"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"ଡିଭାଇସ ବ୍ୟବହାର କରାଯାଉନଥିବା ବେଳେ ଅପଡେଟ ଇନଷ୍ଟଲ ହେବ"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"ଅତିରିକ୍ତ ସୁରକ୍ଷା ଆବଶ୍ୟକ। କିଛି ସମୟ ପାଇଁ PIN ବ୍ୟବହାର କରାଯାଇନାହିଁ।"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"ଅତିରିକ୍ତ ସୁରକ୍ଷା ଆବଶ୍ୟକ। କିଛି ସମୟ ପାଇଁ ପାସୱାର୍ଡ ବ୍ୟବହାର କରାଯାଇନାହିଁ।"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"ଅତିରିକ୍ତ ସୁରକ୍ଷା ଆବଶ୍ୟକ। କିଛି ସମୟ ପାଇଁ ପାଟର୍ନ ବ୍ୟବହାର କରାଯାଇନାହିଁ।"</string>
diff --git a/packages/SystemUI/res-keyguard/values-pa/strings.xml b/packages/SystemUI/res-keyguard/values-pa/strings.xml
index 2306832..209b63f 100644
--- a/packages/SystemUI/res-keyguard/values-pa/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-pa/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"ਲਾਕਡਾਊਨ ਤੋਂ ਬਾਅਦ ਪਿੰਨ ਦੀ ਲੋੜ ਹੁੰਦੀ ਹੈ"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"ਲਾਕਡਾਊਨ ਤੋਂ ਬਾਅਦ ਪਾਸਵਰਡ ਦੀ ਲੋੜ ਹੁੰਦੀ ਹੈ"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"ਲਾਕਡਾਊਨ ਤੋਂ ਬਾਅਦ ਪੈਟਰਨ ਦੀ ਲੋੜ ਹੁੰਦੀ ਹੈ"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"ਡੀਵਾਈਸ ਵਰਤੋਂ ਵਿੱਚ ਨਾ ਹੋਣ \'ਤੇ ਅੱਪਡੇਟ ਸਥਾਪਤ ਹੋ ਜਾਵੇਗਾ"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"ਵਾਧੂ ਸੁਰੱਖਿਆ ਦੀ ਲੋੜ ਹੈ। ਪਿੰਨ ਨੂੰ ਕੁਝ ਸਮੇਂ ਲਈ ਵਰਤਿਆ ਨਹੀਂ ਗਿਆ।"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"ਵਾਧੂ ਸੁਰੱਖਿਆ ਦੀ ਲੋੜ ਹੈ। ਪਾਸਵਰਡ ਨੂੰ ਕੁਝ ਸਮੇਂ ਲਈ ਵਰਤਿਆ ਨਹੀਂ ਗਿਆ।"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"ਵਾਧੂ ਸੁਰੱਖਿਆ ਦੀ ਲੋੜ ਹੈ। ਪੈਟਰਨ ਨੂੰ ਕੁਝ ਸਮੇਂ ਲਈ ਵਰਤਿਆ ਨਹੀਂ ਗਿਆ।"</string>
diff --git a/packages/SystemUI/res-keyguard/values-pl/strings.xml b/packages/SystemUI/res-keyguard/values-pl/strings.xml
index f30d2cf..7ec988e 100644
--- a/packages/SystemUI/res-keyguard/values-pl/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-pl/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Po zablokowaniu wymagany jest kod PIN"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Po zablokowaniu wymagane jest hasło"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Po zablokowaniu wymagany jest wzór"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Instalacja aktualizacji nastąpi, gdy urządzenie nie będzie w użyciu"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Wzmocnij ochronę. Od dawna nie używano kodu PIN."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Wzmocnij ochronę. Od dawna nie używano hasła."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Wzmocnij ochronę. Od dawna nie używano wzoru."</string>
diff --git a/packages/SystemUI/res-keyguard/values-pt-rBR/strings.xml b/packages/SystemUI/res-keyguard/values-pt-rBR/strings.xml
index e9b21ed..78a8091 100644
--- a/packages/SystemUI/res-keyguard/values-pt-rBR/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-pt-rBR/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"O PIN é obrigatório após o Bloqueio total"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"A senha é obrigatória após o Bloqueio total"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"O padrão é obrigatório após o Bloqueio total"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"A atualização será instalada quando o dispositivo não estiver em uso"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Segurança necessária. PIN não usado há um tempo."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Segurança necessária. Senha não usada há um tempo."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Segurança necessária. Padrão não usado há um tempo."</string>
diff --git a/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml b/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml
index b10f313..2dc7d27 100644
--- a/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"O PIN é necessário após o bloqueio"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"A palavra-passe é necessária após o bloqueio"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"O padrão é necessário após o bloqueio"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"A atualização é instalada quando o dispositivo não estiver a ser usado"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Mais segurança necessária. PIN não usado há muito."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Mais segurança necessária. Não usada há muito."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"+ segurança necessária. Padrão não usado há muito."</string>
diff --git a/packages/SystemUI/res-keyguard/values-pt/strings.xml b/packages/SystemUI/res-keyguard/values-pt/strings.xml
index e9b21ed..78a8091 100644
--- a/packages/SystemUI/res-keyguard/values-pt/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-pt/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"O PIN é obrigatório após o Bloqueio total"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"A senha é obrigatória após o Bloqueio total"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"O padrão é obrigatório após o Bloqueio total"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"A atualização será instalada quando o dispositivo não estiver em uso"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Segurança necessária. PIN não usado há um tempo."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Segurança necessária. Senha não usada há um tempo."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Segurança necessária. Padrão não usado há um tempo."</string>
diff --git a/packages/SystemUI/res-keyguard/values-ro/strings.xml b/packages/SystemUI/res-keyguard/values-ro/strings.xml
index 3799ce7..e5be788 100644
--- a/packages/SystemUI/res-keyguard/values-ro/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ro/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Codul PIN este solicitat după blocarea strictă"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Parola este solicitată după blocarea strictă"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Modelul este solicitat după blocarea strictă"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Actualizarea se va instala când dispozitivul nu este folosit"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Mai multă securitate necesară. PIN-ul nu a fost folosit de ceva timp."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Mai multă securitate necesară. Parola nu a fost folosită de ceva timp."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Mai multă securitate necesară. Modelul nu a fost folosit de ceva timp."</string>
diff --git a/packages/SystemUI/res-keyguard/values-ru/strings.xml b/packages/SystemUI/res-keyguard/values-ru/strings.xml
index 184b28d..45149a5 100644
--- a/packages/SystemUI/res-keyguard/values-ru/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ru/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"После блокировки необходимо ввести PIN-код."</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"После блокировки необходимо ввести пароль."</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"После блокировки необходимо ввести графический ключ."</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Обновление будет установлено, когда устройство не используется."</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"PIN-код давно не использовался. Усильте защиту."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Пароль давно не использовался. Усильте защиту."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Граф. ключ давно не использовался. Усильте защиту."</string>
diff --git a/packages/SystemUI/res-keyguard/values-si/strings.xml b/packages/SystemUI/res-keyguard/values-si/strings.xml
index a484119..17ced75 100644
--- a/packages/SystemUI/res-keyguard/values-si/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-si/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"අගුළු දැමීමෙන් පසු PIN අවශ්‍ය වේ"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"අගුළු දැමීමෙන් පසු මුරපදය අවශ්‍ය වේ"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"අගුළු දැමීමෙන් පසු රටාව අවශ්‍ය වේ"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"උපාංගය භාවිතයේ නොමැති විට යාවත්කාලීනය ස්ථාපනය වනු ඇත"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"අමතර ආරක්ෂාවක් අවශ්‍යයි. PIN ටික කලකට භාවිතා කර නැත."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"අමතර ආරක්ෂාවක් අවශ්‍යයි. මුරපදය ටික කලකට භාවිතා කර නැත."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"අමතර ආරක්ෂාවක් අවශ්‍යයි. රටාව ටික කලකට භාවිතා කර නැත."</string>
diff --git a/packages/SystemUI/res-keyguard/values-sk/strings.xml b/packages/SystemUI/res-keyguard/values-sk/strings.xml
index 4730273..ef08a6c 100644
--- a/packages/SystemUI/res-keyguard/values-sk/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sk/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Po silnej zámke sa vyžaduje PIN"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Po silnej zámke sa vyžaduje heslo"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Po silnej zámke sa vyžaduje vzor"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Aktualizácia sa nainštaluje, keď zariadenie nebudete používať"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Treba lepšie zabezp. Kód PIN nebol dlhšie použitý."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Treba lepšie zabezp. Heslo nebolo dlhšie použité."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Treba lepšie zabezp. Vzor nebol dlhšie použitý."</string>
diff --git a/packages/SystemUI/res-keyguard/values-sl/strings.xml b/packages/SystemUI/res-keyguard/values-sl/strings.xml
index bddb9ad..a42989c 100644
--- a/packages/SystemUI/res-keyguard/values-sl/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sl/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Po zaklepu se zahteva vnos kode PIN"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Po zaklepu se zahteva vnos gesla"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Po zaklepu se zahteva vnos vzorca"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Posodobitev bo nameščena, ko naprava ne bo v uporabi"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Zahtevana je dodatna varnost. Koda PIN nekaj časa ni bila uporabljena."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Zahtevana je dodatna varnost. Geslo nekaj časa ni bilo uporabljeno."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Zahtevana je dodatna varnost. Vzorec nekaj časa ni bil uporabljen."</string>
diff --git a/packages/SystemUI/res-keyguard/values-sq/strings.xml b/packages/SystemUI/res-keyguard/values-sq/strings.xml
index 1739119..84f7bb5 100644
--- a/packages/SystemUI/res-keyguard/values-sq/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sq/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Pas bllokimit kërkohet kodi PIN"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Pas bllokimit kërkohet fjalëkalimi"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Pas bllokimit kërkohet motivi"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Përditësimi do të instalohet kur pajisja të mos përdoret"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Kërkohet një siguri më e lartë. Kodi PIN nuk është përdorur për njëfarë kohe."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Kërkohet një siguri më e lartë. Fjalëkalimi nuk është përdorur për njëfarë kohe."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Kërkohet një siguri më e lartë. Motivi nuk është përdorur për njëfarë kohe."</string>
diff --git a/packages/SystemUI/res-keyguard/values-sr/strings.xml b/packages/SystemUI/res-keyguard/values-sr/strings.xml
index b8c4b55..437018d 100644
--- a/packages/SystemUI/res-keyguard/values-sr/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sr/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN је обавезан после закључавања"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Лозинка је обавезна после закључавања"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Шаблон је обавезан после закључавања"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Ажурирање ће се инсталирати када се уређај не користи"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Потребна је додатна заштита. PIN дуго није коришћен."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Потребна је додатна заштита. Лозинка дуго није коришћена."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Потребна је додатна заштита. Шаблон дуго није коришћен."</string>
diff --git a/packages/SystemUI/res-keyguard/values-sv/strings.xml b/packages/SystemUI/res-keyguard/values-sv/strings.xml
index bec1771..b4b1996 100644
--- a/packages/SystemUI/res-keyguard/values-sv/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sv/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Pinkod krävs efter låsning"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Lösenord krävs efter låsning"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Mönster krävs efter låsning"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Uppdateringen installeras när enheten inte används"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Ökad säkerhet krävs. Pinkoden har inte använts på länge."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Ökad säkerhet krävs. Lösenordet har inte använts på länge."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Ökad säkerhet krävs. Mönstret har inte använts på länge."</string>
diff --git a/packages/SystemUI/res-keyguard/values-sw/strings.xml b/packages/SystemUI/res-keyguard/values-sw/strings.xml
index c6a8ed5..8ca9046 100644
--- a/packages/SystemUI/res-keyguard/values-sw/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sw/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"PIN inahitajika baada ya kufunga"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Nenosiri linahitajika baada ya kufunga"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Mchoro unahitajika baada ya kufunga"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Sasisho litasakinishwa wakati hutumii kifaa"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Usalama wa ziada unahitajika. PIN haikutumika kwa muda."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Usalama wa ziada unahitajika. Nenosiri halikutumika kwa muda."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Usalama wa ziada unahitajika. Mchoro haukutumika kwa muda."</string>
diff --git a/packages/SystemUI/res-keyguard/values-ta/strings.xml b/packages/SystemUI/res-keyguard/values-ta/strings.xml
index 147b36b..7671194 100644
--- a/packages/SystemUI/res-keyguard/values-ta/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ta/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"முழுப் பூட்டு காரணமாகப் பின் தேவை"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"முழுப் பூட்டு காரணமாகக் கடவுச்சொல் தேவை"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"முழுப் பூட்டு காரணமாகப் பேட்டர்ன் தேவை"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"சாதனம் உபயோகத்தில் இல்லாதபோது புதுப்பிப்பு நிறுவப்படும்"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"சேர்த்த பாதுகாப்பு தேவை. பின் உபயோகிக்கவில்லை."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"சேர்த்த பாதுகாப்பு தேவை. கடவுச்சொல் உபயோகிக்கவில்லை."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"சேர்த்த பாதுகாப்பு தேவை. பேட்டர்ன் உபயோகிக்கவில்லை."</string>
diff --git a/packages/SystemUI/res-keyguard/values-te/strings.xml b/packages/SystemUI/res-keyguard/values-te/strings.xml
index 317fb30..623b589 100644
--- a/packages/SystemUI/res-keyguard/values-te/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-te/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"లాక్‌డౌన్ తర్వాత PIN అవసరం"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"లాక్‌డౌన్ తర్వాత పాస్‌వర్డ్ అవసరం"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"లాక్‌డౌన్ తర్వాత ఆకృతి అవసరం"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"పరికరం ఉపయోగంలో లేనప్పుడు అప్‌డేట్ ఇన్‌స్టాల్ చేయబడుతుంది"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"మరింత సెక్యూరిటీ యాడ్ చెయ్యాలి. PINని ఈమధ్య వాడలేదు."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"యాడెడ్ సెక్యూరిటీ కావాలి. పాస్‌వర్డ్ ఈ మధ్య వాడలేదు."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"మరింత సెక్యూరిటీ కావాలి. ఆకృతిని ఈ మధ్య వాడలేదు."</string>
diff --git a/packages/SystemUI/res-keyguard/values-th/strings.xml b/packages/SystemUI/res-keyguard/values-th/strings.xml
index 85a14fa..c244107 100644
--- a/packages/SystemUI/res-keyguard/values-th/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-th/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"ต้องป้อน PIN หลังจากการปิดล็อก"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"ต้องป้อนรหัสผ่านหลังจากการปิดล็อก"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"ต้องวาดรูปแบบหลังจากการปิดล็อก"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"ระบบจะติดตั้งการอัปเดตเมื่อไม่มีการใช้งานอุปกรณ์"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"ต้องเพิ่มความปลอดภัย ไม่ได้ใช้ PIN มาระยะหนึ่ง"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"ต้องเพิ่มความปลอดภัย ไม่ได้ใช้รหัสผ่านมาระยะหนึ่ง"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"ต้องเพิ่มความปลอดภัย ไม่ได้ใช้รูปแบบมาระยะหนึ่ง"</string>
diff --git a/packages/SystemUI/res-keyguard/values-tl/strings.xml b/packages/SystemUI/res-keyguard/values-tl/strings.xml
index 1e51e0b..cd8f810 100644
--- a/packages/SystemUI/res-keyguard/values-tl/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-tl/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Kailangan ang PIN pagkatapos ng lockdown"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Kailangan ang password pagkatapos ng lockdown"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Kailangan ang pattern pagkatapos ng lockdown"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Ii-install ang update kapag hindi ginagamit ang device"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Kailangan pa ng seguridad. Matagal na hindi ginamit ang PIN."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Kailangan pa ng seguridad. Matagal na hindi ginamit ang password."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Kailangan pa ng seguridad. Matagal na hindi ginamit ang pattern."</string>
diff --git a/packages/SystemUI/res-keyguard/values-tr/strings.xml b/packages/SystemUI/res-keyguard/values-tr/strings.xml
index 05a9c95..ddeba67 100644
--- a/packages/SystemUI/res-keyguard/values-tr/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-tr/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Tam kilitlemenin ardından PIN gerekli"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Tam kilitlemenin ardından şifre gerekli"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Tam kilitlemenin ardından desen gerekli"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Güncelleme, cihazın kullanılmadığı bir sırada yüklenecek"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Daha fazla güvenlik gerekli. PIN bir süredir kullanılmamış."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Daha fazla güvenlik gerekli. Şifre bir süredir kullanılmamış."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Daha fazla güvenlik gerekli. Desen bir süredir kullanılmamış."</string>
diff --git a/packages/SystemUI/res-keyguard/values-uk/strings.xml b/packages/SystemUI/res-keyguard/values-uk/strings.xml
index 1c3c3ca..f06d17d 100644
--- a/packages/SystemUI/res-keyguard/values-uk/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-uk/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Після блокування входу потрібно ввести PIN-код"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Після блокування входу потрібно ввести пароль"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Після блокування входу потрібно намалювати ключ"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Оновлення встановиться, коли пристрій не використовуватиметься"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Потрібен додатковий захист. PIN-код довго не використовувався."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Потрібен додатковий захист. Пароль довго не використовувався."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Потрібен додатковий захист. Ключ довго не використовувався."</string>
diff --git a/packages/SystemUI/res-keyguard/values-ur/strings.xml b/packages/SystemUI/res-keyguard/values-ur/strings.xml
index 7784766..8adbaca 100644
--- a/packages/SystemUI/res-keyguard/values-ur/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ur/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"‏لاک ڈاؤن کے بعد PIN کی ضرورت ہوتی ہے"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"لاک ڈاؤن کے بعد پاس ورڈ کی ضرورت ہوتی ہے"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"لاک ڈاؤن کے بعد پیٹرن کی ضرورت ہوتی ہے"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"آلہ استعمال میں نہ ہونے پر اپ ڈیٹ انسٹال ہو جائے گی"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"‏مزید سیکیورٹی چاہیے۔ PIN کچھ عرصے اسے استعمال نہیں ہوا ہے۔"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"مزید سیکیورٹی چاہیے۔ پاس ورڈ کچھ عرصے سے استعمال نہیں ہوا ہے۔"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"مزید سیکیورٹی چاہیے۔ پیٹرن کچھ عرصے سے استعمال نہیں ہوا ہے۔"</string>
diff --git a/packages/SystemUI/res-keyguard/values-uz/strings.xml b/packages/SystemUI/res-keyguard/values-uz/strings.xml
index 28d18da..96dfa05 100644
--- a/packages/SystemUI/res-keyguard/values-uz/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-uz/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Bloklangandan keyin PIN kodni kiritish kerak"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Bloklangandan keyin parolni kiritish kerak"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Bloklangandan keyin grafik kalitni chizish kerak"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Yangilanish qurilma ishlatilmaganda oʻrnatiladi"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Xavfsizlikni oshiring. PIN kod ancha vaqt ishlatilmadi."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Xavfsizlikni oshiring. Parol ancha vaqt ishlatilmadi."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Xavfsizlikni oshiring. Grafik kalit ancha vaqt chizilmadi"</string>
diff --git a/packages/SystemUI/res-keyguard/values-vi/strings.xml b/packages/SystemUI/res-keyguard/values-vi/strings.xml
index 726a9e7..94d4fe2 100644
--- a/packages/SystemUI/res-keyguard/values-vi/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-vi/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Cần nhập mã PIN sau khi hết thời gian khoá"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Cần nhập mật khẩu sau khi hết thời gian khoá"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Cần vẽ hình mở khoá sau khi hết thời gian khoá"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Bản cập nhật sẽ được cài đặt khi bạn không sử dụng thiết bị"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Cần tăng cường bảo mật. Đã lâu chưa dùng mã PIN."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Cần tăng cường bảo mật. Đã lâu chưa dùng mật khẩu"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Cần tăng cường bảo mật. Đã lâu chưa dùng hình mở khoá."</string>
diff --git a/packages/SystemUI/res-keyguard/values-zh-rCN/strings.xml b/packages/SystemUI/res-keyguard/values-zh-rCN/strings.xml
index 0efe3bf..59261a3 100644
--- a/packages/SystemUI/res-keyguard/values-zh-rCN/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-zh-rCN/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"一旦设备被锁定,必须输入 PIN 码才能解锁"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"一旦设备被锁定,必须输入密码才能解锁"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"一旦设备被锁定,必须绘制图案才能解锁"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"更新会在设备处于未使用状态时安装"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"需要锁定设备以提高安全性。已有一段时间未使用 PIN 码了。"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"需要锁定设备以提高安全性。已有一段时间未使用密码了。"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"需要锁定设备以提高安全性。已有一段时间未使用图案了。"</string>
diff --git a/packages/SystemUI/res-keyguard/values-zh-rHK/strings.xml b/packages/SystemUI/res-keyguard/values-zh-rHK/strings.xml
index 58c3034..dad6f31 100644
--- a/packages/SystemUI/res-keyguard/values-zh-rHK/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-zh-rHK/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"需要輸入 PIN 才能解除鎖定"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"需要輸入密碼解才能解除鎖定"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"需要畫出解鎖圖案才能解除鎖定"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"系統會在裝置未使用時安裝更新"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"需要加強安全設定:已有一段時間沒有使用 PIN。"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"需要加強安全設定:已有一段時間沒有使用密碼。"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"需要加強安全設定:已有一段時間沒有使用解鎖圖案。"</string>
diff --git a/packages/SystemUI/res-keyguard/values-zh-rTW/strings.xml b/packages/SystemUI/res-keyguard/values-zh-rTW/strings.xml
index 35e7824..88b7e43 100644
--- a/packages/SystemUI/res-keyguard/values-zh-rTW/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-zh-rTW/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"裝置鎖定後,必須輸入 PIN 碼才能解鎖"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"裝置鎖定後,必須輸入密碼才能解鎖"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"裝置鎖定後,必須畫出解鎖圖案才能解鎖"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"系統會在裝置處於未使用狀態時安裝更新"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"裝置已有一段時間未鎖定,請使用 PIN 碼鎖定裝置以策安全。"</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"裝置已有一段時間未鎖定,請使用密碼鎖定裝置以策安全。"</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"裝置已有一段時間未鎖定,請使用解鎖圖案鎖定裝置以策安全。"</string>
diff --git a/packages/SystemUI/res-keyguard/values-zu/strings.xml b/packages/SystemUI/res-keyguard/values-zu/strings.xml
index e229c7e..c5e99ab 100644
--- a/packages/SystemUI/res-keyguard/values-zu/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-zu/strings.xml
@@ -76,8 +76,7 @@
     <string name="kg_prompt_after_user_lockdown_pin" msgid="5374732179740050373">"Iphinikhodi iyadingeka ngemva kokukhiya"</string>
     <string name="kg_prompt_after_user_lockdown_password" msgid="9097968458291129795">"Iphasiwedi iyadingeka ngemuva kokukhiya"</string>
     <string name="kg_prompt_after_user_lockdown_pattern" msgid="215072203613597906">"Iphethini iyadingeka ngemva kokukhiya"</string>
-    <!-- no translation found for kg_prompt_unattended_update (4366635751738712452) -->
-    <skip />
+    <string name="kg_prompt_unattended_update" msgid="4366635751738712452">"Isibuyekezo sizofakwa lapho idivayisi ingasetshenziswa"</string>
     <string name="kg_prompt_pin_auth_timeout" msgid="5868644725126275245">"Ukuphepha okwengeziwe kuyadingeka. Iphinikhodi ayisetshenziswanga isikhathi eside."</string>
     <string name="kg_prompt_password_auth_timeout" msgid="5809110458491920871">"Ukuphepha okwengeziwe kuyadingeka. Iphasiwedi ayisetshenziswanga isikhathi eside."</string>
     <string name="kg_prompt_pattern_auth_timeout" msgid="1860605401869262178">"Ukuphepha okwengeziwe kuyadingeka. Iphethini ayisetshenziswanga isikhathi eside."</string>
diff --git a/packages/SystemUI/res-product/values-zh-rCN/strings.xml b/packages/SystemUI/res-product/values-zh-rCN/strings.xml
index 6895219..de308ddb 100644
--- a/packages/SystemUI/res-product/values-zh-rCN/strings.xml
+++ b/packages/SystemUI/res-product/values-zh-rCN/strings.xml
@@ -38,8 +38,8 @@
     <string name="kg_failed_attempts_almost_at_erase_profile" product="default" msgid="3280816298678433681">"您尝试解锁手机后失败的次数已达 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统将移除此工作资料,而这将删除所有的工作资料数据。"</string>
     <string name="kg_failed_attempts_now_erasing_profile" product="tablet" msgid="4417100487251371559">"您尝试解锁平板电脑后失败的次数已达 <xliff:g id="NUMBER">%d</xliff:g> 次。系统将移除此工作资料,而这将删除所有的工作资料数据。"</string>
     <string name="kg_failed_attempts_now_erasing_profile" product="default" msgid="4682221342671290678">"您尝试解锁手机后失败的次数已达 <xliff:g id="NUMBER">%d</xliff:g> 次。系统将移除此工作资料,而这将删除所有的工作资料数据。"</string>
-    <string name="kg_failed_attempts_almost_at_login" product="tablet" msgid="1860049973474855672">"您已 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次画错解锁图案。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用自己的电子邮件帐号解锁平板电脑。\n\n请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
-    <string name="kg_failed_attempts_almost_at_login" product="default" msgid="44112553371516141">"您已 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次画错解锁图案。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用自己的电子邮件帐号解锁手机。\n\n请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
+    <string name="kg_failed_attempts_almost_at_login" product="tablet" msgid="1860049973474855672">"您已 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次画错解锁图案。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用自己的电子邮件账号解锁平板电脑。\n\n请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
+    <string name="kg_failed_attempts_almost_at_login" product="default" msgid="44112553371516141">"您已 <xliff:g id="NUMBER_0">%1$d</xliff:g> 次画错解锁图案。如果再尝试 <xliff:g id="NUMBER_1">%2$d</xliff:g> 次后仍不成功,系统就会要求您使用自己的电子邮件账号解锁手机。\n\n请在 <xliff:g id="NUMBER_2">%3$d</xliff:g> 秒后重试。"</string>
     <string name="thermal_shutdown_title" product="default" msgid="8039593017174903505">"手机先前因过热而关机"</string>
     <string name="thermal_shutdown_title" product="device" msgid="2954206342842856379">"设备先前因过热而关机"</string>
     <string name="thermal_shutdown_title" product="tablet" msgid="8941033526856177533">"平板电脑先前因过热而关机"</string>
diff --git a/packages/SystemUI/res/drawable-television/ic_volume_media.xml b/packages/SystemUI/res/drawable-television/ic_volume_media.xml
deleted file mode 100644
index 6a368d5..0000000
--- a/packages/SystemUI/res/drawable-television/ic_volume_media.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  Copyright (C) 2020 The Android Open Source Project
-
-  Licensed under the Apache License, Version 2.0 (the "License");
-  you may not use this file except in compliance with the License.
-  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-  Unless required by applicable law or agreed to in writing, software
-  distributed under the License is distributed on an "AS IS" BASIS,
-  WITHOUT 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="@dimen/tv_volume_icons_size"
-    android:height="@dimen/tv_volume_icons_size"
-    android:viewportWidth="24.0"
-    android:viewportHeight="24.0">
-    <path
-        android:fillColor="@color/tv_volume_dialog_accent"
-        android:pathData="M3,9v6h4l5,5L12,4L7,9L3,9zM10,8.83v6.34L7.83,13L5,13v-2h2.83L10,8.83zM16.5,12c0,-1.77 -1.02,-3.29 -2.5,-4.03v8.05c1.48,-0.73 2.5,-2.25 2.5,-4.02zM14,3.23v2.06c2.89,0.86 5,3.54 5,6.71s-2.11,5.85 -5,6.71v2.06c4.01,-0.91 7,-4.49 7,-8.77 0,-4.28 -2.99,-7.86 -7,-8.77z"/>
-</vector>
diff --git a/packages/SystemUI/res/drawable-television/ic_volume_media_low.xml b/packages/SystemUI/res/drawable-television/ic_volume_media_low.xml
deleted file mode 100644
index 6eb944f..0000000
--- a/packages/SystemUI/res/drawable-television/ic_volume_media_low.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  Copyright (C) 2020 The Android Open Source Project
-
-  Licensed under the Apache License, Version 2.0 (the "License");
-  you may not use this file except in compliance with the License.
-  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-  Unless required by applicable law or agreed to in writing, software
-  distributed under the License is distributed on an "AS IS" BASIS,
-  WITHOUT 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="@dimen/tv_volume_icons_size"
-    android:height="@dimen/tv_volume_icons_size"
-    android:viewportWidth="24.0"
-    android:viewportHeight="24.0">
-    <group android:translateX="-2">
-        <path
-            android:fillColor="@color/tv_volume_dialog_accent"
-            android:pathData="M16,7.97v8.05c1.48,-0.73 2.5,-2.25 2.5,-4.02 0,-1.77 -1.02,-3.29 -2.5,-4.03zM5,9v6h4l5,5L14,4L9,9L5,9zM12,8.83v6.34L9.83,13L7,13v-2h2.83L12,8.83z"/>
-    </group>
-</vector>
diff --git a/packages/SystemUI/res/drawable-television/ic_volume_media_mute.xml b/packages/SystemUI/res/drawable-television/ic_volume_media_mute.xml
deleted file mode 100644
index b683089..0000000
--- a/packages/SystemUI/res/drawable-television/ic_volume_media_mute.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  Copyright (C) 2020 The Android Open Source Project
-
-  Licensed under the Apache License, Version 2.0 (the "License");
-  you may not use this file except in compliance with the License.
-  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-  Unless required by applicable law or agreed to in writing, software
-  distributed under the License is distributed on an "AS IS" BASIS,
-  WITHOUT 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="@dimen/tv_volume_icons_size"
-    android:height="@dimen/tv_volume_icons_size"
-    android:viewportWidth="24.0"
-    android:viewportHeight="24.0">
-    <group android:translateX="-4">
-        <path
-            android:fillColor="@color/tv_volume_dialog_accent"
-            android:pathData="M14,8.83v6.34L11.83,13H9v-2h2.83L14,8.83M16,4l-5,5H7v6h4l5,5V4z"/>
-    </group>
-</vector>
diff --git a/packages/SystemUI/res/drawable-television/ic_volume_media_off.xml b/packages/SystemUI/res/drawable-television/ic_volume_media_off.xml
deleted file mode 100644
index 7a44aa6..0000000
--- a/packages/SystemUI/res/drawable-television/ic_volume_media_off.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  Copyright (C) 2020 The Android Open Source Project
-
-  Licensed under the Apache License, Version 2.0 (the "License");
-  you may not use this file except in compliance with the License.
-  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-  Unless required by applicable law or agreed to in writing, software
-  distributed under the License is distributed on an "AS IS" BASIS,
-  WITHOUT 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="@dimen/tv_volume_icons_size"
-    android:height="@dimen/tv_volume_icons_size"
-    android:viewportHeight="24"
-    android:viewportWidth="24">
-    <path
-        android:fillColor="@color/tv_volume_dialog_accent"
-        android:pathData="M4.34,2.93L2.93,4.34 7.29,8.7 7,9L3,9v6h4l5,5v-6.59l4.18,4.18c-0.65,0.49 -1.38,0.88 -2.18,1.11v2.06c1.34,-0.3 2.57,-0.92 3.61,-1.75l2.05,2.05 1.41,-1.41L4.34,2.93zM10,15.17L7.83,13L5,13v-2h2.83l0.88,-0.88L10,11.41v3.76zM19,12c0,0.82 -0.15,1.61 -0.41,2.34l1.53,1.53c0.56,-1.17 0.88,-2.48 0.88,-3.87 0,-4.28 -2.99,-7.86 -7,-8.77v2.06c2.89,0.86 5,3.54 5,6.71zM12,4l-1.88,1.88L12,7.76zM16.5,12c0,-1.77 -1.02,-3.29 -2.5,-4.03v1.79l2.48,2.48c0.01,-0.08 0.02,-0.16 0.02,-0.24z"/>
-</vector>
diff --git a/packages/SystemUI/res/drawable-television/volume_row_seekbar.xml b/packages/SystemUI/res/drawable-television/volume_row_seekbar.xml
deleted file mode 100644
index e49fc15..0000000
--- a/packages/SystemUI/res/drawable-television/volume_row_seekbar.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-    Copyright (C) 2021 The Android Open Source Project
-
-    Licensed under the Apache License, Version 2.0 (the "License");
-    you may not use this file except in compliance with the License.
-    You may obtain a copy of the License at
-
-         http://www.apache.org/licenses/LICENSE-2.0
-
-    Unless required by applicable law or agreed to in writing, software
-    distributed under the License is distributed on an "AS IS" BASIS,
-    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-    See the License for the specific language governing permissions and
-    limitations under the License.
--->
-<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
-            android:paddingMode="stack">
-    <item android:id="@android:id/background"
-        android:gravity="center_vertical|fill_horizontal">
-        <layer-list>
-            <item android:id="@+id/volume_seekbar_background_solid">
-                <shape>
-                    <size android:height="@dimen/volume_dialog_slider_width" />
-                    <solid android:color="@color/tv_volume_dialog_seek_bar_background"/>
-                    <corners android:radius="@dimen/volume_dialog_slider_corner_radius" />
-                </shape>
-            </item>
-        </layer-list>
-    </item>
-    <item android:id="@android:id/progress"
-          android:gravity="center_vertical|fill_horizontal">
-            <com.android.systemui.util.RoundedCornerProgressDrawable
-                android:drawable="@drawable/volume_row_seekbar_progress"
-            />
-    </item>
-</layer-list>
diff --git a/packages/SystemUI/res/drawable-television/volume_row_seekbar_progress.xml b/packages/SystemUI/res/drawable-television/volume_row_seekbar_progress.xml
deleted file mode 100644
index bce193a..0000000
--- a/packages/SystemUI/res/drawable-television/volume_row_seekbar_progress.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2021 The Android Open Source Project
-  ~
-  ~ Licensed under the Apache License, Version 2.0 (the "License");
-  ~ you may not use this file except in compliance with the License.
-  ~ You may obtain a copy of the License at
-  ~
-  ~      http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing, software
-  ~ distributed under the License is distributed on an "AS IS" BASIS,
-  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~ See the License for the specific language governing permissions and
-  ~ limitations under the License.
-  -->
-
-<!-- Progress drawable for volume row SeekBars. This is the accent-colored round rect that moves up
-     and down as the progress value changes. -->
-<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
-    android:autoMirrored="true">
-    <item android:id="@+id/volume_seekbar_progress_solid">
-        <shape android:shape="rectangle">
-            <size android:height="@dimen/volume_dialog_slider_width"/>
-            <solid android:color="@color/tv_volume_dialog_seek_bar_fill" />
-            <corners android:radius="@dimen/volume_dialog_slider_width" />
-        </shape>
-    </item>
-</layer-list>
diff --git a/packages/SystemUI/res/layout/combined_qs_header.xml b/packages/SystemUI/res/layout/combined_qs_header.xml
index 12f13e9a..3a15ae4 100644
--- a/packages/SystemUI/res/layout/combined_qs_header.xml
+++ b/packages/SystemUI/res/layout/combined_qs_header.xml
@@ -127,6 +127,8 @@
         android:gravity="center_vertical"
         android:paddingStart="@dimen/shade_header_system_icons_padding_start"
         android:paddingEnd="@dimen/shade_header_system_icons_padding_end"
+        android:paddingTop="@dimen/shade_header_system_icons_padding_top"
+        android:paddingBottom="@dimen/shade_header_system_icons_padding_bottom"
         app:layout_constraintBottom_toBottomOf="parent"
         app:layout_constraintEnd_toEndOf="@id/privacy_container"
         app:layout_constraintTop_toTopOf="@id/clock">
diff --git a/packages/SystemUI/res/layout/screen_share_dialog.xml b/packages/SystemUI/res/layout/screen_share_dialog.xml
index 9af46c5..3796415 100644
--- a/packages/SystemUI/res/layout/screen_share_dialog.xml
+++ b/packages/SystemUI/res/layout/screen_share_dialog.xml
@@ -64,8 +64,7 @@
             android:layout_height="wrap_content"
             android:text="@string/screenrecord_permission_dialog_warning_entire_screen"
             style="@style/TextAppearance.Dialog.Body.Message"
-            android:gravity="start"
-            android:lineHeight="@dimen/screenrecord_warning_line_height"/>
+            android:gravity="start"/>
 
         <!-- Buttons -->
         <LinearLayout
diff --git a/packages/SystemUI/res/values-af/strings.xml b/packages/SystemUI/res/values-af/strings.xml
index 2355341..fe80355 100644
--- a/packages/SystemUI/res/values-af/strings.xml
+++ b/packages/SystemUI/res/values-af/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g>-limiet"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> waarskuwing"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Werkprogramme"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Onderbreek"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Aandbeligting"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Aan by sonsondergang"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Tot sonsopkoms"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Vergroot \'n deel van die skerm"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Maak vergrotinginstellings oop"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Maak vergrotinginstellings toe"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Sleep hoek om grootte te verander"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Laat diagonale rollees toe"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Verander grootte"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Maak <xliff:g id="APPNAME">%1$s</xliff:g> oop"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Om die Wallet-app as ’n kortpad by te voeg, moet jy seker maak dat die app geïnstalleer is"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Om die Wallet-app as ’n kortpad by te voeg, moet jy seker maak dat minstens een kaart bygevoeg is"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Om die QR-kodeskandeerder as ’n kortpad by te voeg, moet jy seker maak dat ’n kamera-app geïnstalleer is"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Om die Home-app as ’n kortpad by te voeg, moet jy seker maak dat die app geïnstalleer is"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Minstens een toestel beskikbaar is"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Kies ’n versteknotasapp om die notaneemkortpad te gebruik"</string>
diff --git a/packages/SystemUI/res/values-am/strings.xml b/packages/SystemUI/res/values-am/strings.xml
index 0fd3f11..63f1765 100644
--- a/packages/SystemUI/res/values-am/strings.xml
+++ b/packages/SystemUI/res/values-am/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> ገደብ"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"የ<xliff:g id="DATA_LIMIT">%s</xliff:g> ማስጠንቀቂያ"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"የሥራ መተግበሪያዎች"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"ባለበት ቆሟል"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"የምሽት ብርሃን"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"ፀሐይ ስትጠልቅ ይበራል"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"ፀሐይ እስክትወጣ ድረስ"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"የማያ ገጹን ክፍል አጉላ"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"የማጉያ ቅንብሮችን ክፈት"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"የማጉላት ቅንብሮችን ዝጋ"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"መጠን ለመቀየር ጠርዙን ይዘው ይጎትቱ"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"ሰያፍ ሽብለላን ፍቀድ"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"መጠን ቀይር"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> ይክፈቱ"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"የWallet መተግበሪያን እንደ አቋራጭ ለማከል መተግበሪያው መጫኑን ያረጋግጡ"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"የWallet መተግበሪያን እንደ አቋራጭ ለማከል ቢያንስ አንድ ካርድ መታከሉን ያረጋግጡ"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"የQR ኮድ መቃኛውን እንደ አቋራጭ ለማከል የካሜራ መተግበሪያ መጫኑን ያረጋግጡ"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"የHome መተግበሪያውን እንደ አቋራጭ ለማከል መተግበሪያው እንደተጫነ ያረጋግጡ"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• ቢያንስ አንድ መሣሪያ ይገኛል"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"የማስታወሻ አያያዝ አቋራጭን ለመጠቀም ነባሪ የማስታወሻ መተግበሪያ ይምረጡ"</string>
diff --git a/packages/SystemUI/res/values-ar/strings.xml b/packages/SystemUI/res/values-ar/strings.xml
index bb99e2c..8128fae 100644
--- a/packages/SystemUI/res/values-ar/strings.xml
+++ b/packages/SystemUI/res/values-ar/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"قيد <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"تحذير <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"تطبيقات العمل"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"متوقّف مؤقَّتًا"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"الإضاءة الليلية"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"تفعيل عند غروب الشمس"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"حتى شروق الشمس"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"تكبير جزء من الشاشة"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"فتح إعدادات التكبير"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"إغلاق إعدادات التكبير"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"اسحب الزاوية لتغيير الحجم."</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"السماح بالتمرير القطري"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"تغيير الحجم"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"فتح \"<xliff:g id="APPNAME">%1$s</xliff:g>\""</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"‏لإضافة تطبيق \"محفظة Google\" كاختصار، تأكَّد من أنّ التطبيق مثبَّت."</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"‏لإضافة تطبيق \"محفظة Google\" كاختصار، تأكَّد من إضافة بطاقة واحدة على الأقل."</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"لإضافة تطبيق الماسح الضوئي لرمز الاستجابة السريعة كاختصار، تأكَّد من أنّ تطبيق الكاميرا مثبَّت."</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"‏لإضافة تطبيق Home كاختصار، تأكَّد من أنّ التطبيق مثبَّت."</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• توفُّر جهاز واحد على الأقل"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"اختَر تطبيقًا تلقائيًا لتدوين الملاحظات لاستخدام اختصار تدوين الملاحظات."</string>
diff --git a/packages/SystemUI/res/values-as/strings.xml b/packages/SystemUI/res/values-as/strings.xml
index d52301c..4915257 100644
--- a/packages/SystemUI/res/values-as/strings.xml
+++ b/packages/SystemUI/res/values-as/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> সীমা"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> সকীয়নি"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"কৰ্মস্থানৰ এপ্‌"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"পজ হৈ আছে"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"ৰাতিৰ পোহৰ"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"সূৰ্যাস্তত অন কৰক"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"সূৰ্যোদয়ৰ লৈকে"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"স্ক্ৰীনৰ কিছু অংশ বিবৰ্ধন কৰক"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"বিবৰ্ধন কৰাৰ ছেটিং খোলক"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"বিবৰ্ধনৰ ছেটিং বন্ধ কৰক"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"আকাৰ সলনি কৰিবলৈ চুককেইটা টানি আনি এৰক"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"কোণীয়াকৈ স্ক্ৰ’ল কৰাৰ অনুমতি দিয়ক"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"আকাৰ সলনি কৰক"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> খোলক"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet এপ্‌টোক এটা শ্বৰ্টকাট হিচাপে যোগ দিবলৈ, এপ্‌টো ইনষ্টল কৰি থোৱাটো নিশ্চিত কৰক"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet এপ্‌টোক এটা শ্বৰ্টকাট হিচাপে যোগ দিবলৈ, কমেও এখন কাৰ্ড যোগ দিয়াটো নিশ্চিত কৰক"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"কিউআৰ ক’ড স্কেনাৰক এটা শ্বৰ্টকাট হিচাপে যোগ দিবলৈ, কেমেৰা এপ্‌টো ইনষ্টল কৰি থোৱাটো নিশ্চিত কৰক"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home এপ্‌টোক এটা শ্বৰ্টকাট হিচাপে যোগ দিবলৈ, এপ্‌টো ইনষ্টল কৰি থোৱাটো নিশ্চিত কৰক"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• অতি কমেও এটা ডিভাইচ উপলব্ধ"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"টোকা গ্ৰহণৰ শ্বৰ্টকাটটো ব্যৱহাৰ কৰিবলৈ এটা ডিফ’ল্ট টোকা গ্ৰহণৰ এপ্‌ বাছনি কৰক"</string>
diff --git a/packages/SystemUI/res/values-az/strings.xml b/packages/SystemUI/res/values-az/strings.xml
index 85220a6..8d9fcbd 100644
--- a/packages/SystemUI/res/values-az/strings.xml
+++ b/packages/SystemUI/res/values-az/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> limit"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> xəbərdarlığı"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"İş tətbiqləri"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Durdurulub"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Gecə işığı"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Qürubda aktiv ediləcək"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Şəfəq vaxtına qədər"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Ekran hissəsinin böyüdülməsi"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Böyütmə ayarlarını açın"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Böyütmə ayarlarını bağlayın"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Ölçüsünü dəyişmək üçün küncündən sürüşdürün"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Diaqonal sürüşdürməyə icazə verin"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Ölçüsünü dəyişin"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> tətbiqini açın"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Pulqabı tətbiqini qısayol kimi əlavə etmək üçün tətbiq quraşdırılmalıdır"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Pulqabı tətbiqini qısayol kimi əlavə etmək üçün kart əlavə edilməlidir"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR kod skanerini qısayol kimi əlavə etmək üçün kamera tətbiqi quraşdırılmalıdır"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home tətbiqini qısayol kimi əlavə etmək üçün tətbiq quraşdırılmalıdır"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Ən azı bir cihaz əlçatandır"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Qeydgötürmə qısayolu üçün defolt qeyd tətbiqi seçin"</string>
diff --git a/packages/SystemUI/res/values-b+sr+Latn/strings.xml b/packages/SystemUI/res/values-b+sr+Latn/strings.xml
index 3790300..e1bd89d 100644
--- a/packages/SystemUI/res/values-b+sr+Latn/strings.xml
+++ b/packages/SystemUI/res/values-b+sr+Latn/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Ograničenje od <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Upozorenje za <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Poslovne aplikacije"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pauzirano"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Noćno svetlo"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Uključuje se po zalasku sunca"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Do izlaska sunca"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Uvećajte deo ekrana"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Otvori podešavanja uvećanja"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Zatvori podešavanja uvećanja"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Zatvori režim izmene"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Prevucite ugao da biste promenili veličinu"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Dozvoli dijagonalno skrolovanje"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Promeni veličinu"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Otvorite: <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Da biste dodali aplikaciju Novčanik kao prečicu, uverite se da je aplikacija instalirana"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Da biste dodali aplikaciju Novčanik kao prečicu, uverite se da je dodata bar jedna kartica"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Da biste dodali Skener QR koda kao prečicu, uverite se da je aplikacija za kameru instalirana"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Da biste dodali aplikaciju Home kao prečicu, uverite se da je aplikacija instalirana"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Dostupan je bar jedan uređaj"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Izaberite podrazumevanu aplikaciju za beleške da biste koristili prečicu za pravljenje beleški"</string>
diff --git a/packages/SystemUI/res/values-be/strings.xml b/packages/SystemUI/res/values-be/strings.xml
index def25b4..5d1b65c 100644
--- a/packages/SystemUI/res/values-be/strings.xml
+++ b/packages/SystemUI/res/values-be/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Ліміт <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Папярэджанне: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Працоўныя праграмы"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Профіль прыпынены"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Начная падсветка"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Уключаць увечары"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Да ўсходу сонца"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Павялічыць частку экрана"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Адкрыць налады павелічэння"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Закрыць налады павелічэння"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Каб змяніць памер, перацягніце вугал"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Дазволіць прагортванне па дыяганалі"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Змяніць памер"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Адкрыць праграму \"<xliff:g id="APPNAME">%1$s</xliff:g>\""</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Вы можаце дадаць ярлык праграмы \"Кашалёк\", толькі калі яна ўсталявана"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Вы можаце дадаць ярлык праграмы \"Кашалёк\", толькі калі дададзена хаця б адна картка"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Вы можаце дадаць ярлык сканера QR-кодаў, толькі калі ўсталявана праграма камеры"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Вы можаце дадаць ярлык праграмы Home, толькі калі яна ўсталявана"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Даступная хаця б адна прылада"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Выберыце стандартную праграму для нататак, якая будзе адкрывацца пры націсканні на ярлык"</string>
diff --git a/packages/SystemUI/res/values-bg/strings.xml b/packages/SystemUI/res/values-bg/strings.xml
index 224ff1f..94ab2c9 100644
--- a/packages/SystemUI/res/values-bg/strings.xml
+++ b/packages/SystemUI/res/values-bg/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Ограничение от <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Предупреждение: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Служебни приложения"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"На пауза"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Нощно осветление"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Ще се вкл. по залез"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"До изгрев"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Увеличаване на част от екрана"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Отваряне на настройките за увеличението"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Затваряне на настройките за увеличение"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Изход от режима на редактиране"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Плъзнете ъгъла за преоразмеряване"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Разрешаване на диагонално превъртане"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Преоразмеряване"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Отваряне на <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"За да добавите пряк път към приложението Wallet, уверете се, че то е инсталирано"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"За да добавите пряк път към приложението Wallet, уверете се, че е добавена поне една карта"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"За да добавите пряк път към скенера за QR кодове, уверете се, че е инсталирано приложение за камера"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"За да добавите пряк път към приложението Home, уверете се, че то е инсталирано"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Налице е поне едно устройство."</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Изберете стандартно приложение за бележки, за да използвате прекия път за водене на бележки"</string>
diff --git a/packages/SystemUI/res/values-bn/strings.xml b/packages/SystemUI/res/values-bn/strings.xml
index aca0931..f80c301 100644
--- a/packages/SystemUI/res/values-bn/strings.xml
+++ b/packages/SystemUI/res/values-bn/strings.xml
@@ -295,6 +295,8 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"সীমা <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> সতর্কতা"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"অফিসের অ্যাপ"</string>
+    <!-- no translation found for quick_settings_work_mode_paused_state (6681788236383735976) -->
+    <skip />
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"নাইট লাইট"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"সূর্যাস্তে চালু হবে"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"সূর্যোদয় পর্যন্ত"</string>
@@ -864,6 +866,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"স্ক্রিনের কিছুটা অংশ বড় করুন"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"বড় করে দেখার সেটিংস খুলুন"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"\'বড় করে দেখা\' সেটিংস বন্ধ করুন"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"ছোট বড় করার জন্য কোণ টেনে আনুন"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"কোনাকুনি স্ক্রল করার অনুমতি দেওয়া"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"ছোট বড় করা"</string>
@@ -1133,7 +1137,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> খুলুন"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet অ্যাপ, শর্টকাট হিসেবে যোগ করতে, অ্যাপ ইনস্টল করা আছে কিনা তা ভালভাবে দেখে নিন"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet অ্যাপ, শর্টকাট হিসেবে যোগ করতে, অন্তত একটি কার্ড যোগ করা হয়েছে কিনা তা ভালভাবে দেখে নিন"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR কোড স্ক্যানার, শর্টকাট হিসেবে যোগ করতে, ক্যামেরা অ্যাপ ইনস্টল করা আছে কিনা তা ভালভাবে দেখে নিন"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home অ্যাপ, শর্টকাট হিসেবে যোগ করতে, অ্যাপ ইনস্টল করা আছে কিনা তা ভালভাবে দেখে নিন"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• অন্তত একটি ডিভাইস উপলভ্য আছে"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"নোট নেওয়ার শর্টকাট ব্যবহার করতে, ডিফল্ট কোনও নোট অ্যাপ বেছে নিন"</string>
diff --git a/packages/SystemUI/res/values-bs/strings.xml b/packages/SystemUI/res/values-bs/strings.xml
index 1e4588d..364e847 100644
--- a/packages/SystemUI/res/values-bs/strings.xml
+++ b/packages/SystemUI/res/values-bs/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Ograničenje <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Upozorenje <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Poslovne aplikacije"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pauzirano"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Noćno svjetlo"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Uključuje se u sumrak"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Do svitanja"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Uvećavanje dijela ekrana"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Otvori postavke uvećavanja"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Zatvori postavke uvećavanja"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Izađi iz načina rada za uređivanje"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Prevucite ugao da promijenite veličinu"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Dozvoli dijagonalno klizanje"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Promijeni veličinu"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Otvori aplikaciju <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Da dodate aplikaciju Novčanik kao prečicu, instalirajte aplikaciju"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Da dodate aplikaciju Novčanik kao prečicu, dodajte barem jednu karticu"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Da dodate skener QR koda kao prečicu, instalirajte aplikaciju kamere"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Da dodate aplikaciju Home kao prečicu, instalirajte aplikaciju"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Dostupan je najmanje jedan uređaj"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Odaberite zadanu aplikaciju za bilješke da koristite prečicu za zapisivanje bilješki"</string>
diff --git a/packages/SystemUI/res/values-ca/strings.xml b/packages/SystemUI/res/values-ca/strings.xml
index a25cda6..557a7e6 100644
--- a/packages/SystemUI/res/values-ca/strings.xml
+++ b/packages/SystemUI/res/values-ca/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Límit: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Advertiment: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Aplicacions de treball"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"En pausa"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Llum nocturna"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Al vespre"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Fins a l\'alba"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Amplia una part de la pantalla"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Obre la configuració de l\'ampliació"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Tanca la configuració de l\'ampliació"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Arrossega el cantó per canviar la mida"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Permet el desplaçament en diagonal"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Canvia la mida"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Obre <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Per afegir l\'aplicació Wallet com a drecera, assegura\'t que estigui instal·lada"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Per afegir l\'aplicació Wallet com a drecera, assegura\'t que s\'hagi afegit almenys una targeta"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Per afegir l\'escàner de codis QR com a drecera, assegura\'t que hi hagi una aplicació de càmera instal·lada"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Per afegir l\'aplicació Home com a drecera, assegura\'t que estigui instal·lada"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Almenys un dispositiu està disponible."</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Selecciona una aplicació de notes predeterminada per utilitzar la drecera de presa de notes"</string>
diff --git a/packages/SystemUI/res/values-cs/strings.xml b/packages/SystemUI/res/values-cs/strings.xml
index 638c26a..0a83c86 100644
--- a/packages/SystemUI/res/values-cs/strings.xml
+++ b/packages/SystemUI/res/values-cs/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limit: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Upozornění při <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Pracovní aplikace"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pozastaveno"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Noční režim"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Při soumraku"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Do svítání"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Zvětšit část obrazovky"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Otevřít nastavení zvětšení"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Zavřít nastavení zvětšení"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Ukončit režim úprav"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Velikost změníte přetažením rohu"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Povolit diagonální posouvání"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Změnit velikost"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Otevřít <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Pokud chcete přidat aplikaci Peněženka jako zkratku, nainstalujte ji"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Pokud chcete přidat aplikaci Peněženka jako zkratku, přidejte alespoň jednu kartu"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Pokud chcete přidat skener QR kódů jako zkratku, ujistěte se, že je nainstalována aplikace k focení a natáčení"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Pokud chcete přidat aplikaci Home jako zkratku, nainstalujte ji"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Je k dispozici alespoň jedno zařízení"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Vyberte výchozí aplikaci k psaní poznámek, ke které přidružíte zkratku pro poznámky"</string>
diff --git a/packages/SystemUI/res/values-da/strings.xml b/packages/SystemUI/res/values-da/strings.xml
index 663aac4..9ebbebb 100644
--- a/packages/SystemUI/res/values-da/strings.xml
+++ b/packages/SystemUI/res/values-da/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Grænse: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Advarsel ved <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Arbejdsapps"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Sat på pause"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Nattelys"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Tænd ved solnedgang"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Indtil solopgang"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Forstør en del af skærmen"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Åbn indstillinger for forstørrelse"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Luk indstillinger for forstørrelse"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Træk i hjørnet for at justere størrelsen"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Tillad diagonal rulning"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Juster"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Åbn <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Hvis du vil tilføje en genvej til Wallet-appen, skal du sørge for, at appen er installeret"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Hvis du vil tilføje en genvej til Wallet-appen, skal du sørge for, at du har tilføjet mindst ét kort"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Hvis du vil tilføje en genvej til QR-kodescanneren, skal du sørge for, at kameraappen er installeret"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Hvis du vil tilføje en genvej til Home-appen, skal du sørge for, at appen er installeret"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Mindst én enhed er tilgængelig"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Vælg en standardapp til noter for at bruge genvejen til notetagning"</string>
diff --git a/packages/SystemUI/res/values-de/strings.xml b/packages/SystemUI/res/values-de/strings.xml
index ead5001..206e832 100644
--- a/packages/SystemUI/res/values-de/strings.xml
+++ b/packages/SystemUI/res/values-de/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> Datenlimit"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Warnung für <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Geschäftliche Apps"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pausiert"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Nachtlicht"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"An bei Sonnenuntergang"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Bis Sonnenaufgang"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Teil des Bildschirms vergrößern"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Vergrößerungseinstellungen öffnen"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Vergrößerungseinstellungen schließen"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Zum Anpassen der Größe Ecke ziehen"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Diagonales Scrollen erlauben"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Größe ändern"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> öffnen"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Damit du die Wallet App als Verknüpfung hinzufügen kannst, muss die App installiert sein"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Damit du die Wallet App als Verknüpfung hinzufügen kannst, muss mindestens eine Karte hinzugefügt sein"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Damit du den QR-Code-Scanner als Verknüpfung hinzufügen kannst, muss eine Kamera-App installiert sein"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Damit du die Home App als Verknüpfung hinzufügen kannst, muss die App installiert sein"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Mindestens ein Gerät ist verfügbar"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Wähle eine Standard-App für Notizen aus, die du für die Verknüpfung verwenden möchtest"</string>
diff --git a/packages/SystemUI/res/values-el/strings.xml b/packages/SystemUI/res/values-el/strings.xml
index 7a74831..c32cd17 100644
--- a/packages/SystemUI/res/values-el/strings.xml
+++ b/packages/SystemUI/res/values-el/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Όριο <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Προειδοποίηση για <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Εφαρμογές εργασιών"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Σε παύση"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Νυχτερινός φωτισμός"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Κατά τη δύση"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Μέχρι την ανατολή"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Μεγέθυνση μέρους της οθόνης"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Άνοιγμα ρυθμίσεων μεγιστοποίησης"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Κλείσιμο ρυθμίσεων μεγιστοποίησης"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Σύρετε τη γωνία για αλλαγή μεγέθους"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Να επιτρέπεται η διαγώνια κύλιση"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Αλλαγή μεγέθους"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Άνοιγμα <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Για να προσθέσετε ως συντόμευση την εφαρμογή Πορτοφόλι, βεβαιωθείτε ότι έχει εγκατασταθεί η εφαρμογή"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Για να προσθέσετε ως συντόμευση την εφαρμογή Πορτοφόλι, βεβαιωθείτε ότι έχει προστεθεί τουλάχιστον μία κάρτα"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Για να προσθέσετε ως συντόμευση τη Σάρωση κωδικών QR, βεβαιωθείτε ότι η εφαρμογή κάμερας είναι εγκατεστημένη"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Για να προσθέσετε την εφαρμογή Home ως συντόμευση, βεβαιωθείτε ότι η εφαρμογή είναι εγκατεστημένη"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Είναι διαθέσιμη τουλάχιστον μία συσκευή"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Επιλέξτε μια προεπιλεγμένη εφαρμογή σημειώσεων για να χρησιμοποιήσετε τη συντόμευση δημιουργίας σημειώσεων"</string>
diff --git a/packages/SystemUI/res/values-en-rAU/strings.xml b/packages/SystemUI/res/values-en-rAU/strings.xml
index 5d713bb..313f617 100644
--- a/packages/SystemUI/res/values-en-rAU/strings.xml
+++ b/packages/SystemUI/res/values-en-rAU/strings.xml
@@ -295,6 +295,8 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> limit"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> warning"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Work apps"</string>
+    <!-- no translation found for quick_settings_work_mode_paused_state (6681788236383735976) -->
+    <skip />
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Night Light"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"On at sunset"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Until sunrise"</string>
@@ -864,6 +866,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Magnify part of screen"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Open magnification settings"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Close magnification settings"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Drag corner to resize"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Allow diagonal scrolling"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Resize"</string>
@@ -1133,7 +1137,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Open <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"To add the Wallet app as a shortcut, make sure that the app is installed"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"To add the Wallet app as a shortcut, make sure that at least one card has been added"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"To add the QR code scanner as a shortcut, make sure that a camera app is installed"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"To add the Home app as a shortcut, make sure that the app is installed"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• At least one device is available"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Select a default notes app to use the note-taking shortcut"</string>
@@ -1166,7 +1169,7 @@
     <string name="assistant_attention_content_description" msgid="6830215897604642875">"Assistant attention on"</string>
     <string name="set_default_notes_app_toast_content" msgid="2812374329662610753">"Set default notes app in Settings"</string>
     <string name="install_app" msgid="5066668100199613936">"Install app"</string>
-    <string name="privacy_dialog_title" msgid="7839968133469098311">"Microphone &amp; Camera"</string>
+    <string name="privacy_dialog_title" msgid="7839968133469098311">"Microphone and Camera"</string>
     <string name="privacy_dialog_summary" msgid="2458769652125995409">"Recent app use"</string>
     <string name="privacy_dialog_more_button" msgid="7610604080293562345">"See recent access"</string>
     <string name="privacy_dialog_done_button" msgid="4504330708531434263">"Done"</string>
diff --git a/packages/SystemUI/res/values-en-rCA/strings.xml b/packages/SystemUI/res/values-en-rCA/strings.xml
index 9d4a4fe..157570a 100644
--- a/packages/SystemUI/res/values-en-rCA/strings.xml
+++ b/packages/SystemUI/res/values-en-rCA/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> limit"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> warning"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Work apps"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Paused"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Night Light"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"On at sunset"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Until sunrise"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Magnify part of screen"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Open magnification settings"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Close magnification settings"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Exit edit mode"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Drag corner to resize"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Allow diagonal scrolling"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Resize"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Open <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"To add the Wallet app as a shortcut, make sure the app is installed"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"To add the Wallet app as a shortcut, make sure at least one card has been added"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"To add the QR code scanner as a shortcut, make sure a camera app is installed"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"To add the Home app as a shortcut, make sure the app is installed"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• At least one device is available"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Select a default notes app to use the notetaking shortcut"</string>
diff --git a/packages/SystemUI/res/values-en-rGB/strings.xml b/packages/SystemUI/res/values-en-rGB/strings.xml
index 5d713bb..313f617 100644
--- a/packages/SystemUI/res/values-en-rGB/strings.xml
+++ b/packages/SystemUI/res/values-en-rGB/strings.xml
@@ -295,6 +295,8 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> limit"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> warning"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Work apps"</string>
+    <!-- no translation found for quick_settings_work_mode_paused_state (6681788236383735976) -->
+    <skip />
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Night Light"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"On at sunset"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Until sunrise"</string>
@@ -864,6 +866,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Magnify part of screen"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Open magnification settings"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Close magnification settings"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Drag corner to resize"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Allow diagonal scrolling"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Resize"</string>
@@ -1133,7 +1137,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Open <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"To add the Wallet app as a shortcut, make sure that the app is installed"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"To add the Wallet app as a shortcut, make sure that at least one card has been added"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"To add the QR code scanner as a shortcut, make sure that a camera app is installed"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"To add the Home app as a shortcut, make sure that the app is installed"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• At least one device is available"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Select a default notes app to use the note-taking shortcut"</string>
@@ -1166,7 +1169,7 @@
     <string name="assistant_attention_content_description" msgid="6830215897604642875">"Assistant attention on"</string>
     <string name="set_default_notes_app_toast_content" msgid="2812374329662610753">"Set default notes app in Settings"</string>
     <string name="install_app" msgid="5066668100199613936">"Install app"</string>
-    <string name="privacy_dialog_title" msgid="7839968133469098311">"Microphone &amp; Camera"</string>
+    <string name="privacy_dialog_title" msgid="7839968133469098311">"Microphone and Camera"</string>
     <string name="privacy_dialog_summary" msgid="2458769652125995409">"Recent app use"</string>
     <string name="privacy_dialog_more_button" msgid="7610604080293562345">"See recent access"</string>
     <string name="privacy_dialog_done_button" msgid="4504330708531434263">"Done"</string>
diff --git a/packages/SystemUI/res/values-en-rIN/strings.xml b/packages/SystemUI/res/values-en-rIN/strings.xml
index 5d713bb..313f617 100644
--- a/packages/SystemUI/res/values-en-rIN/strings.xml
+++ b/packages/SystemUI/res/values-en-rIN/strings.xml
@@ -295,6 +295,8 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> limit"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> warning"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Work apps"</string>
+    <!-- no translation found for quick_settings_work_mode_paused_state (6681788236383735976) -->
+    <skip />
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Night Light"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"On at sunset"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Until sunrise"</string>
@@ -864,6 +866,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Magnify part of screen"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Open magnification settings"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Close magnification settings"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Drag corner to resize"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Allow diagonal scrolling"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Resize"</string>
@@ -1133,7 +1137,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Open <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"To add the Wallet app as a shortcut, make sure that the app is installed"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"To add the Wallet app as a shortcut, make sure that at least one card has been added"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"To add the QR code scanner as a shortcut, make sure that a camera app is installed"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"To add the Home app as a shortcut, make sure that the app is installed"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• At least one device is available"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Select a default notes app to use the note-taking shortcut"</string>
@@ -1166,7 +1169,7 @@
     <string name="assistant_attention_content_description" msgid="6830215897604642875">"Assistant attention on"</string>
     <string name="set_default_notes_app_toast_content" msgid="2812374329662610753">"Set default notes app in Settings"</string>
     <string name="install_app" msgid="5066668100199613936">"Install app"</string>
-    <string name="privacy_dialog_title" msgid="7839968133469098311">"Microphone &amp; Camera"</string>
+    <string name="privacy_dialog_title" msgid="7839968133469098311">"Microphone and Camera"</string>
     <string name="privacy_dialog_summary" msgid="2458769652125995409">"Recent app use"</string>
     <string name="privacy_dialog_more_button" msgid="7610604080293562345">"See recent access"</string>
     <string name="privacy_dialog_done_button" msgid="4504330708531434263">"Done"</string>
diff --git a/packages/SystemUI/res/values-en-rXC/strings.xml b/packages/SystemUI/res/values-en-rXC/strings.xml
index 6a172f0..db7133c 100644
--- a/packages/SystemUI/res/values-en-rXC/strings.xml
+++ b/packages/SystemUI/res/values-en-rXC/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‎‎‎‏‏‎‏‏‏‎‎‎‏‎‎‏‎‏‏‎‏‎‏‏‎‏‏‏‏‎‎‏‎‏‏‎‎‏‎‏‎‎‏‎‏‏‎‏‏‎‎‏‏‏‎‏‏‎‎‎‎‏‎‎‏‏‎<xliff:g id="DATA_LIMIT">%s</xliff:g>‎‏‎‎‏‏‏‎ limit‎‏‎‎‏‎"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‏‏‏‎‎‏‏‎‏‏‎‏‏‏‎‏‏‎‎‎‎‎‏‎‏‏‏‎‎‏‏‎‏‎‎‏‎‏‎‏‏‎‎‏‎‎‏‏‏‏‏‏‏‏‏‏‎‏‏‏‎‎‏‎‎‏‏‎<xliff:g id="DATA_LIMIT">%s</xliff:g>‎‏‎‎‏‏‏‎ warning‎‏‎‎‏‎"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‏‎‎‏‎‏‏‎‎‎‎‏‎‏‎‏‏‏‎‏‎‏‎‎‏‎‎‎‎‏‎‏‎‎‏‎‏‎‎‎‎‎‏‎‎‎‏‎‎‏‎‎‎‏‏‎‎‎‎‏‎Work apps‎‏‎‎‏‎"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‏‏‎‎‏‎‏‏‏‎‏‎‎‏‏‏‏‎‏‎‏‏‏‏‏‏‏‏‏‏‎‏‎‏‏‎‎‎‎‎‏‎‎‏‎‏‎‏‎‎‎‎‏‎‏‎‏‎‎‎‎Paused‎‏‎‎‏‎"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‎‎‎‏‏‎‎‎‎‏‎‏‎‏‎‎‏‏‏‎‏‎‎‎‏‎‏‏‎‏‏‏‏‎‎‏‏‏‏‏‎‎‏‏‎‎‏‏‏‎‏‏‎‎‎‎‎‏‎‎‎Night Light‎‏‎‎‏‎"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‏‏‏‎‏‎‎‏‏‏‎‎‏‎‎‎‎‏‎‏‏‎‎‏‏‎‎‎‎‏‏‏‏‏‏‏‎‏‎‏‏‏‎‎‏‏‏‎‏‎‏‏‏‎‎‎‎‎‏‎‎On at sunset‎‏‎‎‏‎"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‏‎‎‎‎‏‏‎‎‏‎‎‎‏‎‎‎‏‎‎‏‎‏‏‎‎‎‎‎‏‎‎‏‎‏‏‎‎‎‎‎‎‎‎‎‎‏‎‎‎‎‎‏‏‎‏‎‏‎‏‎Until sunrise‎‏‎‎‏‎"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‎‏‏‏‎‏‎‎‏‏‏‏‎‎‎‎‏‎‎‏‎‎‏‎‎‎‎‎‏‎‏‎‏‎‏‏‎‏‏‏‏‎‏‎‎‎‎‏‏‏‏‏‎‎‏‎‎‏‎‏‎Magnify part of screen‎‏‎‎‏‎"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‎‏‎‏‎‏‎‏‏‏‏‏‏‏‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‎‏‏‏‎‎‎‏‎‎‏‎‏‏‏‎‎‎‏‏‏‎‎‎‏‎‎‎‏‏‎Open magnification settings‎‏‎‎‏‎"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‎‎‎‎‎‏‏‎‏‏‎‏‎‏‏‎‎‏‎‎‎‏‏‏‏‎‎‎‏‎‏‏‏‏‏‎‏‏‏‏‏‎‎‏‎‎‏‏‎‎‎‎‏‏‎‎‎‏‎‏‎Close magnification settings‎‏‎‎‏‎"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‎‏‏‏‎‎‎‏‏‎‏‎‏‎‎‏‏‏‏‏‎‏‏‏‎‎‏‎‎‎‏‏‎‏‎‏‏‏‎‏‎‎‏‎‎‏‎‏‏‏‏‏‎‏‎‎‏‏‎‏‎Exit edit mode‎‏‎‎‏‎"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‎‎‎‏‎‏‎‏‏‎‎‎‎‎‎‎‏‏‏‏‏‏‎‏‎‏‏‎‏‎‎‏‏‏‏‎‏‎‎‎‎‏‏‏‏‎‎‏‏‏‎‎‎‏‎‏‎‎‏‎‎Drag corner to resize‎‏‎‎‏‎"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‏‏‎‏‎‎‏‏‎‏‏‎‏‏‏‎‏‎‏‏‏‎‎‎‎‏‏‏‏‏‎‏‏‎‏‏‏‏‏‎‎‏‎‏‏‎‎‎‎‎‏‎‏‏‎‎‏‏‏‎‎Allow diagonal scrolling‎‏‎‎‏‎"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‏‏‏‏‏‎‎‏‎‎‏‎‎‏‏‎‎‏‏‏‏‎‎‎‏‏‏‎‎‏‎‏‎‏‎‎‏‎‏‏‏‎‏‎‏‏‎‏‏‎‏‎‏‏‎‏‏‏‏‏‎Resize‎‏‎‎‏‎"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‎‎‎‏‎‏‎‎‏‏‏‏‎‏‏‎‎‏‏‎‏‏‏‏‎‏‏‏‏‎‎‏‎‏‏‏‏‏‎‏‎‏‎‏‏‎‏‎‎‏‎‎‎‎‏‎‏‎‎‎‎Open ‎‏‎‎‏‏‎<xliff:g id="APPNAME">%1$s</xliff:g>‎‏‎‎‏‏‏‎‎‏‎‎‏‎"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‎‏‎‏‎‏‎‎‏‎‎‏‏‎‏‎‏‎‏‏‎‎‏‏‎‎‏‏‏‏‎‎‎‏‏‏‎‏‎‏‏‏‏‏‏‎‎‎‏‎‎‏‏‎‏‏‎‎‎‎‎To add the Wallet app as a shortcut, make sure the app is installed‎‏‎‎‏‎"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‏‏‎‎‏‏‏‎‎‎‏‏‎‏‎‎‏‎‏‏‎‏‏‎‎‏‎‎‏‎‎‏‏‎‎‏‎‏‎‎‏‏‏‎‏‎‎‏‏‎‏‎‎‏‏‎‏‎‏‎‎To add the Wallet app as a shortcut, make sure at least one card has been added‎‏‎‎‏‎"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‏‎‏‎‎‏‎‏‎‎‏‎‎‏‎‎‏‎‏‎‏‏‏‏‎‎‏‏‎‎‏‏‏‏‎‎‏‏‎‏‎‎‎‏‏‏‏‏‏‏‏‏‏‏‏‎‎‎‏‎‎To add the QR code scanner as a shortcut, make sure a camera app is installed‎‏‎‎‏‎"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‎‏‎‏‏‏‎‏‏‏‏‏‏‎‎‎‏‏‏‎‎‎‏‏‎‏‏‎‏‏‎‎‏‎‎‏‏‏‏‏‏‎‏‏‏‎‏‏‏‎‎‎‎‏‎‏‏‎‎‎‎To add the Home app as a shortcut, make sure the app is installed‎‏‎‎‏‎"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‏‏‏‎‎‏‏‎‎‎‎‎‏‏‎‏‏‎‎‎‏‏‎‏‏‏‏‎‎‎‏‏‎‎‏‎‎‏‎‏‎‏‏‎‎‏‏‎‎‎‎‎‎‏‏‎‎‏‏‏‎• At least one device is available‎‏‎‎‏‎"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‎‎‏‎‏‎‎‏‎‎‏‎‎‎‏‏‎‏‎‏‎‏‎‎‏‏‎‏‏‏‎‏‏‎‏‎‏‎‏‎‎‏‏‏‏‎‏‏‏‎‎‏‎‏‏‎‎‎‏‎‎Select a default notes app to use the notetaking shortcut‎‏‎‎‏‎"</string>
diff --git a/packages/SystemUI/res/values-es-rUS/strings.xml b/packages/SystemUI/res/values-es-rUS/strings.xml
index 4d0ed14..23d2edc 100644
--- a/packages/SystemUI/res/values-es-rUS/strings.xml
+++ b/packages/SystemUI/res/values-es-rUS/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Límite de <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Advertencia de <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Apps de trabajo"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"En pausa"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Luz nocturna"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Al atardecer"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Hasta el amanecer"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Ampliar parte de la pantalla"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Abrir la configuración de ampliación"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Cerrar configuración de ampliación"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Salir del modo de edición"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Arrastra la esquina para cambiar el tamaño"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Desplazamiento en diagonal"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Cambiar tamaño"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Abrir <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Para agregar la app de Billetera como acceso directo, asegúrate de haber instalado la app"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Para agregar la app de Billetera como acceso directo, asegúrate de haber agregado al menos una tarjeta"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Para agregar el escáner de código QR como acceso directo, asegúrate de haber instalado la app de la cámara"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Para agregar la app de Home como acceso directo, asegúrate de haber instalado la app"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Hay al menos un dispositivo disponible"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Selecciona una app de notas predeterminada para usar el acceso directo de toma de notas"</string>
diff --git a/packages/SystemUI/res/values-es/strings.xml b/packages/SystemUI/res/values-es/strings.xml
index 953171a..1eb0abc 100644
--- a/packages/SystemUI/res/values-es/strings.xml
+++ b/packages/SystemUI/res/values-es/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Límite de <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Advertencia de <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Aplicaciones de trabajo"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"En pausa"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Luz nocturna"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Al atardecer"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Hasta el amanecer"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Ampliar parte de la pantalla"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Abrir ajustes de ampliación"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Cerrar ajustes de ampliación"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Arrastra la esquina para cambiar el tamaño"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Permitir ir en diagonal"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Cambiar tamaño"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Abrir <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Para añadir la aplicación Wallet como acceso directo, asegúrate de que está instalada"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Para añadir la aplicación Wallet como acceso directo, asegúrate de haber añadido al menos una tarjeta"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Para añadir el escáner de códigos QR como acceso directo, asegúrate de que hay instalada una aplicación de cámara"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Para añadir la aplicación Home como acceso directo, asegúrate de que está instalada"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Al menos un dispositivo debe estar disponible"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Selecciona una aplicación de notas predeterminada para usar el acceso directo de toma de notas"</string>
diff --git a/packages/SystemUI/res/values-et/strings.xml b/packages/SystemUI/res/values-et/strings.xml
index 1e7bbf4..3881635 100644
--- a/packages/SystemUI/res/values-et/strings.xml
+++ b/packages/SystemUI/res/values-et/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limiit: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> hoiatus"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Töörakendused"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Peatatud"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Öövalgus"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Sissel. päikeselooj."</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Kuni päikesetõusuni"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Ekraanikuva osa suurendamine"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Ava suurendamisseaded"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Sule suurendamisseaded"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Suuruse muutmiseks lohistage nurka"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Luba diagonaalne kerimine"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Muuda suurust"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Ava <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Rahakotirakenduse otsetee lisamiseks veenduge, et rakendus oleks installitud"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Rahakotirakenduse otsetee lisamiseks veenduge, et vähemalt üks kaart oleks lisatud"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR-koodi skanneri otsetee lisamiseks veenduge, et kaamerarakendus oleks installitud"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Rakenduse Home otsetee lisamiseks veenduge, et rakendus oleks installitud"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Vähemalt üks seade on saadaval"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Valige märkmete tegemise vaikerakendus, et kasutada märkmete tegemise otseteed"</string>
@@ -1167,7 +1169,7 @@
     <string name="set_default_notes_app_toast_content" msgid="2812374329662610753">"Määrake seadetes märkmete vaikerakendus."</string>
     <string name="install_app" msgid="5066668100199613936">"Installi rakendus"</string>
     <string name="privacy_dialog_title" msgid="7839968133469098311">"Mikrofon ja kaamera"</string>
-    <string name="privacy_dialog_summary" msgid="2458769652125995409">"Rakenduse hiljutine kasutamine"</string>
+    <string name="privacy_dialog_summary" msgid="2458769652125995409">"Rakenduste hiljutine kasutamine"</string>
     <string name="privacy_dialog_more_button" msgid="7610604080293562345">"Kuva hiljutine juurdepääs"</string>
     <string name="privacy_dialog_done_button" msgid="4504330708531434263">"Valmis"</string>
     <string name="privacy_dialog_expand_action" msgid="9129262348628331377">"Laiendamine ja valikute kuvamine"</string>
diff --git a/packages/SystemUI/res/values-eu/strings.xml b/packages/SystemUI/res/values-eu/strings.xml
index 3ce64b2..0121abc 100644
--- a/packages/SystemUI/res/values-eu/strings.xml
+++ b/packages/SystemUI/res/values-eu/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Muga: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Abisua: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Laneko aplikazioak"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pausatuta"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Gaueko argia"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Ilunabarrean"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Ilunabarrera arte"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Handitu pantailaren zati bat"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Ireki luparen ezarpenak"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Itxi luparen ezarpenak"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Arrastatu izkina bat tamaina aldatzeko"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Eman diagonalki gora eta behera egiteko aukera erabiltzeko baimena"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Aldatu tamaina"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Ireki <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Diru-zorroa aplikazioa lasterbide gisa gehitzeko, ziurtatu aplikazioa instalatuta dagoela."</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Diru-zorroa aplikazioa lasterbide gisa gehitzeko, ziurtatu gutxienez txartel bat gehitu dela."</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR kodeen eskanerra lasterbide gisa gehitzeko, ziurtatu kameraren aplikazioa instalatuta dagoela."</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home aplikazioa lasterbide gisa gehitzeko, ziurtatu aplikazioa instalatuta dagoela."</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Gutxienez gailu bat erabilgarri dago."</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Oharrak idazteko lasterbidea erabiltzeko, hautatu oharretarako aplikazio lehenetsia."</string>
diff --git a/packages/SystemUI/res/values-fa/strings.xml b/packages/SystemUI/res/values-fa/strings.xml
index 33bd9f4..a22f6da 100644
--- a/packages/SystemUI/res/values-fa/strings.xml
+++ b/packages/SystemUI/res/values-fa/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> محدودیت"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"هشدار <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"برنامه‌های کاری"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"موقتاً متوقف شد"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"نور شب"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"غروب روشن می‌شود"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"تا طلوع"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"درشت‌نمایی بخشی از صفحه"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"باز کردن تنظیمات درشت‌نمایی"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"بستن تنظیمات درشت‌نمایی"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"برای تغییر اندازه، گوشه را بکشید"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"اجازه دادن برای پیمایش قطری"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"تغییر اندازه"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"باز کردن <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"برای افزودن برنامه «کیف پول» به‌عنوان میان‌بر، مطمئن شوید این برنامه نصب شده باشد"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"برای افزودن برنامه «کیف پول» به‌عنوان میان‌بر، مطمئن شوید حداقل یک کارت اضافه شده باشد"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"برای افزودن «کدخوان پاسخ‌سریع» به‌عنوان میان‌بر، مطمئن شوید برنامه دوربین نصب شده باشد"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"‏برای افزودن برنامه Home به‌عنوان میان‌بر، مطمئن شوید این برنامه نصب شده باشد"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• حداقل یک دستگاه دردسترس باشد"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"برای استفاده از میان‌بر یادداشت‌برداری، برنامه یادداشت پیش‌فرضی را انتخاب کنید"</string>
diff --git a/packages/SystemUI/res/values-fi/strings.xml b/packages/SystemUI/res/values-fi/strings.xml
index 6da1262..d87f2f6 100644
--- a/packages/SystemUI/res/values-fi/strings.xml
+++ b/packages/SystemUI/res/values-fi/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"kiintiö <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> – varoitus"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Työsovellukset"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Keskeytetty"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Yövalo"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Auringon laskiessa"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Auringonnousuun"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Suurenna osa näytöstä"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Avaa suurennusasetukset"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Sulje suurennusasetukset"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Muuta kokoa vetämällä kulmaa"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Salli diagonaalinen vierittäminen"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Muuta kokoa"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Avaa <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Jos haluat lisätä Wallet-sovelluksen pikakuvakkeena, varmista, että se on asennettuna"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Jos haluat lisätä Wallet-sovelluksen pikakuvakkeena, varmista, että lisättynä on vähintään yksi kortti"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Jos haluat lisätä QR-koodiskannerin pikakuvakkeena, varmista, että kamerasovellus on asennettuna"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Jos haluat lisätä Home-sovelluksen pikakuvakkeena, varmista, että se on asennettuna"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Ainakin yksi laite on käytettävissä"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Valitse muistiinpanojen tekemisen oletussovellus, jota käytetään pikakuvakkeen avulla"</string>
diff --git a/packages/SystemUI/res/values-fr-rCA/strings.xml b/packages/SystemUI/res/values-fr-rCA/strings.xml
index 2f8fcfb..1c6b508 100644
--- a/packages/SystemUI/res/values-fr-rCA/strings.xml
+++ b/packages/SystemUI/res/values-fr-rCA/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limite : <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Avertissement : <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Applications professionnelles"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"En pause"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Éclairage nocturne"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Activé la nuit"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Jusqu\'à l\'aube"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Agrandir une partie de l\'écran"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Ouvrir les paramètres d\'agrandissement"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Fermer les paramètres d\'agrandissement"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Faire glisser le coin pour redimensionner"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Autoriser défilement diagonal"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Redimensionner"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Ouvrir <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Pour ajouter l\'application portefeuille sous forme de raccourci, assurez-vous que l\'application est installée"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Pour ajouter l\'application Portefeuille sous forme de raccourci, assurez-vous qu\'au moins une carte a été ajoutée"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Pour ajouter le numériseur de code QR sous forme de raccourci, assurez-vous qu\'une application d\'appareil photo est installée"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Pour ajouter l\'application Home sous forme de raccourci, assurez-vous que l\'application est installée"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• qu\'au moins un appareil est utilisable;"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Sélectionnez une application de prise de notes par défaut pour utiliser le raccourci de prise de notes"</string>
diff --git a/packages/SystemUI/res/values-fr/strings.xml b/packages/SystemUI/res/values-fr/strings.xml
index 3a77d37..420fd85 100644
--- a/packages/SystemUI/res/values-fr/strings.xml
+++ b/packages/SystemUI/res/values-fr/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> au maximum"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Avertissement : <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Applis pro"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"En pause"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Éclairage nocturne"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Activé la nuit"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Jusqu\'à l\'aube"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Agrandir une partie de l\'écran"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Ouvrir les paramètres d\'agrandissement"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Fermer les paramètres d\'agrandissement"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Faire glisser le coin pour redimensionner"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Autoriser le défilement diagonal"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Redimensionner"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Ouvrir <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Pour ajouter l\'appli Wallet comme raccourci, vérifiez que l\'appli est installée"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Pour ajouter l\'appli Wallet comme raccourci, assurez-vous qu\'au moins une carte a été ajoutée"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Pour ajouter le lecteur de code QR comme raccourci, assurez-vous qu\'une appli d\'appareil photo est installée"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Pour ajouter l\'application Home comme raccourci, vérifiez que l\'appli est installée"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Au moins un appareil est disponible"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Sélectionnez une appli de notes par défaut pour utiliser le raccourci de prise de notes"</string>
diff --git a/packages/SystemUI/res/values-gl/strings.xml b/packages/SystemUI/res/values-gl/strings.xml
index 6390dc8..3389dd8 100644
--- a/packages/SystemUI/res/values-gl/strings.xml
+++ b/packages/SystemUI/res/values-gl/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Límite de <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Advertencia <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Aplicacións do traballo"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"En pausa"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Luz nocturna"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Activación ao solpor"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Ata o amencer"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Amplía parte da pantalla"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Abrir configuración da ampliación"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Pechar configuración de ampliación"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Arrastrar a esquina para cambiar o tamaño"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Permitir desprazamento diagonal"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Cambiar tamaño"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Abrir <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Para engadir a aplicación Wallet como atallo, asegúrate de que estea instalada"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Para engadir a aplicación Wallet como atallo, asegúrate de que se incluíse polo menos unha tarxeta"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Para engadir o escáner de códigos QR como atallo, asegúrate de que a aplicación de cámara estea instalada"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Para engadir a aplicación Google Home como atallo, asegúrate de que estea instalada"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Ten que haber polo menos un dispositivo dispoñible"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Selecciona unha aplicación de notas predeterminada para usar o atallo de tomar notas"</string>
diff --git a/packages/SystemUI/res/values-gu/strings.xml b/packages/SystemUI/res/values-gu/strings.xml
index 6a4fa7f..92ab77f 100644
--- a/packages/SystemUI/res/values-gu/strings.xml
+++ b/packages/SystemUI/res/values-gu/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> મર્યાદા"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> ચેતવણી"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"ઑફિસ માટેની ઍપ"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"થોભાવ્યું"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"રાત્રિ પ્રકાશ"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"સૂર્યાસ્ત વખતે"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"સૂર્યોદય સુધી"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"સ્ક્રીનનો કોઈ ભાગ મોટો કરો"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"મોટા કરવાના સેટિંગ ખોલો"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"મોટા કરવાના સેટિંગ બંધ કરો"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"કદ બદલવા માટે ખૂણો ખેંચો"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"ડાયગોનલ સ્ક્રોલિંગને મંજૂરી આપો"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"કદ બદલો"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> ખોલો"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet ઍપને શૉર્ટકટ તરીકે ઉમેરવા માટે, ખાતરી કરો કે ઍપ ઇન્સ્ટૉલ કરેલી હોય"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet ઍપને શૉર્ટકટ તરીકે ઉમેરવા માટે, ખાતરી કરો કે ઓછામાં ઓછું એક કાર્ડ ઉમેરવામાં આવ્યું હોય"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR કોડ સ્કૅનરને શૉર્ટકટ તરીકે ઉમેરવા માટે, ખાતરી કરો કે કૅમેરા ઍપ ઇન્સ્ટૉલ કરેલી હોય"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home ઍપને શૉર્ટકટ તરીકે ઉમેરવા માટે, ખાતરી કરો કે ઍપ ઇન્સ્ટૉલ કરેલી હોય"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• ઓછામાં ઓછું એક ડિવાઇસ ઉપલબ્ધ છે"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"નોંધ લેવાના શૉર્ટકટનો ઉપયોગ કરવા માટે, નોંધ માટેની ડિફૉલ્ટ ઍપ પસંદ કરો"</string>
diff --git a/packages/SystemUI/res/values-hi/strings.xml b/packages/SystemUI/res/values-hi/strings.xml
index 091dd75..29f80aa 100644
--- a/packages/SystemUI/res/values-hi/strings.xml
+++ b/packages/SystemUI/res/values-hi/strings.xml
@@ -295,6 +295,8 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> सीमा"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> चेतावनी"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"वर्क ऐप्लिकेशन"</string>
+    <!-- no translation found for quick_settings_work_mode_paused_state (6681788236383735976) -->
+    <skip />
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"नाइट लाइट"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"शाम को चालू की जाएगी"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"सुबह तक चालू रहेगी"</string>
@@ -864,6 +866,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"स्क्रीन के किसी हिस्से को ज़ूम करें"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"ज़ूम करने की सुविधा वाली सेटिंग खोलें"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"ज़ूम करने की सुविधा वाली सेटिंग को बंद करें"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"साइज़ बदलने के लिए, कोने को खींचें और छोड़ें"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"तिरछी दिशा में स्क्रोल करने की अनुमति दें"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"साइज़ बदलें"</string>
@@ -1133,7 +1137,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> खोलें"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet ऐप्लिकेशन को शॉर्टकट के तौर पर जोड़ने के लिए, पक्का करें कि ऐप्लिकेशन इंस्टॉल किया गया हो"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet ऐप्लिकेशन को शॉर्टकट के तौर पर जोड़ने के लिए, पक्का करें कि कम से कम एक कार्ड जोड़ा गया हो"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"क्यूआर कोड स्कैनर को शॉर्टकट के तौर पर जोड़ने के लिए, पक्का करें कि कैमरा ऐप्लिकेशन इंस्टॉल किया गया हो"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home ऐप्लिकेशन को शॉर्टकट के तौर पर जोड़ने के लिए, पक्का करें कि ऐप्लिकेशन इंस्टॉल किया गया हो"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• कम से कम एक डिवाइस उपलब्ध है"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"नोट लेने से जुड़ा शॉर्टकट इस्तेमाल करने के लिए, नोट लेने का डिफ़ॉल्ट ऐप्लिकेशन चुनें"</string>
@@ -1168,7 +1171,7 @@
     <string name="install_app" msgid="5066668100199613936">"ऐप्लिकेशन इंस्टॉल करें"</string>
     <string name="privacy_dialog_title" msgid="7839968133469098311">"माइक्रोफ़ोन और कैमरा"</string>
     <string name="privacy_dialog_summary" msgid="2458769652125995409">"हाल ही में इस्तेमाल करने वाला ऐप्लिकेशन"</string>
-    <string name="privacy_dialog_more_button" msgid="7610604080293562345">"हाल ही का ऐक्सेस देखें"</string>
+    <string name="privacy_dialog_more_button" msgid="7610604080293562345">"हाल में ऐक्सेस करने वाले ऐप"</string>
     <string name="privacy_dialog_done_button" msgid="4504330708531434263">"हो गया"</string>
     <string name="privacy_dialog_expand_action" msgid="9129262348628331377">"बड़ा करें और विकल्प दिखाएं"</string>
     <string name="privacy_dialog_collapse_action" msgid="277419962019466347">"छोटा करें"</string>
@@ -1179,7 +1182,7 @@
     <string name="privacy_dialog_active_call_usage" msgid="7858746847946397562">"फ़ोन कॉल पर इस्तेमाल किया जा रहा है"</string>
     <string name="privacy_dialog_recent_call_usage" msgid="1214810644978167344">"हाल ही में, फ़ोन कॉल में इस्तेमाल किया गया"</string>
     <string name="privacy_dialog_active_app_usage" msgid="631997836335929880">"<xliff:g id="APP_NAME">%1$s</xliff:g> पर इस्तेमाल किया जा रहा है"</string>
-    <string name="privacy_dialog_recent_app_usage" msgid="4883417856848222450">"हाल ही में, <xliff:g id="APP_NAME">%1$s</xliff:g> ने इस्तेमाल किया"</string>
+    <string name="privacy_dialog_recent_app_usage" msgid="4883417856848222450">"हाल ही में <xliff:g id="APP_NAME">%1$s</xliff:g> पर इस्तेमाल किया गया"</string>
     <string name="privacy_dialog_active_app_usage_1" msgid="9047570143069220911">"<xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g>) पर इस्तेमाल किया जा रहा है"</string>
     <string name="privacy_dialog_recent_app_usage_1" msgid="2551340497722370109">"हाल ही में, <xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g>) ने इस्तेमाल किया"</string>
     <string name="privacy_dialog_active_app_usage_2" msgid="2770926061339921767">"<xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g> • <xliff:g id="PROXY_LABEL">%3$s</xliff:g>) पर इस्तेमाल किया जा रहा है"</string>
diff --git a/packages/SystemUI/res/values-hr/strings.xml b/packages/SystemUI/res/values-hr/strings.xml
index baf74d2..e58bc76 100644
--- a/packages/SystemUI/res/values-hr/strings.xml
+++ b/packages/SystemUI/res/values-hr/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Ograničenje od <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Upozorenje <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Poslovne aplikacije"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pauzirano"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Noćno svjetlo"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Uključuje se u suton"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Do izlaska sunca"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Povećaj dio zaslona"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Otvori postavke povećavanja"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Zatvori postavke povećavanja"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Zatvaranje načina uređivanja"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Povucite kut da biste promijenili veličinu"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Dopusti dijagonalno pomicanje"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Promijeni veličinu"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Otvorite <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Za dodavanje aplikacije Wallet kao prečaca provjerite je li instalirana"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Provjerite je li dodana barem jedna kartica kako biste dodali aplikaciju Wallet kao prečac"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Provjerite je li instalirana aplikacija kamere kako biste dodali čitač QR koda kao prečac"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Provjerite je li aplikacija Home instalirana kako biste je dodali kao prečac"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Dostupan je najmanje jedan uređaj"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Odaberite zadanu aplikaciju za bilješke da biste koristili prečac za pisanje bilježaka"</string>
diff --git a/packages/SystemUI/res/values-hu/strings.xml b/packages/SystemUI/res/values-hu/strings.xml
index e225682..49ba82b 100644
--- a/packages/SystemUI/res/values-hu/strings.xml
+++ b/packages/SystemUI/res/values-hu/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> korlát"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Figyelem! <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Munkahelyi alkalmazások"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Szüneteltetve"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Éjszakai fény"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Be: naplemente"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Napfelkeltéig"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Képernyő bizonyos részének nagyítása"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Nagyítási beállítások megnyitása"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Nagyítási beállítások bezárása"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Az átméretezéshez húzza a kívánt sarkot"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Átlós görgetés engedélyezése"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Átméretezés"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"A(z) <xliff:g id="APPNAME">%1$s</xliff:g> megnyitása"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Ha szeretné felvenni Wallet alkalmazást gyorsparancsként, gondoskodjon az app telepítéséről"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Ha szeretné felvenni Wallet alkalmazást gyorsparancsként, győződjön meg róla, hogy hozzáadott legalább egy kártyát a szolgáltatáshoz"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Ha szeretné felvenni a QR-kód-szkennelőt gyorsparancsként, győződjön meg róla, hogy van az eszközre telepítve kameraalkalmazás"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Ha szeretné felvenni Home appot gyorsparancsként, gondoskodjon az alkalmazás telepítéséről"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Legalább egy eszköz rendelkezésre áll"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Válassza ki az alapértelmezett jegyzetkészítő alkalmazást, amelyet a jegyzetelési gyorsparancshoz szeretne használni"</string>
diff --git a/packages/SystemUI/res/values-hy/strings.xml b/packages/SystemUI/res/values-hy/strings.xml
index e573682..7b72456 100644
--- a/packages/SystemUI/res/values-hy/strings.xml
+++ b/packages/SystemUI/res/values-hy/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Սահմանաչափ՝ <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> զգուշացում"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Աշխատանքային հավելվածներ"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Դադարեցված է"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Գիշերային ռեժիմ"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Կմիացվի մայրամուտին"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Մինչև լուսաբաց"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Խոշորացնել էկրանի որոշակի հատվածը"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Բացել խոշորացման կարգավորումները"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Փակել խոշորացման կարգավորումները"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Քաշեք անկյունը՝ չափը փոխելու համար"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Թույլատրել անկյունագծով ոլորումը"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Փոխել չափը"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Բացել <xliff:g id="APPNAME">%1$s</xliff:g> հավելվածը"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet հավելվածի դյուրանցումն ավելացնելու համար համոզվեք, որ հավելվածը տեղադրված է"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet հավելվածի դյուրանցումն ավելացնելու համար համոզվեք, որ առնվազն մեկ քարտ ավելացված է"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR կոդերի սկաների դյուրանցումն ավելացնելու համար համոզվեք, որ տեսախցիկի հավելվածը տեղադրված է"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home հավելվածի դյուրանցումն ավելացնելու համար համոզվեք, որ հավելվածը տեղադրված է"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Հասանելի է առնվազն մեկ սարք"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Ընտրեք նշումների կանխադրված հավելված՝ նշումների ստեղծման դյուրանցումն օգտագործելու համար"</string>
diff --git a/packages/SystemUI/res/values-in/strings.xml b/packages/SystemUI/res/values-in/strings.xml
index 0e8c3a1..fc12a14 100644
--- a/packages/SystemUI/res/values-in/strings.xml
+++ b/packages/SystemUI/res/values-in/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Batas <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Peri­ngatan <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Aplikasi kerja"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Dijeda"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Cahaya Malam"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Aktif saat malam"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Sampai pagi"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Perbesar sebagian layar"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Buka setelan pembesaran"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Tutup setelan pembesaran"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Tarik pojok persegi untuk mengubah ukuran"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Izinkan scrolling diagonal"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Ubah ukuran"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Buka <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Untuk menambahkan aplikasi Wallet sebagai pintasan, pastikan aplikasi sudah diinstal"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Untuk menambahkan aplikasi Wallet sebagai pintasan, pastikan minimal satu kartu telah ditambahkan"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Untuk menambahkan pemindai kode QR sebagai pintasan, pastikan aplikasi kamera sudah diinstal"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Untuk menambahkan aplikasi Home sebagai pintasan, pastikan aplikasi sudah diinstal"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Tersedia minimal satu perangkat"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Pilih aplikasi catatan default untuk menggunakan pintasan pembuatan catatan"</string>
diff --git a/packages/SystemUI/res/values-is/strings.xml b/packages/SystemUI/res/values-is/strings.xml
index 8411db4..2c784a6 100644
--- a/packages/SystemUI/res/values-is/strings.xml
+++ b/packages/SystemUI/res/values-is/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> hámark"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> viðvörun"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Vinnuforrit"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Hlé"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Næturljós"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Kveikt við sólsetur"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Til sólarupprásar"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Stækka hluta skjásins"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Opna stillingar stækkunar"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Loka stillingum stækkunar"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Dragðu horn til að breyta stærð"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Leyfa skáflettingu"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Breyta stærð"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Opna <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Til að bæta Veskisforritinu við sem flýtileið skaltu ganga úr skugga um að forritið sé uppsett"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Til að bæta Veskisforritinu við sem flýtileið skaltu ganga úr skugga um að hafa bætt að minnsta kosti einu korti við"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Til að bæta QR-kóðaskanna við sem flýtileið skaltu ganga úr skugga um að myndavélarforrit sé uppsett"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Til að bæta Home-forritinu við sem flýtileið skaltu ganga úr skugga um að forritið sé uppsett"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Að minnsta kosti eitt tæki er tiltækt"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Veldu sjálfgefið glósuforrit til að nota flýtileið fyrir glósugerð"</string>
diff --git a/packages/SystemUI/res/values-it/strings.xml b/packages/SystemUI/res/values-it/strings.xml
index 561da81..7c22297 100644
--- a/packages/SystemUI/res/values-it/strings.xml
+++ b/packages/SystemUI/res/values-it/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limite di <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Avviso <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"App di lavoro"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"In pausa"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Luminosità notturna"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Attivata al tramonto"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Fino all\'alba"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Ingrandisci parte dello schermo"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Apri le impostazioni di ingrandimento"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Chiudi impostazioni di ingrandimento"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Trascina l\'angolo per ridimensionare"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Scorrimento diagonale"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Ridimensiona"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Apri <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Per aggiungere l\'app Wallet come scorciatoia, assicurati che l\'app sia installata"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Per aggiungere l\'app Wallet come scorciatoia, assicurati che sia stata aggiunta almeno una carta"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Per aggiungere lo scanner di codici QR come scorciatoia, assicurati che ci sia un\'app fotocamera installata"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Per aggiungere l\'app Home come scorciatoia, assicurati che l\'app sia installata"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Ci sia almeno un dispositivo disponibile"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Seleziona un\'app per le note predefinita per usare la scorciatoia per l\'aggiunta di note"</string>
diff --git a/packages/SystemUI/res/values-iw/strings.xml b/packages/SystemUI/res/values-iw/strings.xml
index c905b04..f1dd497 100644
--- a/packages/SystemUI/res/values-iw/strings.xml
+++ b/packages/SystemUI/res/values-iw/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"הגבלה של <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"אזהרה – <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"אפליקציות לעבודה"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"בהשהיה"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"תאורת לילה"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"התכונה מופעלת בשקיעה"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"עד הזריחה"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"הגדלת חלק מהמסך"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"פתיחת הגדרות ההגדלה"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"סגירת הגדרות ההגדלה"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"צריך לגרור את הפינה כדי לשנות את הגודל"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"הפעלת גלילה באלכסון"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"שינוי גודל"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"פתיחת <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"‏כדי להוסיף את אפליקציית Wallet כקיצור דרך, צריך לוודא שהאפליקציה מותקנת"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"‏כדי להוסיף את אפליקציית Wallet כקיצור דרך, צריך לוודא שנוסף לפחות כרטיס אחד"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"‏כדי להוסיף את סורק קודי ה-QR כקיצור דרך, צריך לוודא שמותקנת אפליקציית מצלמה"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"‏כדי להוסיף את אפליקציית Home כקיצור דרך, צריך לוודא שהאפליקציה מותקנת"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• יש לפחות מכשיר אחד זמין"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"צריך לבחור אפליקציית פתקים שתיפתח כברירת מחדל כשייעשה שימוש במקש הקיצור לכתיבת פתקים"</string>
diff --git a/packages/SystemUI/res/values-ja/strings.xml b/packages/SystemUI/res/values-ja/strings.xml
index 8a40d71..5d3919e 100644
--- a/packages/SystemUI/res/values-ja/strings.xml
+++ b/packages/SystemUI/res/values-ja/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"上限: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"警告: 上限は<xliff:g id="DATA_LIMIT">%s</xliff:g>です"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"仕事用アプリ"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"一時停止中"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"夜間モード"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"日の入りに ON"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"日の出まで"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"画面の一部を拡大します"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"画面の拡大設定を開く"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"拡大の設定を閉じる"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"編集モードを終了"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"サイズを変更するには角をドラッグ"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"斜めスクロールを許可"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"サイズ変更"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> を開く"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"ウォレット アプリをショートカットとして追加するには、アプリがインストールされていることを確認してください"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"ウォレット アプリをショートカットとして追加するには、カードが 1 枚以上追加されていることを確認してください"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR コードスキャナをショートカットとして追加するには、カメラアプリがインストールされていることを確認してください"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Google Home アプリをショートカットとして追加するには、アプリがインストールされていることを確認してください"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• 利用できるデバイスが 1 台以上ある"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"メモのショートカットを使用するデフォルトのメモアプリを選択してください"</string>
diff --git a/packages/SystemUI/res/values-ka/strings.xml b/packages/SystemUI/res/values-ka/strings.xml
index 0c5c76e..daa0ae7 100644
--- a/packages/SystemUI/res/values-ka/strings.xml
+++ b/packages/SystemUI/res/values-ka/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"ლიმიტი: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> გაფრთხილება"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"სამსახურის აპები"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"დაპაუზებულია"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"ღამის განათება"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"ჩაირთოს მზის ჩასვლისას"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"მზის ამოსვლამდე"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"ეკრანის ნაწილის გადიდება"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"გახსენით გადიდების პარამეტრები"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"გადიდების პარამეტრების დახურვა"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"რედაქტირების რეჟიმიდან გასვლა"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"ჩავლებით გადაიტანეთ კუთხე ზომის შესაცვლელად"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"დიაგონალური გადაადგილების დაშვება"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"ზომის შეცვლა"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> აპის გახსნა"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"საფულის აპის მალსახმობის დასამატებლად დარწმუნდით, რომ აპი დაინსტალირებულია"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"საფულის აპის მალსახმობის დასამატებლად დარწმუნდით, რომ დამატებულია მინიმუმ ერთი ბარათი"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR კოდის სკანერის მალსახმობის დასამატებლად დარწმუნდით, რომ დაინსტალირებულია კამერის აპი"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"მთავარი აპის მალსახმობის დასამატებლად დარწმუნდით, რომ აპი დაინსტალირებულია"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• ხელმისაწვდომია მინიმუმ ერთი მოწყობილობა"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"აირჩიეთ ჩანიშვნების ნაგულისხმევი აპი, რათა ჩანიშვნების შექმნის მალსახმობი გამოიყენოთ"</string>
diff --git a/packages/SystemUI/res/values-kk/strings.xml b/packages/SystemUI/res/values-kk/strings.xml
index 953292d..18f7855 100644
--- a/packages/SystemUI/res/values-kk/strings.xml
+++ b/packages/SystemUI/res/values-kk/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> шегі"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> туралы ескерту"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Жұмыс қолданбалары"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Кідіртілген"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Түнгі жарық"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Күн батқанда қосу"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Күн шыққанға дейін"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Экранның бөлігін ұлғайту"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Ұлғайту параметрлерін ашу"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Ұлғайту параметрлерін жабу"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Өлшемін өзгерту үшін бұрышынан сүйреңіз."</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Диагональ бойынша айналдыруға рұқсат беру"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Өлшемін өзгерту"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> ашу"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet қолданбасын таңбаша ретінде қосу үшін қолданбаның орнатылғанын тексеріңіз."</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet қолданбасын таңбаша ретінде қосу үшін кемінде бір картаның қосылғанын тексеріңіз."</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR кодының сканерін таңбаша ретінде қосу үшін камера қолданбасының орнатылғанын тексеріңіз."</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home қолданбасын таңбаша ретінде қосу үшін қолданбаның орнатылғанын тексеріңіз."</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Кемінде бір құрылғы қолжетімді."</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Жазба жазу таңбашасын пайдалану үшін әдепкі жазба қолданбаны таңдаңыз."</string>
diff --git a/packages/SystemUI/res/values-km/strings.xml b/packages/SystemUI/res/values-km/strings.xml
index 535400f..d5ef4b5 100644
--- a/packages/SystemUI/res/values-km/strings.xml
+++ b/packages/SystemUI/res/values-km/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"ដែន​កំណត់ <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> ការ​ព្រមាន"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"កម្មវិធីការងារ"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"បានផ្អាក"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"ពន្លឺពេលយប់"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"បើក​នៅពេល​ថ្ងៃលិច"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"រហូត​ដល់​ពេល​ថ្ងៃរះ"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"ពង្រីក​ផ្នែកនៃ​អេក្រង់"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"បើកការកំណត់​ការពង្រីក"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"បិទការកំណត់ការពង្រីក"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"អូសជ្រុងដើម្បីប្ដូរទំហំ"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"អនុញ្ញាត​ការរំកិលបញ្ឆិត"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"ប្ដូរ​ទំហំ"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"បើក <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"ដើម្បីបញ្ចូល​កម្មវិធី Wallet ជាផ្លូវកាត់ សូមប្រាកដថា​កម្មវិធីត្រូវបានដំឡើង"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"ដើម្បីបញ្ចូល​កម្មវិធី Wallet ជាផ្លូវកាត់ សូមប្រាកដថា​បានបញ្ចូលកាត​យ៉ាងហោចណាស់មួយ"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"ដើម្បីបញ្ចូលកម្មវិធី​ស្កេនកូដ QR ជាផ្លូវកាត់ សូមប្រាកដថា​កម្មវិធីកាមេរ៉ាត្រូវបានដំឡើង"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"ដើម្បីបញ្ចូល​កម្មវិធី Home ជាផ្លូវកាត់ សូមប្រាកដថា​កម្មវិធីត្រូវបានដំឡើង"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• ឧបករណ៍យ៉ាងតិចមួយអាចប្រើបាន"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"ជ្រើសរើសកម្មវិធីកំណត់ចំណាំលំនាំដើម ដើម្បីប្រើផ្លូវកាត់សម្រាប់ការកត់ចំណាំ"</string>
diff --git a/packages/SystemUI/res/values-kn/strings.xml b/packages/SystemUI/res/values-kn/strings.xml
index 0a2bb64..0b82b55 100644
--- a/packages/SystemUI/res/values-kn/strings.xml
+++ b/packages/SystemUI/res/values-kn/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> ಮಿತಿ"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> ಎಚ್ಚರಿಕೆ"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"ಕೆಲಸಕ್ಕೆ ಸಂಬಂಧಿಸಿದ ಆ್ಯಪ್‌ಗಳು"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"ವಿರಾಮಗೊಳಿಸಲಾಗಿದೆ"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"ನೈಟ್ ಲೈಟ್"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"ಸೂರ್ಯಾಸ್ತದಲ್ಲಿ"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"ಸೂರ್ಯೋದಯದವರೆಗೆ"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"ಸ್ಕ್ರೀನ್‌ನ ಅರ್ಧಭಾಗವನ್ನು ಝೂಮ್ ಮಾಡಿ"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"ಹಿಗ್ಗಿಸುವಿಕೆ ಸೆಟ್ಟಿಂಗ್‌ಗಳನ್ನು ತೆರೆಯಿರಿ"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"ಮ್ಯಾಗ್ನಿಫಿಕೇಶನ್ ಸೆಟ್ಟಿಂಗ್‌ಗಳನ್ನು ಮುಚ್ಚಿರಿ"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"ಎಡಿಟ್ ಮೋಡ್‌ನಿಂದ ನಿರ್ಗಮಿಸಿ"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"ಮರುಗಾತ್ರಗೊಳಿಸಲು ಮೂಲೆಯನ್ನು ಡ್ರ್ಯಾಗ್ ಮಾಡಿ"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"ಡಯಾಗನಲ್ ಸ್ಕ್ರೋಲಿಂಗ್ ಅನ್ನು ಅನುಮತಿಸಿ"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"ಮರುಗಾತ್ರಗೊಳಿಸಿ"</string>
@@ -1038,7 +1040,7 @@
     <string name="game_status" msgid="1340694320630973259">"ಪ್ಲೇ ಮಾಡಲಾಗುತ್ತಿದೆ"</string>
     <string name="empty_user_name" msgid="3389155775773578300">"ಸ್ನೇಹಿತರು"</string>
     <string name="empty_status" msgid="5938893404951307749">"ರಾತ್ರಿ ಚಾಟ್ ಮಾಡೋಣ!"</string>
-    <string name="status_before_loading" msgid="1500477307859631381">"ವಿಷಯ ಶೀಘ್ರದಲ್ಲೇ ಕಾಣಿಸಿಕೊಳ್ಳುತ್ತವೆ"</string>
+    <string name="status_before_loading" msgid="1500477307859631381">"ಕಂಟೆಂಟ್‌ ಶೀಘ್ರದಲ್ಲೇ ಕಾಣಿಸಿಕೊಳ್ಳುತ್ತವೆ"</string>
     <string name="missed_call" msgid="4228016077700161689">"ಮಿಸ್ಡ್ ಕಾಲ್"</string>
     <string name="messages_count_overflow_indicator" msgid="7850934067082006043">"<xliff:g id="NUMBER">%d</xliff:g>+"</string>
     <string name="people_tile_description" msgid="8154966188085545556">"ಇತ್ತೀಚಿನ ಸಂದೇಶಗಳು, ಮಿಸ್ಡ್ ಕಾಲ್‌ಗಳು ಮತ್ತು ಸ್ಥಿತಿ ಅಪ್‌ಡೇಟ್‌ಗಳು"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> ಅನ್ನು ತೆರೆಯಿರಿ"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"ವಾಲೆಟ್ ಆ್ಯಪ್ ಅನ್ನು ಶಾರ್ಟ್‌ಕಟ್ ಆಗಿ ಸೇರಿಸಲು, ಆ್ಯಪ್ ಅನ್ನು ಇನ್‌ಸ್ಟಾಲ್ ಮಾಡಲಾಗಿದೆಯೇ ಎಂಬುದನ್ನು ಖಚಿತಪಡಿಸಿಕೊಳ್ಳಿ"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"ವಾಲೆಟ್ ಆ್ಯಪ್ ಅನ್ನು ಶಾರ್ಟ್‌ಕಟ್ ಆಗಿ ಸೇರಿಸಲು, ಕನಿಷ್ಠ ಒಂದು ಕಾರ್ಡ್ ಅನ್ನು ಸೇರಿಸಲಾಗಿದೆಯೇ ಎಂಬುದನ್ನು ಖಚಿತಪಡಿಸಿಕೊಳ್ಳಿ"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR ಕೋಡ್ ಸ್ಕ್ಯಾನರ್ ಅನ್ನು ಶಾರ್ಟ್‌ಕಟ್ ಆಗಿ ಸೇರಿಸಲು, ಕ್ಯಾಮರಾ ಆ್ಯಪ್ ಅನ್ನು ಇನ್‌ಸ್ಟಾಲ್ ಮಾಡಲಾಗಿದೆಯೇ ಎಂಬುದನ್ನು ಖಚಿತಪಡಿಸಿಕೊಳ್ಳಿ"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home ಆ್ಯಪ್ ಅನ್ನು ಶಾರ್ಟ್‌ಕಟ್ ಆಗಿ ಸೇರಿಸಲು, ಆ್ಯಪ್ ಇನ್‌ಸ್ಟಾಲ್ ಆಗಿದೆಯೇ ಎಂಬುದನ್ನು ಖಚಿತಪಡಿಸಿಕೊಳ್ಳಿ"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• ಕನಿಷ್ಠ ಒಂದು ಸಾಧನ ಲಭ್ಯವಿದೆ"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"ನೋಟ್ಸ್ ಮಾಡಿಕೊಳ್ಳುವಿಕೆ ಶಾರ್ಟ್‌ಕಟ್ ಅನ್ನು ಬಳಸಲು ಡೀಫಾಲ್ಟ್ ಟಿಪ್ಪಣಿಗಳ ಆ್ಯಪ್ ಆಯ್ಕೆಮಾಡಿ"</string>
diff --git a/packages/SystemUI/res/values-ko/strings.xml b/packages/SystemUI/res/values-ko/strings.xml
index d267fed..ea7d5c2 100644
--- a/packages/SystemUI/res/values-ko/strings.xml
+++ b/packages/SystemUI/res/values-ko/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"한도: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> 경고"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"직장 앱"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"일시중지됨"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"야간 조명"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"일몰에"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"일출까지"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"화면 일부 확대"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"확대 설정 열기"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"확대 설정 닫기"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"모서리를 드래그하여 크기 조절"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"대각선 스크롤 허용"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"크기 조절"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> 열기"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"월렛 앱을 바로가기로 추가하려면 앱이 설치되어 있는지 확인하세요."</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"월렛 앱을 바로가기로 추가하려면 하나 이상의 카드가 추가되어 있는지 확인하세요."</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR 코드 스캐너를 바로가기로 추가하려면 카메라 앱이 설치되어 있는지 확인하세요."</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home 앱을 바로가기로 추가하려면 앱이 설치되어 있는지 확인하세요."</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• 1대 이상의 기기를 사용할 수 있습니다."</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"메모 바로가기를 사용하려면 기본 메모 앱을 선택합니다."</string>
diff --git a/packages/SystemUI/res/values-ky/strings.xml b/packages/SystemUI/res/values-ky/strings.xml
index 768e8a5..cb9e67a 100644
--- a/packages/SystemUI/res/values-ky/strings.xml
+++ b/packages/SystemUI/res/values-ky/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> чектөө"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> эскертүү"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Жумуш колдонмолору"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Тындырылды"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Түнкү режим"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Күн батканда күйөт"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Күн чыкканга чейин"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Экрандын бир бөлүгүн чоңойтуу"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Чоңойтуу параметрлерин ачуу"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Чоңойтуу параметрлерин жабуу"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Өлчөмүн өзгөртүү үчүн бурчун сүйрөңүз"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Диагональ боюнча сыдырууга уруксат берүү"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Өлчөмүн өзгөртүү"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> ачуу"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Капчык колдонмосун ыкчам баскыч катары кошуу үчүн колдонмону орнотуу керек"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Капчык колдонмосун ыкчам баскыч катары кошуу үчүн кеминде бир картаны кошуу керек"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR кодунун сканерин ыкчам баскыч катары кошуу үчүн камера колдонмосун орнотуу керек"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home колдонмосун ыкчам баскыч катары кошуу үчүн колдонмону орнотуу керек"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Кеминде бир түзмөк жеткиликтүү"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Эскертме жазуу ыкчам баскычын колдонуу үчүн демейки эскертме жазуу колдонмосун тандаңыз"</string>
diff --git a/packages/SystemUI/res/values-lo/strings.xml b/packages/SystemUI/res/values-lo/strings.xml
index e8b4003..3e26137 100644
--- a/packages/SystemUI/res/values-lo/strings.xml
+++ b/packages/SystemUI/res/values-lo/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"ຈຳ​ກັດ <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"ຄຳ​ເຕືອນ <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"ແອັບບ່ອນເຮັດວຽກ"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"ຢຸດໄວ້ຊົ່ວຄາວ"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"ແສງກາງຄືນ"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"ເປີດຕອນຕາເວັນຕົກ"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"ຈົນກວ່າຕາເວັນຂຶ້ນ"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"ຂະຫຍາຍບາງສ່ວນຂອງໜ້າຈໍ"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"ເປີດການຕັ້ງຄ່າການຂະຫຍາຍ"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"ປິດການຕັ້ງຄ່າການຂະຫຍາຍ"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"ລາກຢູ່ມຸມເພື່ອປັບຂະໜາດ"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"ອະນຸຍາດໃຫ້ເລື່ອນທາງຂວາງ"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"ປ່ຽນຂະໜາດ"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"ເປີດ <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"ເພື່ອເພີ່ມແອັບ Wallet ເປັນທາງລັດ, ກະລຸນາກວດສອບໃຫ້ແນ່ໃຈວ່າໄດ້ຕິດຕັ້ງແອັບແລ້ວ"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"ເພື່ອເພີ່ມແອັ Wallet ເປັນທາງລັດ, ກະລຸນາກວດສອບໃຫ້ແນ່ໃຈວ່າໄດ້ເພີ່ມຢ່າງໜ້ອຍ 1 ບັດແລ້ວ"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"ເພື່ອເພີ່ມຕົວສະແກນລະຫັດ QR ເປັນທາງລັດ, ກະລຸນາກວດສອບໃຫ້ແນ່ໃຈວ່າໄດ້ຕິດຕັ້ງແອັບກ້ອງຖ່າຍຮູບແລ້ວ"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"ເພື່ອເພີ່ມແອັບ Home ເປັນທາງລັດ, ກະລຸນາກວດສອບໃຫ້ແນ່ໃຈວ່າໄດ້ຕິດຕັ້ງແອັບແລ້ວ"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• ມີຢ່າງໜ້ອຍ 1 ອຸປະກອນພ້ອມໃຫ້ນຳໃຊ້"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"ເລືອກແອັບບັນທຶກເລີ່ມຕົ້ນເພື່ອໃຊ້ທາງລັດການຈົດບັນທຶກ"</string>
diff --git a/packages/SystemUI/res/values-lt/strings.xml b/packages/SystemUI/res/values-lt/strings.xml
index 2426533..a7d874c 100644
--- a/packages/SystemUI/res/values-lt/strings.xml
+++ b/packages/SystemUI/res/values-lt/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limitas: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> įspėjimas"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Darbo programos"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pristabdyta"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Nakties šviesa"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Per saulėlydį"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Iki saulėtekio"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Didinti ekrano dalį"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Atidaryti didinimo nustatymus"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Uždaryti didinimo nustatymus"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Norėdami keisti dydį, vilkite kampą"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Slinkimo įstrižai leidimas"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Pakeisti dydį"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Atidaryti „<xliff:g id="APPNAME">%1$s</xliff:g>“"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Jei norite pridėti programą „Wallet“ kaip šaukinį, įsitikinkite, kad programa įdiegta"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Jei norite pridėti programą „Wallet“ kaip šaukinį, įsitikinkite, kad pridėta bent viena kortelė"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Jei norite pridėti QR kodų skaitytuvą kaip šaukinį, įsitikinkite, kad fotoaparato programa įdiegta"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Jei norite pridėti programą „Home“ kaip šaukinį, įsitikinkite, kad programa įdiegta"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Pasiekiamas bent vienas įrenginys"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Pasirinkite numatytąją užrašų programą, kuriai norite naudoti užrašų kūrimo šaukinį"</string>
diff --git a/packages/SystemUI/res/values-lv/strings.xml b/packages/SystemUI/res/values-lv/strings.xml
index 9bda2b8..972380c 100644
--- a/packages/SystemUI/res/values-lv/strings.xml
+++ b/packages/SystemUI/res/values-lv/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Ierobežojums: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> brīdinājums"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Darba lietotnes"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Darbība apturēta"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Nakts režīms"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Saulrietā"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Līdz saullēktam"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Palielināt ekrāna daļu"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Atvērt palielinājuma iestatījumus"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Aizvērt palielinājuma iestatījumus"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Velciet stūri, lai mainītu izmērus"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Atļaut ritināšanu pa diagonāli"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Mainīt lielumu"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Atvērt lietotni <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Lai varētu pievienot lietotni Maks kā saīsni, lietotnei ir jābūt instalētai."</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Lai varētu pievienot lietotni Maks kā saīsni, ir jābūt pievienotai vismaz vienai kartei."</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Lai varētu pievienot lietotni Kvadrātkoda skeneris kā saīsni, ir jābūt instalētai kameras lietotnei."</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Lai varētu pievienot lietotni Home kā saīsni, lietotnei ir jābūt instalētai."</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Ir pieejama vismaz viena ierīce."</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Atlasiet noklusējuma piezīmju lietotni, lai izmantotu piezīmju pierakstīšanas saīsni."</string>
diff --git a/packages/SystemUI/res/values-mk/strings.xml b/packages/SystemUI/res/values-mk/strings.xml
index 9b8b04c..4b1e5a8 100644
--- a/packages/SystemUI/res/values-mk/strings.xml
+++ b/packages/SystemUI/res/values-mk/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Лимит: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Предупредување: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Работни апликации"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Паузирано"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Ноќно светло"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Вклуч. на зајдисонце"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"До изгрејсонце"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Зголемувајте дел од екранот"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Отвори поставки за зголемување"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Затворете ги поставките за зголемување"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Повлечете на аголот за да ја промените големината"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Дозволете дијагонално лизгање"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Промени големина"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Отворете ја <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"За да ја додадете апликацијата Wallet како кратенка, апликацијата мора да е инсталирана"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"За да ја додадете апликацијата Wallet како кратенка, мора да имате додадено најмалку една картичка"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"За да го додадете скенерот на QR-кодови како кратенка, погрижете се дека имате инсталирано апликација за камера"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"За да ја додадете апликацијата Home како кратенка, апликацијата мора да е инсталирана"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• достапен е најмалку еден уред"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Изберете стандардна апликација за белешки за да ја користите кратенката за фаќање белешки"</string>
diff --git a/packages/SystemUI/res/values-ml/strings.xml b/packages/SystemUI/res/values-ml/strings.xml
index b7a03d8..7202f5e 100644
--- a/packages/SystemUI/res/values-ml/strings.xml
+++ b/packages/SystemUI/res/values-ml/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> പരിധി"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> മുന്നറിയിപ്പ്"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"ഔദ്യോഗിക ആപ്പുകൾ"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"തൽക്കാലം നിർത്തി"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"നൈറ്റ് ലൈറ്റ്"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"സൂര്യാസ്‌തമയത്തിന്"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"സൂര്യോദയം വരെ"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"സ്‌ക്രീനിന്റെ ഭാഗം മാഗ്നിഫൈ ചെയ്യുക"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"മാഗ്നിഫിക്കേഷൻ ക്രമീകരണം തുറക്കുക"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"മാഗ്നിഫിക്കേഷൻ ക്രമീകരണം അടയ്‌ക്കുക"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"എഡിറ്റ് മോഡിൽ നിന്ന് പുറത്തുകടക്കുക"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"വലുപ്പം മാറ്റാൻ മൂല വലിച്ചിടുക"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"ഡയഗണൽ സ്‌ക്രോളിംഗ് അനുവദിക്കുക"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"വലുപ്പം മാറ്റുക"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> തുറക്കുക"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"കുറുക്കുവഴിയായി Wallet ആപ്പ് ചേർക്കാൻ, ആപ്പ് ഇൻസ്‌റ്റാൾ ചെയ്തിട്ടുണ്ടെന്ന് ഉറപ്പാക്കുക"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"കുറുക്കുവഴിയായി Wallet ആപ്പ് ചേർക്കാൻ, ഒരു കാർഡെങ്കിലും ചേർത്തിട്ടുണ്ടെന്ന് ഉറപ്പാക്കുക"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"കുറുക്കുവഴിയായി QR കോഡ് സ്‌കാനർ ചേർക്കാൻ, ക്യാമറാ ആപ്പ് ഇൻസ്‌റ്റാൾ ചെയ്തിട്ടുണ്ടെന്ന് ഉറപ്പാക്കുക"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"കുറുക്കുവഴിയായി Home ആപ്പ് ചേർക്കാൻ, ആപ്പ് ഇൻസ്‌റ്റാൾ ചെയ്തിട്ടുണ്ടെന്ന് ഉറപ്പാക്കുക"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• ഒരു ഉപകരണമെങ്കിലും ലഭ്യമാണ്"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"കുറിപ്പ് രേഖപ്പെടുത്തൽ കുറുക്കുവഴി ഉപയോഗിക്കുന്നതിന് ഒരു ഡിഫോൾട്ട് കുറിപ്പ് ആപ്പ് തിരഞ്ഞെടുക്കുക"</string>
diff --git a/packages/SystemUI/res/values-mn/strings.xml b/packages/SystemUI/res/values-mn/strings.xml
index 7a2ca61..470e0fd 100644
--- a/packages/SystemUI/res/values-mn/strings.xml
+++ b/packages/SystemUI/res/values-mn/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> хязгаар"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> анхааруулга"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Ажлын аппууд"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Түр зогсоосон"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Шөнийн гэрэл"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Нар жаргах үед"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Нар мандах хүртэл"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Дэлгэцийн нэг хэсгийг томруулах"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Томруулах тохиргоог нээх"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Томруулах тохиргоог хаах"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Хэмжээг өөрчлөхийн тулд булангаас чирнэ үү"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Хөндлөн гүйлгэхийг зөвшөөрөх"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Хэмжээг өөрчлөх"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g>-г нээх"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet аппыг товчлолоор нэмэхийн тулд уг аппыг суулгасан эсэхийг шалгана уу"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet аппыг товчлолоор нэмэхийн тулд дор хаяж нэг карт нэмсэн эсэхийг шалгана уу"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR код сканнерыг товчлолоор нэмэхийн тулд камерын аппыг суулгасан эсэхийг шалгана уу"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home аппыг товчлолоор нэмэхийн тулд уг аппыг суулгасан эсэхийг шалгана уу"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Дор хаяж нэг төхөөрөмж боломжтой"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Тэмдэглэл хөтлөх товчлолыг ашиглахын тулд тэмдэглэлийн өгөгдмөл аппыг сонгоно уу"</string>
diff --git a/packages/SystemUI/res/values-mr/strings.xml b/packages/SystemUI/res/values-mr/strings.xml
index ccbc209..f5abe78 100644
--- a/packages/SystemUI/res/values-mr/strings.xml
+++ b/packages/SystemUI/res/values-mr/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> मर्यादा"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> चेतावणी"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"कामाशी संबंधित अ‍ॅप्स"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"थांबवले आहे"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"रात्रीचा प्रकाश"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"संध्याकाळी सुरू असते"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"सूर्योदयापर्यंत"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"स्क्रीनचा काही भाग मॅग्निफाय करा"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"मॅग्निफिकेशन सेटिंग्ज उघडा"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"मॅग्निफिकेशन सेटिंग्ज बंद करा"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"आकार बदलण्यासाठी कोपरा ड्रॅग करा"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"तिरपे स्क्रोल करण्याची अनुमती द्या"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"आकार बदला"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> उघडा"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet ॲप शॉर्टकट म्हणून जोडण्यासाठी ॲप इंस्टॉल केले असल्याची खात्री करा"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet ॲप शॉर्टकट म्हणून जोडण्यासाठी किमान एक कार्ड जोडले असल्याची खात्री करा"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR कोड स्कॅनर शॉर्टकट म्हणून जोडण्यासाठी कॅमेरा ॲप इंस्टॉल केले असल्याची खात्री करा"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home अ‍ॅप शॉर्टकट म्हणून जोडण्यासाठी ॲप इंस्टॉल केले असल्याची खात्री करा"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• किमान एक डिव्हाइस उपलब्ध करणे"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"टिपा घेण्यासंबंधित शॉर्टकट वापरण्याकरिता टिपांसाठीचे डीफॉल्ट अ‍ॅप निवडा"</string>
diff --git a/packages/SystemUI/res/values-ms/strings.xml b/packages/SystemUI/res/values-ms/strings.xml
index 586c96e..6b74c43 100644
--- a/packages/SystemUI/res/values-ms/strings.xml
+++ b/packages/SystemUI/res/values-ms/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> had"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Amaran <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Apl kerja"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Dijeda"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Cahaya Malam"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Dihidupkan pd senja"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Hingga matahari terbit"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Besarkan sebahagian skrin"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Buka tetapan pembesaran"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Tutup tetapan pembesaran"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Keluar daripada mod edit"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Seret sudut untuk mengubah saiz"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Benarkan penatalan pepenjuru"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Ubah saiz"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Buka <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Untuk menambahkan apl Wallet sebagai pintasan, pastikan apl telah dipasang"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Untuk menambahkan apl Wallet sebagai pintasan, pastikan sekurang-kurangnya satu kad telah ditambahkan"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Untuk menambahkan pengimbas kod QR sebagai pintasan, pastikan apl kamera telah dipasang"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Untuk menambahkan apl Home sebagai pintasan, pastikan apl telah dipasang"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Sekurang-kurangnya satu peranti tersedia"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Pilih apl nota lalai untuk menggunakan pintasan pengambilan nota"</string>
diff --git a/packages/SystemUI/res/values-my/strings.xml b/packages/SystemUI/res/values-my/strings.xml
index aa5853f..2e2567d 100644
--- a/packages/SystemUI/res/values-my/strings.xml
+++ b/packages/SystemUI/res/values-my/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> ကန့်သတ်ချက်"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> သတိပေးချက်"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"အလုပ်သုံးအက်ပ်များ"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"ခဏရပ်ထားသည်"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"ညအလင်းရောင်"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"နေဝင်ချိန်၌ ဖွင့်ရန်"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"နေထွက်ချိန် အထိ"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"ဖန်သားပြင် တစ်စိတ်တစ်ပိုင်းကို ချဲ့ပါ"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"ချဲ့ခြင်း ဆက်တင်များ ဖွင့်ရန်"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"ချဲ့ခြင်း ဆက်တင်များ ပိတ်ရန်"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"ပြင်ဆင်မုဒ်မှ ထွက်ရန်"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"အရွယ်အစားပြန်ပြုပြင်ရန် ထောင့်စွန်းကို ဖိဆွဲပါ"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"ထောင့်ဖြတ် လှိမ့်ခွင့်ပြုရန်"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"အရွယ်အစားပြန်ပြုပြင်ရန်"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> ဖွင့်ရန်"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet အက်ပ်ကို ဖြတ်လမ်းလင့်ခ်အဖြစ်ထည့်ရန် ၎င်းအားထည့်သွင်းထားကြောင်း သေချာပါစေ"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet အက်ပ်ကို ဖြတ်လမ်းလင့်ခ်အဖြစ်ထည့်ရန် အနည်းဆုံး ကတ်တစ်ခုထည့်ထားကြောင်း သေချာပါစေ"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR ကုဒ် စကင်ဖတ်စနစ်ကို ဖြတ်လမ်းလင့်ခ်အဖြစ်ထည့်ရန် ကင်မရာအက်ပ်အားထည့်သွင်းထားကြောင်း သေချာပါစေ"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home အက်ပ်ကို ဖြတ်လမ်းလင့်ခ်အဖြစ်ထည့်ရန် ၎င်းအားထည့်သွင်းထားကြောင်း သေချာပါစေ"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• အနည်းဆုံး စက်တစ်ခုသုံးနိုင်ရမည်"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"မှတ်စုရေးသည့် ဖြတ်လမ်းလင့်ခ်သုံးရန်အတွက် မူရင်းမှတ်စုများအက်ပ် ရွေးရန်"</string>
diff --git a/packages/SystemUI/res/values-nb/strings.xml b/packages/SystemUI/res/values-nb/strings.xml
index 90025c6..8ef7794 100644
--- a/packages/SystemUI/res/values-nb/strings.xml
+++ b/packages/SystemUI/res/values-nb/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Grense på <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Advarsel for <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Jobbapper"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Satt på pause"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Nattlys"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"På ved solnedgang"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Til soloppgang"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Forstørr en del av skjermen"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Åpne innstillinger for forstørring"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Lukk forstørringsinnstillingene"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Dra hjørnet for å endre størrelse"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Tillat diagonal rulling"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Endre størrelse"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Åpne <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"For å legge til Wallet-appen som snarvei, sørg for at appen er installert"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"For å legge til Wallet-appen som snarvei, sørg for at minst ett kort er lagt til"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"For å legge til QR-kodeskanneren som snarvei, sørg for at du har en kameraapp installert"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"For å legge til Home-appen som snarvei, sørg for at appen er installert"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• minst én enhet er tilgjengelig"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Velg en standard notatapp du vil bruke med notatsnarveien"</string>
diff --git a/packages/SystemUI/res/values-ne/strings.xml b/packages/SystemUI/res/values-ne/strings.xml
index dd15313..c56ebb6 100644
--- a/packages/SystemUI/res/values-ne/strings.xml
+++ b/packages/SystemUI/res/values-ne/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> सीमा"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> चेतावनी दिँदै"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"कामसम्बन्धी एपहरू"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"पज गरिएको छ"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Night Light"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"सूर्यास्तमा सक्रिय"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"सूर्योदयसम्म"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"स्क्रिनको केही भाग म्याग्निफाइ गर्नुहोस्"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"जुम इनसम्बन्धी सेटिङ खोल्नुहोस्"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"जुम इन गर्ने सुविधाको सेटिङ बन्द गर्नुहोस्"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"आकार बदल्न कुनाबाट ड्र्याग गर्नुहोस्"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"डायगोनल तरिकाले स्क्रोल गर्ने अनुमति दिनुहोस्"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"आकार बदल्नुहोस्"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> खोल्नुहोस्"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"सर्टकटका रूपमा Wallet एप हाल्न उक्त एप इन्स्टल गरिएको छ भन्ने कुरा सुनिश्चित गर्नुहोस्"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"सर्टकटका रूपमा Wallet एप हाल्न कम्तीमा एउटा कार्ड हालिएको छ भन्ने कुरा सुनिश्चित गर्नुहोस्"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"सर्टकटका रूपमा QR कोड स्क्यानर हाल्न क्यामेरा एप इन्स्टल गरिएको छ भन्ने कुरा सुनिश्चित गर्नुहोस्"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home एपलाई सर्टकटका रूपमा हाल्न उक्त एप इन्स्टल गरिएको छ भन्ने कुरा सुनिश्चित गर्नुहोस्"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• कम्तीमा एउटा डिभाइस उपलब्ध छ"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"नोट बनाउनेसम्बन्धी सर्टकट प्रयोग गर्न नोट बनाउने डिफल्ट एप चयन गर्नुहोस्"</string>
diff --git a/packages/SystemUI/res/values-nl/strings.xml b/packages/SystemUI/res/values-nl/strings.xml
index 1b657c9..088bcbd 100644
--- a/packages/SystemUI/res/values-nl/strings.xml
+++ b/packages/SystemUI/res/values-nl/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limiet van <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Waarschuwing voor <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Werk-apps"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Onderbroken"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Nachtverlichting"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Aan bij zonsondergang"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Tot zonsopkomst"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Deel van het scherm vergroten"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Instellingen voor vergroting openen"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Instellingen voor vergroting sluiten"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Bewerkingsmodus sluiten"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Sleep een hoek om het formaat te wijzigen"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Diagonaal scrollen toestaan"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Formaat aanpassen"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> openen"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Als je de Wallet-app wilt toevoegen als sneltoets, zorg je dat de app is geïnstalleerd"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Als je de Wallet-app wilt toevoegen als sneltoets, zorg je dat er minstens één kaart is toegevoegd"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Als je de QR-codescanner wilt toevoegen als sneltoets, zorg je dat er een camera-app is geïnstalleerd"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Als je de Home-app wilt toevoegen als sneltoets, zorg je dat de app is geïnstalleerd"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Er is minstens één apparaat beschikbaar"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Selecteer een standaard notitie-app om de sneltoets voor notities maken te gebruiken"</string>
diff --git a/packages/SystemUI/res/values-or/strings.xml b/packages/SystemUI/res/values-or/strings.xml
index 3da07a8..64955e4 100644
--- a/packages/SystemUI/res/values-or/strings.xml
+++ b/packages/SystemUI/res/values-or/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> ସୀମା"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> ଚେତାବନୀ"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"ୱାର୍କ ଆପ୍ସ"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"ବିରତ କରାଯାଇଛି"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"ନାଇଟ୍ ଲାଇଟ୍"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"ସୂର୍ଯ୍ୟାସ୍ତ ବେଳେ ଅନ୍ ହେବ"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"ସୂର୍ଯ୍ୟୋଦୟ ପର୍ଯ୍ୟନ୍ତ"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"ସ୍କ୍ରିନର ଅଂଶ ମାଗ୍ନିଫାଏ କରନ୍ତୁ"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"ମାଗ୍ନିଫିକେସନ ସେଟିଂସ ଖୋଲନ୍ତୁ"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"ମେଗ୍ନିଫିକେସନ ସେଟିଂସକୁ ବନ୍ଦ କରନ୍ତୁ"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"ରିସାଇଜ କରିବା ପାଇଁ କୋଣକୁ ଡ୍ରାଗ କରନ୍ତୁ"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"ଡାଏଗୋନାଲ ସ୍କ୍ରୋଲିଂକୁ ଅନୁମତି ଦିଅନ୍ତୁ"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"ରିସାଇଜ କରନ୍ତୁ"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> ଖୋଲନ୍ତୁ"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"ଏକ ସର୍ଟକଟ ଭାବେ Wallet ଆପ ଯୋଗ କରିବା ପାଇଁ ଏହି ଆପ ଇନଷ୍ଟଲ କରାଯାଇଥିବା ସୁନିଶ୍ଚିତ କରନ୍ତୁ"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"ଏକ ସର୍ଟକଟ ଭାବେ Wallet ଆପ ଯୋଗ କରିବାକୁ ଅତିକମରେ ଗୋଟିଏ ଆପ ଯୋଗ କରାଯାଇଥିବା ସୁନିଶ୍ଚିତ କରନ୍ତୁ"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"ଏକ ସର୍ଟକଟ ଭାବେ QR କୋଡ ସ୍କାନର ଯୋଗ କରିବାକୁ ଏକ କେମେରା ଆପ ଇନଷ୍ଟଲ କରାଯାଇଥିବା ସୁନିଶ୍ଚିତ କରନ୍ତୁ"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"ଏକ ସର୍ଟକଟ ଭାବେ Home ଆପ ଯୋଗ କରିବା ପାଇଁ ଏହି ଆପ ଇନଷ୍ଟଲ କରାଯାଇଥିବା ସୁନିଶ୍ଚିତ କରନ୍ତୁ"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• ଅତିକମରେ ଗୋଟିଏ ଡିଭାଇସ ଉପଲବ୍ଧ ଅଛି"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"ନୋଟଟେକିଂ ସର୍ଟକଟ ବ୍ୟବହାର କରିବାକୁ ଏକ ଡିଫଲ୍ଟ ନୋଟ୍ସ ଆପ୍ସ ଚୟନ କରନ୍ତୁ"</string>
diff --git a/packages/SystemUI/res/values-pa/strings.xml b/packages/SystemUI/res/values-pa/strings.xml
index b8a92c2..b3d4482 100644
--- a/packages/SystemUI/res/values-pa/strings.xml
+++ b/packages/SystemUI/res/values-pa/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> ਸੀਮਾ"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> ਚਿਤਾਵਨੀ"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"ਕੰਮ ਸੰਬੰਧੀ ਐਪਾਂ"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"ਰੋਕਿਆ ਗਿਆ"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"ਰਾਤ ਦੀ ਰੋਸ਼ਨੀ"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"ਸੂਰਜ ਛਿਪਣ \'ਤੇ ਚਾਲੂ"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"ਸੂਰਜ ਚੜ੍ਹਨ ਤੱਕ"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"ਸਕ੍ਰੀਨ ਦੇ ਹਿੱਸੇ ਨੂੰ ਵੱਡਾ ਕਰੋ"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"ਵੱਡਦਰਸ਼ੀਕਰਨ ਸੈਟਿੰਗਾਂ ਖੋਲ੍ਹੋ"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"ਵੱਡਦਰਸ਼ੀਕਰਨ ਸੈਟਿੰਗਾਂ ਬੰਦ ਕਰੋ"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"ਆਕਾਰ ਬਦਲਣ ਲਈ ਕੋਨਾ ਘਸੀਟੋ"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"ਟੇਡੀ ਦਿਸ਼ਾ ਵਿੱਚ ਸਕ੍ਰੋਲ ਕਰਨ ਦਿਓ"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"ਆਕਾਰ ਬਦਲੋ"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> ਖੋਲ੍ਹੋ"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet ਐਪ ਨੂੰ ਸ਼ਾਰਟਕੱਟ ਵਜੋਂ ਸ਼ਾਮਲ ਕਰਨ ਲਈ, ਪੱਕਾ ਕਰੋ ਕਿ ਐਪ ਸਥਾਪਤ ਹੈ"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet ਐਪ ਨੂੰ ਸ਼ਾਰਟਕੱਟ ਵਜੋਂ ਸ਼ਾਮਲ ਕਰਨ ਲਈ, ਪੱਕਾ ਕਰੋ ਕਿ ਘੱਟੋ-ਘੱਟ ਇੱਕ ਕਾਰਡ ਸ਼ਾਮਲ ਕੀਤਾ ਗਿਆ ਹੈ"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR ਕੋਡ ਸਕੈਨਰ ਨੂੰ ਸ਼ਾਰਟਕੱਟ ਵਜੋਂ ਸ਼ਾਮਲ ਕਰਨ ਲਈ, ਪੱਕਾ ਕਰੋ ਕਿ ਕੈਮਰਾ ਐਪ ਸਥਾਪਤ ਹੈ"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home ਐਪ ਨੂੰ ਸ਼ਾਰਟਕੱਟ ਵਜੋਂ ਸ਼ਾਮਲ ਕਰਨ ਲਈ, ਪੱਕਾ ਕਰੋ ਕਿ ਐਪ ਸਥਾਪਤ ਹੈ"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• ਘੱਟੋ-ਘੱਟ ਇੱਕ ਡੀਵਾਈਸ ਉਪਲਬਧ ਹੈ"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"ਨੋਟ ਬਣਾਉਣ ਵਾਲੇ ਸ਼ਾਰਟਕੱਟ ਦੀ ਵਰਤੋਂ ਕਰਨ ਲਈ ਪੂਰਵ-ਨਿਰਧਾਰਿਤ ਨੋਟ ਐਪ ਚੁਣੋ"</string>
diff --git a/packages/SystemUI/res/values-pl/strings.xml b/packages/SystemUI/res/values-pl/strings.xml
index 8c0a78e..e3beef0 100644
--- a/packages/SystemUI/res/values-pl/strings.xml
+++ b/packages/SystemUI/res/values-pl/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limit <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Ostrzeżenie: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Aplikacje służbowe"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Wstrzymano"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Podświetlenie nocne"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Włącz o zachodzie"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Do wschodu słońca"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Powiększ część ekranu"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Otwórz ustawienia powiększenia"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Zamknij ustawienia powiększenia"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Przeciągnij róg, aby zmienić rozmiar"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Zezwalaj na przewijanie poprzeczne"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Zmień rozmiar"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Otwórz: <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Aby dodać aplikację Portfel jako skrót, upewnij się, że jest zainstalowana"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Aby dodać aplikację Portfel jako skrót, upewnij się, że została dodana co najmniej 1 karta"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Aby dodać Skaner kodów QR jako skrót, upewnij się, że jest zainstalowana aplikacja aparatu"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Aby dodać aplikację Home jako skrót, upewnij się, że jest zainstalowana"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Dostępne jest co najmniej 1 urządzenie."</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Wybierz domyślną aplikację do obsługi notatek, której skrótu będziesz używać do funkcji notowania"</string>
diff --git a/packages/SystemUI/res/values-pt-rBR/strings.xml b/packages/SystemUI/res/values-pt-rBR/strings.xml
index bf976f7..8f5d7fa 100644
--- a/packages/SystemUI/res/values-pt-rBR/strings.xml
+++ b/packages/SystemUI/res/values-pt-rBR/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limite: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Aviso de <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Apps de trabalho"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pausado"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Modo noturno"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Ativ. ao pôr do sol"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Até o nascer do sol"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Ampliar parte da tela"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Abrir as configurações de ampliação"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Fechar configurações de ampliação"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Sair do modo de edição"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Arraste o canto para redimensionar"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Permitir rolagem diagonal"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Redimensionar"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Abrir <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Para adicionar o app Carteira como um atalho, verifique se ele está instalado"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Para adicionar o app Carteira como um atalho, verifique se pelo menos um cartão foi adicionado"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Para adicionar o leitor de código QR como um atalho, verifique se algum app de câmera está instalado"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Para adicionar o app Home como um atalho, verifique se ele está instalado"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Pelo menos um dispositivo está disponível"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Selecione um app de notas padrão para usar o atalho de anotações"</string>
diff --git a/packages/SystemUI/res/values-pt-rPT/strings.xml b/packages/SystemUI/res/values-pt-rPT/strings.xml
index 9974df1..a4f17b6 100644
--- a/packages/SystemUI/res/values-pt-rPT/strings.xml
+++ b/packages/SystemUI/res/values-pt-rPT/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limite de <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Aviso de <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Apps trabalho"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pausado"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Luz noturna"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Ativ. ao pôr-do-sol"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Até ao amanhecer"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Ampliar parte do ecrã"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Abrir definições de ampliação"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Fechar definições de ampliação"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Sair do modo de edição"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Arrastar o canto para redimensionar"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Permitir deslocamento da página na diagonal"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Redimensionar"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Abrir <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Para adicionar a app Carteira como um atalho, certifique-se de que a app está instalada"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Para adicionar a app Carteira como um atalho, certifique-se de que foi adicionado, pelo menos, um cartão"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Para adicionar o Leitor de códigos QR como um atalho, certifique-se de que está instalada uma app de câmara"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Para adicionar a app Home como um atalho, certifique-se de que a app está instalada"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Está disponível, pelo menos, um dispositivo"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Selecione uma app de notas predefinida para usar o atalho de anotação"</string>
diff --git a/packages/SystemUI/res/values-pt/strings.xml b/packages/SystemUI/res/values-pt/strings.xml
index bf976f7..8f5d7fa 100644
--- a/packages/SystemUI/res/values-pt/strings.xml
+++ b/packages/SystemUI/res/values-pt/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limite: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Aviso de <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Apps de trabalho"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pausado"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Modo noturno"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Ativ. ao pôr do sol"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Até o nascer do sol"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Ampliar parte da tela"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Abrir as configurações de ampliação"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Fechar configurações de ampliação"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Sair do modo de edição"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Arraste o canto para redimensionar"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Permitir rolagem diagonal"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Redimensionar"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Abrir <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Para adicionar o app Carteira como um atalho, verifique se ele está instalado"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Para adicionar o app Carteira como um atalho, verifique se pelo menos um cartão foi adicionado"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Para adicionar o leitor de código QR como um atalho, verifique se algum app de câmera está instalado"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Para adicionar o app Home como um atalho, verifique se ele está instalado"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Pelo menos um dispositivo está disponível"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Selecione um app de notas padrão para usar o atalho de anotações"</string>
diff --git a/packages/SystemUI/res/values-ro/strings.xml b/packages/SystemUI/res/values-ro/strings.xml
index 1ed3a37..749106b 100644
--- a/packages/SystemUI/res/values-ro/strings.xml
+++ b/packages/SystemUI/res/values-ro/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limită de <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Avertizare: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Aplicații pentru lucru"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Întreruptă"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Lumină de noapte"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Activată la apus"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Până la răsărit"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Mărește o parte a ecranului"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Deschide setările pentru mărire"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Închide setările de mărire"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Trage de colț pentru a redimensiona"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Permite derularea pe diagonală"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Redimensionează"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Deschide <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Pentru a adăuga aplicația Portofel drept comandă rapidă, asigură-te că aplicația este instalată"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Pentru a adăuga aplicația Portofel drept comandă rapidă, asigură-te că ai adăugat cel puțin un card"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Pentru a adăuga Scanner de coduri QR drept comandă rapidă, asigură-te că este instalată o aplicație pentru camera foto"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Pentru a adăuga aplicația Home drept comandă rapidă, asigură-te că aplicația este instalată"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Este disponibil cel puțin un dispozitiv"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Selectează o aplicație prestabilită pentru note ca să folosești comanda rapidă de luat note"</string>
@@ -1167,7 +1169,7 @@
     <string name="set_default_notes_app_toast_content" msgid="2812374329662610753">"Setează aplicația prestabilită de note din Setări"</string>
     <string name="install_app" msgid="5066668100199613936">"Instalează aplicația"</string>
     <string name="privacy_dialog_title" msgid="7839968133469098311">"Microfon și cameră"</string>
-    <string name="privacy_dialog_summary" msgid="2458769652125995409">"Folosit recent de aplicații"</string>
+    <string name="privacy_dialog_summary" msgid="2458769652125995409">"Utilizare recentă în aplicații"</string>
     <string name="privacy_dialog_more_button" msgid="7610604080293562345">"Vezi accesarea recentă"</string>
     <string name="privacy_dialog_done_button" msgid="4504330708531434263">"Gata"</string>
     <string name="privacy_dialog_expand_action" msgid="9129262348628331377">"Extinde și afișează opțiunile"</string>
@@ -1178,10 +1180,10 @@
     <string name="privacy_dialog_manage_permissions" msgid="2543451567190470413">"Gestionează accesul"</string>
     <string name="privacy_dialog_active_call_usage" msgid="7858746847946397562">"Folosit de un apel telefonic"</string>
     <string name="privacy_dialog_recent_call_usage" msgid="1214810644978167344">"Folosit recent într-un apel telefonic"</string>
-    <string name="privacy_dialog_active_app_usage" msgid="631997836335929880">"Folosit de <xliff:g id="APP_NAME">%1$s</xliff:g>"</string>
-    <string name="privacy_dialog_recent_app_usage" msgid="4883417856848222450">"Folosit recent de <xliff:g id="APP_NAME">%1$s</xliff:g>"</string>
-    <string name="privacy_dialog_active_app_usage_1" msgid="9047570143069220911">"Folosit de <xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g>)"</string>
+    <string name="privacy_dialog_active_app_usage" msgid="631997836335929880">"Se folosește pentru <xliff:g id="APP_NAME">%1$s</xliff:g>"</string>
+    <string name="privacy_dialog_recent_app_usage" msgid="4883417856848222450">"S-a folosit recent de <xliff:g id="APP_NAME">%1$s</xliff:g>"</string>
+    <string name="privacy_dialog_active_app_usage_1" msgid="9047570143069220911">"Se folosește pentru <xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g>)"</string>
     <string name="privacy_dialog_recent_app_usage_1" msgid="2551340497722370109">"Folosit recent de <xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g>)"</string>
-    <string name="privacy_dialog_active_app_usage_2" msgid="2770926061339921767">"Folosit de <xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g> • <xliff:g id="PROXY_LABEL">%3$s</xliff:g>)"</string>
+    <string name="privacy_dialog_active_app_usage_2" msgid="2770926061339921767">"Se folosește pentru <xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g> • <xliff:g id="PROXY_LABEL">%3$s</xliff:g>)"</string>
     <string name="privacy_dialog_recent_app_usage_2" msgid="2874689735085367167">"Folosit recent de <xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g> • <xliff:g id="PROXY_LABEL">%3$s</xliff:g>)"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-ru/strings.xml b/packages/SystemUI/res/values-ru/strings.xml
index 400db7b..5f7445a 100644
--- a/packages/SystemUI/res/values-ru/strings.xml
+++ b/packages/SystemUI/res/values-ru/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Ограничение: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Предупреждение: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Рабочие приложения"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Приостановлен"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Ночная подсветка"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Вкл. на закате"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"До рассвета"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Увеличить часть экрана"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Открыть настройки увеличения"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Закрыть настройки увеличения"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Потяните за угол, чтобы изменить размер"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Разрешить прокручивать по диагонали"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Изменить размер"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Открыть \"<xliff:g id="APPNAME">%1$s</xliff:g>\""</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Вы можете добавить ярлык приложения \"Кошелек\", только если оно установлено."</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Вы можете добавить ярлык приложения \"Кошелек\", только если добавлена хотя бы одна карта."</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Вы можете добавить ярлык сканера QR-кодов, только если установлено приложение камеры."</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Вы можете добавить ярлык приложения Home, только если оно установлено."</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Доступно хотя бы одно устройство."</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Выберите стандартное приложение для заметок, которое будет открываться при нажатии на ярлык."</string>
diff --git a/packages/SystemUI/res/values-si/strings.xml b/packages/SystemUI/res/values-si/strings.xml
index 37a14f9..5cc1fa9 100644
--- a/packages/SystemUI/res/values-si/strings.xml
+++ b/packages/SystemUI/res/values-si/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> සීමිත"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> අවවාද කිරීම"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"කාර්යාල යෙදුම්"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"විරාමයි"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"රාත්‍රී ආලෝකය"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"හිරු බැසීමේදී ක්‍රි."</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"හිරු නගින තෙක්"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"තිරයේ කොටසක් විශාලනය කරන්න"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"විශාලන සැකසීම් විවෘත කරන්න"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"විශාලන සැකසීම් වසන්න"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"ප්‍රමාණය වෙනස් කිරීමට කොන අදින්න"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"විකර්ණ අනුචලනයට ඉඩ දෙන්න"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"ප්‍රතිප්‍රමාණය කරන්න"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> විවෘත කරන්න"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"කෙටිමඟක් ලෙස Wallet යෙදුම එක් කිරීම සඳහා, යෙදුම ස්ථාපනය කර ඇති බවට වග බලා ගන්න"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"කෙටිමඟක් ලෙස Wallet යෙදුම එක් කිරීම සඳහා, අවම වශයෙන් එක් කාඩ්පතක් එක් කර ඇති බවට වග බලා ගන්න"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"කෙටිමඟක් ලෙස QR කේත ස්කෑනරය එක් කිරීම සඳහා, කැමරා යෙදුමක් ස්ථාපනය කර ඇති බවට වග බලා ගන්න"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home යෙදුම කෙටිමඟක් ලෙස එක් කිරීම සඳහා, යෙදුම ස්ථාපනය කර ඇති බව සහතික කර ගන්න"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• අවම වශයෙන් එක උපාංගයක් ලැබේ"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"සටහන් ගැනීමේ කෙටිමඟ භාවිතා කිරීමට පෙරනිමි සටහන් යෙදුමක් තෝරන්න"</string>
diff --git a/packages/SystemUI/res/values-sk/strings.xml b/packages/SystemUI/res/values-sk/strings.xml
index baa9b4f..1da7aca 100644
--- a/packages/SystemUI/res/values-sk/strings.xml
+++ b/packages/SystemUI/res/values-sk/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Limit: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Upozornenie pri <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Pracovné aplikácie"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pozastavené"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Nočný režim"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Zapne sa pri západe slnka"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Do východu slnka"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Zväčšiť časť obrazovky"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Otvoriť nastavenia zväčšenia"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Zavrieť nastavenia zväčšenia"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Veľkosť zmeníte presunutím rohu"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Povoliť diagonálne posúvanie"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Zmeniť veľkosť"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Otvoriť <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Ak chcete pridať aplikáciu Peňaženka ako odkaz, uistite sa, že je nainštalovaná"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Ak chcete pridať aplikáciu Peňaženka ako odkaz, uistite sa, že bola pridaná aspoň jedna karta"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Ak chcete pridať skener QR kódov ako odkaz, uistite, že je nainštalovaná aplikácia fotoaparátu"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Ak chcete pridať aplikáciu Home ako odkaz, uistite sa, že je nainštalovaná"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• K dispozícii je minimálne jedno zariadenie"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Ak chcete používať odkaz na písanie poznámok, vyberte predvolenú aplikáciu na písanie poznámok"</string>
diff --git a/packages/SystemUI/res/values-sl/strings.xml b/packages/SystemUI/res/values-sl/strings.xml
index 3608293..79e5437 100644
--- a/packages/SystemUI/res/values-sl/strings.xml
+++ b/packages/SystemUI/res/values-sl/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Omejitev: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Opozorilo – <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Delovne aplikacije"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Začasno zaustavljeno"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Nočna svetloba"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Ob sončnem zahodu"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Do sončnega vzhoda"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Povečava dela zaslona"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Odpri nastavitve povečave"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Zapri nastavitve povečave"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Zapri način za urejanje"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Povlecite vogal, da spremenite velikost."</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Dovoli diagonalno pomikanje"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Spremeni velikost"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Odpri aplikacijo <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Če želite aplikacijo Denarnica dodati kot bližnjico, poskrbite, da je aplikacija nameščena."</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Če želite aplikacijo Denarnica dodati kot bližnjico, poskrbite, da je dodana vsaj ena kartica."</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Če želite optični bralnik kod QR dodati kot bližnjico, poskrbite, da je nameščena fotografska aplikacija."</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Če želite aplikacijo Home dodati kot bližnjico, poskrbite, da je aplikacija nameščena."</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Na voljo mora biti vsaj ena naprava."</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Izberite privzeto aplikacijo za zapiske, ki jo želite povezati z bližnjico do ustvarjanja zapiskov."</string>
diff --git a/packages/SystemUI/res/values-sq/strings.xml b/packages/SystemUI/res/values-sq/strings.xml
index 6e1edff..5b58fc7 100644
--- a/packages/SystemUI/res/values-sq/strings.xml
+++ b/packages/SystemUI/res/values-sq/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Kufiri: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Paralajmërim për kufirin prej <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Aplikacionet e punës"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Vendosur në pauzë"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Drita e natës"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Në perëndim të diellit"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Deri në lindje të diellit"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Zmadho një pjesë të ekranit"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Hap cilësimet e zmadhimit"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Mbyll cilësimet e zmadhimit"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Zvarrit këndin për të ndryshuar përmasat"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Lejo lëvizjen diagonale"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Ndrysho përmasat"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Hap \"<xliff:g id="APPNAME">%1$s</xliff:g>\""</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Për të shtuar aplikacionin \"Portofoli\" si një shkurtore, sigurohu që aplikacioni të jetë i instaluar"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Për të shtuar aplikacionin \"Portofoli\" si një shkurtore, sigurohu që të jetë shtuar të paktën një kartë"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Për të shtuar skanerin e kodeve QR si një shkurtore, sigurohu që aplikacioni i kamerës të jetë i instaluar"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Për të shtuar aplikacionin Home si një shkurtore, sigurohu që aplikacioni të jetë i instaluar"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Ofrohet të paktën një pajisje"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Zgjidh një aplikacion të parazgjedhur shënimesh për të përdorur shkurtoren e mbajtjes së shënimeve"</string>
diff --git a/packages/SystemUI/res/values-sr/strings.xml b/packages/SystemUI/res/values-sr/strings.xml
index 0a73cf5..eee0fe6 100644
--- a/packages/SystemUI/res/values-sr/strings.xml
+++ b/packages/SystemUI/res/values-sr/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Ограничење од <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Упозорење за <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Пословне апликације"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Паузирано"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Ноћно светло"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Укључује се по заласку сунца"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"До изласка сунца"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Увећајте део екрана"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Отвори подешавања увећања"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Затвори подешавања увећања"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"Затвори режим измене"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Превуците угао да бисте променили величину"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Дозволи дијагонално скроловање"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Промени величину"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Отворите: <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Да бисте додали апликацију Новчаник као пречицу, уверите се да је апликација инсталирана"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Да бисте додали апликацију Новчаник као пречицу, уверите се да је додата бар једна картица"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Да бисте додали Скенер QR кода као пречицу, уверите се да је апликација за камеру инсталирана"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Да бисте додали апликацију Home као пречицу, уверите се да је апликација инсталирана"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Доступан је бар један уређај"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Изаберите подразумевану апликацију за белешке да бисте користили пречицу за прављење белешки"</string>
diff --git a/packages/SystemUI/res/values-sv/strings.xml b/packages/SystemUI/res/values-sv/strings.xml
index 9329e19..b996649 100644
--- a/packages/SystemUI/res/values-sv/strings.xml
+++ b/packages/SystemUI/res/values-sv/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Gräns: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Varning <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Jobbappar"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pausad"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Nattljus"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"På från solnedgången"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Till soluppgången"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Förstora en del av skärmen"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Öppna inställningarna för förstoring"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Stäng inställningarna för förstoring"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Dra i hörnet för att ändra storlek"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Tillåt diagonal scrollning"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Ändra storlek"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Öppna <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Se till att Wallet-appen är installerad om du vill lägga till den som genväg"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Se till att minst ett kort har lagts till om du vill lägga till Wallet-appen som genväg"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Se till att en kameraapp är installerad om du vill lägga till QR-skannern som genväg"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Se till att Home-appen är installerad om du vill lägga till den som genväg"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• minst en enhet är tillgänglig"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Välj en standardapp för anteckningar om du vill använda genvägen för anteckningar"</string>
diff --git a/packages/SystemUI/res/values-sw/strings.xml b/packages/SystemUI/res/values-sw/strings.xml
index 7c0df30..b00f9b6 100644
--- a/packages/SystemUI/res/values-sw/strings.xml
+++ b/packages/SystemUI/res/values-sw/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"kikomo <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Onyo <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Programu za kazini"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Umesitishwa"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Mwanga wa Usiku"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Itawashwa machweo"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Hadi macheo"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Kuza sehemu ya skrini"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Fungua mipangilio ya ukuzaji"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Funga mipangilio ya ukuzaji"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Buruta kona ili ubadilishe ukubwa"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Ruhusu usogezaji wa kimshazari"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Badilisha ukubwa"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Fungua <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Ili uweke programu ya Pochi kuwa njia ya mkato, hakikisha umesakinisha programu hiyo"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Ili uweke programu ya Pochi kuwa njia ya mkato, hakikisha umeweka angalau kadi moja"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Ili uweke kichanganuzi cha msimbo wa QR kuwa njia ya mkato, hakikisha umesakinisha programu ya kamera"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Ili uweke programu ya Google Home kuwa njia ya mkato, hakikisha umesakinisha programu hiyo"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Angalau kifaa kimoja kinapatikana"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Chagua programu chaguomsingi ya madokezo ili utumie njia ya mkato ya kuandika madokezo"</string>
diff --git a/packages/SystemUI/res/values-sw600dp/dimens.xml b/packages/SystemUI/res/values-sw600dp/dimens.xml
index 7e892f7..915dcdb 100644
--- a/packages/SystemUI/res/values-sw600dp/dimens.xml
+++ b/packages/SystemUI/res/values-sw600dp/dimens.xml
@@ -21,9 +21,11 @@
     <dimen name="status_bar_header_height_keyguard">@dimen/status_bar_height</dimen>
 
     <!-- padding for container with status icons and battery -->
-    <dimen name="status_bar_icons_padding_end">12dp</dimen>
+    <dimen name="status_bar_icons_padding_end">4dp</dimen>
     <!-- start padding is smaller to account for status icon margins coming from drawable itself -->
-    <dimen name="status_bar_icons_padding_start">11dp</dimen>
+    <dimen name="status_bar_icons_padding_start">3dp</dimen>
+    <dimen name="status_bar_icons_padding_bottom">2dp</dimen>
+    <dimen name="status_bar_icons_padding_top">2dp</dimen>
 
     <dimen name="status_bar_padding_end">0dp</dimen>
 
@@ -78,8 +80,10 @@
 
     <dimen name="large_screen_shade_header_height">42dp</dimen>
     <!-- start padding is smaller to account for status icon margins coming from drawable itself -->
-    <dimen name="shade_header_system_icons_padding_start">11dp</dimen>
-    <dimen name="shade_header_system_icons_padding_end">12dp</dimen>
+    <dimen name="shade_header_system_icons_padding_start">3dp</dimen>
+    <dimen name="shade_header_system_icons_padding_end">4dp</dimen>
+    <dimen name="shade_header_system_icons_padding_top">2dp</dimen>
+    <dimen name="shade_header_system_icons_padding_bottom">2dp</dimen>
 
     <!-- Lockscreen shade transition values -->
     <dimen name="lockscreen_shade_transition_by_tap_distance">200dp</dimen>
diff --git a/packages/SystemUI/res/values-sw720dp/dimens.xml b/packages/SystemUI/res/values-sw720dp/dimens.xml
index d74eca6..dc1f0e4 100644
--- a/packages/SystemUI/res/values-sw720dp/dimens.xml
+++ b/packages/SystemUI/res/values-sw720dp/dimens.xml
@@ -16,9 +16,6 @@
 */
 -->
 <resources>
-    <!-- it's a bit smaller on 720dp to account for status_bar_icon_horizontal_margin -->
-    <dimen name="status_bar_icons_padding_start">10dp</dimen>
-
     <!-- gap on either side of status bar notification icons -->
     <dimen name="status_bar_icon_horizontal_margin">1sp</dimen>
 
@@ -30,9 +27,6 @@
 
     <dimen name="large_screen_shade_header_height">56dp</dimen>
 
-    <!-- it's a bit smaller on 720dp to account for status_bar_icon_horizontal_margin -->
-    <dimen name="shade_header_system_icons_padding_start">10dp</dimen>
-
     <!-- Biometric Auth pattern view size, better to align keyguard_security_width -->
     <dimen name="biometric_auth_pattern_view_size">348dp</dimen>
 </resources>
diff --git a/packages/SystemUI/res/values-ta/strings.xml b/packages/SystemUI/res/values-ta/strings.xml
index 4c6816b..57f537f 100644
--- a/packages/SystemUI/res/values-ta/strings.xml
+++ b/packages/SystemUI/res/values-ta/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> வரம்பு"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> எச்சரிக்கை"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"பணி ஆப்ஸ்"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"இடைநிறுத்தப்பட்டது"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"நைட் லைட்"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"மாலையில் ஆன் செய்"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"காலை வரை"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"திரையின் ஒரு பகுதியைப் பெரிதாக்கும்"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"பெரிதாக்கல் அமைப்புகளைத் திற"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"பெரிதாக்கல் அமைப்புகளை மூடுக"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"அளவை மாற்ற மூலையை இழுக்கவும்"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"குறுக்கே ஸ்க்ரோல் செய்வதை அனுமதி"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"அளவை மாற்று"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> ஆப்ஸைத் திற"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet ஆப்ஸை ஷார்ட்கட்டாகச் சேர்க்க, அந்த ஆப்ஸ் நிறுவப்பட்டுள்ளதை உறுதிசெய்துகொள்ளவும்"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet ஆப்ஸை ஷார்ட்கட்டாகச் சேர்க்க, அதில் குறைந்தது ஒரு கார்டாவது சேர்க்கப்பட்டுள்ளதை உறுதிசெய்துகொள்ளவும்"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR குறியீடு ஸ்கேனரை ஷார்ட்கட்டாகச் சேர்க்க, கேமரா ஆப்ஸ் நிறுவப்பட்டுள்ளதை உறுதிசெய்துகொள்ளவும்"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home ஆப்ஸை ஷார்ட்கட்டாகச் சேர்க்க, அந்த ஆப்ஸ் நிறுவப்பட்டுள்ளதை உறுதிசெய்துகொள்ளவும்"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• குறைந்தபட்சம் ஒரு சாதனமாவது இருக்கிறது"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"குறிப்பெடுத்தல் ஷார்ட்கட்டைப் பயன்படுத்த, குறிப்பெடுப்பதற்கான இயல்புநிலை ஆப்ஸைத் தேர்ந்தெடுக்கவும்"</string>
diff --git a/packages/SystemUI/res/values-te/strings.xml b/packages/SystemUI/res/values-te/strings.xml
index f501d32..124f273 100644
--- a/packages/SystemUI/res/values-te/strings.xml
+++ b/packages/SystemUI/res/values-te/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> పరిమితి"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> హెచ్చరిక"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"వర్క్ యాప్‌లు"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"పాజ్ చేయబడింది"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"రాత్రి కాంతి"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"సూర్యాస్తమయానికి"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"సూర్యోదయం వరకు"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"స్క్రీన్‌లో భాగాన్ని మ్యాగ్నిఫై చేయండి"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"మ్యాగ్నిఫికేషన్ సెట్టింగ్‌లను తెరవండి"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"మాగ్నిఫికేషన్ సెట్టింగ్‌లను మూసివేయండి"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"సవరణ మోడ్ నుండి ఎగ్జిట్ అవ్వండి"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"సైజ్ మార్చడానికి మూలను లాగండి"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"డయాగనల్ స్క్రోలింగ్‌ను అనుమతించండి"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"సైజ్ మార్చండి"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g>‌ను తెరవండి"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet యాప్‌ను షార్ట్‌కట్‌గా జోడించడానికి, యాప్ ఇన్‌స్టాల్ చేయబడిందని నిర్ధారించుకోండి"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet యాప్‌ను షార్ట్‌కట్‌గా జోడించడానికి, కనీసం ఒక కార్డ్ జోడించబడిందని నిర్ధారించుకోండి"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR కోడ్ స్కానర్‌ను షార్ట్‌కట్‌గా జోడించడానికి, కెమెరా యాప్ ఇన్‌స్టాల్ చేయబడిందని నిర్ధారించుకోండి"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home యాప్‌ను షార్ట్‌కట్‌గా జోడించడానికి, యాప్ ఇన్‌స్టాల్ చేయబడిందని నిర్ధారించుకోండి"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• కనీసం ఒక పరికరమైనా అందుబాటులో ఉందని"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"నోట్‌టేకింగ్ షార్ట్‌కట్‌ను ఉపయోగించడానికి ఆటోమేటిక్ సెట్టింగ్ నోట్స్ యాప్‌ను ఎంచుకోండి"</string>
diff --git a/packages/SystemUI/res/values-th/strings.xml b/packages/SystemUI/res/values-th/strings.xml
index 7c524d9..46fec04 100644
--- a/packages/SystemUI/res/values-th/strings.xml
+++ b/packages/SystemUI/res/values-th/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"ขีดจำกัด <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"คำเตือน <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"แอปงาน"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"หยุดชั่วคราว"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"แสงตอนกลางคืน"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"เปิดตอนพระอาทิตย์ตก"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"จนพระอาทิตย์ขึ้น"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"ขยายบางส่วนของหน้าจอ"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"เปิดการตั้งค่าการขยาย"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"ปิดการตั้งค่าการขยาย"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"ออกจากโหมดแก้ไข"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"ลากที่มุมเพื่อปรับขนาด"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"อนุญาตการเลื่อนแบบทแยงมุม"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"ปรับขนาด"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"เปิด <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"หากต้องการเพิ่มแอป Wallet เป็นทางลัด โปรดตรวจสอบว่าได้ติดตั้งแอปแล้ว"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"หากต้องการเพิ่มแอป Wallet เป็นทางลัด โปรดตรวจสอบว่าได้เพิ่มบัตรอย่างน้อย 1 ใบแล้ว"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"หากต้องการเพิ่มเครื่องมือสแกนคิวอาร์โค้ดเป็นทางลัด โปรดตรวจสอบว่าได้ติดตั้งแอปกล้องแล้ว"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"หากต้องการเพิ่มแอป Home เป็นทางลัด โปรดตรวจสอบว่าได้ติดตั้งแอปแล้ว"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• มีอุปกรณ์พร้อมใช้งานอย่างน้อย 1 รายการ"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"เลือกแอปโน้ตเริ่มต้นเพื่อใช้ทางลัดการจดบันทึก"</string>
diff --git a/packages/SystemUI/res/values-tl/strings.xml b/packages/SystemUI/res/values-tl/strings.xml
index fc2d8cf..079bd9b 100644
--- a/packages/SystemUI/res/values-tl/strings.xml
+++ b/packages/SystemUI/res/values-tl/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> ang limitasyon"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Babala sa <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Mga app para sa trabaho"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Naka-pause"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Night Light"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Mao-on sa sunset"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Hanggang sunrise"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"I-magnify ang isang bahagi ng screen"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Buksan ang mga setting ng pag-magnify"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Isara ang mga setting ng pag-magnify"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"I-drag ang sulok para i-resize"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Payagan ang diagonal na pag-scroll"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"I-resize"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Buksan ang <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Para maidagdag ang Wallet app bilang shortcut, siguraduhing naka-install ang app"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Para maidagdag ang Wallet app bilang shortcut, siguraduhing may naidagdag na kahit isang card man lang"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Para maidagdag ang scanner ng QR code bilang shortcut, siguraduhing may naka-install na camera app"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Para maidagdag ang Home app bilang shortcut, siguraduhing naka-install ang app"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• May kahit isang device na available"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Pumili ng default na app ng mga tala para magamit ang shortcut sa paggawa ng tala"</string>
diff --git a/packages/SystemUI/res/values-tr/strings.xml b/packages/SystemUI/res/values-tr/strings.xml
index 803acae..7ba95ec 100644
--- a/packages/SystemUI/res/values-tr/strings.xml
+++ b/packages/SystemUI/res/values-tr/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Sınır: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> uyarısı"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"İş uygulamaları"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Duraklatıldı"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Gece Işığı"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Gün batımı açılacak"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Sabaha kadar"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Ekranın bir parçasını büyütün"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Büyütme ayarlarını aç"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Büyütme ayarlarını kapat"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Yeniden boyutlandırmak için köşeyi sürükleyin"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Çapraz kaydırmaya izin ver"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Yeniden boyutlandır"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> uygulamasını aç"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Cüzdan uygulamasını kısayol olarak eklemek için uygulamanın yüklü olduğundan emin olun"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Cüzdan uygulamasını kısayol olarak eklemek için en az bir kart eklendiğinden emin olun"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR kodu tarayıcıyı kısayol olarak eklemek için bir kamera uygulamasının yüklü olduğundan emin olun"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home uygulamasını kısayol olarak eklemek için uygulamanın yüklü olduğundan emin olun"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• En az bir cihaz mevcut olmalıdır"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Not alma kısayolunu kullanmak için varsayılan bir notlar uygulaması seçin"</string>
diff --git a/packages/SystemUI/res/values-uk/strings.xml b/packages/SystemUI/res/values-uk/strings.xml
index 668fb59..3feefef 100644
--- a/packages/SystemUI/res/values-uk/strings.xml
+++ b/packages/SystemUI/res/values-uk/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Обмеження: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Застереження: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Робочі додатки"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Призупинено"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Нічний екран"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Вмикається ввечері"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"До сходу сонця"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Збільшити частину екрана"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Відкрити налаштування збільшення"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Закрити налаштування збільшення"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Потягніть кут, щоб змінити розмір"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Дозволити прокручування по діагоналі"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Змінити розмір"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Відкрити <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Щоб додати ярлик для запуску додатка Google Гаманець, переконайтеся, що додаток установлено"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Щоб додати ярлик для запуску додатка Google Гаманець, переконайтеся, що він містить дані принаймні однієї картки"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Щоб додати ярлик для запуску сканера QR-коду, переконайтеся, що встановлено додаток для камери"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Щоб додати ярлик для запуску додатка Google Home, переконайтеся, що додаток установлено"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Принаймні один пристрій доступний"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Виберіть стандартний додаток для нотаток, щоб створювати їх за допомогою ярлика"</string>
diff --git a/packages/SystemUI/res/values-ur/strings.xml b/packages/SystemUI/res/values-ur/strings.xml
index 33d11d9..29d3762 100644
--- a/packages/SystemUI/res/values-ur/strings.xml
+++ b/packages/SystemUI/res/values-ur/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> حد"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> وارننگ"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"دفتری ایپس"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"موقوف ہے"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"نائٹ لائٹ"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"غروب آفتاب کے وقت آن ہوگی"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"طلوع آفتاب تک"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"اسکرین کا حصہ بڑا کریں"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"میگنیفکیشن کی ترتیبات کھولیں"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"میگنیفکیشن کی ترتیبات بند کریں"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"سائز تبدیل کرنے کے لیے کونے کو گھسیٹیں"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"وتری سکرولنگ کی اجازت دیں"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"سائز تبدیل کریں"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"<xliff:g id="APPNAME">%1$s</xliff:g> کھولیں"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"والٹ ایپ کو شارٹ کٹ کے طور پر شامل کرنے کے لیے، یقینی بنائیں کہ ایپ انسٹال ہے"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"والٹ ایپ کو شارٹ کٹ کے طور پر شامل کرنے کے لیے، یقینی بنائیں کہ کم از کم ایک کارڈ شامل کیا گیا ہے"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"‏QR کوڈ اسکینر کو شارٹ کٹ کے طور پر شامل کرنے کے لیے، یقینی بنائیں کہ کیمرا ایپ انسٹال ہے"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"ہوم ایپ کو شارٹ کٹ کے طور پر شامل کرنے کے لیے، یقینی بنائیں کہ ایپ انسٹال ہے"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• کم از کم ایک آلہ دستیاب ہے"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"نوٹ لینے والے شارٹ کٹ کا استعمال کرنے کے لیے ڈیفالٹ نوٹس ایپ منتخب کریں"</string>
@@ -1178,8 +1180,8 @@
     <string name="privacy_dialog_manage_permissions" msgid="2543451567190470413">"رسائی کا نظم کریں"</string>
     <string name="privacy_dialog_active_call_usage" msgid="7858746847946397562">"فون کال کے زیر استعمال"</string>
     <string name="privacy_dialog_recent_call_usage" msgid="1214810644978167344">"فون کال میں حال ہی میں استعمال کیا گیا"</string>
-    <string name="privacy_dialog_active_app_usage" msgid="631997836335929880">"<xliff:g id="APP_NAME">%1$s</xliff:g> کے زیر استعمال"</string>
-    <string name="privacy_dialog_recent_app_usage" msgid="4883417856848222450">"<xliff:g id="APP_NAME">%1$s</xliff:g> کے ذریعے حال ہی میں استعمال کیا گیا"</string>
+    <string name="privacy_dialog_active_app_usage" msgid="631997836335929880">"‫<xliff:g id="APP_NAME">%1$s</xliff:g> کے زیر استعمال"</string>
+    <string name="privacy_dialog_recent_app_usage" msgid="4883417856848222450">"حال ہی میں <xliff:g id="APP_NAME">%1$s</xliff:g> نے استعمال کیا"</string>
     <string name="privacy_dialog_active_app_usage_1" msgid="9047570143069220911">"<xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g>) کے زیر استعمال"</string>
     <string name="privacy_dialog_recent_app_usage_1" msgid="2551340497722370109">"<xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g>) کے ذریعے حال ہی میں استعمال کیا گیا"</string>
     <string name="privacy_dialog_active_app_usage_2" msgid="2770926061339921767">"<xliff:g id="APP_NAME">%1$s</xliff:g> (<xliff:g id="ATTRIBUTION_LABEL">%2$s</xliff:g> • <xliff:g id="PROXY_LABEL">%3$s</xliff:g>) کے زیر استعمال"</string>
diff --git a/packages/SystemUI/res/values-uz/strings.xml b/packages/SystemUI/res/values-uz/strings.xml
index 65f5653..b7defbb 100644
--- a/packages/SystemUI/res/values-uz/strings.xml
+++ b/packages/SystemUI/res/values-uz/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Cheklov: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Ogohlantirish: <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Ish ilovalari"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Pauzada"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Tungi rejim"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Kunbotarda yoqish"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Quyosh chiqqunicha"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Ekran qismini kattalashtirish"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Kattalashtirish sozlamalarini ochish"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Kattalashtirish sozlamalarini yopish"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Oʻlchamini oʻzgartirish uchun burchakni torting"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Diagonal aylantirishga ruxsat berish"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Oʻlchamini oʻzgartirish"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Ochish: <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Wallet ilovasini yorliq sifatida qoʻshish uchun ilova oʻrnatilganiga ishonch hosil qiling"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Wallet ilovasini yorliq sifatida qoʻshish uchun kamida bitta karta kiritilganiga ishonch hosil qiling"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"QR kod skanerini yorliq sifatida qoʻshish uchun kamera ilovasi oʻrnatilganiga ishonch hosil qiling"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Home ilovasini yorliq sifatida qoʻshish uchun ilova oʻrnatilganiga ishonch hosil qiling"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Kamida bitta qurilma mavjud"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Qayd yozish yorligʻidan foydalanish uchun birlamchi qayd ilovasini tanlang"</string>
diff --git a/packages/SystemUI/res/values-vi/strings.xml b/packages/SystemUI/res/values-vi/strings.xml
index 8be1dd5..2d49b02 100644
--- a/packages/SystemUI/res/values-vi/strings.xml
+++ b/packages/SystemUI/res/values-vi/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"Giới hạn <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"Cảnh báo <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Ứng dụng công việc"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Đã tạm dừng"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Ánh sáng đêm"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Bật khi trời tối"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Cho đến khi trời sáng"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Phóng to một phần màn hình"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Mở chế độ cài đặt phóng to"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Đóng bảng cài đặt tính năng phóng to"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Kéo góc để thay đổi kích thước"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Cho phép cuộn chéo"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Đổi kích thước"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Mở <xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Để tạo lối tắt cho ứng dụng Wallet, hãy đảm bảo bạn đã cài đặt ứng dụng đó"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Để tạo lối tắt cho ứng dụng Wallet, hãy đảm bảo bạn đã thêm ít nhất một thẻ"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Để tạo lối tắt cho Trình quét mã QR, hãy đảm bảo rằng bạn đã cài đặt một ứng dụng máy ảnh"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Để tạo lối tắt cho ứng dụng Home, hãy đảm bảo bạn đã cài đặt ứng dụng đó"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Có ít nhất một thiết bị đang hoạt động"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Chọn một ứng dụng ghi chú mặc định để dùng lối tắt ghi chú"</string>
diff --git a/packages/SystemUI/res/values-zh-rCN/strings.xml b/packages/SystemUI/res/values-zh-rCN/strings.xml
index 299ebf9..8d2b89b 100644
--- a/packages/SystemUI/res/values-zh-rCN/strings.xml
+++ b/packages/SystemUI/res/values-zh-rCN/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"上限为<xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g>警告"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"工作应用"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"已暂停"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"护眼模式"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"在日落时开启"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"在日出时关闭"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"放大部分屏幕"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"打开放大功能设置"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"关闭放大设置"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"退出修改模式"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"拖动一角即可调整大小"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"允许沿对角线滚动"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"调整大小"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"打开<xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"若要将 Google 钱包应用添加为快捷方式,请确保已安装该应用"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"若要将 Google 钱包应用添加为快捷方式,请确保至少已添加一张银行卡"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"若要将二维码扫描器添加为快捷方式,请确保已安装相机应用"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"若要将 Home 应用添加为快捷方式,请确保已安装该应用"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• 至少有一台设备可用"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"选择默认记事应用即可使用记事快捷方式"</string>
diff --git a/packages/SystemUI/res/values-zh-rHK/strings.xml b/packages/SystemUI/res/values-zh-rHK/strings.xml
index fb40f32..9e408f2 100644
--- a/packages/SystemUI/res/values-zh-rHK/strings.xml
+++ b/packages/SystemUI/res/values-zh-rHK/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"上限為 <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> 警告"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"工作應用程式"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"已暫停"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"夜間模式"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"在日落時開啟"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"在日出時關閉"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"放大部分螢幕畫面"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"開啟放大設定"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"關閉放大設定"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"結束編輯模式"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"拖曳角落即可調整大小"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"允許斜角捲動"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"調整大小"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"開啟「<xliff:g id="APPNAME">%1$s</xliff:g>」"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"如要將「錢包」應用程式新增為捷徑,請確認已安裝該應用程式"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"如要將「錢包」應用程式新增為捷徑,請確認已新增至少一張付款卡"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"如要將 QR 碼掃瞄器新增為捷徑,請確認已安裝相機應用程式"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"如要將 Home 應用程式新增為捷徑,請確認已安裝該應用程式"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• 至少一部裝置可用"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"選取預設的筆記應用程式,即可使用筆記捷徑"</string>
diff --git a/packages/SystemUI/res/values-zh-rTW/strings.xml b/packages/SystemUI/res/values-zh-rTW/strings.xml
index 4750b5b..5831ac5 100644
--- a/packages/SystemUI/res/values-zh-rTW/strings.xml
+++ b/packages/SystemUI/res/values-zh-rTW/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"上限為 <xliff:g id="DATA_LIMIT">%s</xliff:g>"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> 警告"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"工作應用程式"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"已暫停"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"夜燈"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"於日落時開啟"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"於日出時關閉"</string>
@@ -864,6 +865,7 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"放大局部螢幕畫面"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"開啟放大功能設定"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"關閉放大設定"</string>
+    <string name="magnification_exit_edit_mode_click_label" msgid="1664818325144887117">"結束編輯模式"</string>
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"拖曳角落即可調整大小"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"允許沿對角線捲動"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"調整大小"</string>
@@ -1133,7 +1135,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"開啟「<xliff:g id="APPNAME">%1$s</xliff:g>」"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"如要將錢包應用程式新增為捷徑,請確認已安裝該應用程式"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"如要將錢包應用程式新增為捷徑,請確認已新增至少一張卡片"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"如要將 QR code 掃描器新增為捷徑,請確認已安裝相機應用程式"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"如要將 Google Home 應用程式新增為捷徑,請確認已安裝該應用程式"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• 至少要有一部可用裝置"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"選取預設的記事應用程式,即可使用筆記捷徑"</string>
diff --git a/packages/SystemUI/res/values-zu/strings.xml b/packages/SystemUI/res/values-zu/strings.xml
index e22d1d7..5013f8d 100644
--- a/packages/SystemUI/res/values-zu/strings.xml
+++ b/packages/SystemUI/res/values-zu/strings.xml
@@ -295,6 +295,7 @@
     <string name="quick_settings_cellular_detail_data_limit" msgid="1791389609409211628">"<xliff:g id="DATA_LIMIT">%s</xliff:g> umkhawulo"</string>
     <string name="quick_settings_cellular_detail_data_warning" msgid="7957253810481086455">"<xliff:g id="DATA_LIMIT">%s</xliff:g> isexwayiso"</string>
     <string name="quick_settings_work_mode_label" msgid="6440531507319809121">"Ama-app omsebenzi"</string>
+    <string name="quick_settings_work_mode_paused_state" msgid="6681788236383735976">"Kumisiwe"</string>
     <string name="quick_settings_night_display_label" msgid="8180030659141778180">"Ukukhanya kwasebusuku"</string>
     <string name="quick_settings_night_secondary_label_on_at_sunset" msgid="3358706312129866626">"Kuvulwe ekushoneni kwelanga"</string>
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4063448287758262485">"Kuze kube sekuphumeni kwelanga"</string>
@@ -864,6 +865,8 @@
     <string name="magnification_mode_switch_state_window" msgid="8597100249594076965">"Khulisa ingxenye eyesikrini"</string>
     <string name="magnification_open_settings_click_label" msgid="6151849212725923363">"Vula amasethingi okukhuliswa"</string>
     <string name="magnification_close_settings_click_label" msgid="4642477260651704517">"Vala amasethingi okukhuliswa"</string>
+    <!-- no translation found for magnification_exit_edit_mode_click_label (1664818325144887117) -->
+    <skip />
     <string name="magnification_drag_corner_to_resize" msgid="1249766311052418130">"Hudula ikhona ukuze usayize kabusha"</string>
     <string name="accessibility_allow_diagonal_scrolling" msgid="3258050349191496398">"Vumela ukuskrola oku-diagonal"</string>
     <string name="accessibility_resize" msgid="5733759136600611551">"Shintsha usayizi"</string>
@@ -1133,7 +1136,6 @@
     <string name="keyguard_affordance_enablement_dialog_action_template" msgid="8164857863036314664">"Vula i-<xliff:g id="APPNAME">%1$s</xliff:g>"</string>
     <string name="wallet_quick_affordance_unavailable_install_the_app" msgid="7298552910007208368">"Ukuze ungeze i-app ye-Wallet njengesinqamuleli, qinisekisa ukuthi i-app ifakiwe"</string>
     <string name="wallet_quick_affordance_unavailable_configure_the_app" msgid="4387433357429873258">"Ukuze ungeze i-app ye-Wallet njengesinqamuleli, qinisekisa ukuthi okungenani ikhadi elilodwa lingeziwe"</string>
-    <string name="qr_scanner_quick_affordance_unavailable_explanation" msgid="3049582306241150946">"Ukuze ungeze Iskena sekhodi ye-QR njengesinqamuleli, qinisekisa ukuthi i-app yekhamera ifakiwe"</string>
     <string name="home_quick_affordance_unavailable_install_the_app" msgid="6187820778998446168">"Ukuze ungeze i-App yasekhaya njengesinqamuleli, qinisekisa ukuthi i-app ifakiwe"</string>
     <string name="home_quick_affordance_unavailable_configure_the_app" msgid="7953595390775156839">"• Okungenani idivayisi eyodwa iyatholakala"</string>
     <string name="notes_app_quick_affordance_unavailable_explanation" msgid="4796955161600178530">"Khetha i-app yamanothi azenzakalelayo ukuze usebenzise isinqamuleli sokubhala amanothi"</string>
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index 12b3ec3..eb9d0b3 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -780,6 +780,9 @@
     <!-- Flag to enable privacy dot views, it shall be true for normal case -->
     <bool name="config_enablePrivacyDot">true</bool>
 
+    <!-- Flag to enable privacy chip animation, it shall be true for normal case -->
+    <bool name="config_enablePrivacyChipAnimation">true</bool>
+
     <!-- Class for the communal source connector to be used -->
     <string name="config_communalSourceConnector" translatable="false"></string>
 
@@ -920,4 +923,7 @@
     "$packageName" part that will be replaced by the code with the package name of the target app.
     -->
     <string name="config_appStoreAppLinkTemplate" translatable="false"></string>
+
+    <!-- Flag controlling whether visual query attention detection has been enabled. -->
+    <bool name="config_enableVisualQueryAttentionDetection">false</bool>
 </resources>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 572a7fe7..2dc1b45 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -351,9 +351,9 @@
 
     <!-- paddings for container with status icons and battery -->
     <!-- padding start is a bit smaller than end to account for status icon margin-->
-    <dimen name="status_bar_icons_padding_start">11dp</dimen>
+    <dimen name="status_bar_icons_padding_start">3dp</dimen>
 
-    <dimen name="status_bar_icons_padding_end">0dp</dimen>
+    <dimen name="status_bar_icons_padding_end">4dp</dimen>
     <dimen name="status_bar_icons_padding_bottom">0dp</dimen>
     <dimen name="status_bar_icons_padding_top">0dp</dimen>
 
@@ -364,7 +364,7 @@
     <dimen name="status_bar_padding_start">8dp</dimen>
 
     <!-- the padding on the end of the statusbar -->
-    <dimen name="status_bar_padding_end">8dp</dimen>
+    <dimen name="status_bar_padding_end">4dp</dimen>
 
     <!-- the padding on the top of the statusbar (usually 0) -->
     <dimen name="status_bar_padding_top">0dp</dimen>
@@ -496,9 +496,10 @@
     <dimen name="large_screen_shade_header_min_height">@dimen/qs_header_row_min_height</dimen>
     <dimen name="large_screen_shade_header_left_padding">@dimen/qs_horizontal_margin</dimen>
     <dimen name="shade_header_system_icons_height">@dimen/large_screen_shade_header_min_height</dimen>
-    <dimen name="shade_header_system_icons_height_large_screen">32dp</dimen>
     <dimen name="shade_header_system_icons_padding_start">0dp</dimen>
     <dimen name="shade_header_system_icons_padding_end">0dp</dimen>
+    <dimen name="shade_header_system_icons_padding_top">0dp</dimen>
+    <dimen name="shade_header_system_icons_padding_bottom">0dp</dimen>
 
     <!-- The top margin of the panel that holds the list of notifications.
          On phones it's always 0dp but it's overridden in Car UI
@@ -1606,7 +1607,7 @@
     <!-- Status bar user chip -->
     <dimen name="status_bar_user_chip_avatar_size">16dp</dimen>
     <!-- below also works as break between user chip and hover state of status icons -->
-    <dimen name="status_bar_user_chip_end_margin">4dp</dimen>
+    <dimen name="status_bar_user_chip_end_margin">8dp</dimen>
     <dimen name="status_bar_user_chip_text_size">12sp</dimen>
 
     <!-- System UI Dialog -->
diff --git a/packages/SystemUI/res/values/flags.xml b/packages/SystemUI/res/values/flags.xml
index 763930d..0d45422 100644
--- a/packages/SystemUI/res/values/flags.xml
+++ b/packages/SystemUI/res/values/flags.xml
@@ -38,4 +38,9 @@
          protected. -->
     <bool name="flag_battery_shield_icon">false</bool>
 
+    <!-- Whether face auth will immediately stop when the display state is OFF -->
+    <bool name="flag_stop_face_auth_on_display_off">true</bool>
+
+    <!-- Whether we want to stop pulsing while running the face scanning animation -->
+    <bool name="flag_stop_pulsing_face_scanning_animation">true</bool>
 </resources>
diff --git a/packages/SystemUI/res/values/ids.xml b/packages/SystemUI/res/values/ids.xml
index 15ca9d4..4e72518 100644
--- a/packages/SystemUI/res/values/ids.xml
+++ b/packages/SystemUI/res/values/ids.xml
@@ -212,10 +212,14 @@
     <item type="id" name="keyguard_indication_text" />
     <item type="id" name="keyguard_indication_text_bottom" />
     <item type="id" name="nssl_guideline" />
+    <item type="id" name="split_shade_guideline" />
     <item type="id" name="lock_icon" />
     <item type="id" name="lock_icon_bg" />
 
     <!-- Privacy dialog -->
     <item type="id" name="privacy_dialog_close_app_button" />
     <item type="id" name="privacy_dialog_manage_app_button" />
+
+    <!-- Communal mode -->
+    <item type="id" name="communal_widget_wrapper" />
 </resources>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index ee9b132..cddfda2 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -747,6 +747,9 @@
     off. This means a separate profile on a user's phone that's specifically for their
     work apps and managed by their company. "Work" is used as an adjective. [CHAR LIMIT=NONE] -->
     <string name="quick_settings_work_mode_label">Work apps</string>
+    <!-- QuickSettings: Subtitle for the Work profile Quick Settings tile when it's in the off
+    state. This corresponds to the work profile not being currently accessible. [CHAR LIMIT=20] -->
+    <string name="quick_settings_work_mode_paused_state">Paused</string>
     <!-- QuickSettings: Label for the toggle to activate Night display (renamed "Night Light" with title caps). [CHAR LIMIT=20] -->
     <string name="quick_settings_night_display_label">Night Light</string>
     <!-- QuickSettings: Secondary text for when the Night Light will be enabled at sunset. [CHAR LIMIT=20] -->
@@ -2403,6 +2406,8 @@
     <string name="magnification_open_settings_click_label">Open magnification settings</string>
     <!-- Click action label for magnification settings panel. [CHAR LIMIT=NONE] -->
     <string name="magnification_close_settings_click_label">Close magnification settings</string>
+    <!-- Click action label for exiting magnifier edit mode. [CHAR LIMIT=NONE] -->
+    <string name="magnification_exit_edit_mode_click_label">Exit edit mode</string>
     <!-- Label of the corner of a rectangle that you can tap and drag to resize the magnification area. [CHAR LIMIT=NONE] -->
     <string name="magnification_drag_corner_to_resize">Drag corner to resize</string>
 
@@ -3053,13 +3058,6 @@
     <string name="wallet_quick_affordance_unavailable_configure_the_app">To add the Wallet app as a shortcut, make sure at least one card has been added</string>
 
     <!--
-    Requirement for the QR code scanner functionality to be available for the user to use. This is
-    shown as part of a bulleted list of requirements. When all requirements are met, the piece of
-    functionality can be accessed through a shortcut button on the lock screen. [CHAR LIMIT=NONE].
-    -->
-    <string name="qr_scanner_quick_affordance_unavailable_explanation">To add the QR code scanner as a shortcut, make sure a camera app is installed</string>
-
-    <!--
     Explains that the lock screen shortcut for the "home" app is not available because the app isn't
     installed. This is shown as part of a dialog that explains to the user why they cannot select
     this shortcut for their lock screen right now. [CHAR LIMIT=NONE].
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index d520670..10340c6 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -451,6 +451,11 @@
 
     <style name="Theme.SystemUI.Dialog.Alert" parent="@*android:style/Theme.DeviceDefault.Light.Dialog.Alert" />
 
+    <style name="Theme.SystemUI.Dialog.Alert.SensorPrivacy" parent="Theme.SystemUI.Dialog.Alert">
+        <item name="android:windowNoTitle">true</item>
+        <item name="android:windowContentOverlay">@null</item>
+    </style>
+
     <style name="Theme.SystemUI.Dialog.GlobalActions" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar.Fullscreen">
         <item name="android:colorError">@*android:color/error_color_material_dark</item>
         <item name="android:windowIsFloating">true</item>
diff --git a/packages/SystemUI/res/xml/large_screen_shade_header.xml b/packages/SystemUI/res/xml/large_screen_shade_header.xml
index cb2c3a1..fe61c46 100644
--- a/packages/SystemUI/res/xml/large_screen_shade_header.xml
+++ b/packages/SystemUI/res/xml/large_screen_shade_header.xml
@@ -56,11 +56,11 @@
     <Constraint android:id="@+id/shade_header_system_icons">
         <Layout
             android:layout_width="wrap_content"
-            android:layout_height="@dimen/shade_header_system_icons_height_large_screen"
+            android:layout_height="wrap_content"
             app:layout_constraintBottom_toBottomOf="parent"
             app:layout_constraintEnd_toStartOf="@id/privacy_container"
             app:layout_constraintTop_toTopOf="parent"
-            app:layout_constraintEnd_toEndOf="@id/carrier_group"/>
+            app:layout_constraintStart_toEndOf="@id/carrier_group"/>
         <PropertySet android:alpha="1" />
     </Constraint>
 
diff --git a/packages/SystemUI/shared/src/com/android/systemui/flags/Flag.kt b/packages/SystemUI/shared/src/com/android/systemui/flags/Flag.kt
index b6aae69..f1a4007 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/flags/Flag.kt
+++ b/packages/SystemUI/shared/src/com/android/systemui/flags/Flag.kt
@@ -24,14 +24,12 @@
 
 /**
  * Base interface for flags that can change value on a running device.
- * @property id unique id to help identify this flag. Must be unique. This will be removed soon.
  * @property teamfood Set to true to include this flag as part of the teamfood flag. This will
  *                    be removed soon.
  * @property name Used for server-side flagging where appropriate. Also used for display. No spaces.
  * @property namespace The server-side namespace that this flag lives under.
  */
 interface Flag<T> {
-    val id: Int
     val teamfood: Boolean
     val name: String
     val namespace: String
@@ -58,7 +56,6 @@
  */
 // Consider using the "parcelize" kotlin library.
 abstract class BooleanFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     override val default: Boolean = false,
@@ -74,8 +71,17 @@
         }
     }
 
+    private constructor(
+            id: Int,
+            name: String,
+            namespace: String,
+            default: Boolean,
+            teamfood: Boolean,
+            overridden: Boolean,
+            ) : this(name, namespace, default, teamfood, overridden)
+
     private constructor(parcel: Parcel) : this(
-        id = parcel.readInt(),
+        parcel.readInt(),
         name = parcel.readString() ?: "",
         namespace = parcel.readString() ?: "",
         default = parcel.readBoolean(),
@@ -84,7 +90,7 @@
     )
 
     override fun writeToParcel(parcel: Parcel, flags: Int) {
-        parcel.writeInt(id)
+        parcel.writeInt(0)
         parcel.writeString(name)
         parcel.writeString(namespace)
         parcel.writeBoolean(default)
@@ -99,12 +105,11 @@
  * It can be changed or overridden in debug builds but not in release builds.
  */
 data class UnreleasedFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     override val teamfood: Boolean = false,
     override val overridden: Boolean = false
-) : BooleanFlag(id, name, namespace, false, teamfood, overridden)
+) : BooleanFlag(name, namespace, false, teamfood, overridden)
 
 /**
  * A Flag that is true by default.
@@ -112,12 +117,11 @@
  * It can be changed or overridden in any build, meaning it can be turned off if needed.
  */
 data class ReleasedFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     override val teamfood: Boolean = false,
     override val overridden: Boolean = false
-) : BooleanFlag(id, name, namespace, true, teamfood, overridden)
+) : BooleanFlag(name, namespace, true, teamfood, overridden)
 
 /**
  * A Flag that reads its default values from a resource overlay instead of code.
@@ -125,7 +129,6 @@
  * Prefer [UnreleasedFlag] and [ReleasedFlag].
  */
 data class ResourceBooleanFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     @BoolRes override val resourceId: Int,
@@ -140,7 +143,6 @@
  * Prefer [UnreleasedFlag] and [ReleasedFlag].
  */
 data class SysPropBooleanFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     override val default: Boolean = false,
@@ -150,7 +152,6 @@
 }
 
 data class StringFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     override val default: String = "",
@@ -165,15 +166,21 @@
         }
     }
 
+    private constructor(id: Int, name: String, namespace: String, default: String) : this(
+            name,
+            namespace,
+            default
+    )
+
     private constructor(parcel: Parcel) : this(
-        id = parcel.readInt(),
+        parcel.readInt(),
         name = parcel.readString() ?: "",
         namespace = parcel.readString() ?: "",
         default = parcel.readString() ?: ""
     )
 
     override fun writeToParcel(parcel: Parcel, flags: Int) {
-        parcel.writeInt(id)
+        parcel.writeInt(0)
         parcel.writeString(name)
         parcel.writeString(namespace)
         parcel.writeString(default)
@@ -181,7 +188,6 @@
 }
 
 data class ResourceStringFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     @StringRes override val resourceId: Int,
@@ -189,7 +195,6 @@
 ) : ResourceFlag<String>
 
 data class IntFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     override val default: Int = 0,
@@ -205,15 +210,21 @@
         }
     }
 
+    private constructor(id: Int, name: String, namespace: String, default: Int) : this(
+            name,
+            namespace,
+            default
+    )
+
     private constructor(parcel: Parcel) : this(
-        id = parcel.readInt(),
+        parcel.readInt(),
         name = parcel.readString() ?: "",
         namespace = parcel.readString() ?: "",
         default = parcel.readInt()
     )
 
     override fun writeToParcel(parcel: Parcel, flags: Int) {
-        parcel.writeInt(id)
+        parcel.writeInt(0)
         parcel.writeString(name)
         parcel.writeString(namespace)
         parcel.writeInt(default)
@@ -221,7 +232,6 @@
 }
 
 data class ResourceIntFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     @IntegerRes override val resourceId: Int,
@@ -229,11 +239,10 @@
 ) : ResourceFlag<Int>
 
 data class LongFlag constructor(
-    override val id: Int,
-    override val default: Long = 0,
-    override val teamfood: Boolean = false,
     override val name: String,
     override val namespace: String,
+    override val default: Long = 0,
+    override val teamfood: Boolean = false,
     override val overridden: Boolean = false
 ) : ParcelableFlag<Long> {
 
@@ -245,15 +254,21 @@
         }
     }
 
+    private constructor(id: Int, name: String, namespace: String, default: Long) : this(
+            name,
+            namespace,
+            default
+    )
+
     private constructor(parcel: Parcel) : this(
-        id = parcel.readInt(),
+        parcel.readInt(),
         name = parcel.readString() ?: "",
         namespace = parcel.readString() ?: "",
         default = parcel.readLong()
     )
 
     override fun writeToParcel(parcel: Parcel, flags: Int) {
-        parcel.writeInt(id)
+        parcel.writeInt(0)
         parcel.writeString(name)
         parcel.writeString(namespace)
         parcel.writeLong(default)
@@ -261,7 +276,6 @@
 }
 
 data class FloatFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     override val default: Float = 0f,
@@ -277,15 +291,21 @@
         }
     }
 
+    private constructor(id: Int, name: String, namespace: String, default: Float) : this(
+            name,
+            namespace,
+            default
+    )
+
     private constructor(parcel: Parcel) : this(
-        id = parcel.readInt(),
+        parcel.readInt(),
         name = parcel.readString() ?: "",
         namespace = parcel.readString() ?: "",
         default = parcel.readFloat()
     )
 
     override fun writeToParcel(parcel: Parcel, flags: Int) {
-        parcel.writeInt(id)
+        parcel.writeInt(0)
         parcel.writeString(name)
         parcel.writeString(namespace)
         parcel.writeFloat(default)
@@ -293,7 +313,6 @@
 }
 
 data class ResourceFloatFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     override val resourceId: Int,
@@ -301,7 +320,6 @@
 ) : ResourceFlag<Int>
 
 data class DoubleFlag constructor(
-    override val id: Int,
     override val name: String,
     override val namespace: String,
     override val default: Double = 0.0,
@@ -317,15 +335,21 @@
         }
     }
 
+    private constructor(id: Int, name: String, namespace: String, default: Double) : this(
+            name,
+            namespace,
+            default
+    )
+
     private constructor(parcel: Parcel) : this(
-        id = parcel.readInt(),
+        parcel.readInt(),
         name = parcel.readString() ?: "",
         namespace = parcel.readString() ?: "",
         default = parcel.readDouble()
     )
 
     override fun writeToParcel(parcel: Parcel, flags: Int) {
-        parcel.writeInt(id)
+        parcel.writeInt(0)
         parcel.writeString(name)
         parcel.writeString(namespace)
         parcel.writeDouble(default)
diff --git a/packages/SystemUI/shared/src/com/android/systemui/flags/FlagManager.kt b/packages/SystemUI/shared/src/com/android/systemui/flags/FlagManager.kt
index da1641c..1366226 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/flags/FlagManager.kt
+++ b/packages/SystemUI/shared/src/com/android/systemui/flags/FlagManager.kt
@@ -116,13 +116,6 @@
     }
 
     /** Returns the stored value or null if not set.  */
-    // TODO(b/265188950): Remove method this once ids are fully deprecated.
-    fun <T> readFlagValue(id: Int, serializer: FlagSerializer<T>): T? {
-        val data = settings.getStringFromSecure(idToSettingsKey(id))
-        return serializer.fromSettingsData(data)
-    }
-
-    /** Returns the stored value or null if not set.  */
     fun <T> readFlagValue(name: String, serializer: FlagSerializer<T>): T? {
         val data = settings.getString(nameToSettingsKey(name))
         return serializer.fromSettingsData(data)
@@ -158,11 +151,6 @@
         return intent
     }
 
-    // TODO(b/265188950): Remove method this once ids are fully deprecated.
-    fun idToSettingsKey(id: Int): String {
-        return "$SETTINGS_PREFIX/$id"
-    }
-
     fun nameToSettingsKey(name: String): String {
         return "$SETTINGS_PREFIX/$name"
     }
diff --git a/packages/SystemUI/shared/src/com/android/systemui/flags/FlagSettingsHelper.kt b/packages/SystemUI/shared/src/com/android/systemui/flags/FlagSettingsHelper.kt
index 6beb851..e0a7fea 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/flags/FlagSettingsHelper.kt
+++ b/packages/SystemUI/shared/src/com/android/systemui/flags/FlagSettingsHelper.kt
@@ -22,7 +22,6 @@
 
 class FlagSettingsHelper(private val contentResolver: ContentResolver) {
 
-    // TODO(b/265188950): Remove method this once ids are fully deprecated.
     fun getStringFromSecure(key: String): String? = Settings.Secure.getString(contentResolver, key)
 
     fun getString(key: String): String? = Settings.Global.getString(contentResolver, key)
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/model/Task.java b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/model/Task.java
index fac2f91..3605ac2 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/model/Task.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/model/Task.java
@@ -336,6 +336,14 @@
 
     @Override
     public boolean equals(Object o) {
+        if (o == this) {
+            return true;
+        }
+
+        if (!(o instanceof Task)) {
+            return false;
+        }
+
         // Check that the id matches
         Task t = (Task) o;
         return key.equals(t.key);
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerKt.kt b/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerKt.kt
index c142933..5edd283 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerKt.kt
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerKt.kt
@@ -27,6 +27,6 @@
      */
     fun ActivityManager.isInForeground(packageName: String): Boolean {
         val tasks: List<ActivityManager.RunningTaskInfo> = getRunningTasks(1)
-        return tasks.isNotEmpty() && packageName == tasks[0].topActivity.packageName
+        return tasks.isNotEmpty() && packageName == tasks[0].topActivity?.packageName
     }
 }
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/InteractionJankMonitorWrapper.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/InteractionJankMonitorWrapper.java
index c844db7..77f6d03 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/InteractionJankMonitorWrapper.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/InteractionJankMonitorWrapper.java
@@ -28,8 +28,6 @@
 import java.lang.annotation.RetentionPolicy;
 
 public final class InteractionJankMonitorWrapper {
-    private static final String TAG = "JankMonitorWrapper";
-
     // Launcher journeys.
     public static final int CUJ_APP_LAUNCH_FROM_RECENTS =
             InteractionJankMonitor.CUJ_LAUNCHER_APP_LAUNCH_FROM_RECENTS;
@@ -37,6 +35,8 @@
             InteractionJankMonitor.CUJ_LAUNCHER_APP_LAUNCH_FROM_ICON;
     public static final int CUJ_APP_CLOSE_TO_HOME =
             InteractionJankMonitor.CUJ_LAUNCHER_APP_CLOSE_TO_HOME;
+    public static final int CUJ_APP_CLOSE_TO_HOME_FALLBACK =
+            InteractionJankMonitor.CUJ_LAUNCHER_APP_CLOSE_TO_HOME_FALLBACK;
     public static final int CUJ_APP_CLOSE_TO_PIP =
             InteractionJankMonitor.CUJ_LAUNCHER_APP_CLOSE_TO_PIP;
     public static final int CUJ_QUICK_SWITCH =
@@ -68,6 +68,7 @@
             CUJ_APP_LAUNCH_FROM_RECENTS,
             CUJ_APP_LAUNCH_FROM_ICON,
             CUJ_APP_CLOSE_TO_HOME,
+            CUJ_APP_CLOSE_TO_HOME_FALLBACK,
             CUJ_APP_CLOSE_TO_PIP,
             CUJ_QUICK_SWITCH,
             CUJ_APP_LAUNCH_FROM_WIDGET,
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/smartspace/SmartspaceState.kt b/packages/SystemUI/shared/src/com/android/systemui/shared/system/smartspace/SmartspaceState.kt
index d7e61d6..ebc57d2 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/smartspace/SmartspaceState.kt
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/smartspace/SmartspaceState.kt
@@ -31,15 +31,15 @@
     var visibleOnScreen = false
 
     constructor(parcel: Parcel) : this() {
-        this.boundsOnScreen = parcel.readParcelable(Rect::javaClass.javaClass.classLoader)
+        this.boundsOnScreen = parcel.readParcelable(Rect::javaClass.javaClass.classLoader) ?: Rect()
         this.selectedPage = parcel.readInt()
         this.visibleOnScreen = parcel.readBoolean()
     }
 
-    override fun writeToParcel(dest: Parcel?, flags: Int) {
-        dest?.writeParcelable(boundsOnScreen, 0)
-        dest?.writeInt(selectedPage)
-        dest?.writeBoolean(visibleOnScreen)
+    override fun writeToParcel(dest: Parcel, flags: Int) {
+        dest.writeParcelable(boundsOnScreen, 0)
+        dest.writeInt(selectedPage)
+        dest.writeBoolean(visibleOnScreen)
     }
 
     override fun describeContents(): Int {
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt b/packages/SystemUI/shared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt
index aca9907..dac130d 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt
+++ b/packages/SystemUI/shared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt
@@ -39,7 +39,7 @@
 
     fun init() {
         rotationChangeProvider.addCallback(rotationListener)
-        rotationListener.onRotationChanged(context.display.rotation)
+        context.display?.rotation?.let { rotationListener.onRotationChanged(it) }
     }
 
     private val rotationListener = RotationListener { rotation ->
diff --git a/packages/SystemUI/src-debug/com/android/systemui/flags/FlagsFactory.kt b/packages/SystemUI/src-debug/com/android/systemui/flags/FlagsFactory.kt
index c22d689..3360c96 100644
--- a/packages/SystemUI/src-debug/com/android/systemui/flags/FlagsFactory.kt
+++ b/packages/SystemUI/src-debug/com/android/systemui/flags/FlagsFactory.kt
@@ -29,35 +29,31 @@
         }
 
     fun unreleasedFlag(
-        id: Int,
         name: String,
         namespace: String = "systemui",
         teamfood: Boolean = false
     ): UnreleasedFlag {
-        val flag = UnreleasedFlag(id = id, name = name, namespace = namespace, teamfood = teamfood)
+        val flag = UnreleasedFlag(name = name, namespace = namespace, teamfood = teamfood)
         checkForDupesAndAdd(flag)
         return flag
     }
 
     fun releasedFlag(
-        id: Int,
         name: String,
         namespace: String = "systemui",
     ): ReleasedFlag {
-        val flag = ReleasedFlag(id = id, name = name, namespace = namespace, teamfood = false)
+        val flag = ReleasedFlag(name = name, namespace = namespace, teamfood = false)
         checkForDupesAndAdd(flag)
         return flag
     }
 
     fun resourceBooleanFlag(
-        id: Int,
         @BoolRes resourceId: Int,
         name: String,
         namespace: String = "systemui",
     ): ResourceBooleanFlag {
         val flag =
             ResourceBooleanFlag(
-                id = id,
                 name = name,
                 namespace = namespace,
                 resourceId = resourceId,
@@ -68,13 +64,11 @@
     }
 
     fun sysPropBooleanFlag(
-        id: Int,
         name: String,
         namespace: String = "systemui",
         default: Boolean = false
     ): SysPropBooleanFlag {
-        val flag =
-            SysPropBooleanFlag(id = id, name = name, namespace = "systemui", default = default)
+        val flag = SysPropBooleanFlag(name = name, namespace = "systemui", default = default)
         checkForDupesAndAdd(flag)
         return flag
     }
diff --git a/packages/SystemUI/src-release/com/android/systemui/flags/FlagsFactory.kt b/packages/SystemUI/src-release/com/android/systemui/flags/FlagsFactory.kt
index 5502da1..75465c2 100644
--- a/packages/SystemUI/src-release/com/android/systemui/flags/FlagsFactory.kt
+++ b/packages/SystemUI/src-release/com/android/systemui/flags/FlagsFactory.kt
@@ -29,35 +29,31 @@
         }
 
     fun unreleasedFlag(
-        id: Int,
         name: String,
         namespace: String = "systemui",
         teamfood: Boolean = false
     ): UnreleasedFlag {
         // Unreleased flags are always false in this build.
-        val flag = UnreleasedFlag(id = id, name = "", namespace = "", teamfood = false)
+        val flag = UnreleasedFlag(name = name, namespace = namespace, teamfood = false)
         return flag
     }
 
     fun releasedFlag(
-        id: Int,
         name: String,
         namespace: String = "systemui",
     ): ReleasedFlag {
-        val flag = ReleasedFlag(id = id, name = name, namespace = namespace, teamfood = false)
+        val flag = ReleasedFlag(name = name, namespace = namespace, teamfood = false)
         flagMap[name] = flag
         return flag
     }
 
     fun resourceBooleanFlag(
-        id: Int,
         @BoolRes resourceId: Int,
         name: String,
         namespace: String = "systemui",
     ): ResourceBooleanFlag {
         val flag =
             ResourceBooleanFlag(
-                id = id,
                 name = name,
                 namespace = namespace,
                 resourceId = resourceId,
@@ -68,13 +64,11 @@
     }
 
     fun sysPropBooleanFlag(
-        id: Int,
         name: String,
         namespace: String = "systemui",
         default: Boolean = false
     ): SysPropBooleanFlag {
-        val flag =
-            SysPropBooleanFlag(id = id, name = name, namespace = namespace, default = default)
+        val flag = SysPropBooleanFlag(name = name, namespace = namespace, default = default)
         flagMap[name] = flag
         return flag
     }
diff --git a/packages/SystemUI/src/com/android/keyguard/BouncerKeyguardMessageArea.kt b/packages/SystemUI/src/com/android/keyguard/BouncerKeyguardMessageArea.kt
index 78a5c98..495367b 100644
--- a/packages/SystemUI/src/com/android/keyguard/BouncerKeyguardMessageArea.kt
+++ b/packages/SystemUI/src/com/android/keyguard/BouncerKeyguardMessageArea.kt
@@ -105,7 +105,7 @@
 
         hideAnimator.addListener(
             object : AnimatorListenerAdapter() {
-                override fun onAnimationEnd(animation: Animator?) {
+                override fun onAnimationEnd(animation: Animator) {
                     super@BouncerKeyguardMessageArea.setMessage(msg, animate)
                 }
             }
@@ -118,7 +118,7 @@
 
         showAnimator.addListener(
             object : AnimatorListenerAdapter() {
-                override fun onAnimationEnd(animation: Animator?) {
+                override fun onAnimationEnd(animation: Animator) {
                     textAboutToShow = null
                 }
             }
diff --git a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
index 0b9e6e9..2f3c1f2 100644
--- a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
+++ b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
@@ -144,7 +144,7 @@
                 smallClockOnAttachStateChangeListener =
                     object : OnAttachStateChangeListener {
                         var pastVisibility: Int? = null
-                        override fun onViewAttachedToWindow(view: View?) {
+                        override fun onViewAttachedToWindow(view: View) {
                             value.events.onTimeFormatChanged(DateFormat.is24HourFormat(context))
                             if (view != null) {
                                 smallClockFrame = view.parent as FrameLayout
@@ -168,7 +168,7 @@
                             }
                         }
 
-                        override fun onViewDetachedFromWindow(p0: View?) {
+                        override fun onViewDetachedFromWindow(p0: View) {
                             smallClockFrame?.viewTreeObserver
                                     ?.removeOnGlobalLayoutListener(onGlobalLayoutListener)
                         }
@@ -178,10 +178,10 @@
 
                 largeClockOnAttachStateChangeListener =
                     object : OnAttachStateChangeListener {
-                        override fun onViewAttachedToWindow(p0: View?) {
+                        override fun onViewAttachedToWindow(p0: View) {
                             value.events.onTimeFormatChanged(DateFormat.is24HourFormat(context))
                         }
-                        override fun onViewDetachedFromWindow(p0: View?) {
+                        override fun onViewDetachedFromWindow(p0: View) {
                         }
                 }
                 value.largeClock.view
diff --git a/packages/SystemUI/src/com/android/keyguard/ConnectedDisplayKeyguardPresentation.kt b/packages/SystemUI/src/com/android/keyguard/ConnectedDisplayKeyguardPresentation.kt
new file mode 100644
index 0000000..899cad89
--- /dev/null
+++ b/packages/SystemUI/src/com/android/keyguard/ConnectedDisplayKeyguardPresentation.kt
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.keyguard
+
+import android.app.Presentation
+import android.content.Context
+import android.graphics.Color
+import android.os.Bundle
+import android.view.Display
+import android.view.LayoutInflater
+import android.view.View
+import android.view.WindowManager
+import com.android.keyguard.dagger.KeyguardStatusViewComponent
+import com.android.systemui.R
+import dagger.assisted.Assisted
+import dagger.assisted.AssistedFactory
+import dagger.assisted.AssistedInject
+
+/** [Presentation] shown in connected displays while on keyguard. */
+class ConnectedDisplayKeyguardPresentation
+@AssistedInject
+constructor(
+    @Assisted display: Display,
+    context: Context,
+    private val keyguardStatusViewComponentFactory: KeyguardStatusViewComponent.Factory,
+) :
+    Presentation(
+        context,
+        display,
+        R.style.Theme_SystemUI_KeyguardPresentation,
+        WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG
+    ) {
+
+    private lateinit var keyguardStatusViewController: KeyguardStatusViewController
+    private lateinit var clock: KeyguardStatusView
+
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+
+        setContentView(
+            LayoutInflater.from(context)
+                .inflate(R.layout.keyguard_clock_presentation, /* root= */ null)
+        )
+        val window = window ?: error("no window available.")
+
+        // Logic to make the lock screen fullscreen
+        window.decorView.systemUiVisibility =
+            (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
+                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
+                View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
+        window.attributes.fitInsetsTypes = 0
+        window.isNavigationBarContrastEnforced = false
+        window.navigationBarColor = Color.TRANSPARENT
+
+        clock = findViewById(R.id.clock)
+        keyguardStatusViewController =
+            keyguardStatusViewComponentFactory.build(clock).keyguardStatusViewController.apply {
+                setDisplayedOnSecondaryDisplay()
+                init()
+            }
+    }
+
+    /** [ConnectedDisplayKeyguardPresentation] factory. */
+    @AssistedFactory
+    interface Factory {
+        /** Creates a new [Presentation] for the given [display]. */
+        fun create(
+            display: Display,
+        ): ConnectedDisplayKeyguardPresentation
+    }
+}
diff --git a/packages/SystemUI/src/com/android/keyguard/FaceAuthReason.kt b/packages/SystemUI/src/com/android/keyguard/FaceAuthReason.kt
index 22cdb30..2abb7a4 100644
--- a/packages/SystemUI/src/com/android/keyguard/FaceAuthReason.kt
+++ b/packages/SystemUI/src/com/android/keyguard/FaceAuthReason.kt
@@ -33,6 +33,7 @@
 import com.android.keyguard.InternalFaceAuthReasons.BIOMETRIC_ENABLED
 import com.android.keyguard.InternalFaceAuthReasons.CAMERA_LAUNCHED
 import com.android.keyguard.InternalFaceAuthReasons.DEVICE_WOKEN_UP_ON_REACH_GESTURE
+import com.android.keyguard.InternalFaceAuthReasons.DISPLAY_OFF
 import com.android.keyguard.InternalFaceAuthReasons.DREAM_STARTED
 import com.android.keyguard.InternalFaceAuthReasons.DREAM_STOPPED
 import com.android.keyguard.InternalFaceAuthReasons.ENROLLMENTS_CHANGED
@@ -131,6 +132,7 @@
     const val NON_STRONG_BIOMETRIC_ALLOWED_CHANGED =
         "Face auth stopped because non strong biometric allowed changed"
     const val POSTURE_CHANGED = "Face auth started/stopped due to device posture changed."
+    const val DISPLAY_OFF = "Face auth stopped due to display state OFF."
 }
 
 /**
@@ -221,7 +223,8 @@
     FACE_AUTH_UPDATED_STRONG_AUTH_CHANGED(1255, STRONG_AUTH_ALLOWED_CHANGED),
     @UiEvent(doc = NON_STRONG_BIOMETRIC_ALLOWED_CHANGED)
     FACE_AUTH_NON_STRONG_BIOMETRIC_ALLOWED_CHANGED(1256, NON_STRONG_BIOMETRIC_ALLOWED_CHANGED),
-    @UiEvent(doc = ACCESSIBILITY_ACTION) FACE_AUTH_ACCESSIBILITY_ACTION(1454, ACCESSIBILITY_ACTION);
+    @UiEvent(doc = ACCESSIBILITY_ACTION) FACE_AUTH_ACCESSIBILITY_ACTION(1454, ACCESSIBILITY_ACTION),
+    @UiEvent(doc = DISPLAY_OFF) FACE_AUTH_DISPLAY_OFF(1461, DISPLAY_OFF);
 
     override fun getId(): Int = this.id
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java
index b81e081..e3f9de1 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java
@@ -102,6 +102,12 @@
         super.onViewAttached();
         mView.setKeyDownListener(mKeyDownListener);
         mEmergencyButtonController.setEmergencyButtonCallback(mEmergencyButtonCallback);
+        // if the user is currently locked out, enforce it.
+        long deadline = mLockPatternUtils.getLockoutAttemptDeadline(
+                KeyguardUpdateMonitor.getCurrentUser());
+        if (shouldLockout(deadline)) {
+            handleAttemptLockout(deadline);
+        }
     }
 
     @Override
@@ -278,12 +284,6 @@
     @Override
     public void onResume(int reason) {
         mResumed = true;
-        // if the user is currently locked out, enforce it.
-        long deadline = mLockPatternUtils.getLockoutAttemptDeadline(
-                KeyguardUpdateMonitor.getCurrentUser());
-        if (shouldLockout(deadline)) {
-            handleAttemptLockout(deadline);
-        }
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
index 30b8ed0..06b6692 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
@@ -1,10 +1,5 @@
 package com.android.keyguard;
 
-import static android.view.View.ALPHA;
-import static android.view.View.SCALE_X;
-import static android.view.View.SCALE_Y;
-import static android.view.View.TRANSLATION_Y;
-
 import static com.android.keyguard.KeyguardStatusAreaView.TRANSLATE_X_CLOCK_DESIGN;
 import static com.android.keyguard.KeyguardStatusAreaView.TRANSLATE_Y_CLOCK_DESIGN;
 import static com.android.keyguard.KeyguardStatusAreaView.TRANSLATE_Y_CLOCK_SIZE;
@@ -44,6 +39,7 @@
 public class KeyguardClockSwitch extends RelativeLayout {
 
     private static final String TAG = "KeyguardClockSwitch";
+    public static final String MISSING_CLOCK_ID = "CLOCK_MISSING";
 
     private static final long CLOCK_OUT_MILLIS = 133;
     private static final long CLOCK_IN_MILLIS = 167;
@@ -149,6 +145,13 @@
         updateStatusArea(/* animate= */false);
     }
 
+    /** Sets whether the large clock is being shown on a connected display. */
+    public void setLargeClockOnSecondaryDisplay(boolean onSecondaryDisplay) {
+        if (mClock != null) {
+            mClock.getLargeClock().getEvents().onSecondaryDisplayChanged(onSecondaryDisplay);
+        }
+    }
+
     /**
      * Enable or disable split shade specific positioning
      */
@@ -194,6 +197,14 @@
         return mLogBuffer;
     }
 
+    /** Returns the id of the currently rendering clock */
+    public String getClockId() {
+        if (mClock == null) {
+            return MISSING_CLOCK_ID;
+        }
+        return mClock.getConfig().getId();
+    }
+
     void setClock(ClockController clock, int statusBarState) {
         mClock = clock;
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
index 2c224f62..dd39f1d 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
@@ -104,6 +104,7 @@
 
     private final KeyguardUnlockAnimationController mKeyguardUnlockAnimationController;
 
+    private boolean mShownOnSecondaryDisplay = false;
     private boolean mOnlyClock = false;
     private boolean mIsActiveDreamLockscreenHosted = false;
     private FeatureFlags mFeatureFlags;
@@ -185,8 +186,18 @@
     }
 
     /**
-     * Mostly used for alternate displays, limit the information shown
+     * When set, limits the information shown in an external display.
      */
+    public void setShownOnSecondaryDisplay(boolean shownOnSecondaryDisplay) {
+        mShownOnSecondaryDisplay = shownOnSecondaryDisplay;
+    }
+
+    /**
+     * Mostly used for alternate displays, limit the information shown
+     *
+     * @deprecated use {@link KeyguardClockSwitchController#setShownOnSecondaryDisplay}
+     */
+    @Deprecated
     public void setOnlyClock(boolean onlyClock) {
         mOnlyClock = onlyClock;
     }
@@ -221,6 +232,15 @@
         }
     }
 
+    private void hideSliceViewAndNotificationIconContainer() {
+        View ksv = mView.findViewById(R.id.keyguard_slice_view);
+        ksv.setVisibility(View.GONE);
+
+        View nic = mView.findViewById(
+                R.id.left_aligned_notification_icon_container);
+        nic.setVisibility(View.GONE);
+    }
+
     @Override
     protected void onViewAttached() {
         mClockRegistry.registerClockChangeListener(mClockChangedListener);
@@ -234,34 +254,20 @@
         mKeyguardDateWeatherViewInvisibility =
                 mView.getResources().getInteger(R.integer.keyguard_date_weather_view_invisibility);
 
-        if (mOnlyClock) {
-            View ksv = mView.findViewById(R.id.keyguard_slice_view);
-            ksv.setVisibility(View.GONE);
+        if (mShownOnSecondaryDisplay) {
+            mView.setLargeClockOnSecondaryDisplay(true);
+            displayClock(LARGE, /* animate= */ false);
+            hideSliceViewAndNotificationIconContainer();
+            return;
+        }
 
-            View nic = mView.findViewById(
-                    R.id.left_aligned_notification_icon_container);
-            nic.setVisibility(View.GONE);
+        if (mOnlyClock) {
+            hideSliceViewAndNotificationIconContainer();
             return;
         }
         updateAodIcons();
-
         mStatusArea = mView.findViewById(R.id.keyguard_status_area);
 
-        if (mSmartspaceController.isEnabled()) {
-            View ksv = mView.findViewById(R.id.keyguard_slice_view);
-            int viewIndex = mStatusArea.indexOfChild(ksv);
-            ksv.setVisibility(View.GONE);
-
-            // TODO(b/261757708): add content observer for the Settings toggle and add/remove
-            //  weather according to the Settings.
-            if (mSmartspaceController.isDateWeatherDecoupled()) {
-                addDateWeatherView(viewIndex);
-                viewIndex += 1;
-            }
-
-            addSmartspaceView(viewIndex);
-        }
-
         mSecureSettings.registerContentObserverForUser(
                 Settings.Secure.LOCKSCREEN_USE_DOUBLE_LINE_CLOCK,
                 false, /* notifyForDescendants */
@@ -275,13 +281,27 @@
                 mShowWeatherObserver,
                 UserHandle.USER_ALL
         );
-
         updateDoubleLineClock();
-        setDateWeatherVisibility();
-        setWeatherVisibility();
 
         mKeyguardUnlockAnimationController.addKeyguardUnlockAnimationListener(
                 mKeyguardUnlockAnimationListener);
+
+        if (mSmartspaceController.isEnabled()) {
+            View ksv = mView.findViewById(R.id.keyguard_slice_view);
+            int viewIndex = mStatusArea.indexOfChild(ksv);
+            ksv.setVisibility(View.GONE);
+
+            mSmartspaceController.removeViewsFromParent(mStatusArea);
+            addSmartspaceView();
+            // TODO(b/261757708): add content observer for the Settings toggle and add/remove
+            //  weather according to the Settings.
+            if (mSmartspaceController.isDateWeatherDecoupled()) {
+                addDateWeatherView();
+            }
+        }
+
+        setDateWeatherVisibility();
+        setWeatherVisibility();
     }
 
     int getNotificationIconAreaHeight() {
@@ -295,6 +315,7 @@
         setClock(null);
 
         mSecureSettings.unregisterContentObserver(mDoubleLineClockObserver);
+        mSecureSettings.unregisterContentObserver(mShowWeatherObserver);
 
         mKeyguardUnlockAnimationController.removeKeyguardUnlockAnimationListener(
                 mKeyguardUnlockAnimationListener);
@@ -302,29 +323,22 @@
 
     void onLocaleListChanged() {
         if (mSmartspaceController.isEnabled()) {
+            mSmartspaceController.removeViewsFromParent(mStatusArea);
+            addSmartspaceView();
             if (mSmartspaceController.isDateWeatherDecoupled()) {
                 mDateWeatherView.removeView(mWeatherView);
-                int index = mStatusArea.indexOfChild(mDateWeatherView);
-                if (index >= 0) {
-                    mStatusArea.removeView(mDateWeatherView);
-                    addDateWeatherView(index);
-                }
+                addDateWeatherView();
                 setDateWeatherVisibility();
                 setWeatherVisibility();
             }
-            int index = mStatusArea.indexOfChild(mSmartspaceView);
-            if (index >= 0) {
-                mStatusArea.removeView(mSmartspaceView);
-                addSmartspaceView(index);
-            }
         }
     }
 
-    private void addDateWeatherView(int index) {
+    private void addDateWeatherView() {
         mDateWeatherView = (ViewGroup) mSmartspaceController.buildAndConnectDateView(mView);
         LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                 MATCH_PARENT, WRAP_CONTENT);
-        mStatusArea.addView(mDateWeatherView, index, lp);
+        mStatusArea.addView(mDateWeatherView, 0, lp);
         int startPadding = getContext().getResources().getDimensionPixelSize(
                 R.dimen.below_clock_padding_start);
         int endPadding = getContext().getResources().getDimensionPixelSize(
@@ -344,11 +358,11 @@
         mWeatherView.setPaddingRelative(0, 0, 4, 0);
     }
 
-    private void addSmartspaceView(int index) {
+    private void addSmartspaceView() {
         mSmartspaceView = mSmartspaceController.buildAndConnectView(mView);
         LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                 MATCH_PARENT, WRAP_CONTENT);
-        mStatusArea.addView(mSmartspaceView, index, lp);
+        mStatusArea.addView(mSmartspaceView, 0, lp);
         int startPadding = getContext().getResources().getDimensionPixelSize(
                 R.dimen.below_clock_padding_start);
         int endPadding = getContext().getResources().getDimensionPixelSize(
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java b/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
index 9f21a31..1c5a575 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
@@ -43,16 +43,19 @@
 import com.android.systemui.dagger.SysUISingleton;
 import com.android.systemui.dagger.qualifiers.Main;
 import com.android.systemui.dagger.qualifiers.UiBackground;
+import com.android.systemui.flags.FeatureFlags;
+import com.android.systemui.flags.Flags;
 import com.android.systemui.navigationbar.NavigationBarController;
 import com.android.systemui.navigationbar.NavigationBarView;
 import com.android.systemui.settings.DisplayTracker;
 import com.android.systemui.statusbar.policy.KeyguardStateController;
 
+import dagger.Lazy;
+
 import java.util.concurrent.Executor;
 
 import javax.inject.Inject;
 
-import dagger.Lazy;
 
 @SysUISingleton
 public class KeyguardDisplayManager {
@@ -64,6 +67,9 @@
     private final DisplayTracker mDisplayTracker;
     private final Lazy<NavigationBarController> mNavigationBarControllerLazy;
     private final KeyguardStatusViewComponent.Factory mKeyguardStatusViewComponentFactory;
+    private final ConnectedDisplayKeyguardPresentation.Factory
+            mConnectedDisplayKeyguardPresentationFactory;
+    private final FeatureFlags mFeatureFlags;
     private final Context mContext;
 
     private boolean mShowing;
@@ -105,7 +111,10 @@
             @Main Executor mainExecutor,
             @UiBackground Executor uiBgExecutor,
             DeviceStateHelper deviceStateHelper,
-            KeyguardStateController keyguardStateController) {
+            KeyguardStateController keyguardStateController,
+            ConnectedDisplayKeyguardPresentation.Factory
+                    connectedDisplayKeyguardPresentationFactory,
+            FeatureFlags featureFlags) {
         mContext = context;
         mNavigationBarControllerLazy = navigationBarControllerLazy;
         mKeyguardStatusViewComponentFactory = keyguardStatusViewComponentFactory;
@@ -115,6 +124,8 @@
         mDisplayTracker.addDisplayChangeCallback(mDisplayCallback, mainExecutor);
         mDeviceStateHelper = deviceStateHelper;
         mKeyguardStateController = keyguardStateController;
+        mConnectedDisplayKeyguardPresentationFactory = connectedDisplayKeyguardPresentationFactory;
+        mFeatureFlags = featureFlags;
     }
 
     private boolean isKeyguardShowable(Display display) {
@@ -185,8 +196,12 @@
         return false;
     }
 
-    KeyguardPresentation createPresentation(Display display) {
-        return new KeyguardPresentation(mContext, display, mKeyguardStatusViewComponentFactory);
+    Presentation createPresentation(Display display) {
+        if (mFeatureFlags.isEnabled(Flags.ENABLE_CLOCK_KEYGUARD_PRESENTATION)) {
+            return mConnectedDisplayKeyguardPresentationFactory.create(display);
+        } else {
+            return new KeyguardPresentation(mContext, display, mKeyguardStatusViewComponentFactory);
+        }
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardFaceListenModel.kt b/packages/SystemUI/src/com/android/keyguard/KeyguardFaceListenModel.kt
index 461d390..bb799fc 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardFaceListenModel.kt
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardFaceListenModel.kt
@@ -27,6 +27,7 @@
     override var userId: Int = 0,
     override var listening: Boolean = false,
     // keep sorted
+    var allowedDisplayState: Boolean = false,
     var alternateBouncerShowing: Boolean = false,
     var authInterruptActive: Boolean = false,
     var biometricSettingEnabledForUser: Boolean = false,
@@ -57,6 +58,8 @@
             userId.toString(),
             listening.toString(),
             // keep sorted
+            allowedDisplayState.toString(),
+            alternateBouncerShowing.toString(),
             authInterruptActive.toString(),
             biometricSettingEnabledForUser.toString(),
             bouncerFullyShown.toString(),
@@ -74,7 +77,6 @@
             supportsDetect.toString(),
             switchingUser.toString(),
             systemUser.toString(),
-            alternateBouncerShowing.toString(),
             udfpsFingerDown.toString(),
             userNotTrustedOrDetectionIsNeeded.toString(),
         )
@@ -96,7 +98,9 @@
                 userId = model.userId
                 listening = model.listening
                 // keep sorted
+                allowedDisplayState = model.allowedDisplayState
                 alternateBouncerShowing = model.alternateBouncerShowing
+                authInterruptActive = model.authInterruptActive
                 biometricSettingEnabledForUser = model.biometricSettingEnabledForUser
                 bouncerFullyShown = model.bouncerFullyShown
                 faceAndFpNotAuthenticated = model.faceAndFpNotAuthenticated
@@ -105,7 +109,6 @@
                 faceLockedOut = model.faceLockedOut
                 goingToSleep = model.goingToSleep
                 keyguardAwake = model.keyguardAwake
-                goingToSleep = model.goingToSleep
                 keyguardGoingAway = model.keyguardGoingAway
                 listeningForFaceAssistant = model.listeningForFaceAssistant
                 occludingAppRequestingFaceAuth = model.occludingAppRequestingFaceAuth
@@ -140,6 +143,8 @@
                 "userId",
                 "listening",
                 // keep sorted
+                "allowedDisplayState",
+                "alternateBouncerShowing",
                 "authInterruptActive",
                 "biometricSettingEnabledForUser",
                 "bouncerFullyShown",
@@ -157,7 +162,6 @@
                 "supportsDetect",
                 "switchingUser",
                 "systemUser",
-                "udfpsBouncerShowing",
                 "udfpsFingerDown",
                 "userNotTrustedOrDetectionIsNeeded",
             )
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardFingerprintListenModel.kt b/packages/SystemUI/src/com/android/keyguard/KeyguardFingerprintListenModel.kt
index f23ae67..4160ae1 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardFingerprintListenModel.kt
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardFingerprintListenModel.kt
@@ -42,7 +42,6 @@
     var keyguardIsVisible: Boolean = false,
     var keyguardOccluded: Boolean = false,
     var occludingAppRequestingFp: Boolean = false,
-    var shouldListenSfpsState: Boolean = false,
     var shouldListenForFingerprintAssistant: Boolean = false,
     var strongerAuthRequired: Boolean = false,
     var switchingUser: Boolean = false,
@@ -74,7 +73,6 @@
             keyguardIsVisible.toString(),
             keyguardOccluded.toString(),
             occludingAppRequestingFp.toString(),
-            shouldListenSfpsState.toString(),
             shouldListenForFingerprintAssistant.toString(),
             strongerAuthRequired.toString(),
             switchingUser.toString(),
@@ -115,7 +113,6 @@
                 keyguardIsVisible = model.keyguardIsVisible
                 keyguardOccluded = model.keyguardOccluded
                 occludingAppRequestingFp = model.occludingAppRequestingFp
-                shouldListenSfpsState = model.shouldListenSfpsState
                 shouldListenForFingerprintAssistant = model.shouldListenForFingerprintAssistant
                 strongerAuthRequired = model.strongerAuthRequired
                 switchingUser = model.switchingUser
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java
index 20e4656..42dbc48 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java
@@ -30,13 +30,13 @@
 import com.android.internal.widget.LockPatternUtils;
 import com.android.keyguard.KeyguardSecurityModel.SecurityMode;
 import com.android.systemui.R;
+import com.android.systemui.bouncer.domain.interactor.BouncerMessageInteractor;
+import com.android.systemui.bouncer.ui.BouncerMessageView;
+import com.android.systemui.bouncer.ui.binder.BouncerMessageViewBinder;
 import com.android.systemui.classifier.FalsingCollector;
 import com.android.systemui.dagger.qualifiers.Main;
 import com.android.systemui.flags.FeatureFlags;
 import com.android.systemui.flags.Flags;
-import com.android.systemui.bouncer.domain.interactor.BouncerMessageInteractor;
-import com.android.systemui.bouncer.ui.BouncerMessageView;
-import com.android.systemui.bouncer.ui.binder.BouncerMessageViewBinder;
 import com.android.systemui.log.BouncerLogger;
 import com.android.systemui.statusbar.policy.DevicePostureController;
 import com.android.systemui.util.ViewController;
@@ -95,6 +95,12 @@
     @CallSuper
     protected void onViewAttached() {
         updateMessageAreaVisibility();
+        if (TextUtils.isEmpty(mMessageAreaController.getMessage())
+                && getInitialMessageResId() != 0) {
+            mMessageAreaController.setMessage(
+                    mView.getResources().getString(getInitialMessageResId()),
+                    /* animate= */ false);
+        }
     }
 
     private void updateMessageAreaVisibility() {
@@ -147,12 +153,6 @@
     }
 
     public void startAppearAnimation() {
-        if (TextUtils.isEmpty(mMessageAreaController.getMessage())
-                && getInitialMessageResId() != 0) {
-            mMessageAreaController.setMessage(
-                    mView.getResources().getString(getInitialMessageResId()),
-                    /* animate= */ false);
-        }
         mView.startAppearAnimation();
     }
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
index 03d9eb3..59ee0d8 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
@@ -32,6 +32,7 @@
 import android.animation.AnimatorListenerAdapter;
 import android.animation.ValueAnimator;
 import android.content.Context;
+import android.content.res.ColorStateList;
 import android.graphics.Insets;
 import android.graphics.Rect;
 import android.os.Trace;
@@ -71,6 +72,8 @@
     private Interpolator mLinearOutSlowInInterpolator;
     private Interpolator mFastOutLinearInInterpolator;
     private DisappearAnimationListener mDisappearAnimationListener;
+    private static final int[] DISABLE_STATE_SET = {-android.R.attr.state_enabled};
+    private static final int[] ENABLE_STATE_SET = {android.R.attr.state_enabled};
 
     public KeyguardPasswordView(Context context) {
         this(context, null);
@@ -148,7 +151,10 @@
 
     @Override
     protected void setPasswordEntryEnabled(boolean enabled) {
-        mPasswordEntry.setEnabled(enabled);
+        int color = mPasswordEntry.getTextColors().getColorForState(
+                enabled ? ENABLE_STATE_SET : DISABLE_STATE_SET, 0);
+        mPasswordEntry.setBackgroundTintList(ColorStateList.valueOf(color));
+        mPasswordEntry.setCursorVisible(enabled);
     }
 
     @Override
@@ -189,17 +195,18 @@
                             if (controller.isCancelled()) {
                                 return;
                             }
+                            float value = (float) animation.getAnimatedValue();
+                            float fraction = anim.getAnimatedFraction();
                             Insets shownInsets = controller.getShownStateInsets();
                             int dist = (int) (-shownInsets.bottom / 4
-                                    * anim.getAnimatedFraction());
+                                    * fraction);
                             Insets insets = Insets.add(shownInsets, Insets.of(0, 0, 0, dist));
                             if (mDisappearAnimationListener != null) {
                                 mDisappearAnimationListener.setTranslationY(-dist);
                             }
 
-                            controller.setInsetsAndAlpha(insets,
-                                    (float) animation.getAnimatedValue(),
-                                    anim.getAnimatedFraction());
+                            controller.setInsetsAndAlpha(insets, value, fraction);
+                            setAlpha(value);
                         });
                         anim.addListener(new AnimatorListenerAdapter() {
                             @Override
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordViewController.java
index 1f6b09b..5dbd014 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordViewController.java
@@ -265,7 +265,8 @@
     private boolean hasMultipleEnabledIMEsOrSubtypes(InputMethodManager imm,
             final boolean shouldIncludeAuxiliarySubtypes) {
         final List<InputMethodInfo> enabledImis =
-                imm.getEnabledInputMethodListAsUser(KeyguardUpdateMonitor.getCurrentUser());
+                imm.getEnabledInputMethodListAsUser(
+                        UserHandle.of(KeyguardUpdateMonitor.getCurrentUser()));
 
         // Number of the filtered IMEs
         int filteredImisCount = 0;
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java
index 49f788c..a30b447 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java
@@ -238,6 +238,12 @@
         }
         mView.onDevicePostureChanged(mPostureController.getDevicePosture());
         mPostureController.addCallback(mPostureCallback);
+        // if the user is currently locked out, enforce it.
+        long deadline = mLockPatternUtils.getLockoutAttemptDeadline(
+                KeyguardUpdateMonitor.getCurrentUser());
+        if (deadline != 0) {
+            handleAttemptLockout(deadline);
+        }
     }
 
     @Override
@@ -268,12 +274,6 @@
     @Override
     public void onResume(int reason) {
         super.onResume(reason);
-        // if the user is currently locked out, enforce it.
-        long deadline = mLockPatternUtils.getLockoutAttemptDeadline(
-                KeyguardUpdateMonitor.getCurrentUser());
-        if (deadline != 0) {
-            handleAttemptLockout(deadline);
-        }
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardPinViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardPinViewController.java
index b3e08c0..574a059 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardPinViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPinViewController.java
@@ -79,6 +79,10 @@
         mPasswordEntry.setUserActivityListener(this::onUserInput);
         mView.onDevicePostureChanged(mPostureController.getDevicePosture());
         mPostureController.addCallback(mPostureCallback);
+        if (mFeatureFlags.isEnabled(Flags.AUTO_PIN_CONFIRMATION)) {
+            mPasswordEntry.setUsePinShapes(true);
+            updateAutoConfirmationState();
+        }
     }
 
     protected void onUserInput() {
@@ -100,10 +104,6 @@
 
     @Override
     public void startAppearAnimation() {
-        if (mFeatureFlags.isEnabled(Flags.AUTO_PIN_CONFIRMATION)) {
-            mPasswordEntry.setUsePinShapes(true);
-            updateAutoConfirmationState();
-        }
         super.startAppearAnimation();
     }
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
index 8a0c9ef..3f3efe9 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
@@ -100,6 +100,7 @@
 import com.android.systemui.R;
 import com.android.systemui.classifier.FalsingA11yDelegate;
 import com.android.systemui.plugins.FalsingManager;
+import com.android.systemui.shade.TouchLogger;
 import com.android.systemui.shared.system.SysUiStatsLog;
 import com.android.systemui.statusbar.policy.BaseUserSwitcherAdapter;
 import com.android.systemui.statusbar.policy.UserSwitcherController;
@@ -666,6 +667,11 @@
     }
 
     @Override
+    public boolean dispatchTouchEvent(MotionEvent ev) {
+        return TouchLogger.logDispatchTouch(TAG, ev, super.dispatchTouchEvent(ev));
+    }
+
+    @Override
     protected void dispatchDraw(Canvas canvas) {
         super.dispatchDraw(canvas);
         if (mViewMediatorCallback != null) {
@@ -1198,8 +1204,6 @@
                 });
                 mPopup.show();
             });
-
-            mUserSwitcherViewGroup.setAlpha(0f);
         }
 
         @Override
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
index aff2591..04692c4 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
@@ -33,7 +33,6 @@
 import android.app.admin.DevicePolicyManager;
 import android.content.Intent;
 import android.content.res.ColorStateList;
-import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.hardware.biometrics.BiometricOverlayConstants;
 import android.media.AudioManager;
@@ -69,6 +68,7 @@
 import com.android.settingslib.utils.ThreadUtils;
 import com.android.systemui.Gefingerpoken;
 import com.android.systemui.R;
+import com.android.systemui.authentication.domain.interactor.AuthenticationInteractor;
 import com.android.systemui.biometrics.FaceAuthAccessibilityDelegate;
 import com.android.systemui.biometrics.SideFpsController;
 import com.android.systemui.biometrics.SideFpsUiRequestSource;
@@ -78,13 +78,13 @@
 import com.android.systemui.flags.FeatureFlags;
 import com.android.systemui.flags.Flags;
 import com.android.systemui.keyguard.domain.interactor.KeyguardFaceAuthInteractor;
+import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor;
 import com.android.systemui.log.SessionTracker;
 import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.plugins.FalsingManager;
-import com.android.systemui.scene.domain.interactor.SceneInteractor;
-import com.android.systemui.scene.shared.model.SceneKey;
 import com.android.systemui.shared.system.SysUiStatsLog;
 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.UserSwitcherController;
 import com.android.systemui.user.domain.interactor.UserInteractor;
@@ -128,6 +128,7 @@
     private final KeyguardFaceAuthInteractor mKeyguardFaceAuthInteractor;
     private final BouncerMessageInteractor mBouncerMessageInteractor;
     private int mTranslationY;
+    private final KeyguardTransitionInteractor mKeyguardTransitionInteractor;
     // Whether the volume keys should be handled by keyguard. If true, then
     // they will be handled here for specific media types such as music, otherwise
     // the audio service will bring up the volume dialog.
@@ -143,11 +144,22 @@
     private Runnable mCancelAction;
     private boolean mWillRunDismissFromKeyguard;
 
-    private int mLastOrientation = Configuration.ORIENTATION_UNDEFINED;
+    private int mLastOrientation;
 
     private SecurityMode mCurrentSecurityMode = SecurityMode.Invalid;
+    private int mCurrentUser = UserHandle.USER_NULL;
     private UserSwitcherController.UserSwitchCallback mUserSwitchCallback =
-            () -> showPrimarySecurityScreen(false);
+            new UserSwitcherController.UserSwitchCallback() {
+        @Override
+        public void onUserSwitched() {
+            if (mCurrentUser == KeyguardUpdateMonitor.getCurrentUser()) {
+                return;
+            }
+            mCurrentUser = KeyguardUpdateMonitor.getCurrentUser();
+            showPrimarySecurityScreen(false);
+            reinflateViewFlipper((l) -> {});
+        }
+    };
 
     @VisibleForTesting
     final Gefingerpoken mGlobalTouchListener = new Gefingerpoken() {
@@ -301,6 +313,10 @@
                     mViewMediatorCallback.keyguardDone(fromPrimaryAuth, targetUserId);
                 }
             }
+
+            if (mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                mKeyguardTransitionInteractor.startDismissKeyguardTransition();
+            }
         }
 
         @Override
@@ -339,7 +355,6 @@
                 @Override
                 public void onThemeChanged() {
                     reloadColors();
-                    reset();
                 }
 
                 @Override
@@ -349,7 +364,14 @@
 
                 @Override
                 public void onDensityOrFontScaleChanged() {
-                    KeyguardSecurityContainerController.this.onDensityOrFontScaleChanged();
+                    KeyguardSecurityContainerController.this
+                            .onDensityOrFontScaleOrOrientationChanged();
+                }
+
+                @Override
+                public void onOrientationChanged(int orientation) {
+                    KeyguardSecurityContainerController.this
+                            .onDensityOrFontScaleOrOrientationChanged();
                 }
             };
     private final KeyguardUpdateMonitorCallback mKeyguardUpdateMonitorCallback =
@@ -388,8 +410,9 @@
                 }
             };
     private final UserInteractor mUserInteractor;
-    private final Provider<SceneInteractor> mSceneInteractor;
+    private final Provider<AuthenticationInteractor> mAuthenticationInteractor;
     private final Provider<JavaAdapter> mJavaAdapter;
+    private final DeviceProvisionedController mDeviceProvisionedController;
     @Nullable private Job mSceneTransitionCollectionJob;
 
     @Inject
@@ -418,8 +441,10 @@
             BouncerMessageInteractor bouncerMessageInteractor,
             Provider<JavaAdapter> javaAdapter,
             UserInteractor userInteractor,
+            DeviceProvisionedController deviceProvisionedController,
             FaceAuthAccessibilityDelegate faceAuthAccessibilityDelegate,
-            Provider<SceneInteractor> sceneInteractor
+            KeyguardTransitionInteractor keyguardTransitionInteractor,
+            Provider<AuthenticationInteractor> authenticationInteractor
     ) {
         super(view);
         view.setAccessibilityDelegate(faceAuthAccessibilityDelegate);
@@ -448,8 +473,10 @@
         mKeyguardFaceAuthInteractor = keyguardFaceAuthInteractor;
         mBouncerMessageInteractor = bouncerMessageInteractor;
         mUserInteractor = userInteractor;
-        mSceneInteractor = sceneInteractor;
+        mAuthenticationInteractor = authenticationInteractor;
         mJavaAdapter = javaAdapter;
+        mKeyguardTransitionInteractor = keyguardTransitionInteractor;
+        mDeviceProvisionedController = deviceProvisionedController;
     }
 
     @Override
@@ -474,21 +501,21 @@
         showPrimarySecurityScreen(false);
 
         if (mFeatureFlags.isEnabled(Flags.SCENE_CONTAINER)) {
-            // When the scene framework transitions from bouncer to gone, we dismiss the keyguard.
+            // When the scene framework says that the lockscreen has been dismissed, dismiss the
+            // keyguard here, revealing the underlying app or launcher:
             mSceneTransitionCollectionJob = mJavaAdapter.get().alwaysCollectFlow(
-                mSceneInteractor.get().getTransitions(),
-                sceneTransitionModel -> {
-                    if (sceneTransitionModel != null
-                            && sceneTransitionModel.getFrom() == SceneKey.Bouncer.INSTANCE
-                            && sceneTransitionModel.getTo() == SceneKey.Gone.INSTANCE) {
+                mAuthenticationInteractor.get().isLockscreenDismissed(),
+                isLockscreenDismissed -> {
+                    if (isLockscreenDismissed) {
                         final int selectedUserId = mUserInteractor.getSelectedUserId();
                         showNextSecurityScreenOrFinish(
-                                /* authenticated= */ true,
-                                selectedUserId,
-                                /* bypassSecondaryLockScreen= */ true,
-                                mSecurityModel.getSecurityMode(selectedUserId));
+                            /* authenticated= */ true,
+                            selectedUserId,
+                            /* bypassSecondaryLockScreen= */ true,
+                            mSecurityModel.getSecurityMode(selectedUserId));
                     }
-                });
+                }
+            );
         }
     }
 
@@ -677,6 +704,14 @@
         mSecurityViewFlipperController.reset();
     }
 
+    /** Prepares views in the bouncer before starting appear animation. */
+    public void prepareToShow() {
+        View bouncerUserSwitcher = mView.findViewById(R.id.keyguard_bouncer_user_switcher);
+        if (bouncerUserSwitcher != null) {
+            bouncerUserSwitcher.setAlpha(0f);
+        }
+    }
+
     @Override
     public void onResume(int reason) {
         if (DEBUG) Log.d(TAG, "screen on, instance " + Integer.toHexString(hashCode()));
@@ -826,9 +861,11 @@
                     // Shortcut for SIM PIN/PUK to go to directly to user's security screen or home
                     SecurityMode securityMode = mSecurityModel.getSecurityMode(targetUserId);
                     boolean isLockscreenDisabled = mLockPatternUtils.isLockScreenDisabled(
-                            KeyguardUpdateMonitor.getCurrentUser());
-                    if (securityMode == SecurityMode.None || isLockscreenDisabled) {
-                        finish = isLockscreenDisabled;
+                            KeyguardUpdateMonitor.getCurrentUser())
+                            || !mDeviceProvisionedController.isUserSetup(targetUserId);
+
+                    if (securityMode == SecurityMode.None && isLockscreenDisabled) {
+                        finish = true;
                         eventSubtype = BOUNCER_DISMISS_SIM;
                         uiEvent = BouncerUiEvent.BOUNCER_DISMISS_SIM;
                     } else {
@@ -1143,11 +1180,11 @@
     }
 
     private void reloadColors() {
-        reinflateViewFlipper(controller -> mView.reloadColors());
+        mView.reloadColors();
     }
 
     /** Handles density or font scale changes. */
-    private void onDensityOrFontScaleChanged() {
+    private void onDensityOrFontScaleOrOrientationChanged() {
         reinflateViewFlipper(controller -> mView.onDensityOrFontScaleChanged());
     }
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityViewTransition.kt b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityViewTransition.kt
index 96ac8ad..e1c060f 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityViewTransition.kt
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityViewTransition.kt
@@ -66,11 +66,11 @@
     }
 
     override fun createAnimator(
-        sceneRoot: ViewGroup?,
+        sceneRoot: ViewGroup,
         startValues: TransitionValues?,
         endValues: TransitionValues?
     ): Animator? {
-        if (sceneRoot == null || startValues == null || endValues == null) {
+        if (startValues == null || endValues == null) {
             return null
         }
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
index 7585279..5774e42 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
@@ -23,12 +23,14 @@
 import android.os.Build;
 import android.os.Trace;
 import android.util.AttributeSet;
+import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.ViewPropertyAnimator;
 import android.widget.GridLayout;
 
 import com.android.systemui.R;
+import com.android.systemui.shade.TouchLogger;
 import com.android.systemui.statusbar.CrossFadeHelper;
 
 import java.io.PrintWriter;
@@ -110,6 +112,11 @@
         }
     }
 
+    @Override
+    public boolean dispatchTouchEvent(MotionEvent ev) {
+        return TouchLogger.logDispatchTouch(TAG, ev, super.dispatchTouchEvent(ev));
+    }
+
     public void dump(PrintWriter pw, String[] args) {
         pw.println("KeyguardStatusView:");
         pw.println("  mDarkAmount: " + mDarkAmount);
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusViewController.java
index 8e92941..c314586 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusViewController.java
@@ -150,7 +150,8 @@
     @Override
     public void onInit() {
         mKeyguardClockSwitchController.init();
-        mDumpManager.registerDumpable(this);
+
+        mDumpManager.registerDumpable(getInstanceName(), this);
         if (mFeatureFlags.isEnabled(Flags.MIGRATE_KEYGUARD_STATUS_VIEW)) {
             startCoroutines(EmptyCoroutineContext.INSTANCE);
         }
@@ -186,11 +187,16 @@
         mConfigurationController.removeCallback(mConfigurationListener);
     }
 
+    /** Sets the StatusView as shown on an external display. */
+    public void setDisplayedOnSecondaryDisplay() {
+        mKeyguardClockSwitchController.setShownOnSecondaryDisplay(true);
+    }
+
     /**
      * Called in notificationPanelViewController to avoid leak
      */
     public void onDestroy() {
-        mDumpManager.unregisterDumpable(TAG);
+        mDumpManager.unregisterDumpable(getInstanceName());
     }
 
     /**
@@ -385,7 +391,7 @@
      * Updates the alignment of the KeyguardStatusView and animates the transition if requested.
      */
     public void updateAlignment(
-            ConstraintLayout notifContainerParent,
+            ConstraintLayout layout,
             boolean splitShadeEnabled,
             boolean shouldBeCentered,
             boolean animate) {
@@ -395,16 +401,23 @@
         }
 
         mStatusViewCentered = shouldBeCentered;
-        if (notifContainerParent == null) {
+        if (layout == null) {
             return;
         }
 
         ConstraintSet constraintSet = new ConstraintSet();
-        constraintSet.clone(notifContainerParent);
-        int statusConstraint = shouldBeCentered ? PARENT_ID : R.id.qs_edge_guideline;
+        constraintSet.clone(layout);
+        int guideline;
+        if (mFeatureFlags.isEnabled(Flags.MIGRATE_KEYGUARD_STATUS_VIEW)) {
+            guideline = R.id.split_shade_guideline;
+        } else {
+            guideline = R.id.qs_edge_guideline;
+        }
+
+        int statusConstraint = shouldBeCentered ? PARENT_ID : guideline;
         constraintSet.connect(R.id.keyguard_status_view, END, statusConstraint, END);
         if (!animate) {
-            constraintSet.applyTo(notifContainerParent);
+            constraintSet.applyTo(layout);
             return;
         }
 
@@ -447,7 +460,7 @@
             // old animation rather than setting up the custom animations.
             if (clockContainerView == null || clockContainerView.getChildCount() == 0) {
                 transition.addListener(mKeyguardStatusAlignmentTransitionListener);
-                TransitionManager.beginDelayedTransition(notifContainerParent, transition);
+                TransitionManager.beginDelayedTransition(layout, transition);
             } else {
                 View clockView = clockContainerView.getChildAt(0);
 
@@ -481,14 +494,14 @@
                 }
 
                 set.addListener(mKeyguardStatusAlignmentTransitionListener);
-                TransitionManager.beginDelayedTransition(notifContainerParent, set);
+                TransitionManager.beginDelayedTransition(layout, set);
             }
         } else {
             transition.addListener(mKeyguardStatusAlignmentTransitionListener);
-            TransitionManager.beginDelayedTransition(notifContainerParent, transition);
+            TransitionManager.beginDelayedTransition(layout, transition);
         }
 
-        constraintSet.applyTo(notifContainerParent);
+        constraintSet.applyTo(layout);
     }
 
     @Override
@@ -496,6 +509,10 @@
         mView.dump(pw, args);
     }
 
+    String getInstanceName() {
+        return TAG + "#" + hashCode();
+    }
+
     @VisibleForTesting
     static class SplitShadeTransitionAdapter extends Transition {
         private static final String PROP_BOUNDS_LEFT = "splitShadeTransitionAdapter:boundsLeft";
@@ -531,7 +548,8 @@
 
         @Nullable
         @Override
-        public Animator createAnimator(ViewGroup sceneRoot, @Nullable TransitionValues startValues,
+        public Animator createAnimator(@NonNull ViewGroup sceneRoot,
+                @Nullable TransitionValues startValues,
                 @Nullable TransitionValues endValues) {
             if (startValues == null || endValues == null) {
                 return null;
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
index c03053d..0ba6c05 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
@@ -41,6 +41,7 @@
 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT;
 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN;
 import static com.android.keyguard.FaceAuthReasonKt.apiRequestReasonToUiEvent;
+import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_DISPLAY_OFF;
 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_NON_STRONG_BIOMETRIC_ALLOWED_CHANGED;
 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_STOPPED_DREAM_STARTED;
 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_STOPPED_FACE_CANCEL_NOT_RECEIVED;
@@ -135,6 +136,7 @@
 import android.text.TextUtils;
 import android.util.SparseArray;
 import android.util.SparseBooleanArray;
+import android.view.Display;
 
 import androidx.annotation.NonNull;
 import androidx.annotation.Nullable;
@@ -175,6 +177,7 @@
 import com.android.systemui.log.SessionTracker;
 import com.android.systemui.plugins.WeatherData;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
+import com.android.systemui.settings.DisplayTracker;
 import com.android.systemui.settings.UserTracker;
 import com.android.systemui.shared.system.TaskStackChangeListener;
 import com.android.systemui.shared.system.TaskStackChangeListeners;
@@ -335,6 +338,25 @@
             }
         }
     };
+    private final DisplayTracker.Callback mDisplayCallback = new DisplayTracker.Callback() {
+        @Override
+        public void onDisplayChanged(int displayId) {
+            if (displayId != Display.DEFAULT_DISPLAY) {
+                return;
+            }
+
+            if (mDisplayTracker.getDisplay(mDisplayTracker.getDefaultDisplayId()).getState()
+                    == Display.STATE_OFF) {
+                mAllowedDisplayStateForFaceAuth = false;
+                updateFaceListeningState(
+                        BIOMETRIC_ACTION_STOP,
+                        FACE_AUTH_DISPLAY_OFF
+                );
+            } else {
+                mAllowedDisplayStateForFaceAuth = true;
+            }
+        }
+    };
     private final FaceWakeUpTriggersConfig mFaceWakeUpTriggersConfig;
 
     HashMap<Integer, SimData> mSimDatas = new HashMap<>();
@@ -355,6 +377,7 @@
     private boolean mOccludingAppRequestingFp;
     private boolean mOccludingAppRequestingFace;
     private boolean mSecureCameraLaunched;
+    private boolean mAllowedDisplayStateForFaceAuth = true;
     @VisibleForTesting
     protected boolean mTelephonyCapable;
     private boolean mAllowFingerprintOnCurrentOccludingActivity;
@@ -403,6 +426,7 @@
     private KeyguardFaceAuthInteractor mFaceAuthInteractor;
     private final TaskStackChangeListeners mTaskStackChangeListeners;
     private final IActivityTaskManager mActivityTaskManager;
+    private final DisplayTracker mDisplayTracker;
     private final LockPatternUtils mLockPatternUtils;
     @VisibleForTesting
     @DevicePostureInt
@@ -2187,6 +2211,7 @@
         Trace.beginSection("KeyguardUpdateMonitor#handleStartedWakingUp");
         Assert.isMainThread();
 
+        mAllowedDisplayStateForFaceAuth = true;
         updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
         if (mFaceWakeUpTriggersConfig.shouldTriggerFaceAuthOnWakeUpFrom(pmWakeReason)) {
             FACE_AUTH_UPDATED_STARTED_WAKING_UP.setExtraInfo(pmWakeReason);
@@ -2342,7 +2367,8 @@
             Optional<FingerprintInteractiveToAuthProvider> interactiveToAuthProvider,
             FeatureFlags featureFlags,
             TaskStackChangeListeners taskStackChangeListeners,
-            IActivityTaskManager activityTaskManagerService) {
+            IActivityTaskManager activityTaskManagerService,
+            DisplayTracker displayTracker) {
         mContext = context;
         mSubscriptionManager = subscriptionManager;
         mUserTracker = userTracker;
@@ -2390,6 +2416,10 @@
                 .collect(Collectors.toSet());
         mTaskStackChangeListeners = taskStackChangeListeners;
         mActivityTaskManager = activityTaskManagerService;
+        mDisplayTracker = displayTracker;
+        if (mFeatureFlags.isEnabled(Flags.STOP_FACE_AUTH_ON_DISPLAY_OFF)) {
+            mDisplayTracker.addDisplayChangeCallback(mDisplayCallback, mainExecutor);
+        }
 
         mHandler = new Handler(mainLooper) {
             @Override
@@ -3098,18 +3128,9 @@
                 && !strongerAuthRequired
                 && userDoesNotHaveTrust);
 
-        boolean shouldListenSideFpsState = true;
-        if (isSideFps) {
-            final boolean interactiveToAuthEnabled =
-                    mFingerprintInteractiveToAuthProvider != null &&
-                            mFingerprintInteractiveToAuthProvider.isEnabled(getCurrentUser());
-            shouldListenSideFpsState =
-                    interactiveToAuthEnabled ? isDeviceInteractive() && !mGoingToSleep : true;
-        }
 
         boolean shouldListen = shouldListenKeyguardState && shouldListenUserState
-                && shouldListenBouncerState && shouldListenUdfpsState
-                && shouldListenSideFpsState;
+                && shouldListenBouncerState && shouldListenUdfpsState;
         logListenerModelData(
                 new KeyguardFingerprintListenModel(
                     System.currentTimeMillis(),
@@ -3130,7 +3151,6 @@
                     isKeyguardVisible(),
                     mKeyguardOccluded,
                     mOccludingAppRequestingFp,
-                    shouldListenSideFpsState,
                     shouldListenForFingerprintAssistant,
                     strongerAuthRequired,
                     mSwitchingUser,
@@ -3199,7 +3219,8 @@
                 && (!mSecureCameraLaunched || mAlternateBouncerShowing)
                 && faceAndFpNotAuthenticated
                 && !mGoingToSleep
-                && isPostureAllowedForFaceAuth;
+                && isPostureAllowedForFaceAuth
+                && mAllowedDisplayStateForFaceAuth;
 
         // Aggregate relevant fields for debug logging.
         logListenerModelData(
@@ -3207,6 +3228,7 @@
                     System.currentTimeMillis(),
                     user,
                     shouldListen,
+                    mAllowedDisplayStateForFaceAuth,
                     mAlternateBouncerShowing,
                     mAuthInterruptActive,
                     biometricEnabledForUser,
@@ -3282,6 +3304,9 @@
                         mFingerprintDetectionCallback,
                         new FingerprintAuthenticateOptions.Builder()
                                 .setUserId(userId)
+                                .setVendorReason(
+                                        mFingerprintInteractiveToAuthProvider.getVendorExtension(
+                                                getCurrentUser()))
                                 .build());
             } else {
                 mLogger.v("startListeningForFingerprint");
@@ -3290,6 +3315,9 @@
                         null /* handler */,
                         new FingerprintAuthenticateOptions.Builder()
                                 .setUserId(userId)
+                                .setVendorReason(
+                                        mFingerprintInteractiveToAuthProvider.getVendorExtension(
+                                                getCurrentUser()))
                                 .build()
                 );
             }
@@ -4400,6 +4428,7 @@
 
         mLockPatternUtils.unregisterStrongAuthTracker(mStrongAuthTracker);
         mTrustManager.unregisterTrustListener(this);
+        mDisplayTracker.removeCallback(mDisplayCallback);
 
         mHandler.removeCallbacksAndMessages(null);
     }
@@ -4464,14 +4493,6 @@
             } else if (isSfpsSupported()) {
                 pw.println("        sfpsEnrolled=" + isSfpsEnrolled());
                 pw.println("        shouldListenForSfps=" + shouldListenForFingerprint(false));
-                if (isSfpsEnrolled()) {
-                    final boolean interactiveToAuthEnabled =
-                                    mFingerprintInteractiveToAuthProvider != null &&
-                                            mFingerprintInteractiveToAuthProvider
-                                            .isEnabled(getCurrentUser());
-                    pw.println("        interactiveToAuthEnabled="
-                            + interactiveToAuthEnabled);
-                }
             }
             new DumpsysTableLogger(
                     "KeyguardFingerprintListen",
diff --git a/packages/SystemUI/src/com/android/keyguard/LockIconView.java b/packages/SystemUI/src/com/android/keyguard/LockIconView.java
index 1a0c7f9..8611dbbb 100644
--- a/packages/SystemUI/src/com/android/keyguard/LockIconView.java
+++ b/packages/SystemUI/src/com/android/keyguard/LockIconView.java
@@ -22,6 +22,7 @@
 import android.content.res.ColorStateList;
 import android.graphics.Color;
 import android.graphics.Point;
+import android.graphics.Rect;
 import android.graphics.RectF;
 import android.graphics.drawable.Drawable;
 import android.util.AttributeSet;
@@ -154,11 +155,16 @@
     }
 
     float getLocationTop() {
-        return mLockIconCenter.y - mRadius;
+        Rect r = new Rect();
+        mLockIcon.getGlobalVisibleRect(r);
+        return r.top;
     }
 
     float getLocationBottom() {
-        return mLockIconCenter.y + mRadius;
+        Rect r = new Rect();
+        mLockIcon.getGlobalVisibleRect(r);
+        return r.bottom;
+
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/keyguard/LockIconViewController.java b/packages/SystemUI/src/com/android/keyguard/LockIconViewController.java
index 4845a61..951a6ae 100644
--- a/packages/SystemUI/src/com/android/keyguard/LockIconViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/LockIconViewController.java
@@ -25,6 +25,7 @@
 import static com.android.systemui.doze.util.BurnInHelperKt.getBurnInOffset;
 import static com.android.systemui.flags.Flags.DOZING_MIGRATION_1;
 import static com.android.systemui.flags.Flags.LOCKSCREEN_WALLPAPER_DREAM_ENABLED;
+import static com.android.systemui.flags.Flags.ONE_WAY_HAPTICS_API_MIGRATION;
 import static com.android.systemui.util.kotlin.JavaAdapterKt.collectFlow;
 
 import android.content.res.Configuration;
@@ -39,6 +40,7 @@
 import android.util.DisplayMetrics;
 import android.util.Log;
 import android.util.MathUtils;
+import android.view.HapticFeedbackConstants;
 import android.view.MotionEvent;
 import android.view.VelocityTracker;
 import android.view.View;
@@ -613,12 +615,7 @@
             case MotionEvent.ACTION_DOWN:
             case MotionEvent.ACTION_HOVER_ENTER:
                 if (!mDownDetected && mAccessibilityManager.isTouchExplorationEnabled()) {
-                    mVibrator.vibrate(
-                            Process.myUid(),
-                            getContext().getOpPackageName(),
-                            UdfpsController.EFFECT_CLICK,
-                            "lock-icon-down",
-                            TOUCH_VIBRATION_ATTRIBUTES);
+                    vibrateOnTouchExploration();
                 }
 
                 // The pointer that causes ACTION_DOWN is always at index 0.
@@ -699,13 +696,8 @@
             mOnGestureDetectedRunnable.run();
         }
 
-        // play device entry haptic (same as biometric success haptic)
-        mVibrator.vibrate(
-                Process.myUid(),
-                getContext().getOpPackageName(),
-                UdfpsController.EFFECT_CLICK,
-                "lock-screen-lock-icon-longpress",
-                TOUCH_VIBRATION_ATTRIBUTES);
+        // play device entry haptic (consistent with UDFPS controller longpress)
+        vibrateOnLongPress();
 
         mKeyguardViewController.showPrimaryBouncer(/* scrim */ true);
     }
@@ -753,6 +745,37 @@
         });
     }
 
+    @VisibleForTesting
+    void vibrateOnTouchExploration() {
+        if (mFeatureFlags.isEnabled(ONE_WAY_HAPTICS_API_MIGRATION)) {
+            mVibrator.performHapticFeedback(
+                    mView,
+                    HapticFeedbackConstants.CONTEXT_CLICK
+            );
+        } else {
+            mVibrator.vibrate(
+                    Process.myUid(),
+                    getContext().getOpPackageName(),
+                    UdfpsController.EFFECT_CLICK,
+                    "lock-icon-down",
+                    TOUCH_VIBRATION_ATTRIBUTES);
+        }
+    }
+
+    @VisibleForTesting
+    void vibrateOnLongPress() {
+        if (mFeatureFlags.isEnabled(ONE_WAY_HAPTICS_API_MIGRATION)) {
+            mVibrator.performHapticFeedback(mView, UdfpsController.LONG_PRESS);
+        } else {
+            mVibrator.vibrate(
+                    Process.myUid(),
+                    getContext().getOpPackageName(),
+                    UdfpsController.EFFECT_CLICK,
+                    "lock-screen-lock-icon-longpress",
+                    TOUCH_VIBRATION_ATTRIBUTES);
+        }
+    }
+
     private final AuthController.Callback mAuthControllerCallback = new AuthController.Callback() {
         @Override
         public void onAllAuthenticatorsRegistered(@BiometricAuthenticator.Modality int modality) {
diff --git a/packages/SystemUI/src/com/android/keyguard/NumPadAnimator.java b/packages/SystemUI/src/com/android/keyguard/NumPadAnimator.java
index a04a48d..e773416 100644
--- a/packages/SystemUI/src/com/android/keyguard/NumPadAnimator.java
+++ b/packages/SystemUI/src/com/android/keyguard/NumPadAnimator.java
@@ -58,6 +58,7 @@
     private float mStartRadius;
     private float mEndRadius;
     private int mHeight;
+    private int mWidth;
 
     private static final int EXPAND_ANIMATION_MS = 100;
     private static final int EXPAND_COLOR_ANIMATION_MS = 50;
@@ -95,11 +96,17 @@
         mBackground.setCornerRadius(mEndRadius + (mStartRadius - mEndRadius) * progress);
         int height = (int) (mHeight * 0.7f + mHeight * 0.3 * progress);
         int difference = mHeight - height;
-        mBackground.setBounds(0, difference / 2, mHeight, mHeight - difference / 2);
+
+        int left = 0;
+        int top = difference / 2;
+        int right = mWidth;
+        int bottom = mHeight - difference / 2;
+        mBackground.setBounds(left, top, right, bottom);
     }
 
-    void onLayout(int height) {
+    void onLayout(int width, int height) {
         boolean shouldUpdateHeight = height != mHeight;
+        mWidth = width;
         mHeight = height;
         mStartRadius = height / 2f;
         mEndRadius = height / 4f;
@@ -121,7 +128,7 @@
         ContextThemeWrapper ctw = new ContextThemeWrapper(context, mStyle);
         @SuppressLint("ResourceType") TypedArray a = ctw.obtainStyledAttributes(customAttrs);
         mNormalBackgroundColor = getPrivateAttrColorIfUnset(ctw, a, 0, 0,
-                       NUM_PAD_BACKGROUND);
+                NUM_PAD_BACKGROUND);
         a.recycle();
 
         mPressedBackgroundColor = getColorAttrDefaultColor(context, NUM_PAD_BACKGROUND_PRESSED);
diff --git a/packages/SystemUI/src/com/android/keyguard/NumPadButton.java b/packages/SystemUI/src/com/android/keyguard/NumPadButton.java
index 3f1741a6..5c2f3b3 100644
--- a/packages/SystemUI/src/com/android/keyguard/NumPadButton.java
+++ b/packages/SystemUI/src/com/android/keyguard/NumPadButton.java
@@ -74,8 +74,9 @@
     @Override
     protected void onLayout(boolean changed, int l, int t, int r, int b) {
         super.onLayout(changed, l, t, r, b);
-
-        if (mAnimator != null) mAnimator.onLayout(b - t);
+        int width = r - l;
+        int height = b - t;
+        if (mAnimator != null) mAnimator.onLayout(width, height);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/keyguard/NumPadKey.java b/packages/SystemUI/src/com/android/keyguard/NumPadKey.java
index edc298c..466d154 100644
--- a/packages/SystemUI/src/com/android/keyguard/NumPadKey.java
+++ b/packages/SystemUI/src/com/android/keyguard/NumPadKey.java
@@ -211,7 +211,9 @@
         left = centerX - mKlondikeText.getMeasuredWidth() / 2;
         mKlondikeText.layout(left, top, left + mKlondikeText.getMeasuredWidth(), bottom);
 
-        if (mAnimator != null) mAnimator.onLayout(b - t);
+        int width = r - l;
+        int height = b - t;
+        if (mAnimator != null) mAnimator.onLayout(width, height);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/Dependency.java b/packages/SystemUI/src/com/android/systemui/Dependency.java
index b01e136..0180384 100644
--- a/packages/SystemUI/src/com/android/systemui/Dependency.java
+++ b/packages/SystemUI/src/com/android/systemui/Dependency.java
@@ -130,14 +130,14 @@
 import com.android.systemui.util.leak.LeakReporter;
 import com.android.systemui.util.sensors.AsyncSensorManager;
 
-import dagger.Lazy;
-
 import java.util.concurrent.Executor;
 import java.util.function.Consumer;
 
 import javax.inject.Inject;
 import javax.inject.Named;
 
+import dagger.Lazy;
+
 /**
  * Class to handle ugly dependencies throughout sysui until we determine the
  * long-term dependency injection solution.
@@ -278,7 +278,6 @@
     @Inject Lazy<AccessibilityManagerWrapper> mAccessibilityManagerWrapper;
     @Inject Lazy<SysuiColorExtractor> mSysuiColorExtractor;
     @Inject Lazy<TunablePaddingService> mTunablePaddingService;
-    @Inject Lazy<ForegroundServiceController> mForegroundServiceController;
     @Inject Lazy<UiOffloadThread> mUiOffloadThread;
     @Inject Lazy<PowerUI.WarningsUI> mWarningsUI;
     @Inject Lazy<LightBarController> mLightBarController;
@@ -456,8 +455,6 @@
 
         mProviders.put(TunablePaddingService.class, mTunablePaddingService::get);
 
-        mProviders.put(ForegroundServiceController.class, mForegroundServiceController::get);
-
         mProviders.put(UiOffloadThread.class, mUiOffloadThread::get);
 
         mProviders.put(PowerUI.WarningsUI.class, mWarningsUI::get);
diff --git a/packages/SystemUI/src/com/android/systemui/FaceScanningOverlay.kt b/packages/SystemUI/src/com/android/systemui/FaceScanningOverlay.kt
index 403c809..95e2dba 100644
--- a/packages/SystemUI/src/com/android/systemui/FaceScanningOverlay.kt
+++ b/packages/SystemUI/src/com/android/systemui/FaceScanningOverlay.kt
@@ -36,6 +36,8 @@
 import com.android.keyguard.KeyguardUpdateMonitorCallback
 import com.android.settingslib.Utils
 import com.android.systemui.biometrics.AuthController
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
 import com.android.systemui.log.ScreenDecorationsLogger
 import com.android.systemui.plugins.statusbar.StatusBarStateController
 import com.android.systemui.util.asIndenting
@@ -54,6 +56,7 @@
     val mainExecutor: Executor,
     val logger: ScreenDecorationsLogger,
     val authController: AuthController,
+    val featureFlags: FeatureFlags,
 ) : ScreenDecorations.DisplayCutoutView(context, pos) {
     private var showScanningAnim = false
     private val rimPaint = Paint()
@@ -294,6 +297,15 @@
     }
 
     private fun createFaceScanningRimAnimator(): AnimatorSet {
+        val dontPulse = featureFlags.isEnabled(Flags.STOP_PULSING_FACE_SCANNING_ANIMATION)
+        if (dontPulse) {
+            return AnimatorSet().apply {
+                playSequentially(
+                        cameraProtectionAnimator,
+                        createRimAppearAnimator(),
+                )
+            }
+        }
         return AnimatorSet().apply {
             playSequentially(
                 cameraProtectionAnimator,
diff --git a/packages/SystemUI/src/com/android/systemui/ForegroundServiceController.java b/packages/SystemUI/src/com/android/systemui/ForegroundServiceController.java
deleted file mode 100644
index 15e8c4e..0000000
--- a/packages/SystemUI/src/com/android/systemui/ForegroundServiceController.java
+++ /dev/null
@@ -1,183 +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.annotation.Nullable;
-import android.app.AppOpsManager;
-import android.os.Handler;
-import android.os.UserHandle;
-import android.service.notification.StatusBarNotification;
-import android.util.ArraySet;
-import android.util.SparseArray;
-
-import com.android.internal.messages.nano.SystemMessageProto;
-import com.android.systemui.appops.AppOpsController;
-import com.android.systemui.dagger.SysUISingleton;
-import com.android.systemui.dagger.qualifiers.Main;
-import com.android.systemui.util.Assert;
-
-import javax.inject.Inject;
-
-/**
- * Tracks state of foreground services and notifications related to foreground services per user.
- */
-@SysUISingleton
-public class ForegroundServiceController {
-    public static final int[] APP_OPS = new int[] {AppOpsManager.OP_SYSTEM_ALERT_WINDOW};
-
-    private final SparseArray<ForegroundServicesUserState> mUserServices = new SparseArray<>();
-    private final Object mMutex = new Object();
-    private final Handler mMainHandler;
-
-    @Inject
-    public ForegroundServiceController(
-            AppOpsController appOpsController,
-            @Main Handler mainHandler) {
-        mMainHandler = mainHandler;
-        appOpsController.addCallback(APP_OPS, (code, uid, packageName, active) -> {
-            mMainHandler.post(() -> {
-                onAppOpChanged(code, uid, packageName, active);
-            });
-        });
-    }
-
-    /**
-     * @return true if this user has services missing notifications and therefore needs a
-     * disclosure notification for running a foreground service.
-     */
-    public boolean isDisclosureNeededForUser(int userId) {
-        synchronized (mMutex) {
-            final ForegroundServicesUserState services = mUserServices.get(userId);
-            if (services == null) return false;
-            return services.isDisclosureNeeded();
-        }
-    }
-
-    /**
-     * @return true if this user/pkg has a missing or custom layout notification and therefore needs
-     * a disclosure notification showing the user which appsOps the app is using.
-     */
-    public boolean isSystemAlertWarningNeeded(int userId, String pkg) {
-        synchronized (mMutex) {
-            final ForegroundServicesUserState services = mUserServices.get(userId);
-            if (services == null) return false;
-            return services.getStandardLayoutKeys(pkg) == null;
-        }
-    }
-
-    /**
-     * Gets active app ops for this user and package
-     */
-    @Nullable
-    public ArraySet<Integer> getAppOps(int userId, String pkg) {
-        synchronized (mMutex) {
-            final ForegroundServicesUserState services = mUserServices.get(userId);
-            if (services == null) {
-                return null;
-            }
-            return services.getFeatures(pkg);
-        }
-    }
-
-    /**
-     * Records active app ops and updates the app op for the pending or visible notifications
-     * with the given parameters.
-     * App Ops are stored in FSC in addition to NotificationEntry in case they change before we
-     * have a notification to tag.
-     * @param appOpCode code for appOp to add/remove
-     * @param uid of user the notification is sent to
-     * @param packageName package that created the notification
-     * @param active whether the appOpCode is active or not
-     */
-    void onAppOpChanged(int appOpCode, int uid, String packageName, boolean active) {
-        Assert.isMainThread();
-
-        int userId = UserHandle.getUserId(uid);
-        // Record active app ops
-        synchronized (mMutex) {
-            ForegroundServicesUserState userServices = mUserServices.get(userId);
-            if (userServices == null) {
-                userServices = new ForegroundServicesUserState();
-                mUserServices.put(userId, userServices);
-            }
-            if (active) {
-                userServices.addOp(packageName, appOpCode);
-            } else {
-                userServices.removeOp(packageName, appOpCode);
-            }
-        }
-    }
-
-    /**
-     * Looks up the {@link ForegroundServicesUserState} for the given {@code userId}, then performs
-     * the given {@link UserStateUpdateCallback} on it.  If no state exists for the user ID, creates
-     * a new one if {@code createIfNotFound} is true, then performs the update on the new state.
-     * If {@code createIfNotFound} is false, no update is performed.
-     *
-     * @return false if no user state was found and none was created; true otherwise.
-     */
-    boolean updateUserState(int userId,
-            UserStateUpdateCallback updateCallback,
-            boolean createIfNotFound) {
-        synchronized (mMutex) {
-            ForegroundServicesUserState userState = mUserServices.get(userId);
-            if (userState == null) {
-                if (createIfNotFound) {
-                    userState = new ForegroundServicesUserState();
-                    mUserServices.put(userId, userState);
-                } else {
-                    return false;
-                }
-            }
-            return updateCallback.updateUserState(userState);
-        }
-    }
-
-    /**
-     * @return true if {@code sbn} is the system-provided disclosure notification containing the
-     * list of running foreground services.
-     */
-    public boolean isDisclosureNotification(StatusBarNotification sbn) {
-        return sbn.getId() == SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES
-                && sbn.getTag() == null
-                && sbn.getPackageName().equals("android");
-    }
-
-    /**
-     * @return true if sbn is one of the window manager "drawing over other apps" notifications
-     */
-    public boolean isSystemAlertNotification(StatusBarNotification sbn) {
-        return sbn.getPackageName().equals("android")
-                && sbn.getTag() != null
-                && sbn.getTag().contains("AlertWindowNotification");
-    }
-
-    /**
-     * Callback provided to {@link #updateUserState(int, UserStateUpdateCallback, boolean)}
-     * to perform the update.
-     */
-    interface UserStateUpdateCallback {
-        /**
-         * Perform update operations on the provided {@code userState}.
-         *
-         * @return true if the update succeeded.
-         */
-        boolean updateUserState(ForegroundServicesUserState userState);
-
-        /** Called if the state was not found and was not created. */
-        default void userStateNotFound(int userId) {
-        }
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/ForegroundServiceNotificationListener.java b/packages/SystemUI/src/com/android/systemui/ForegroundServiceNotificationListener.java
deleted file mode 100644
index a1a3b72..0000000
--- a/packages/SystemUI/src/com/android/systemui/ForegroundServiceNotificationListener.java
+++ /dev/null
@@ -1,150 +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.systemui;
-
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.content.Context;
-import android.os.Bundle;
-import android.service.notification.StatusBarNotification;
-import android.util.Log;
-
-import com.android.systemui.dagger.SysUISingleton;
-import com.android.systemui.statusbar.notification.collection.NotifPipeline;
-import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionListener;
-
-import javax.inject.Inject;
-
-/** Updates foreground service notification state in response to notification data events. */
-@SysUISingleton
-public class ForegroundServiceNotificationListener {
-
-    private static final String TAG = "FgServiceController";
-    private static final boolean DBG = false;
-
-    private final Context mContext;
-    private final ForegroundServiceController mForegroundServiceController;
-    private final NotifPipeline mNotifPipeline;
-
-    @Inject
-    public ForegroundServiceNotificationListener(Context context,
-            ForegroundServiceController foregroundServiceController,
-            NotifPipeline notifPipeline) {
-        mContext = context;
-        mForegroundServiceController = foregroundServiceController;
-        mNotifPipeline = notifPipeline;
-    }
-
-    /** Initializes this listener by connecting it to the notification pipeline. */
-    public void init() {
-        mNotifPipeline.addCollectionListener(new NotifCollectionListener() {
-            @Override
-            public void onEntryAdded(NotificationEntry entry) {
-                addNotification(entry, entry.getImportance());
-            }
-
-            @Override
-            public void onEntryUpdated(NotificationEntry entry) {
-                updateNotification(entry, entry.getImportance());
-            }
-
-            @Override
-            public void onEntryRemoved(NotificationEntry entry, int reason) {
-                removeNotification(entry.getSbn());
-            }
-        });
-    }
-
-    /**
-     * @param entry notification that was just posted
-     */
-    private void addNotification(NotificationEntry entry, int importance) {
-        updateNotification(entry, importance);
-    }
-
-    /**
-     * @param sbn notification that was just removed
-     */
-    private void removeNotification(StatusBarNotification sbn) {
-        mForegroundServiceController.updateUserState(
-                sbn.getUserId(),
-                new ForegroundServiceController.UserStateUpdateCallback() {
-                    @Override
-                    public boolean updateUserState(ForegroundServicesUserState userState) {
-                        if (mForegroundServiceController.isDisclosureNotification(sbn)) {
-                            // if you remove the dungeon entirely, we take that to mean there are
-                            // no running services
-                            userState.setRunningServices(null, 0);
-                            return true;
-                        } else {
-                            // this is safe to call on any notification, not just
-                            // FLAG_FOREGROUND_SERVICE
-                            return userState.removeNotification(sbn.getPackageName(), sbn.getKey());
-                        }
-                    }
-
-                    @Override
-                    public void userStateNotFound(int userId) {
-                        if (DBG) {
-                            Log.w(TAG, String.format(
-                                    "user %d with no known notifications got removeNotification "
-                                            + "for %s",
-                                    sbn.getUserId(), sbn));
-                        }
-                    }
-                },
-                false /* don't create */);
-    }
-
-    /**
-     * @param entry notification that was just changed in some way
-     */
-    private void updateNotification(NotificationEntry entry, int newImportance) {
-        final StatusBarNotification sbn = entry.getSbn();
-        mForegroundServiceController.updateUserState(
-                sbn.getUserId(),
-                userState -> {
-                    if (mForegroundServiceController.isDisclosureNotification(sbn)) {
-                        final Bundle extras = sbn.getNotification().extras;
-                        if (extras != null) {
-                            final String[] svcs = extras.getStringArray(
-                                    Notification.EXTRA_FOREGROUND_APPS);
-                            userState.setRunningServices(svcs, sbn.getNotification().when);
-                        }
-                    } else {
-                        userState.removeNotification(sbn.getPackageName(), sbn.getKey());
-                        if (0 != (sbn.getNotification().flags
-                                & Notification.FLAG_FOREGROUND_SERVICE)) {
-                            if (newImportance > NotificationManager.IMPORTANCE_MIN) {
-                                userState.addImportantNotification(sbn.getPackageName(),
-                                        sbn.getKey());
-                            }
-                        }
-                        final Notification.Builder builder =
-                                Notification.Builder.recoverBuilder(
-                                        mContext, sbn.getNotification());
-                        if (builder.usesStandardHeader()) {
-                            userState.addStandardLayoutNotification(
-                                    sbn.getPackageName(), sbn.getKey());
-                        }
-                    }
-                    return true;
-                },
-                true /* create if not found */);
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/LatencyTester.java b/packages/SystemUI/src/com/android/systemui/LatencyTester.java
index 6ea0fc3..b33d501 100644
--- a/packages/SystemUI/src/com/android/systemui/LatencyTester.java
+++ b/packages/SystemUI/src/com/android/systemui/LatencyTester.java
@@ -80,7 +80,6 @@
 
     @Override
     public void start() {
-        updateEnabled();
     }
 
     private void fakeWakeAndUnlock(BiometricSourceType type) {
diff --git a/packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnificationController.java b/packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnificationController.java
index 4a31f3d..f1cebba 100644
--- a/packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnificationController.java
+++ b/packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnificationController.java
@@ -1476,6 +1476,12 @@
     private class MirrorWindowA11yDelegate extends View.AccessibilityDelegate {
 
         private CharSequence getClickAccessibilityActionLabel() {
+            if (mEditSizeEnable) {
+                // Perform click action to exit edit mode
+                return mContext.getResources().getString(
+                        R.string.magnification_exit_edit_mode_click_label);
+            }
+
             return mSettingsPanelVisibility
                     ? mContext.getResources().getString(
                             R.string.magnification_close_settings_click_label)
@@ -1518,8 +1524,14 @@
 
         private boolean performA11yAction(int action) {
             if (action == AccessibilityAction.ACTION_CLICK.getId()) {
-                // Simulate tapping the drag view so it opens the Settings.
-                handleSingleTap(mDragView);
+                if (mEditSizeEnable) {
+                    // When edit mode is enabled, click the magnifier to exit edit mode.
+                    setEditMagnifierSizeMode(false);
+                } else {
+                    // Simulate tapping the drag view so it opens the Settings.
+                    handleSingleTap(mDragView);
+                }
+
             } else if (action == R.id.accessibility_action_zoom_in) {
                 performScale(mScale + A11Y_CHANGE_SCALE_DIFFERENCE);
             } else if (action == R.id.accessibility_action_zoom_out) {
diff --git a/packages/SystemUI/src/com/android/systemui/appops/AppOpsControllerImpl.java b/packages/SystemUI/src/com/android/systemui/appops/AppOpsControllerImpl.java
index 9708d9a..eec16e6 100644
--- a/packages/SystemUI/src/com/android/systemui/appops/AppOpsControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/appops/AppOpsControllerImpl.java
@@ -20,6 +20,7 @@
 import static android.hardware.SensorPrivacyManager.Sensors.MICROPHONE;
 import static android.media.AudioManager.ACTION_MICROPHONE_MUTE_CHANGED;
 
+import android.annotation.Nullable;
 import android.app.AppOpsManager;
 import android.content.BroadcastReceiver;
 import android.content.Context;
@@ -96,19 +97,57 @@
     private final SparseArray<ArrayList<AudioRecordingConfiguration>> mRecordingsByUid =
             new SparseArray<>();
 
-    protected static final int[] OPS = new int[] {
-            AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION,
-            AppOpsManager.OP_CAMERA,
-            AppOpsManager.OP_PHONE_CALL_CAMERA,
-            AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
+    @VisibleForTesting
+    protected static final int[] OPS_MIC = new int[] {
             AppOpsManager.OP_RECORD_AUDIO,
-            AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO,
-            AppOpsManager.OP_RECEIVE_EXPLICIT_USER_INTERACTION_AUDIO,
             AppOpsManager.OP_PHONE_CALL_MICROPHONE,
-            AppOpsManager.OP_COARSE_LOCATION,
-            AppOpsManager.OP_FINE_LOCATION
+            AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO,
+            AppOpsManager.OP_RECEIVE_SANDBOX_TRIGGER_AUDIO,
+            AppOpsManager.OP_RECEIVE_EXPLICIT_USER_INTERACTION_AUDIO
     };
 
+    protected static final int[] OPS_CAMERA = new int[] {
+            AppOpsManager.OP_CAMERA,
+            AppOpsManager.OP_PHONE_CALL_CAMERA
+    };
+
+    protected static final int[] OPS_LOC = new int[] {
+            AppOpsManager.OP_FINE_LOCATION,
+            AppOpsManager.OP_COARSE_LOCATION,
+            AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION
+    };
+
+    protected static final int[] OPS_OTHERS = new int[] {
+            AppOpsManager.OP_SYSTEM_ALERT_WINDOW
+    };
+
+    protected static final int[] OPS = concatOps(OPS_MIC, OPS_CAMERA, OPS_LOC, OPS_OTHERS);
+
+    /**
+     * @param opArrays the given op arrays.
+     * @return the concatenations of the given op arrays. Null arrays are treated as empty.
+     */
+    private static int[] concatOps(@Nullable int[]...opArrays) {
+        if (opArrays == null) {
+            return new int[0];
+        }
+        int totalLength = 0;
+        for (int[] opArray : opArrays) {
+            if (opArray == null || opArray.length == 0) {
+                continue;
+            }
+            totalLength += opArray.length;
+        }
+        final int[] concatOps = new int[totalLength];
+        int index = 0;
+        for (int[] opArray : opArrays) {
+            if (opArray == null || opArray.length == 0) continue;
+            System.arraycopy(opArray, 0, concatOps, index, opArray.length);
+            index += opArray.length;
+        }
+        return concatOps;
+    }
+
     @Inject
     public AppOpsControllerImpl(
             Context context,
@@ -533,12 +572,17 @@
     }
 
     private boolean isOpCamera(int op) {
-        return op == AppOpsManager.OP_CAMERA || op == AppOpsManager.OP_PHONE_CALL_CAMERA;
+        for (int i = 0; i < OPS_CAMERA.length; i++) {
+            if (op == OPS_CAMERA[i]) return true;
+        }
+        return false;
     }
 
     private boolean isOpMicrophone(int op) {
-        return op == AppOpsManager.OP_RECORD_AUDIO || op == AppOpsManager.OP_PHONE_CALL_MICROPHONE
-                || op == AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO;
+        for (int i = 0; i < OPS_MIC.length; i++) {
+            if (op == OPS_MIC[i]) return true;
+        }
+        return false;
     }
 
     protected class H extends Handler {
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java b/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
index 2b83e6b..590056f 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
@@ -23,6 +23,8 @@
 import android.util.Log;
 
 import com.android.internal.app.AssistUtils;
+import com.android.internal.app.IVisualQueryDetectionAttentionListener;
+import com.android.internal.app.IVisualQueryRecognitionStatusListener;
 import com.android.internal.app.IVoiceInteractionSessionListener;
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
@@ -39,10 +41,13 @@
 import com.android.systemui.statusbar.policy.DeviceProvisionedController;
 import com.android.systemui.util.settings.SecureSettings;
 
-import javax.inject.Inject;
-
 import dagger.Lazy;
 
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.inject.Inject;
+
 /**
  * Class to manage everything related to assist in SystemUI.
  */
@@ -78,6 +83,18 @@
         void hide();
     }
 
+    /**
+     * An interface for a listener that receives notification that visual query attention has
+     * either been gained or lost.
+     */
+    public interface VisualQueryAttentionListener {
+        /** Called when visual query attention has been gained. */
+        void onAttentionGained();
+
+        /** Called when visual query attention has been lost. */
+        void onAttentionLost();
+    }
+
     private static final String TAG = "AssistManager";
 
     // Note that VERBOSE logging may leak PII (e.g. transcription contents).
@@ -127,6 +144,23 @@
     private final SecureSettings mSecureSettings;
 
     private final DeviceProvisionedController mDeviceProvisionedController;
+
+    private final List<VisualQueryAttentionListener> mVisualQueryAttentionListeners =
+            new ArrayList<>();
+
+    private final IVisualQueryDetectionAttentionListener mVisualQueryDetectionAttentionListener =
+            new IVisualQueryDetectionAttentionListener.Stub() {
+        @Override
+        public void onAttentionGained() {
+            mVisualQueryAttentionListeners.forEach(VisualQueryAttentionListener::onAttentionGained);
+        }
+
+        @Override
+        public void onAttentionLost() {
+            mVisualQueryAttentionListeners.forEach(VisualQueryAttentionListener::onAttentionLost);
+        }
+    };
+
     private final CommandQueue mCommandQueue;
     protected final AssistUtils mAssistUtils;
 
@@ -157,6 +191,7 @@
         mSecureSettings = secureSettings;
 
         registerVoiceInteractionSessionListener();
+        registerVisualQueryRecognitionStatusListener();
 
         mUiController = defaultUiController;
 
@@ -266,6 +301,24 @@
         mAssistUtils.hideCurrentSession();
     }
 
+    /**
+     * Add the given {@link VisualQueryAttentionListener} to the list of listeners awaiting
+     * notification of gaining/losing visual query attention.
+     */
+    public void addVisualQueryAttentionListener(VisualQueryAttentionListener listener) {
+        if (!mVisualQueryAttentionListeners.contains(listener)) {
+            mVisualQueryAttentionListeners.add(listener);
+        }
+    }
+
+    /**
+     * Remove the given {@link VisualQueryAttentionListener} from the list of listeners awaiting
+     * notification of gaining/losing visual query attention.
+     */
+    public void removeVisualQueryAttentionListener(VisualQueryAttentionListener listener) {
+        mVisualQueryAttentionListeners.remove(listener);
+    }
+
     private void startAssistInternal(Bundle args, @NonNull ComponentName assistComponent,
             boolean isService) {
         if (isService) {
@@ -326,6 +379,27 @@
                 null, null);
     }
 
+    private void registerVisualQueryRecognitionStatusListener() {
+        if (!mContext.getResources()
+                .getBoolean(R.bool.config_enableVisualQueryAttentionDetection)) {
+            return;
+        }
+
+        mAssistUtils.subscribeVisualQueryRecognitionStatus(
+                new IVisualQueryRecognitionStatusListener.Stub() {
+                    @Override
+                    public void onStartPerceiving() {
+                        mAssistUtils.enableVisualQueryDetection(
+                                mVisualQueryDetectionAttentionListener);
+                    }
+
+                    @Override
+                    public void onStopPerceiving() {
+                        mAssistUtils.disableVisualQueryDetection();
+                    }
+                });
+    }
+
     public void launchVoiceAssistFromKeyguard() {
         mAssistUtils.launchVoiceAssistFromKeyguard();
     }
diff --git a/packages/SystemUI/src/com/android/systemui/authentication/shared/model/AuthenticationMethodModel.kt b/packages/SystemUI/src/com/android/systemui/authentication/data/model/AuthenticationMethodModel.kt
similarity index 73%
copy from packages/SystemUI/src/com/android/systemui/authentication/shared/model/AuthenticationMethodModel.kt
copy to packages/SystemUI/src/com/android/systemui/authentication/data/model/AuthenticationMethodModel.kt
index 97c6697..6d23b11 100644
--- a/packages/SystemUI/src/com/android/systemui/authentication/shared/model/AuthenticationMethodModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/authentication/data/model/AuthenticationMethodModel.kt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2023 The Android Open Source Project
+ * Copyright 2023 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.systemui.authentication.shared.model
+package com.android.systemui.authentication.data.model
 
 /** Enumerates all known authentication methods. */
 sealed class AuthenticationMethodModel(
@@ -29,17 +29,9 @@
     /** There is no authentication method on the device. We shouldn't even show the lock screen. */
     object None : AuthenticationMethodModel(isSecure = false)
 
-    /** The most basic authentication method. The lock screen can be swiped away when displayed. */
-    object Swipe : AuthenticationMethodModel(isSecure = false)
-
     object Pin : AuthenticationMethodModel(isSecure = true)
 
     object Password : AuthenticationMethodModel(isSecure = true)
 
-    object Pattern : AuthenticationMethodModel(isSecure = true) {
-        data class PatternCoordinate(
-            val x: Int,
-            val y: Int,
-        )
-    }
+    object Pattern : AuthenticationMethodModel(isSecure = true)
 }
diff --git a/packages/SystemUI/src/com/android/systemui/authentication/data/repository/AuthenticationRepository.kt b/packages/SystemUI/src/com/android/systemui/authentication/data/repository/AuthenticationRepository.kt
index deb3d03..8d1fc5d 100644
--- a/packages/SystemUI/src/com/android/systemui/authentication/data/repository/AuthenticationRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/authentication/data/repository/AuthenticationRepository.kt
@@ -14,15 +14,21 @@
  * limitations under the License.
  */
 
+@file:OptIn(ExperimentalCoroutinesApi::class)
+
 package com.android.systemui.authentication.data.repository
 
+import android.app.admin.DevicePolicyManager
+import android.content.IntentFilter
+import android.os.UserHandle
 import com.android.internal.widget.LockPatternChecker
 import com.android.internal.widget.LockPatternUtils
 import com.android.internal.widget.LockscreenCredential
 import com.android.keyguard.KeyguardSecurityModel
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel
 import com.android.systemui.authentication.shared.model.AuthenticationResultModel
 import com.android.systemui.authentication.shared.model.AuthenticationThrottlingModel
+import com.android.systemui.broadcast.BroadcastDispatcher
 import com.android.systemui.dagger.qualifiers.Application
 import com.android.systemui.dagger.qualifiers.Background
 import com.android.systemui.keyguard.data.repository.KeyguardRepository
@@ -37,13 +43,17 @@
 import kotlin.coroutines.suspendCoroutine
 import kotlinx.coroutines.CoroutineDispatcher
 import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.flow.asStateFlow
 import kotlinx.coroutines.flow.combine
 import kotlinx.coroutines.flow.distinctUntilChanged
 import kotlinx.coroutines.flow.filter
+import kotlinx.coroutines.flow.flatMapLatest
 import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onStart
 import kotlinx.coroutines.launch
 import kotlinx.coroutines.withContext
 
@@ -54,9 +64,10 @@
      * Whether the device is unlocked.
      *
      * A device that is not yet unlocked requires unlocking by completing an authentication
-     * challenge according to the current authentication method.
-     *
-     * Note that this state has no real bearing on whether the lockscreen is showing or dismissed.
+     * challenge according to the current authentication method, unless in cases when the current
+     * authentication method is not "secure" (for example, None); in such cases, the value of this
+     * flow will always be `true`, even if the lockscreen is showing and still needs to be dismissed
+     * by the user to proceed.
      */
     val isUnlocked: StateFlow<Boolean>
 
@@ -86,8 +97,29 @@
     val throttling: StateFlow<AuthenticationThrottlingModel>
 
     /**
+     * The currently-configured authentication method. This determines how the authentication
+     * challenge needs to be completed in order to unlock an otherwise locked device.
+     *
+     * Note: there may be other ways to unlock the device that "bypass" the need for this
+     * authentication challenge (notably, biometrics like fingerprint or face unlock).
+     *
+     * Note: by design, this is a [Flow] and not a [StateFlow]; a consumer who wishes to get a
+     * snapshot of the current authentication method without establishing a collector of the flow
+     * can do so by invoking [getAuthenticationMethod].
+     */
+    val authenticationMethod: Flow<AuthenticationMethodModel>
+
+    /**
      * Returns the currently-configured authentication method. This determines how the
-     * authentication challenge is completed in order to unlock an otherwise locked device.
+     * authentication challenge needs to be completed in order to unlock an otherwise locked device.
+     *
+     * Note: there may be other ways to unlock the device that "bypass" the need for this
+     * authentication challenge (notably, biometrics like fingerprint or face unlock).
+     *
+     * Note: by design, this is offered as a convenience method alongside [authenticationMethod].
+     * The flow should be used for code that wishes to stay up-to-date its logic as the
+     * authentication changes over time and this method should be used for simple code that only
+     * needs to check the current value.
      */
     suspend fun getAuthenticationMethod(): AuthenticationMethodModel
 
@@ -141,6 +173,7 @@
     private val userRepository: UserRepository,
     keyguardRepository: KeyguardRepository,
     private val lockPatternUtils: LockPatternUtils,
+    broadcastDispatcher: BroadcastDispatcher,
 ) : AuthenticationRepository {
 
     override val isUnlocked = keyguardRepository.isKeyguardUnlocked
@@ -148,7 +181,7 @@
     override suspend fun isLockscreenEnabled(): Boolean {
         return withContext(backgroundDispatcher) {
             val selectedUserId = userRepository.selectedUserId
-            !lockPatternUtils.isLockPatternEnabled(selectedUserId)
+            !lockPatternUtils.isLockScreenDisabled(selectedUserId)
         }
     }
 
@@ -172,18 +205,31 @@
     private val UserRepository.selectedUserId: Int
         get() = getSelectedUserInfo().id
 
+    override val authenticationMethod: Flow<AuthenticationMethodModel> =
+        userRepository.selectedUserInfo
+            .map { it.id }
+            .distinctUntilChanged()
+            .flatMapLatest { selectedUserId ->
+                broadcastDispatcher
+                    .broadcastFlow(
+                        filter =
+                            IntentFilter(
+                                DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
+                            ),
+                        user = UserHandle.of(selectedUserId),
+                    )
+                    .onStart { emit(Unit) }
+                    .map { selectedUserId }
+            }
+            .map { selectedUserId ->
+                withContext(backgroundDispatcher) {
+                    blockingAuthenticationMethodInternal(selectedUserId)
+                }
+            }
+
     override suspend fun getAuthenticationMethod(): AuthenticationMethodModel {
         return withContext(backgroundDispatcher) {
-            val selectedUserId = userRepository.selectedUserId
-            when (getSecurityMode.apply(selectedUserId)) {
-                KeyguardSecurityModel.SecurityMode.PIN,
-                KeyguardSecurityModel.SecurityMode.SimPin,
-                KeyguardSecurityModel.SecurityMode.SimPuk -> AuthenticationMethodModel.Pin
-                KeyguardSecurityModel.SecurityMode.Password -> AuthenticationMethodModel.Password
-                KeyguardSecurityModel.SecurityMode.Pattern -> AuthenticationMethodModel.Pattern
-                KeyguardSecurityModel.SecurityMode.None -> AuthenticationMethodModel.None
-                KeyguardSecurityModel.SecurityMode.Invalid -> error("Invalid security mode!")
-            }
+            blockingAuthenticationMethodInternal(userRepository.selectedUserId)
         }
     }
 
@@ -301,6 +347,27 @@
 
         return flow.asStateFlow()
     }
+
+    /**
+     * Returns the authentication method for the given user ID.
+     *
+     * WARNING: this is actually a blocking IPC/"binder" call that's expensive to do on the main
+     * thread. We keep it not marked as `suspend` because we want to be able to run this without a
+     * `runBlocking` which has a ton of performance/blocking problems.
+     */
+    private fun blockingAuthenticationMethodInternal(
+        userId: Int,
+    ): AuthenticationMethodModel {
+        return when (getSecurityMode.apply(userId)) {
+            KeyguardSecurityModel.SecurityMode.PIN,
+            KeyguardSecurityModel.SecurityMode.SimPin,
+            KeyguardSecurityModel.SecurityMode.SimPuk -> AuthenticationMethodModel.Pin
+            KeyguardSecurityModel.SecurityMode.Password -> AuthenticationMethodModel.Password
+            KeyguardSecurityModel.SecurityMode.Pattern -> AuthenticationMethodModel.Pattern
+            KeyguardSecurityModel.SecurityMode.None -> AuthenticationMethodModel.None
+            KeyguardSecurityModel.SecurityMode.Invalid -> error("Invalid security mode!")
+        }
+    }
 }
 
 @Module
diff --git a/packages/SystemUI/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractor.kt b/packages/SystemUI/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractor.kt
index d4371bf..ecd7bae 100644
--- a/packages/SystemUI/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractor.kt
@@ -18,13 +18,17 @@
 
 import com.android.internal.widget.LockPatternView
 import com.android.internal.widget.LockscreenCredential
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel as DataLayerAuthenticationMethodModel
 import com.android.systemui.authentication.data.repository.AuthenticationRepository
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.domain.model.AuthenticationMethodModel as DomainLayerAuthenticationMethodModel
+import com.android.systemui.authentication.shared.model.AuthenticationPatternCoordinate
 import com.android.systemui.authentication.shared.model.AuthenticationThrottlingModel
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
 import com.android.systemui.dagger.qualifiers.Background
 import com.android.systemui.keyguard.data.repository.KeyguardRepository
+import com.android.systemui.scene.domain.interactor.SceneInteractor
+import com.android.systemui.scene.shared.model.SceneKey
 import com.android.systemui.user.data.repository.UserRepository
 import com.android.systemui.util.time.SystemClock
 import javax.inject.Inject
@@ -35,9 +39,12 @@
 import kotlinx.coroutines.Job
 import kotlinx.coroutines.async
 import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.SharingStarted
 import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.combine
 import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.filter
 import kotlinx.coroutines.flow.map
 import kotlinx.coroutines.flow.stateIn
 import kotlinx.coroutines.launch
@@ -53,29 +60,91 @@
     @Background private val backgroundDispatcher: CoroutineDispatcher,
     private val userRepository: UserRepository,
     private val keyguardRepository: KeyguardRepository,
+    sceneInteractor: SceneInteractor,
     private val clock: SystemClock,
 ) {
     /**
+     * The currently-configured authentication method. This determines how the authentication
+     * challenge needs to be completed in order to unlock an otherwise locked device.
+     *
+     * Note: there may be other ways to unlock the device that "bypass" the need for this
+     * authentication challenge (notably, biometrics like fingerprint or face unlock).
+     *
+     * Note: by design, this is a [Flow] and not a [StateFlow]; a consumer who wishes to get a
+     * snapshot of the current authentication method without establishing a collector of the flow
+     * can do so by invoking [getAuthenticationMethod].
+     *
+     * Note: this layer adds the synthetic authentication method of "swipe" which is special. When
+     * the current authentication method is "swipe", the user does not need to complete any
+     * authentication challenge to unlock the device; they just need to dismiss the lockscreen to
+     * get past it. This also means that the value of [isUnlocked] remains `false` even when the
+     * lockscreen is showing and still needs to be dismissed by the user to proceed.
+     */
+    val authenticationMethod: Flow<DomainLayerAuthenticationMethodModel> =
+        repository.authenticationMethod.map { rawModel -> rawModel.toDomainLayer() }
+
+    /**
      * Whether the device is unlocked.
      *
      * A device that is not yet unlocked requires unlocking by completing an authentication
-     * challenge according to the current authentication method.
-     *
-     * Note that this state has no real bearing on whether the lock screen is showing or dismissed.
+     * challenge according to the current authentication method, unless in cases when the current
+     * authentication method is not "secure" (for example, None and Swipe); in such cases, the value
+     * of this flow will always be `true`, even if the lockscreen is showing and still needs to be
+     * dismissed by the user to proceed.
      */
     val isUnlocked: StateFlow<Boolean> =
-        repository.isUnlocked
-            .map { isUnlocked ->
-                if (getAuthenticationMethod() is AuthenticationMethodModel.None) {
-                    true
-                } else {
-                    isUnlocked
-                }
+        combine(
+                repository.isUnlocked,
+                authenticationMethod,
+            ) { isUnlocked, authenticationMethod ->
+                !authenticationMethod.isSecure || isUnlocked
             }
             .stateIn(
                 scope = applicationScope,
                 started = SharingStarted.Eagerly,
-                initialValue = true,
+                initialValue = false,
+            )
+
+    /**
+     * Whether the lockscreen has been dismissed (by any method). This can be false even when the
+     * device is unlocked, e.g. when swipe to unlock is enabled.
+     *
+     * Note:
+     * - `false` doesn't mean the lockscreen is visible (it may be occluded or covered by other UI).
+     * - `true` doesn't mean the lockscreen is invisible (since this state changes before the
+     *   transition occurs).
+     */
+    val isLockscreenDismissed: StateFlow<Boolean> =
+        sceneInteractor.desiredScene
+            .map { it.key }
+            .filter { currentScene ->
+                currentScene == SceneKey.Gone || currentScene == SceneKey.Lockscreen
+            }
+            .map { it == SceneKey.Gone }
+            .stateIn(
+                scope = applicationScope,
+                started = SharingStarted.WhileSubscribed(),
+                initialValue = false,
+            )
+
+    /**
+     * Whether it's currently possible to swipe up to dismiss the lockscreen without requiring
+     * authentication. This returns false whenever the lockscreen has been dismissed.
+     *
+     * Note: `true` doesn't mean the lockscreen is visible. It may be occluded or covered by other
+     * UI.
+     */
+    val canSwipeToDismiss =
+        combine(authenticationMethod, isLockscreenDismissed) {
+                authenticationMethod,
+                isLockscreenDismissed ->
+                authenticationMethod is DomainLayerAuthenticationMethodModel.Swipe &&
+                    !isLockscreenDismissed
+            }
+            .stateIn(
+                scope = applicationScope,
+                started = SharingStarted.WhileSubscribed(),
+                initialValue = false,
             )
 
     /** The current authentication throttling state, only meaningful if [isThrottled] is `true`. */
@@ -129,18 +198,24 @@
 
     /**
      * Returns the currently-configured authentication method. This determines how the
-     * authentication challenge is completed in order to unlock an otherwise locked device.
+     * authentication challenge needs to be completed in order to unlock an otherwise locked device.
+     *
+     * Note: there may be other ways to unlock the device that "bypass" the need for this
+     * authentication challenge (notably, biometrics like fingerprint or face unlock).
+     *
+     * Note: by design, this is offered as a convenience method alongside [authenticationMethod].
+     * The flow should be used for code that wishes to stay up-to-date its logic as the
+     * authentication changes over time and this method should be used for simple code that only
+     * needs to check the current value.
+     *
+     * Note: this layer adds the synthetic authentication method of "swipe" which is special. When
+     * the current authentication method is "swipe", the user does not need to complete any
+     * authentication challenge to unlock the device; they just need to dismiss the lockscreen to
+     * get past it. This also means that the value of [isUnlocked] remains `false` even when the
+     * lockscreen is showing and still needs to be dismissed by the user to proceed.
      */
-    suspend fun getAuthenticationMethod(): AuthenticationMethodModel {
-        val authMethod = repository.getAuthenticationMethod()
-        return if (
-            authMethod is AuthenticationMethodModel.None && repository.isLockscreenEnabled()
-        ) {
-            // We treat "None" as "Swipe" when the lockscreen is enabled.
-            AuthenticationMethodModel.Swipe
-        } else {
-            authMethod
-        }
+    suspend fun getAuthenticationMethod(): DomainLayerAuthenticationMethodModel {
+        return repository.getAuthenticationMethod().toDomainLayer()
     }
 
     /**
@@ -270,21 +345,38 @@
         }
     }
 
-    private fun AuthenticationMethodModel.createCredential(
+    private fun DomainLayerAuthenticationMethodModel.createCredential(
         input: List<Any>
     ): LockscreenCredential? {
         return when (this) {
-            is AuthenticationMethodModel.Pin ->
+            is DomainLayerAuthenticationMethodModel.Pin ->
                 LockscreenCredential.createPin(input.joinToString(""))
-            is AuthenticationMethodModel.Password ->
+            is DomainLayerAuthenticationMethodModel.Password ->
                 LockscreenCredential.createPassword(input.joinToString(""))
-            is AuthenticationMethodModel.Pattern ->
+            is DomainLayerAuthenticationMethodModel.Pattern ->
                 LockscreenCredential.createPattern(
                     input
-                        .map { it as AuthenticationMethodModel.Pattern.PatternCoordinate }
+                        .map { it as AuthenticationPatternCoordinate }
                         .map { LockPatternView.Cell.of(it.y, it.x) }
                 )
             else -> null
         }
     }
+
+    private suspend fun DataLayerAuthenticationMethodModel.toDomainLayer():
+        DomainLayerAuthenticationMethodModel {
+        return when (this) {
+            is DataLayerAuthenticationMethodModel.None ->
+                if (repository.isLockscreenEnabled()) {
+                    DomainLayerAuthenticationMethodModel.Swipe
+                } else {
+                    DomainLayerAuthenticationMethodModel.None
+                }
+            is DataLayerAuthenticationMethodModel.Pin -> DomainLayerAuthenticationMethodModel.Pin
+            is DataLayerAuthenticationMethodModel.Password ->
+                DomainLayerAuthenticationMethodModel.Password
+            is DataLayerAuthenticationMethodModel.Pattern ->
+                DomainLayerAuthenticationMethodModel.Pattern
+        }
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/authentication/shared/model/AuthenticationMethodModel.kt b/packages/SystemUI/src/com/android/systemui/authentication/domain/model/AuthenticationMethodModel.kt
similarity index 86%
rename from packages/SystemUI/src/com/android/systemui/authentication/shared/model/AuthenticationMethodModel.kt
rename to packages/SystemUI/src/com/android/systemui/authentication/domain/model/AuthenticationMethodModel.kt
index 97c6697..d7e6099 100644
--- a/packages/SystemUI/src/com/android/systemui/authentication/shared/model/AuthenticationMethodModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/authentication/domain/model/AuthenticationMethodModel.kt
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.systemui.authentication.shared.model
+package com.android.systemui.authentication.domain.model
 
 /** Enumerates all known authentication methods. */
 sealed class AuthenticationMethodModel(
@@ -36,10 +36,5 @@
 
     object Password : AuthenticationMethodModel(isSecure = true)
 
-    object Pattern : AuthenticationMethodModel(isSecure = true) {
-        data class PatternCoordinate(
-            val x: Int,
-            val y: Int,
-        )
-    }
+    object Pattern : AuthenticationMethodModel(isSecure = true)
 }
diff --git a/core/java/android/view/selectiontoolbar/WidgetInfo.aidl b/packages/SystemUI/src/com/android/systemui/authentication/shared/model/AuthenticationPatternCoordinate.kt
similarity index 74%
rename from core/java/android/view/selectiontoolbar/WidgetInfo.aidl
rename to packages/SystemUI/src/com/android/systemui/authentication/shared/model/AuthenticationPatternCoordinate.kt
index 1057c51..8a3f780 100644
--- a/core/java/android/view/selectiontoolbar/WidgetInfo.aidl
+++ b/packages/SystemUI/src/com/android/systemui/authentication/shared/model/AuthenticationPatternCoordinate.kt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2021 The Android Open Source Project
+ * Copyright 2023 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,9 +14,9 @@
  * limitations under the License.
  */
 
-package android.view.selectiontoolbar;
+package com.android.systemui.authentication.shared.model
 
-/**
- * @hide
- */
-parcelable WidgetInfo;
+data class AuthenticationPatternCoordinate(
+    val x: Int,
+    val y: Int,
+)
diff --git a/packages/SystemUI/src/com/android/systemui/battery/AccessorizedBatteryDrawable.kt b/packages/SystemUI/src/com/android/systemui/battery/AccessorizedBatteryDrawable.kt
index b34f1b4..b81d7fc 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/AccessorizedBatteryDrawable.kt
+++ b/packages/SystemUI/src/com/android/systemui/battery/AccessorizedBatteryDrawable.kt
@@ -178,6 +178,11 @@
         mainBatteryDrawable.charging = charging
     }
 
+    /** Returns whether the battery is currently charging. */
+    fun getCharging(): Boolean {
+        return mainBatteryDrawable.charging
+    }
+
     /** Sets the current level (out of 100) of the battery. */
     fun setBatteryLevel(level: Int) {
         mainBatteryDrawable.setBatteryLevel(level)
diff --git a/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java b/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
index 46fcdbc..87ea411 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
+++ b/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
@@ -77,8 +77,9 @@
     private int mShowPercentMode = MODE_DEFAULT;
     private boolean mShowPercentAvailable;
     private String mEstimateText = null;
-    private boolean mCharging;
+    private boolean mPluggedIn;
     private boolean mIsBatteryDefender;
+    private boolean mIsIncompatibleCharging;
     private boolean mDisplayShieldEnabled;
     // Error state where we know nothing about the current battery state
     private boolean mBatteryStateUnknown;
@@ -202,10 +203,10 @@
      * @param pluggedIn whether the device is plugged in or not
      */
     public void onBatteryLevelChanged(@IntRange(from = 0, to = 100) int level, boolean pluggedIn) {
-        mDrawable.setCharging(pluggedIn);
-        mDrawable.setBatteryLevel(level);
-        mCharging = pluggedIn;
+        mPluggedIn = pluggedIn;
         mLevel = level;
+        mDrawable.setCharging(isCharging());
+        mDrawable.setBatteryLevel(level);
         updatePercentText();
     }
 
@@ -224,6 +225,15 @@
         }
     }
 
+    void onIsIncompatibleChargingChanged(boolean isIncompatibleCharging) {
+        boolean valueChanged = mIsIncompatibleCharging != isIncompatibleCharging;
+        mIsIncompatibleCharging = isIncompatibleCharging;
+        if (valueChanged) {
+            mDrawable.setCharging(isCharging());
+            updateContentDescription();
+        }
+    }
+
     private TextView loadPercentView() {
         return (TextView) LayoutInflater.from(getContext())
                 .inflate(R.layout.battery_percentage_view, null);
@@ -263,7 +273,7 @@
         }
 
         if (mBatteryPercentView != null) {
-            if (mShowPercentMode == MODE_ESTIMATE && !mCharging) {
+            if (mShowPercentMode == MODE_ESTIMATE && !isCharging()) {
                 mBatteryEstimateFetcher.fetchBatteryTimeRemainingEstimate(
                         (String estimate) -> {
                     if (mBatteryPercentView == null) {
@@ -316,7 +326,7 @@
         } else if (mIsBatteryDefender) {
             contentDescription =
                     context.getString(R.string.accessibility_battery_level_charging_paused, mLevel);
-        } else if (mCharging) {
+        } else if (isCharging()) {
             contentDescription =
                     context.getString(R.string.accessibility_battery_level_charging, mLevel);
         } else {
@@ -464,16 +474,24 @@
         }
     }
 
+    private boolean isCharging() {
+        return mPluggedIn && !mIsIncompatibleCharging;
+    }
+
     public void dump(PrintWriter pw, String[] args) {
         String powerSave = mDrawable == null ? null : mDrawable.getPowerSaveEnabled() + "";
         String displayShield = mDrawable == null ? null : mDrawable.getDisplayShield() + "";
+        String charging = mDrawable == null ? null : mDrawable.getCharging() + "";
         CharSequence percent = mBatteryPercentView == null ? null : mBatteryPercentView.getText();
         pw.println("  BatteryMeterView:");
         pw.println("    mDrawable.getPowerSave: " + powerSave);
         pw.println("    mDrawable.getDisplayShield: " + displayShield);
+        pw.println("    mDrawable.getCharging: " + charging);
         pw.println("    mBatteryPercentView.getText(): " + percent);
         pw.println("    mTextColor: #" + Integer.toHexString(mTextColor));
         pw.println("    mBatteryStateUnknown: " + mBatteryStateUnknown);
+        pw.println("    mIsIncompatibleCharging: " + mIsIncompatibleCharging);
+        pw.println("    mPluggedIn: " + mPluggedIn);
         pw.println("    mLevel: " + mLevel);
         pw.println("    mMode: " + mShowPercentMode);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterViewController.java b/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterViewController.java
index 6a5749c..0ca3883 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterViewController.java
@@ -32,6 +32,8 @@
 
 import com.android.systemui.R;
 import com.android.systemui.dagger.qualifiers.Main;
+import com.android.systemui.flags.FeatureFlags;
+import com.android.systemui.flags.Flags;
 import com.android.systemui.settings.UserTracker;
 import com.android.systemui.statusbar.phone.StatusBarIconController;
 import com.android.systemui.statusbar.phone.StatusBarLocation;
@@ -50,6 +52,7 @@
     private final TunerService mTunerService;
     private final Handler mMainHandler;
     private final ContentResolver mContentResolver;
+    private final FeatureFlags mFeatureFlags;
     private final BatteryController mBatteryController;
 
     private final String mSlotBattery;
@@ -99,6 +102,13 @@
                 }
 
                 @Override
+                public void onIsIncompatibleChargingChanged(boolean isIncompatibleCharging) {
+                    if (mFeatureFlags.isEnabled(Flags.INCOMPATIBLE_CHARGING_BATTERY_ICON)) {
+                        mView.onIsIncompatibleChargingChanged(isIncompatibleCharging);
+                    }
+                }
+
+                @Override
                 public void dump(@NonNull PrintWriter pw, @NonNull String[] args) {
                     pw.print(super.toString());
                     pw.println(" location=" + mLocation);
@@ -129,6 +139,7 @@
             TunerService tunerService,
             @Main Handler mainHandler,
             ContentResolver contentResolver,
+            FeatureFlags featureFlags,
             BatteryController batteryController) {
         super(view);
         mLocation = location;
@@ -137,6 +148,7 @@
         mTunerService = tunerService;
         mMainHandler = mainHandler;
         mContentResolver = contentResolver;
+        mFeatureFlags = featureFlags;
         mBatteryController = batteryController;
 
         mView.setBatteryEstimateFetcher(mBatteryController::getEstimatedTimeRemainingString);
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
index 58adfa1..58c8000 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
@@ -82,6 +82,7 @@
 import com.android.systemui.flags.FeatureFlags;
 import com.android.systemui.flags.Flags;
 import com.android.systemui.keyguard.WakefulnessLifecycle;
+import com.android.systemui.statusbar.VibratorHelper;
 import com.android.systemui.util.concurrency.DelayableExecutor;
 
 import java.io.PrintWriter;
@@ -288,12 +289,13 @@
             @NonNull Provider<PromptSelectorInteractor> promptSelectorInteractor,
             @NonNull PromptViewModel promptViewModel,
             @NonNull Provider<CredentialViewModel> credentialViewModelProvider,
-            @NonNull @Background DelayableExecutor bgExecutor) {
+            @NonNull @Background DelayableExecutor bgExecutor,
+            @NonNull VibratorHelper vibratorHelper) {
         this(config, featureFlags, applicationCoroutineScope, fpProps, faceProps,
                 wakefulnessLifecycle, panelInteractionDetector, userManager, lockPatternUtils,
                 jankMonitor, authBiometricFingerprintViewModelProvider, promptSelectorInteractor,
                 promptCredentialInteractor, promptViewModel, credentialViewModelProvider,
-                new Handler(Looper.getMainLooper()), bgExecutor);
+                new Handler(Looper.getMainLooper()), bgExecutor, vibratorHelper);
     }
 
     @VisibleForTesting
@@ -314,7 +316,8 @@
             @NonNull PromptViewModel promptViewModel,
             @NonNull Provider<CredentialViewModel> credentialViewModelProvider,
             @NonNull Handler mainHandler,
-            @NonNull @Background DelayableExecutor bgExecutor) {
+            @NonNull @Background DelayableExecutor bgExecutor,
+            @NonNull VibratorHelper vibratorHelper) {
         super(config.mContext);
 
         mConfig = config;
@@ -364,7 +367,8 @@
         if (featureFlags.isEnabled(Flags.BIOMETRIC_BP_STRONG)) {
             showPrompt(config, layoutInflater, promptViewModel,
                     Utils.findFirstSensorProperties(fpProps, mConfig.mSensorIds),
-                    Utils.findFirstSensorProperties(faceProps, mConfig.mSensorIds));
+                    Utils.findFirstSensorProperties(faceProps, mConfig.mSensorIds),
+                    vibratorHelper, featureFlags);
         } else {
             showLegacyPrompt(config, layoutInflater, fpProps, faceProps);
         }
@@ -388,7 +392,10 @@
     private void showPrompt(@NonNull Config config, @NonNull LayoutInflater layoutInflater,
             @NonNull PromptViewModel viewModel,
             @Nullable FingerprintSensorPropertiesInternal fpProps,
-            @Nullable FaceSensorPropertiesInternal faceProps) {
+            @Nullable FaceSensorPropertiesInternal faceProps,
+            @NonNull VibratorHelper vibratorHelper,
+            @NonNull FeatureFlags featureFlags
+    ) {
         if (Utils.isBiometricAllowed(config.mPromptInfo)) {
             mPromptSelectorInteractorProvider.get().useBiometricsForAuthentication(
                     config.mPromptInfo,
@@ -401,7 +408,8 @@
             mBiometricView = BiometricViewBinder.bind(view, viewModel, mPanelController,
                     // TODO(b/201510778): This uses the wrong timeout in some cases
                     getJankListener(view, TRANSIT, AuthDialog.ANIMATE_MEDIUM_TO_LARGE_DURATION_MS),
-                    mBackgroundView, mBiometricCallback, mApplicationCoroutineScope);
+                    mBackgroundView, mBiometricCallback, mApplicationCoroutineScope,
+                    vibratorHelper, featureFlags);
 
             // TODO(b/251476085): migrate these dependencies
             if (fpProps != null && fpProps.isAnyUdfpsType()) {
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
index 3df7ca5..7b288a8 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
@@ -85,9 +85,12 @@
 import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.keyguard.data.repository.BiometricType;
 import com.android.systemui.statusbar.CommandQueue;
+import com.android.systemui.statusbar.VibratorHelper;
 import com.android.systemui.util.concurrency.DelayableExecutor;
 import com.android.systemui.util.concurrency.Execution;
 
+import kotlin.Unit;
+
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -101,7 +104,6 @@
 import javax.inject.Inject;
 import javax.inject.Provider;
 
-import kotlin.Unit;
 import kotlinx.coroutines.CoroutineScope;
 
 /**
@@ -183,6 +185,7 @@
     @NonNull private final UdfpsUtils mUdfpsUtils;
     private final @Background DelayableExecutor mBackgroundExecutor;
     private final DisplayInfo mCachedDisplayInfo = new DisplayInfo();
+    @NonNull private final VibratorHelper mVibratorHelper;
 
     @VisibleForTesting
     final TaskStackListener mTaskStackListener = new TaskStackListener() {
@@ -771,7 +774,8 @@
             @NonNull InteractionJankMonitor jankMonitor,
             @Main Handler handler,
             @Background DelayableExecutor bgExecutor,
-            @NonNull UdfpsUtils udfpsUtils) {
+            @NonNull UdfpsUtils udfpsUtils,
+            @NonNull VibratorHelper vibratorHelper) {
         mContext = context;
         mFeatureFlags = featureFlags;
         mExecution = execution;
@@ -794,6 +798,7 @@
         mFaceEnrolledForUser = new SparseBooleanArray();
         mUdfpsUtils = udfpsUtils;
         mApplicationCoroutineScope = applicationCoroutineScope;
+        mVibratorHelper = vibratorHelper;
 
         mLogContextInteractor = logContextInteractor;
         mAuthBiometricFingerprintViewModelProvider = authBiometricFingerprintViewModelProvider;
@@ -1044,7 +1049,7 @@
         final int userId = mCurrentDialogArgs.argi1;
         if (isFaceAuthEnrolled(userId) && isFingerprintEnrolled(userId)) {
             messageRes = modality == TYPE_FACE
-                    ? R.string.biometric_face_not_recognized
+                    ? R.string.fingerprint_dialog_use_fingerprint_instead
                     : R.string.fingerprint_error_not_match;
         } else {
             messageRes = R.string.biometric_not_recognized;
@@ -1341,7 +1346,7 @@
                 wakefulnessLifecycle, panelInteractionDetector, userManager, lockPatternUtils,
                 mInteractionJankMonitor, mAuthBiometricFingerprintViewModelProvider,
                 mPromptCredentialInteractor, mPromptSelectorInteractor, viewModel,
-                mCredentialViewModelProvider, bgExecutor);
+                mCredentialViewModelProvider, bgExecutor, mVibratorHelper);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleController.kt b/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleController.kt
index 946ddba..ea9fe5f 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleController.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleController.kt
@@ -230,7 +230,7 @@
                         lightRevealScrim.revealAmount = animator.animatedValue as Float
                     }
                     addListener(object : AnimatorListenerAdapter() {
-                        override fun onAnimationEnd(animation: Animator?) {
+                        override fun onAnimationEnd(animation: Animator) {
                             // Reset light reveal scrim to the default, so the CentralSurfaces
                             // can handle any subsequent light reveal changes
                             // (ie: from dozing changes)
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleView.kt b/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleView.kt
index 5ede16d..4c2dc41 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleView.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleView.kt
@@ -147,12 +147,12 @@
             retractDwellAnimator = AnimatorSet().apply {
                 playTogether(retractDwellRippleAnimator, retractAlphaAnimator)
                 addListener(object : AnimatorListenerAdapter() {
-                    override fun onAnimationStart(animation: Animator?) {
+                    override fun onAnimationStart(animation: Animator) {
                         dwellPulseOutAnimator?.cancel()
                         drawDwell = true
                     }
 
-                    override fun onAnimationEnd(animation: Animator?) {
+                    override fun onAnimationEnd(animation: Animator) {
                         drawDwell = false
                         resetDwellAlpha()
                     }
@@ -182,13 +182,13 @@
                     invalidate()
                 }
                 addListener(object : AnimatorListenerAdapter() {
-                    override fun onAnimationStart(animation: Animator?) {
+                    override fun onAnimationStart(animation: Animator) {
                         retractDwellAnimator?.cancel()
                         dwellPulseOutAnimator?.cancel()
                         drawDwell = true
                     }
 
-                    override fun onAnimationEnd(animation: Animator?) {
+                    override fun onAnimationEnd(animation: Animator) {
                         drawDwell = false
                         resetDwellAlpha()
                     }
@@ -239,14 +239,14 @@
                     expandDwellRippleAnimator
             )
             addListener(object : AnimatorListenerAdapter() {
-                override fun onAnimationStart(animation: Animator?) {
+                override fun onAnimationStart(animation: Animator) {
                     retractDwellAnimator?.cancel()
                     fadeDwellAnimator?.cancel()
                     visibility = VISIBLE
                     drawDwell = true
                 }
 
-                override fun onAnimationEnd(animation: Animator?) {
+                override fun onAnimationEnd(animation: Animator) {
                     drawDwell = false
                 }
             })
@@ -273,12 +273,12 @@
 
         unlockedRippleAnimator = rippleAnimator.apply {
             addListener(object : AnimatorListenerAdapter() {
-                override fun onAnimationStart(animation: Animator?) {
+                override fun onAnimationStart(animation: Animator) {
                     drawRipple = true
                     visibility = VISIBLE
                 }
 
-                override fun onAnimationEnd(animation: Animator?) {
+                override fun onAnimationEnd(animation: Animator) {
                     onAnimationEnd?.run()
                     drawRipple = false
                     visibility = GONE
@@ -327,7 +327,7 @@
         }
     }
 
-    override fun onDraw(canvas: Canvas?) {
+    override fun onDraw(canvas: Canvas) {
         // To reduce overdraw, we mask the effect to a circle whose radius is big enough to cover
         // the active effect area. Values here should be kept in sync with the
         // animation implementation in the ripple shader. (Twice bigger)
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/FaceAuthAccessibilityDelegate.kt b/packages/SystemUI/src/com/android/systemui/biometrics/FaceAuthAccessibilityDelegate.kt
index b9fa240..a24a47b 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/FaceAuthAccessibilityDelegate.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/FaceAuthAccessibilityDelegate.kt
@@ -40,7 +40,7 @@
     private val keyguardUpdateMonitor: KeyguardUpdateMonitor,
     private val faceAuthInteractor: KeyguardFaceAuthInteractor,
 ) : View.AccessibilityDelegate() {
-    override fun onInitializeAccessibilityNodeInfo(host: View?, info: AccessibilityNodeInfo) {
+    override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo) {
         super.onInitializeAccessibilityNodeInfo(host, info)
         if (keyguardUpdateMonitor.shouldListenForFace()) {
             val clickActionToRetryFace =
@@ -52,7 +52,7 @@
         }
     }
 
-    override fun performAccessibilityAction(host: View?, action: Int, args: Bundle?): Boolean {
+    override fun performAccessibilityAction(host: View, action: Int, args: Bundle?): Boolean {
         return if (action == AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK.id) {
             keyguardUpdateMonitor.requestFaceAuth(FaceAuthApiRequestReason.ACCESSIBILITY_ACTION)
             faceAuthInteractor.onAccessibilityAction()
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/FingerprintInteractiveToAuthProvider.java b/packages/SystemUI/src/com/android/systemui/biometrics/FingerprintInteractiveToAuthProvider.java
index 902bb18..4bc07e8 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/FingerprintInteractiveToAuthProvider.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/FingerprintInteractiveToAuthProvider.java
@@ -16,6 +16,8 @@
 
 package com.android.systemui.biometrics;
 
+import android.hardware.biometrics.common.AuthenticateReason;
+
 /** Provides the status of the interactive to auth feature. */
 public interface FingerprintInteractiveToAuthProvider {
     /**
@@ -24,4 +26,11 @@
      * @return true if the InteractiveToAuthFeature is enabled, false if disabled.
      */
     boolean isEnabled(int userId);
+
+    /**
+     *
+     * @param userId the user Id.
+     * @return Vendor extension if needed for authentication.
+     */
+    AuthenticateReason.Vendor getVendorExtension(int userId);
 }
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/SideFpsController.kt b/packages/SystemUI/src/com/android/systemui/biometrics/SideFpsController.kt
index 063f62e..0d7d9cc 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/SideFpsController.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/SideFpsController.kt
@@ -119,7 +119,7 @@
     private var overlayView: View? = null
         set(value) {
             field?.let { oldView ->
-                val lottie = oldView.findViewById(R.id.sidefps_animation) as LottieAnimationView
+                val lottie = oldView.requireViewById(R.id.sidefps_animation) as LottieAnimationView
                 lottie.pauseAnimation()
                 windowManager.removeView(oldView)
                 orientationListener.disable()
@@ -186,7 +186,7 @@
     }
 
     private fun listenForAlternateBouncerVisibility() {
-        alternateBouncerInteractor.setAlternateBouncerUIAvailable(true)
+        alternateBouncerInteractor.setAlternateBouncerUIAvailable(true, "SideFpsController")
         scope.launch {
             alternateBouncerInteractor.isVisible.collect { isVisible: Boolean ->
                 if (isVisible) {
@@ -274,7 +274,7 @@
             }
         overlayOffsets = offsets
 
-        val lottie = view.findViewById(R.id.sidefps_animation) as LottieAnimationView
+        val lottie = view.requireViewById(R.id.sidefps_animation) as LottieAnimationView
         view.rotation =
             display.asSideFpsAnimationRotation(
                 offsets.isYAligned(),
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java
index 39a45f7..b23e085 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java
@@ -646,8 +646,9 @@
             shouldPilfer = true;
         }
 
-        // Pilfer only once per gesture
-        if (shouldPilfer && !mPointerPilfered) {
+        // Pilfer only once per gesture, don't pilfer for BP
+        if (shouldPilfer && !mPointerPilfered
+                && getBiometricSessionType() != SESSION_BIOMETRIC_PROMPT) {
             mInputManager.pilferPointers(
                     mOverlay.getOverlayView().getViewRootImpl().getInputToken());
             mPointerPilfered = true;
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsFpmEmptyView.kt b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsFpmEmptyView.kt
index 8352d0a..5dafa61 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsFpmEmptyView.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsFpmEmptyView.kt
@@ -38,7 +38,8 @@
     override fun getDrawable(): UdfpsDrawable = fingerprintDrawable
 
     fun updateAccessibilityViewLocation(sensorBounds: Rect) {
-        val fingerprintAccessibilityView: View = findViewById(R.id.udfps_enroll_accessibility_view)
+        val fingerprintAccessibilityView: View =
+            requireViewById(R.id.udfps_enroll_accessibility_view)
         val params: ViewGroup.LayoutParams = fingerprintAccessibilityView.layoutParams
         params.width = sensorBounds.width()
         params.height = sensorBounds.height()
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsKeyguardAccessibilityDelegate.kt b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsKeyguardAccessibilityDelegate.kt
index fb7b56e..8497879 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsKeyguardAccessibilityDelegate.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsKeyguardAccessibilityDelegate.kt
@@ -33,7 +33,7 @@
     @Main private val resources: Resources,
     private val keyguardViewManager: StatusBarKeyguardViewManager,
 ) : View.AccessibilityDelegate() {
-    override fun onInitializeAccessibilityNodeInfo(host: View?, info: AccessibilityNodeInfo) {
+    override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo) {
         super.onInitializeAccessibilityNodeInfo(host, info)
         val clickAction =
             AccessibilityNodeInfo.AccessibilityAction(
@@ -43,7 +43,7 @@
         info.addAction(clickAction)
     }
 
-    override fun performAccessibilityAction(host: View?, action: Int, args: Bundle?): Boolean {
+    override fun performAccessibilityAction(host: View, action: Int, args: Bundle?): Boolean {
         // when an a11y service is enabled, double tapping on the fingerprint sensor should
         // show the primary bouncer
         return if (action == AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK.id) {
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsKeyguardViewControllerLegacy.kt b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsKeyguardViewControllerLegacy.kt
index 15bd731..e3fd3ce1 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsKeyguardViewControllerLegacy.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsKeyguardViewControllerLegacy.kt
@@ -83,6 +83,7 @@
         dumpManager,
     ),
     UdfpsKeyguardViewControllerAdapter {
+    private val uniqueIdentifier = this.toString()
     private val useExpandedOverlay: Boolean =
         featureFlags.isEnabled(Flags.UDFPS_NEW_TOUCH_DETECTION)
     private var showingUdfpsBouncer = false
@@ -282,7 +283,7 @@
 
     public override fun onViewAttached() {
         super.onViewAttached()
-        alternateBouncerInteractor.setAlternateBouncerUIAvailable(true)
+        alternateBouncerInteractor.setAlternateBouncerUIAvailable(true, uniqueIdentifier)
         val dozeAmount = statusBarStateController.dozeAmount
         lastDozeAmount = dozeAmount
         stateListener.onDozeAmountChanged(dozeAmount, dozeAmount)
@@ -305,14 +306,15 @@
         activityLaunchAnimator.addListener(activityLaunchAnimatorListener)
         view.mUseExpandedOverlay = useExpandedOverlay
         view.startIconAsyncInflate {
-            (view.findViewById(R.id.udfps_animation_view_internal) as View).accessibilityDelegate =
-                udfpsKeyguardAccessibilityDelegate
+            val animationViewInternal: View =
+                view.requireViewById(R.id.udfps_animation_view_internal)
+            animationViewInternal.accessibilityDelegate = udfpsKeyguardAccessibilityDelegate
         }
     }
 
     override fun onViewDetached() {
         super.onViewDetached()
-        alternateBouncerInteractor.setAlternateBouncerUIAvailable(false)
+        alternateBouncerInteractor.setAlternateBouncerUIAvailable(false, uniqueIdentifier)
         faceDetectRunning = false
         keyguardStateController.removeCallback(keyguardStateControllerCallback)
         statusBarStateController.removeCallback(stateListener)
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/Utils.kt b/packages/SystemUI/src/com/android/systemui/biometrics/Utils.kt
index b538085..1ca57e7 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/Utils.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/Utils.kt
@@ -60,6 +60,13 @@
         return dp * (density / DisplayMetrics.DENSITY_DEFAULT)
     }
 
+    /**
+     * Note: Talkback 14.0 has new rate-limitation design to reduce frequency
+     * of TYPE_WINDOW_CONTENT_CHANGED events to once every 30 seconds.
+     * (context: b/281765653#comment18)
+     * Using {@link View#announceForAccessibility} instead as workaround when sending events
+     * exceeding this frequency is required.
+     */
     @JvmStatic
     fun notifyAccessibilityContentChanged(am: AccessibilityManager, view: ViewGroup) {
         if (!am.isEnabled) {
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractor.kt b/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractor.kt
index 1f1a1b5..2a02667 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/CredentialInteractor.kt
@@ -89,7 +89,7 @@
                 )
             val hat = gkResponse.gatekeeperHAT
             lockPatternUtils.removeGatekeeperPasswordHandle(pwHandle)
-            emit(CredentialStatus.Success.Verified(hat))
+            emit(CredentialStatus.Success.Verified(checkNotNull(hat)))
         } else if (response.timeout > 0) {
             // if requests are being throttled, update the error message every
             // second until the temporary lock has expired
@@ -226,8 +226,7 @@
             is BiometricPromptRequest.Credential.Password ->
                 DevicePolicyResources.Strings.SystemUi.BIOMETRIC_DIALOG_WORK_PASSWORD_LAST_ATTEMPT
         }
-    return devicePolicyManager.resources.getString(id) {
-        // use fallback a string if not found
+    val getFallbackString = {
         val defaultId =
             when (request) {
                 is BiometricPromptRequest.Credential.Pin ->
@@ -239,6 +238,8 @@
             }
         getString(defaultId)
     }
+
+    return devicePolicyManager.resources?.getString(id, getFallbackString) ?: getFallbackString()
 }
 
 private fun Context.getLastAttemptBeforeWipeUserMessage(
@@ -266,8 +267,8 @@
                 DevicePolicyResources.Strings.SystemUi.BIOMETRIC_DIALOG_WORK_LOCK_FAILED_ATTEMPTS
             else -> DevicePolicyResources.UNDEFINED
         }
-    return devicePolicyManager.resources.getString(id) {
-        // use fallback a string if not found
+
+    val getFallbackString = {
         val defaultId =
             when (userType) {
                 UserType.PRIMARY ->
@@ -279,4 +280,6 @@
             }
         getString(defaultId)
     }
+
+    return devicePolicyManager.resources?.getString(id, getFallbackString) ?: getFallbackString()
 }
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/CredentialPasswordView.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/CredentialPasswordView.kt
index eca0ada..709fe85 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/CredentialPasswordView.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/CredentialPasswordView.kt
@@ -121,7 +121,7 @@
                 titleView.ellipsize = TextUtils.TruncateAt.MARQUEE
                 titleView.marqueeRepeatLimit = -1
                 // select to enable marquee unless a screen reader is enabled
-                titleView.isSelected = accessibilityManager.shouldMarquee()
+                titleView.isSelected = accessibilityManager?.shouldMarquee() ?: false
             } else {
                 titleView.isSingleLine = false
                 titleView.ellipsize = null
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
index 7b78761..d054751 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
@@ -17,6 +17,7 @@
 package com.android.systemui.biometrics.ui.binder
 
 import android.animation.Animator
+import android.annotation.SuppressLint
 import android.content.Context
 import android.hardware.biometrics.BiometricAuthenticator
 import android.hardware.biometrics.BiometricConstants
@@ -25,6 +26,8 @@
 import android.os.Bundle
 import android.text.method.ScrollingMovementMethod
 import android.util.Log
+import android.view.HapticFeedbackConstants
+import android.view.MotionEvent
 import android.view.View
 import android.view.View.IMPORTANT_FOR_ACCESSIBILITY_NO
 import android.view.accessibility.AccessibilityManager
@@ -45,7 +48,6 @@
 import com.android.systemui.biometrics.AuthBiometricViewAdapter
 import com.android.systemui.biometrics.AuthIconController
 import com.android.systemui.biometrics.AuthPanelController
-import com.android.systemui.biometrics.Utils
 import com.android.systemui.biometrics.domain.model.BiometricModalities
 import com.android.systemui.biometrics.shared.model.BiometricModality
 import com.android.systemui.biometrics.shared.model.PromptKind
@@ -55,9 +57,13 @@
 import com.android.systemui.biometrics.ui.viewmodel.PromptMessage
 import com.android.systemui.biometrics.ui.viewmodel.PromptSize
 import com.android.systemui.biometrics.ui.viewmodel.PromptViewModel
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags.ONE_WAY_HAPTICS_API_MIGRATION
 import com.android.systemui.lifecycle.repeatWhenAttached
+import com.android.systemui.statusbar.VibratorHelper
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.collect
 import kotlinx.coroutines.flow.combine
 import kotlinx.coroutines.flow.first
 import kotlinx.coroutines.flow.map
@@ -69,6 +75,7 @@
 object BiometricViewBinder {
 
     /** Binds a [BiometricPromptLayout] to a [PromptViewModel]. */
+    @SuppressLint("ClickableViewAccessibility")
     @JvmStatic
     fun bind(
         view: BiometricPromptLayout,
@@ -78,20 +85,19 @@
         backgroundView: View,
         legacyCallback: Callback,
         applicationScope: CoroutineScope,
+        vibratorHelper: VibratorHelper,
+        featureFlags: FeatureFlags,
     ): AuthBiometricViewAdapter {
         val accessibilityManager = view.context.getSystemService(AccessibilityManager::class.java)!!
-        fun notifyAccessibilityChanged() {
-            Utils.notifyAccessibilityContentChanged(accessibilityManager, view)
-        }
 
         val textColorError =
             view.resources.getColor(R.color.biometric_dialog_error, view.context.theme)
         val textColorHint =
             view.resources.getColor(R.color.biometric_dialog_gray, view.context.theme)
 
-        val titleView = view.findViewById<TextView>(R.id.title)
-        val subtitleView = view.findViewById<TextView>(R.id.subtitle)
-        val descriptionView = view.findViewById<TextView>(R.id.description)
+        val titleView = view.requireViewById<TextView>(R.id.title)
+        val subtitleView = view.requireViewById<TextView>(R.id.subtitle)
+        val descriptionView = view.requireViewById<TextView>(R.id.description)
 
         // set selected to enable marquee unless a screen reader is enabled
         titleView.isSelected =
@@ -100,18 +106,18 @@
             !accessibilityManager.isEnabled || !accessibilityManager.isTouchExplorationEnabled
         descriptionView.movementMethod = ScrollingMovementMethod()
 
-        val iconViewOverlay = view.findViewById<LottieAnimationView>(R.id.biometric_icon_overlay)
-        val iconView = view.findViewById<LottieAnimationView>(R.id.biometric_icon)
-        val indicatorMessageView = view.findViewById<TextView>(R.id.indicator)
+        val iconViewOverlay = view.requireViewById<LottieAnimationView>(R.id.biometric_icon_overlay)
+        val iconView = view.requireViewById<LottieAnimationView>(R.id.biometric_icon)
+        val indicatorMessageView = view.requireViewById<TextView>(R.id.indicator)
 
         // Negative-side (left) buttons
-        val negativeButton = view.findViewById<Button>(R.id.button_negative)
-        val cancelButton = view.findViewById<Button>(R.id.button_cancel)
-        val credentialFallbackButton = view.findViewById<Button>(R.id.button_use_credential)
+        val negativeButton = view.requireViewById<Button>(R.id.button_negative)
+        val cancelButton = view.requireViewById<Button>(R.id.button_cancel)
+        val credentialFallbackButton = view.requireViewById<Button>(R.id.button_use_credential)
 
         // Positive-side (right) buttons
-        val confirmationButton = view.findViewById<Button>(R.id.button_confirm)
-        val retryButton = view.findViewById<Button>(R.id.button_try_again)
+        val confirmationButton = view.requireViewById<Button>(R.id.button_confirm)
+        val retryButton = view.requireViewById<Button>(R.id.button_try_again)
 
         // TODO(b/251476085): temporary workaround for the unsafe callbacks & legacy controllers
         val adapter =
@@ -297,21 +303,19 @@
 
                 // reuse the icon as a confirm button
                 launch {
-                    viewModel.isConfirmButtonVisible
+                    viewModel.isIconConfirmButton
                         .map { isPending ->
                             when {
                                 isPending && iconController.actsAsConfirmButton ->
-                                    View.OnClickListener { viewModel.confirmAuthenticated() }
+                                    View.OnTouchListener { _: View, event: MotionEvent ->
+                                        viewModel.onOverlayTouch(event)
+                                    }
                                 else -> null
                             }
                         }
-                        .collect { onClick ->
-                            iconViewOverlay.setOnClickListener(onClick)
-                            iconView.setOnClickListener(onClick)
-                            if (onClick == null) {
-                                iconViewOverlay.isClickable = false
-                                iconView.isClickable = false
-                            }
+                        .collect { onTouch ->
+                            iconViewOverlay.setOnTouchListener(onTouch)
+                            iconView.setOnTouchListener(onTouch)
                         }
                 }
 
@@ -326,30 +330,30 @@
                     }
                 }
 
-                // not sure why this is here, but the legacy code did it probably needed?
-                launch {
-                    viewModel.isAuthenticating.collect { isAuthenticating ->
-                        if (isAuthenticating) {
-                            notifyAccessibilityChanged()
-                        }
-                    }
-                }
-
                 // dismiss prompt when authenticated and confirmed
                 launch {
                     viewModel.isAuthenticated.collect { authState ->
                         // Disable background view for cancelling authentication once authenticated,
                         // and remove from talkback
                         if (authState.isAuthenticated) {
+                            // Prevents Talkback from speaking subtitle after already authenticated
+                            subtitleView.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
                             backgroundView.setOnClickListener(null)
                             backgroundView.importantForAccessibility =
                                 IMPORTANT_FOR_ACCESSIBILITY_NO
+
+                            // Allow icon to be used as confirmation button with a11y enabled
+                            if (accessibilityManager.isTouchExplorationEnabled) {
+                                iconViewOverlay.setOnClickListener {
+                                    viewModel.confirmAuthenticated()
+                                }
+                                iconView.setOnClickListener { viewModel.confirmAuthenticated() }
+                            }
                         }
                         if (authState.isAuthenticatedAndConfirmed) {
                             view.announceForAccessibility(
                                 view.resources.getString(R.string.biometric_dialog_authenticated)
                             )
-                            notifyAccessibilityChanged()
 
                             launch {
                                 delay(authState.delay)
@@ -381,7 +385,30 @@
                             !accessibilityManager.isEnabled ||
                                 !accessibilityManager.isTouchExplorationEnabled
 
-                        notifyAccessibilityChanged()
+                        /**
+                         * Note: Talkback 14.0 has new rate-limitation design to reduce frequency of
+                         * TYPE_WINDOW_CONTENT_CHANGED events to once every 30 seconds. (context:
+                         * b/281765653#comment18) Using {@link View#announceForAccessibility}
+                         * instead as workaround since sending events exceeding this frequency is
+                         * required.
+                         */
+                        indicatorMessageView?.text?.let {
+                            if (it.isNotBlank()) {
+                                view.announceForAccessibility(it)
+                            }
+                        }
+                    }
+                }
+
+                // Play haptics
+                if (featureFlags.isEnabled(ONE_WAY_HAPTICS_API_MIGRATION)) {
+                    launch {
+                        viewModel.hapticsToPlay.collect { hapticFeedbackConstant ->
+                            if (hapticFeedbackConstant != HapticFeedbackConstants.NO_HAPTICS) {
+                                vibratorHelper.performHapticFeedback(view, hapticFeedbackConstant)
+                                viewModel.clearHaptics()
+                            }
+                        }
                     }
                 }
             }
@@ -477,7 +504,7 @@
             modalities.hasFaceAndFingerprint &&
                 (viewModel.fingerprintStartMode.first() != FingerprintStartMode.Pending) &&
                 (authenticatedModality == BiometricModality.Face) ->
-                R.string.biometric_dialog_tap_confirm_with_face
+                R.string.biometric_dialog_tap_confirm_with_face_alt_1
             else -> null
         }
 
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewSizeBinder.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewSizeBinder.kt
index 1a286cf..370b36b 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewSizeBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewSizeBinder.kt
@@ -72,7 +72,7 @@
             }
         }
 
-        val iconHolderView = view.findViewById<View>(R.id.biometric_icon_frame)
+        val iconHolderView = view.requireViewById<View>(R.id.biometric_icon_frame)
         val iconPadding = view.resources.getDimension(R.dimen.biometric_dialog_icon_padding)
         val fullSizeYOffset =
             view.resources.getDimension(R.dimen.biometric_dialog_medium_to_large_translation_offset)
@@ -205,7 +205,7 @@
 }
 
 private fun View.isLandscape(): Boolean {
-    val r = context.display.rotation
+    val r = context.display?.rotation
     return r == Surface.ROTATION_90 || r == Surface.ROTATION_270
 }
 
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/controller/UdfpsKeyguardViewController.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/controller/UdfpsKeyguardViewController.kt
index 2a9f3ea..c9b1624 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/controller/UdfpsKeyguardViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/controller/UdfpsKeyguardViewController.kt
@@ -46,6 +46,7 @@
         dumpManager,
     ),
     UdfpsKeyguardViewControllerAdapter {
+    private val uniqueIdentifier = this.toString()
     override val tag: String
         get() = TAG
 
@@ -55,12 +56,12 @@
 
     public override fun onViewAttached() {
         super.onViewAttached()
-        alternateBouncerInteractor.setAlternateBouncerUIAvailable(true)
+        alternateBouncerInteractor.setAlternateBouncerUIAvailable(true, uniqueIdentifier)
     }
 
     public override fun onViewDetached() {
         super.onViewDetached()
-        alternateBouncerInteractor.setAlternateBouncerUIAvailable(false)
+        alternateBouncerInteractor.setAlternateBouncerUIAvailable(false, uniqueIdentifier)
     }
 
     override fun shouldPauseAuth(): Boolean {
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
index dca19c5..89561a5 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
@@ -17,11 +17,15 @@
 
 import android.hardware.biometrics.BiometricPrompt
 import android.util.Log
+import android.view.HapticFeedbackConstants
+import android.view.MotionEvent
 import com.android.systemui.biometrics.AuthBiometricView
 import com.android.systemui.biometrics.domain.interactor.PromptSelectorInteractor
 import com.android.systemui.biometrics.domain.model.BiometricModalities
 import com.android.systemui.biometrics.shared.model.BiometricModality
 import com.android.systemui.biometrics.shared.model.PromptKind
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags.ONE_WAY_HAPTICS_API_MIGRATION
 import com.android.systemui.statusbar.VibratorHelper
 import javax.inject.Inject
 import kotlinx.coroutines.Job
@@ -43,6 +47,7 @@
 constructor(
     private val interactor: PromptSelectorInteractor,
     private val vibrator: VibratorHelper,
+    private val featureFlags: FeatureFlags,
 ) {
     /** The set of modalities available for this prompt */
     val modalities: Flow<BiometricModalities> =
@@ -63,11 +68,18 @@
     /** If the user has successfully authenticated and confirmed (when explicitly required). */
     val isAuthenticated: Flow<PromptAuthState> = _isAuthenticated.asStateFlow()
 
+    private val _isOverlayTouched: MutableStateFlow<Boolean> = MutableStateFlow(false)
+
     /**
      * If the API caller or the user's personal preferences require explicit confirmation after
      * successful authentication.
      */
-    val isConfirmationRequired: Flow<Boolean> = interactor.isConfirmationRequired
+    val isConfirmationRequired: Flow<Boolean> =
+        combine(_isOverlayTouched, interactor.isConfirmationRequired) {
+            isOverlayTouched,
+            isConfirmationRequired ->
+            !isOverlayTouched && isConfirmationRequired
+        }
 
     /** The kind of credential the user has. */
     val credentialKind: Flow<PromptKind> = interactor.credentialKind
@@ -90,6 +102,11 @@
     private val _forceLargeSize = MutableStateFlow(false)
     private val _forceMediumSize = MutableStateFlow(false)
 
+    private val _hapticsToPlay = MutableStateFlow(HapticFeedbackConstants.NO_HAPTICS)
+
+    /** Event fired to the view indicating a [HapticFeedbackConstants] to be played */
+    val hapticsToPlay = _hapticsToPlay.asStateFlow()
+
     /** The size of the prompt. */
     val size: Flow<PromptSize> =
         combine(
@@ -141,6 +158,12 @@
             }
             .distinctUntilChanged()
 
+    /** If the icon can be used as a confirmation button. */
+    val isIconConfirmButton: Flow<Boolean> =
+        combine(size, interactor.isConfirmationRequired) { size, isConfirmationRequired ->
+            size.isNotSmall && isConfirmationRequired
+        }
+
     /** If the negative button should be shown. */
     val isNegativeButtonVisible: Flow<Boolean> =
         combine(
@@ -289,8 +312,10 @@
             if (message.isNotBlank()) PromptMessage.Help(message) else PromptMessage.Empty
         _forceMediumSize.value = true
         _legacyState.value =
-            if (alreadyAuthenticated) {
+            if (alreadyAuthenticated && isConfirmationRequired.first()) {
                 AuthBiometricView.STATE_PENDING_CONFIRMATION
+            } else if (alreadyAuthenticated && !isConfirmationRequired.first()) {
+                AuthBiometricView.STATE_AUTHENTICATED
             } else {
                 AuthBiometricView.STATE_HELP
             }
@@ -388,18 +413,10 @@
     }
 
     private suspend fun needsExplicitConfirmation(modality: BiometricModality): Boolean {
-        val availableModalities = modalities.first()
         val confirmationRequired = isConfirmationRequired.first()
 
-        if (availableModalities.hasFaceAndFingerprint) {
-            // coex only needs confirmation when face is successful, unless it happens on the
-            // first attempt (i.e. without failure) before fingerprint scanning starts
-            val fingerprintStarted = fingerprintStartMode.first() != FingerprintStartMode.Pending
-            if (modality == BiometricModality.Face) {
-                return fingerprintStarted || confirmationRequired
-            }
-        }
-        if (availableModalities.hasFaceOnly) {
+        // Only worry about confirmationRequired if face was used to unlock
+        if (modality == BiometricModality.Face) {
             return confirmationRequired
         }
         // fingerprint only never requires confirmation
@@ -430,6 +447,26 @@
     }
 
     /**
+     * Touch event occurred on the overlay
+     *
+     * Tracks whether a finger is currently down to set [_isOverlayTouched] to be used as user
+     * confirmation
+     */
+    fun onOverlayTouch(event: MotionEvent): Boolean {
+        if (event.actionMasked == MotionEvent.ACTION_DOWN) {
+            _isOverlayTouched.value = true
+
+            if (_isAuthenticated.value.needsUserConfirmation) {
+                confirmAuthenticated()
+            }
+            return true
+        } else if (event.actionMasked == MotionEvent.ACTION_UP) {
+            _isOverlayTouched.value = false
+        }
+        return false
+    }
+
+    /**
      * Switch to the credential view.
      *
      * TODO(b/251476085): this should be decoupled from the shared panel controller
@@ -438,11 +475,26 @@
         _forceLargeSize.value = true
     }
 
-    private fun VibratorHelper.success(modality: BiometricModality) =
-        vibrateAuthSuccess("$TAG, modality = $modality BP::success")
+    private fun VibratorHelper.success(modality: BiometricModality) {
+        if (featureFlags.isEnabled(ONE_WAY_HAPTICS_API_MIGRATION)) {
+            _hapticsToPlay.value = HapticFeedbackConstants.CONFIRM
+        } else {
+            vibrateAuthSuccess("$TAG, modality = $modality BP::success")
+        }
+    }
 
-    private fun VibratorHelper.error(modality: BiometricModality = BiometricModality.None) =
-        vibrateAuthError("$TAG, modality = $modality BP::error")
+    private fun VibratorHelper.error(modality: BiometricModality = BiometricModality.None) {
+        if (featureFlags.isEnabled(ONE_WAY_HAPTICS_API_MIGRATION)) {
+            _hapticsToPlay.value = HapticFeedbackConstants.REJECT
+        } else {
+            vibrateAuthError("$TAG, modality = $modality BP::error")
+        }
+    }
+
+    /** Clears the [hapticsToPlay] variable by setting it to the NO_HAPTICS default. */
+    fun clearHaptics() {
+        _hapticsToPlay.value = HapticFeedbackConstants.NO_HAPTICS
+    }
 
     companion object {
         private const val TAG = "PromptViewModel"
diff --git a/packages/SystemUI/src/com/android/systemui/bouncer/data/factory/BouncerMessageFactory.kt b/packages/SystemUI/src/com/android/systemui/bouncer/data/factory/BouncerMessageFactory.kt
index 1817ea9..64bf688 100644
--- a/packages/SystemUI/src/com/android/systemui/bouncer/data/factory/BouncerMessageFactory.kt
+++ b/packages/SystemUI/src/com/android/systemui/bouncer/data/factory/BouncerMessageFactory.kt
@@ -36,7 +36,6 @@
 import com.android.keyguard.KeyguardSecurityView.PROMPT_REASON_TIMEOUT
 import com.android.keyguard.KeyguardSecurityView.PROMPT_REASON_TRUSTAGENT_EXPIRED
 import com.android.keyguard.KeyguardSecurityView.PROMPT_REASON_USER_REQUEST
-import com.android.keyguard.KeyguardUpdateMonitor
 import com.android.systemui.R.string.bouncer_face_not_recognized
 import com.android.systemui.R.string.keyguard_enter_password
 import com.android.systemui.R.string.keyguard_enter_pattern
@@ -80,13 +79,14 @@
 import com.android.systemui.bouncer.shared.model.BouncerMessageModel
 import com.android.systemui.bouncer.shared.model.Message
 import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyguard.data.repository.BiometricSettingsRepository
 import javax.inject.Inject
 
 @SysUISingleton
 class BouncerMessageFactory
 @Inject
 constructor(
-    private val updateMonitor: KeyguardUpdateMonitor,
+    private val biometricSettingsRepository: BiometricSettingsRepository,
     private val securityModel: KeyguardSecurityModel,
 ) {
 
@@ -99,7 +99,7 @@
             getBouncerMessage(
                 reason,
                 securityModel.getSecurityMode(userId),
-                updateMonitor.isUnlockingWithFingerprintAllowed
+                biometricSettingsRepository.isFingerprintAuthCurrentlyAllowed.value
             )
         return pair?.let {
             BouncerMessageModel(
diff --git a/packages/SystemUI/src/com/android/systemui/bouncer/data/repository/BouncerMessageRepository.kt b/packages/SystemUI/src/com/android/systemui/bouncer/data/repository/BouncerMessageRepository.kt
index 6fb0d4c..97c1bdb 100644
--- a/packages/SystemUI/src/com/android/systemui/bouncer/data/repository/BouncerMessageRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/bouncer/data/repository/BouncerMessageRepository.kt
@@ -123,20 +123,11 @@
     fingerprintAuthRepository: DeviceEntryFingerprintAuthRepository,
 ) : BouncerMessageRepository {
 
-    private val isFaceEnrolledAndEnabled =
-        and(
-            biometricSettingsRepository.isFaceAuthenticationEnabled,
-            biometricSettingsRepository.isFaceEnrolled
-        )
-
-    private val isFingerprintEnrolledAndEnabled =
-        and(
-            biometricSettingsRepository.isFingerprintEnabledByDevicePolicy,
-            biometricSettingsRepository.isFingerprintEnrolled
-        )
-
     private val isAnyBiometricsEnabledAndEnrolled =
-        or(isFaceEnrolledAndEnabled, isFingerprintEnrolledAndEnabled)
+        or(
+            biometricSettingsRepository.isFaceAuthEnrolledAndEnabled,
+            biometricSettingsRepository.isFingerprintEnrolledAndEnabled,
+        )
 
     private val wasRebootedForMainlineUpdate
         get() = systemPropertiesHelper.get(SYS_BOOT_REASON_PROP) == REBOOT_MAINLINE_UPDATE
@@ -335,8 +326,5 @@
     }
 }
 
-private fun and(flow: Flow<Boolean>, anotherFlow: Flow<Boolean>) =
-    flow.combine(anotherFlow) { a, b -> a && b }
-
 private fun or(flow: Flow<Boolean>, anotherFlow: Flow<Boolean>) =
     flow.combine(anotherFlow) { a, b -> a || b }
diff --git a/packages/SystemUI/src/com/android/systemui/bouncer/domain/interactor/AlternateBouncerInteractor.kt b/packages/SystemUI/src/com/android/systemui/bouncer/domain/interactor/AlternateBouncerInteractor.kt
index e3e9b3a..9a7fec1 100644
--- a/packages/SystemUI/src/com/android/systemui/bouncer/domain/interactor/AlternateBouncerInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/bouncer/domain/interactor/AlternateBouncerInteractor.kt
@@ -40,6 +40,7 @@
 ) {
     var receivedDownTouch = false
     val isVisible: Flow<Boolean> = bouncerRepository.alternateBouncerVisible
+    private val alternateBouncerUiAvailableFromSource: HashSet<String> = HashSet()
 
     /**
      * Sets the correct bouncer states to show the alternate bouncer if it can show.
@@ -69,15 +70,20 @@
         return bouncerRepository.alternateBouncerVisible.value
     }
 
-    fun setAlternateBouncerUIAvailable(isAvailable: Boolean) {
-        bouncerRepository.setAlternateBouncerUIAvailable(isAvailable)
+    fun setAlternateBouncerUIAvailable(isAvailable: Boolean, token: String) {
+        if (isAvailable) {
+            alternateBouncerUiAvailableFromSource.add(token)
+        } else {
+            alternateBouncerUiAvailableFromSource.remove(token)
+        }
+        bouncerRepository.setAlternateBouncerUIAvailable(
+            alternateBouncerUiAvailableFromSource.isNotEmpty()
+        )
     }
 
     fun canShowAlternateBouncerForFingerprint(): Boolean {
         return bouncerRepository.alternateBouncerUIAvailable.value &&
-            biometricSettingsRepository.isFingerprintEnrolled.value &&
-            biometricSettingsRepository.isStrongBiometricAllowed.value &&
-            biometricSettingsRepository.isFingerprintEnabledByDevicePolicy.value &&
+            biometricSettingsRepository.isFingerprintAuthCurrentlyAllowed.value &&
             !keyguardUpdateMonitor.isFingerprintLockedOut &&
             !keyguardStateController.isUnlocked &&
             !statusBarStateController.isDozing
diff --git a/packages/SystemUI/src/com/android/systemui/bouncer/domain/interactor/BouncerInteractor.kt b/packages/SystemUI/src/com/android/systemui/bouncer/domain/interactor/BouncerInteractor.kt
index 8ed964d..1bf3a9e 100644
--- a/packages/SystemUI/src/com/android/systemui/bouncer/domain/interactor/BouncerInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/bouncer/domain/interactor/BouncerInteractor.kt
@@ -14,14 +14,12 @@
  * limitations under the License.
  */
 
-@file:OptIn(ExperimentalCoroutinesApi::class)
-
 package com.android.systemui.bouncer.domain.interactor
 
 import android.content.Context
 import com.android.systemui.R
 import com.android.systemui.authentication.domain.interactor.AuthenticationInteractor
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.domain.model.AuthenticationMethodModel
 import com.android.systemui.authentication.shared.model.AuthenticationThrottlingModel
 import com.android.systemui.bouncer.data.repository.BouncerRepository
 import com.android.systemui.dagger.SysUISingleton
@@ -35,7 +33,6 @@
 import javax.inject.Inject
 import kotlin.time.Duration.Companion.milliseconds
 import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.SharingStarted
 import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.flow.combine
@@ -107,14 +104,6 @@
     }
 
     /**
-     * Returns the currently-configured authentication method. This determines how the
-     * authentication challenge is completed in order to unlock an otherwise locked device.
-     */
-    suspend fun getAuthenticationMethod(): AuthenticationMethodModel {
-        return authenticationInteractor.getAuthenticationMethod()
-    }
-
-    /**
      * Either shows the bouncer or unlocks the device, if the bouncer doesn't need to be shown.
      *
      * @param message An optional message to show to the user in the bouncer.
@@ -124,13 +113,15 @@
     ) {
         applicationScope.launch {
             if (authenticationInteractor.isAuthenticationRequired()) {
-                repository.setMessage(message ?: promptMessage(getAuthenticationMethod()))
-                sceneInteractor.setCurrentScene(
+                repository.setMessage(
+                    message ?: promptMessage(authenticationInteractor.getAuthenticationMethod())
+                )
+                sceneInteractor.changeScene(
                     scene = SceneModel(SceneKey.Bouncer),
                     loggingReason = "request to unlock device while authentication required",
                 )
             } else {
-                sceneInteractor.setCurrentScene(
+                sceneInteractor.changeScene(
                     scene = SceneModel(SceneKey.Gone),
                     loggingReason = "request to unlock device while authentication isn't required",
                 )
@@ -143,7 +134,9 @@
      * method.
      */
     fun resetMessage() {
-        applicationScope.launch { repository.setMessage(promptMessage(getAuthenticationMethod())) }
+        applicationScope.launch {
+            repository.setMessage(promptMessage(authenticationInteractor.getAuthenticationMethod()))
+        }
     }
 
     /** Removes the user-facing message. */
@@ -176,12 +169,12 @@
             authenticationInteractor.authenticate(input, tryAutoConfirm) ?: return null
 
         if (isAuthenticated) {
-            sceneInteractor.setCurrentScene(
+            sceneInteractor.changeScene(
                 scene = SceneModel(SceneKey.Gone),
                 loggingReason = "successful authentication",
             )
         } else {
-            repository.setMessage(errorMessage(getAuthenticationMethod()))
+            repository.setMessage(errorMessage(authenticationInteractor.getAuthenticationMethod()))
         }
 
         return isAuthenticated
diff --git a/packages/SystemUI/src/com/android/systemui/bouncer/ui/binder/KeyguardBouncerViewBinder.kt b/packages/SystemUI/src/com/android/systemui/bouncer/ui/binder/KeyguardBouncerViewBinder.kt
index d9ec5d0..56f1cf6 100644
--- a/packages/SystemUI/src/com/android/systemui/bouncer/ui/binder/KeyguardBouncerViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/bouncer/ui/binder/KeyguardBouncerViewBinder.kt
@@ -121,7 +121,7 @@
                             view.visibility = if (isShowing) View.VISIBLE else View.INVISIBLE
                             if (isShowing) {
                                 // Reset security container because these views are not reinflated.
-                                securityContainerController.reset()
+                                securityContainerController.prepareToShow()
                                 securityContainerController.reinflateViewFlipper {
                                     // Reset Security Container entirely.
                                     securityContainerController.onBouncerVisibilityChanged(
diff --git a/packages/SystemUI/src/com/android/systemui/bouncer/ui/viewmodel/BouncerViewModel.kt b/packages/SystemUI/src/com/android/systemui/bouncer/ui/viewmodel/BouncerViewModel.kt
index 68e1a29..5b1998d 100644
--- a/packages/SystemUI/src/com/android/systemui/bouncer/ui/viewmodel/BouncerViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/bouncer/ui/viewmodel/BouncerViewModel.kt
@@ -14,25 +14,20 @@
  * limitations under the License.
  */
 
-@file:OptIn(ExperimentalCoroutinesApi::class)
-
 package com.android.systemui.bouncer.ui.viewmodel
 
 import android.content.Context
 import com.android.systemui.R
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.domain.interactor.AuthenticationInteractor
+import com.android.systemui.authentication.domain.model.AuthenticationMethodModel
 import com.android.systemui.bouncer.domain.interactor.BouncerInteractor
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
 import com.android.systemui.flags.FeatureFlags
 import com.android.systemui.flags.Flags
-import com.android.systemui.util.kotlin.pairwise
 import javax.inject.Inject
 import kotlin.math.ceil
 import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.channels.BufferOverflow
-import kotlinx.coroutines.flow.MutableSharedFlow
 import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.SharingStarted
 import kotlinx.coroutines.flow.StateFlow
@@ -50,23 +45,24 @@
 constructor(
     @Application private val applicationContext: Context,
     @Application private val applicationScope: CoroutineScope,
-    private val interactor: BouncerInteractor,
+    private val bouncerInteractor: BouncerInteractor,
+    private val authenticationInteractor: AuthenticationInteractor,
     featureFlags: FeatureFlags,
 ) {
     private val isInputEnabled: StateFlow<Boolean> =
-        interactor.isThrottled
+        bouncerInteractor.isThrottled
             .map { !it }
             .stateIn(
                 scope = applicationScope,
                 started = SharingStarted.WhileSubscribed(),
-                initialValue = !interactor.isThrottled.value,
+                initialValue = !bouncerInteractor.isThrottled.value,
             )
 
     private val pin: PinBouncerViewModel by lazy {
         PinBouncerViewModel(
             applicationContext = applicationContext,
             applicationScope = applicationScope,
-            interactor = interactor,
+            interactor = bouncerInteractor,
             isInputEnabled = isInputEnabled,
         )
     }
@@ -74,7 +70,7 @@
     private val password: PasswordBouncerViewModel by lazy {
         PasswordBouncerViewModel(
             applicationScope = applicationScope,
-            interactor = interactor,
+            interactor = bouncerInteractor,
             isInputEnabled = isInputEnabled,
         )
     }
@@ -83,31 +79,35 @@
         PatternBouncerViewModel(
             applicationContext = applicationContext,
             applicationScope = applicationScope,
-            interactor = interactor,
+            interactor = bouncerInteractor,
             isInputEnabled = isInputEnabled,
         )
     }
 
     /** View-model for the current UI, based on the current authentication method. */
-    private val _authMethod =
-        MutableSharedFlow<AuthMethodBouncerViewModel?>(
-            replay = 1,
-            onBufferOverflow = BufferOverflow.DROP_OLDEST,
-        )
     val authMethod: StateFlow<AuthMethodBouncerViewModel?> =
-        _authMethod.stateIn(
-            scope = applicationScope,
-            started = SharingStarted.WhileSubscribed(),
-            initialValue = null,
-        )
+        authenticationInteractor.authenticationMethod
+            .map { authenticationMethod ->
+                when (authenticationMethod) {
+                    is AuthenticationMethodModel.Pin -> pin
+                    is AuthenticationMethodModel.Password -> password
+                    is AuthenticationMethodModel.Pattern -> pattern
+                    else -> null
+                }
+            }
+            .stateIn(
+                scope = applicationScope,
+                started = SharingStarted.WhileSubscribed(),
+                initialValue = null,
+            )
 
     init {
         if (featureFlags.isEnabled(Flags.SCENE_CONTAINER)) {
             applicationScope.launch {
-                interactor.isThrottled
+                bouncerInteractor.isThrottled
                     .map { isThrottled ->
                         if (isThrottled) {
-                            when (interactor.getAuthenticationMethod()) {
+                            when (authenticationInteractor.getAuthenticationMethod()) {
                                 is AuthenticationMethodModel.Pin ->
                                     R.string.kg_too_many_failed_pin_attempts_dialog_message
                                 is AuthenticationMethodModel.Password ->
@@ -118,8 +118,9 @@
                             }?.let { stringResourceId ->
                                 applicationContext.getString(
                                     stringResourceId,
-                                    interactor.throttling.value.failedAttemptCount,
-                                    ceil(interactor.throttling.value.remainingMs / 1000f).toInt(),
+                                    bouncerInteractor.throttling.value.failedAttemptCount,
+                                    ceil(bouncerInteractor.throttling.value.remainingMs / 1000f)
+                                        .toInt(),
                                 )
                             }
                         } else {
@@ -133,25 +134,14 @@
                         }
                     }
             }
-
-            applicationScope.launch {
-                _authMethod.subscriptionCount
-                    .pairwise()
-                    .map { (previousCount, currentCount) -> currentCount > previousCount }
-                    .collect { subscriberAdded ->
-                        if (subscriberAdded) {
-                            reloadAuthMethod()
-                        }
-                    }
-            }
         }
     }
 
     /** The user-facing message to show in the bouncer. */
     val message: StateFlow<MessageViewModel> =
         combine(
-                interactor.message,
-                interactor.isThrottled,
+                bouncerInteractor.message,
+                bouncerInteractor.isThrottled,
             ) { message, isThrottled ->
                 toMessageViewModel(message, isThrottled)
             }
@@ -160,8 +150,8 @@
                 started = SharingStarted.WhileSubscribed(),
                 initialValue =
                     toMessageViewModel(
-                        message = interactor.message.value,
-                        isThrottled = interactor.isThrottled.value,
+                        message = bouncerInteractor.message.value,
+                        isThrottled = bouncerInteractor.isThrottled.value,
                     ),
             )
 
@@ -197,17 +187,6 @@
         )
     }
 
-    private suspend fun reloadAuthMethod() {
-        _authMethod.tryEmit(
-            when (interactor.getAuthenticationMethod()) {
-                is AuthenticationMethodModel.Pin -> pin
-                is AuthenticationMethodModel.Password -> password
-                is AuthenticationMethodModel.Pattern -> pattern
-                else -> null
-            }
-        )
-    }
-
     data class MessageViewModel(
         val text: String,
 
diff --git a/packages/SystemUI/src/com/android/systemui/bouncer/ui/viewmodel/PatternBouncerViewModel.kt b/packages/SystemUI/src/com/android/systemui/bouncer/ui/viewmodel/PatternBouncerViewModel.kt
index 4be539d..4425f9f 100644
--- a/packages/SystemUI/src/com/android/systemui/bouncer/ui/viewmodel/PatternBouncerViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/bouncer/ui/viewmodel/PatternBouncerViewModel.kt
@@ -18,7 +18,7 @@
 
 import android.content.Context
 import android.util.TypedValue
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.shared.model.AuthenticationPatternCoordinate
 import com.android.systemui.bouncer.domain.interactor.BouncerInteractor
 import kotlin.math.max
 import kotlin.math.min
@@ -193,8 +193,8 @@
     val x: Int,
     val y: Int,
 ) {
-    fun toCoordinate(): AuthenticationMethodModel.Pattern.PatternCoordinate {
-        return AuthenticationMethodModel.Pattern.PatternCoordinate(
+    fun toCoordinate(): AuthenticationPatternCoordinate {
+        return AuthenticationPatternCoordinate(
             x = x,
             y = y,
         )
diff --git a/packages/SystemUI/src/com/android/systemui/charging/WiredChargingRippleController.kt b/packages/SystemUI/src/com/android/systemui/charging/WiredChargingRippleController.kt
index 5ca36ab..ddb09749 100644
--- a/packages/SystemUI/src/com/android/systemui/charging/WiredChargingRippleController.kt
+++ b/packages/SystemUI/src/com/android/systemui/charging/WiredChargingRippleController.kt
@@ -156,9 +156,9 @@
         }
         windowLayoutParams.packageName = context.opPackageName
         rippleView.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
-            override fun onViewDetachedFromWindow(view: View?) {}
+            override fun onViewDetachedFromWindow(view: View) {}
 
-            override fun onViewAttachedToWindow(view: View?) {
+            override fun onViewAttachedToWindow(view: View) {
                 layoutRipple()
                 rippleView.startRipple(Runnable {
                     windowManager.removeView(rippleView)
@@ -176,7 +176,7 @@
         val height = bounds.height()
         val maxDiameter = Integer.max(width, height) * 2f
         rippleView.setMaxSize(maxDiameter, maxDiameter)
-        when (context.display.rotation) {
+        when (context.display?.rotation) {
             Surface.ROTATION_0 -> {
                 rippleView.setCenter(
                         width * normalizedPortPosX, height * normalizedPortPosY)
diff --git a/packages/SystemUI/src/com/android/systemui/classifier/FalsingA11yDelegate.kt b/packages/SystemUI/src/com/android/systemui/classifier/FalsingA11yDelegate.kt
index 63d57cc..a9f3b77 100644
--- a/packages/SystemUI/src/com/android/systemui/classifier/FalsingA11yDelegate.kt
+++ b/packages/SystemUI/src/com/android/systemui/classifier/FalsingA11yDelegate.kt
@@ -29,7 +29,7 @@
  */
 class FalsingA11yDelegate @Inject constructor(private val falsingCollector: FalsingCollector) :
     View.AccessibilityDelegate() {
-    override fun performAccessibilityAction(host: View?, action: Int, args: Bundle?): Boolean {
+    override fun performAccessibilityAction(host: View, action: Int, args: Bundle?): Boolean {
         if (action == ACTION_CLICK) {
             falsingCollector.onA11yAction()
         }
diff --git a/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardTransitionExecutor.kt b/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardTransitionExecutor.kt
index 0b8e83e..1b45ecd 100644
--- a/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardTransitionExecutor.kt
+++ b/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardTransitionExecutor.kt
@@ -59,7 +59,7 @@
         context.startActivity(intent, transition.first.toBundle())
         val runner = RemoteAnimationAdapter(NULL_ACTIVITY_TRANSITION, 0, 0)
         try {
-            WindowManagerGlobal.getWindowManagerService()
+            checkNotNull(WindowManagerGlobal.getWindowManagerService())
                 .overridePendingAppTransitionRemote(runner, displayTracker.defaultDisplayId)
         } catch (e: Exception) {
             Log.e(TAG, "Error overriding clipboard app transition", e)
diff --git a/packages/SystemUI/src/com/android/systemui/clipboardoverlay/IntentCreator.java b/packages/SystemUI/src/com/android/systemui/clipboardoverlay/IntentCreator.java
index 566a74a..d58fab4 100644
--- a/packages/SystemUI/src/com/android/systemui/clipboardoverlay/IntentCreator.java
+++ b/packages/SystemUI/src/com/android/systemui/clipboardoverlay/IntentCreator.java
@@ -27,7 +27,8 @@
 import com.android.systemui.R;
 
 class IntentCreator {
-    private static final String EXTRA_EDIT_SOURCE_CLIPBOARD = "edit_source_clipboard";
+    private static final String EXTRA_EDIT_SOURCE = "edit_source";
+    private static final String EDIT_SOURCE_CLIPBOARD = "clipboard";
     private static final String REMOTE_COPY_ACTION = "android.intent.action.REMOTE_COPY";
 
     static Intent getTextEditorIntent(Context context) {
@@ -74,7 +75,7 @@
         editIntent.setDataAndType(uri, "image/*");
         editIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
         editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
-        editIntent.putExtra(EXTRA_EDIT_SOURCE_CLIPBOARD, true);
+        editIntent.putExtra(EXTRA_EDIT_SOURCE, EDIT_SOURCE_CLIPBOARD);
         return editIntent;
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/common/ui/data/repository/ConfigurationRepository.kt b/packages/SystemUI/src/com/android/systemui/common/ui/data/repository/ConfigurationRepository.kt
index 3e6ac86..c0d1951 100644
--- a/packages/SystemUI/src/com/android/systemui/common/ui/data/repository/ConfigurationRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/common/ui/data/repository/ConfigurationRepository.kt
@@ -100,7 +100,7 @@
             .stateIn(scope, SharingStarted.WhileSubscribed(), getResolutionScale())
 
     override fun getResolutionScale(): Float {
-        context.display.getDisplayInfo(displayInfo.value)
+        context.display?.getDisplayInfo(displayInfo.value)
         val maxDisplayMode =
             displayUtils.getMaximumResolutionDisplayMode(displayInfo.value.supportedModes)
         maxDisplayMode?.let {
diff --git a/packages/SystemUI/src/com/android/systemui/common/ui/view/LongPressHandlingView.kt b/packages/SystemUI/src/com/android/systemui/common/ui/view/LongPressHandlingView.kt
index 2dd98dc..323070a 100644
--- a/packages/SystemUI/src/com/android/systemui/common/ui/view/LongPressHandlingView.kt
+++ b/packages/SystemUI/src/com/android/systemui/common/ui/view/LongPressHandlingView.kt
@@ -22,6 +22,7 @@
 import android.util.AttributeSet
 import android.view.MotionEvent
 import android.view.View
+import com.android.systemui.shade.TouchLogger
 import kotlin.math.pow
 import kotlin.math.sqrt
 import kotlinx.coroutines.DisposableHandle
@@ -83,6 +84,10 @@
         interactionHandler.isLongPressHandlingEnabled = isEnabled
     }
 
+    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
+        return TouchLogger.logDispatchTouch("long_press", event, super.dispatchTouchEvent(event))
+    }
+
     @SuppressLint("ClickableViewAccessibility")
     override fun onTouchEvent(event: MotionEvent?): Boolean {
         return interactionHandler.onTouchEvent(event?.toModel())
diff --git a/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalWidgetRepository.kt b/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalWidgetRepository.kt
new file mode 100644
index 0000000..e2a7d07
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalWidgetRepository.kt
@@ -0,0 +1,170 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.communal.data.repository
+
+import android.appwidget.AppWidgetHost
+import android.appwidget.AppWidgetManager
+import android.appwidget.AppWidgetProviderInfo
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.content.pm.PackageManager
+import android.os.UserManager
+import com.android.systemui.broadcast.BroadcastDispatcher
+import com.android.systemui.common.coroutine.ChannelExt.trySendWithFailureLogging
+import com.android.systemui.communal.shared.CommunalAppWidgetInfo
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
+import com.android.systemui.log.LogBuffer
+import com.android.systemui.log.core.Logger
+import com.android.systemui.log.dagger.CommunalLog
+import com.android.systemui.settings.UserTracker
+import javax.inject.Inject
+import kotlinx.coroutines.channels.awaitClose
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.callbackFlow
+import kotlinx.coroutines.flow.map
+
+/** Encapsulates the state of widgets for communal mode. */
+interface CommunalWidgetRepository {
+    /** A flow of provider info for the stopwatch widget, or null if widget is unavailable. */
+    val stopwatchAppWidgetInfo: Flow<CommunalAppWidgetInfo?>
+}
+
+@SysUISingleton
+class CommunalWidgetRepositoryImpl
+@Inject
+constructor(
+    private val appWidgetManager: AppWidgetManager,
+    private val appWidgetHost: AppWidgetHost,
+    broadcastDispatcher: BroadcastDispatcher,
+    private val packageManager: PackageManager,
+    private val userManager: UserManager,
+    private val userTracker: UserTracker,
+    @CommunalLog logBuffer: LogBuffer,
+    featureFlags: FeatureFlags,
+) : CommunalWidgetRepository {
+    companion object {
+        const val TAG = "CommunalWidgetRepository"
+        const val WIDGET_LABEL = "Stopwatch"
+    }
+
+    private val logger = Logger(logBuffer, TAG)
+
+    // Whether the [AppWidgetHost] is listening for updates.
+    private var isHostListening = false
+
+    // Widgets that should be rendered in communal mode.
+    private val widgets: HashMap<Int, CommunalAppWidgetInfo> = hashMapOf()
+
+    private val isUserUnlocked: Flow<Boolean> = callbackFlow {
+        if (!featureFlags.isEnabled(Flags.WIDGET_ON_KEYGUARD)) {
+            awaitClose()
+        }
+
+        fun isUserUnlockingOrUnlocked(): Boolean {
+            return userManager.isUserUnlockingOrUnlocked(userTracker.userHandle)
+        }
+
+        fun send() {
+            trySendWithFailureLogging(isUserUnlockingOrUnlocked(), TAG)
+        }
+
+        if (isUserUnlockingOrUnlocked()) {
+            send()
+            awaitClose()
+        } else {
+            val receiver =
+                object : BroadcastReceiver() {
+                    override fun onReceive(context: Context?, intent: Intent?) {
+                        send()
+                    }
+                }
+
+            broadcastDispatcher.registerReceiver(
+                receiver,
+                IntentFilter(Intent.ACTION_USER_UNLOCKED),
+            )
+
+            awaitClose { broadcastDispatcher.unregisterReceiver(receiver) }
+        }
+    }
+
+    override val stopwatchAppWidgetInfo: Flow<CommunalAppWidgetInfo?> =
+        isUserUnlocked.map { isUserUnlocked ->
+            if (!isUserUnlocked) {
+                clearWidgets()
+                stopListening()
+                return@map null
+            }
+
+            startListening()
+
+            val providerInfo =
+                appWidgetManager.installedProviders.find {
+                    it.loadLabel(packageManager).equals(WIDGET_LABEL)
+                }
+
+            if (providerInfo == null) {
+                logger.w("Cannot find app widget: $WIDGET_LABEL")
+                return@map null
+            }
+
+            return@map addWidget(providerInfo)
+        }
+
+    private fun startListening() {
+        if (isHostListening) {
+            return
+        }
+
+        appWidgetHost.startListening()
+        isHostListening = true
+    }
+
+    private fun stopListening() {
+        if (!isHostListening) {
+            return
+        }
+
+        appWidgetHost.stopListening()
+        isHostListening = false
+    }
+
+    private fun addWidget(providerInfo: AppWidgetProviderInfo): CommunalAppWidgetInfo {
+        val existing = widgets.values.firstOrNull { it.providerInfo == providerInfo }
+        if (existing != null) {
+            return existing
+        }
+
+        val appWidgetId = appWidgetHost.allocateAppWidgetId()
+        val widget =
+            CommunalAppWidgetInfo(
+                providerInfo,
+                appWidgetId,
+            )
+        widgets[appWidgetId] = widget
+        return widget
+    }
+
+    private fun clearWidgets() {
+        widgets.keys.forEach { appWidgetId -> appWidgetHost.deleteAppWidgetId(appWidgetId) }
+        widgets.clear()
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalWidgetRepositoryModule.kt b/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalWidgetRepositoryModule.kt
new file mode 100644
index 0000000..3d1185b
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalWidgetRepositoryModule.kt
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.communal.data.repository
+
+import android.appwidget.AppWidgetHost
+import android.appwidget.AppWidgetManager
+import android.content.Context
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dagger.qualifiers.Application
+import dagger.Binds
+import dagger.Module
+import dagger.Provides
+
+@Module
+interface CommunalWidgetRepositoryModule {
+    companion object {
+        private const val APP_WIDGET_HOST_ID = 116
+
+        @SysUISingleton
+        @Provides
+        fun provideAppWidgetManager(@Application context: Context): AppWidgetManager {
+            return AppWidgetManager.getInstance(context)
+        }
+
+        @SysUISingleton
+        @Provides
+        fun provideAppWidgetHost(@Application context: Context): AppWidgetHost {
+            return AppWidgetHost(context, APP_WIDGET_HOST_ID)
+        }
+    }
+
+    @Binds
+    fun communalWidgetRepository(impl: CommunalWidgetRepositoryImpl): CommunalWidgetRepository
+}
diff --git a/packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalInteractor.kt b/packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalInteractor.kt
new file mode 100644
index 0000000..6dc305e
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalInteractor.kt
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.communal.domain.interactor
+
+import com.android.systemui.communal.data.repository.CommunalWidgetRepository
+import com.android.systemui.communal.shared.CommunalAppWidgetInfo
+import com.android.systemui.dagger.SysUISingleton
+import javax.inject.Inject
+import kotlinx.coroutines.flow.Flow
+
+/** Encapsulates business-logic related to communal mode. */
+@SysUISingleton
+class CommunalInteractor
+@Inject
+constructor(
+    widgetRepository: CommunalWidgetRepository,
+) {
+    /** A flow of info about the widget to be displayed, or null if widget is unavailable. */
+    val appWidgetInfo: Flow<CommunalAppWidgetInfo?> = widgetRepository.stopwatchAppWidgetInfo
+}
diff --git a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl b/packages/SystemUI/src/com/android/systemui/communal/shared/CommunalAppWidgetInfo.kt
similarity index 61%
rename from core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl
rename to packages/SystemUI/src/com/android/systemui/communal/shared/CommunalAppWidgetInfo.kt
index f6c47dd..0803a01 100644
--- a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl
+++ b/packages/SystemUI/src/com/android/systemui/communal/shared/CommunalAppWidgetInfo.kt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2022 The Android Open Source Project
+ * Copyright (C) 2023 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -12,17 +12,15 @@
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- */
-
-package android.service.selectiontoolbar;
-
-import android.os.IBinder;
-
-/**
- * The interface from the SelectionToolbarRenderService to the system.
  *
- * @hide
  */
-oneway interface ISelectionToolbarRenderServiceCallback {
-    void transferTouch(in IBinder source, in IBinder target);
-}
+
+package com.android.systemui.communal.shared
+
+import android.appwidget.AppWidgetProviderInfo
+
+/** A data class that stores info about an app widget that displays in communal mode. */
+data class CommunalAppWidgetInfo(
+    val providerInfo: AppWidgetProviderInfo,
+    val appWidgetId: Int,
+)
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/adapter/CommunalWidgetViewAdapter.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/adapter/CommunalWidgetViewAdapter.kt
new file mode 100644
index 0000000..2a08d7f
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/adapter/CommunalWidgetViewAdapter.kt
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.communal.ui.adapter
+
+import android.appwidget.AppWidgetHost
+import android.appwidget.AppWidgetManager
+import android.content.Context
+import android.util.SizeF
+import com.android.systemui.communal.shared.CommunalAppWidgetInfo
+import com.android.systemui.communal.ui.view.CommunalWidgetWrapper
+import com.android.systemui.dagger.qualifiers.Application
+import com.android.systemui.log.LogBuffer
+import com.android.systemui.log.core.Logger
+import com.android.systemui.log.dagger.CommunalLog
+import javax.inject.Inject
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
+
+/** Transforms a [CommunalAppWidgetInfo] to a view that renders the widget. */
+class CommunalWidgetViewAdapter
+@Inject
+constructor(
+    @Application private val context: Context,
+    private val appWidgetManager: AppWidgetManager,
+    private val appWidgetHost: AppWidgetHost,
+    @CommunalLog logBuffer: LogBuffer,
+) {
+    companion object {
+        private const val TAG = "CommunalWidgetViewAdapter"
+    }
+
+    private val logger = Logger(logBuffer, TAG)
+
+    fun adapt(providerInfoFlow: Flow<CommunalAppWidgetInfo?>): Flow<CommunalWidgetWrapper?> =
+        providerInfoFlow.map {
+            if (it == null) {
+                return@map null
+            }
+
+            val appWidgetId = it.appWidgetId
+            val providerInfo = it.providerInfo
+
+            if (appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, providerInfo.provider)) {
+                logger.d("Success binding app widget id: $appWidgetId")
+                return@map CommunalWidgetWrapper(context).apply {
+                    addView(
+                        appWidgetHost.createView(context, appWidgetId, providerInfo).apply {
+                            // Set the widget to minimum width and height
+                            updateAppWidgetSize(
+                                appWidgetManager.getAppWidgetOptions(appWidgetId),
+                                listOf(
+                                    SizeF(
+                                        providerInfo.minResizeWidth.toFloat(),
+                                        providerInfo.minResizeHeight.toFloat()
+                                    )
+                                )
+                            )
+                        }
+                    )
+                }
+            } else {
+                logger.w("Failed binding app widget id")
+                return@map null
+            }
+        }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/binder/CommunalWidgetViewBinder.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/binder/CommunalWidgetViewBinder.kt
new file mode 100644
index 0000000..1b6d3a8
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/binder/CommunalWidgetViewBinder.kt
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.communal.ui.binder
+
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.repeatOnLifecycle
+import com.android.systemui.R
+import com.android.systemui.communal.ui.adapter.CommunalWidgetViewAdapter
+import com.android.systemui.communal.ui.view.CommunalWidgetWrapper
+import com.android.systemui.communal.ui.viewmodel.CommunalWidgetViewModel
+import com.android.systemui.keyguard.domain.interactor.KeyguardBlueprintInteractor
+import com.android.systemui.keyguard.ui.view.KeyguardRootView
+import com.android.systemui.lifecycle.repeatWhenAttached
+import kotlinx.coroutines.launch
+
+/** Binds [CommunalWidgetViewModel] to the keyguard root view. */
+object CommunalWidgetViewBinder {
+
+    @JvmStatic
+    fun bind(
+        rootView: KeyguardRootView,
+        viewModel: CommunalWidgetViewModel,
+        adapter: CommunalWidgetViewAdapter,
+        keyguardBlueprintInteractor: KeyguardBlueprintInteractor,
+    ) {
+        rootView.repeatWhenAttached {
+            repeatOnLifecycle(Lifecycle.State.STARTED) {
+                launch {
+                    adapter.adapt(viewModel.appWidgetInfo).collect {
+                        val oldView =
+                            rootView.findViewById<CommunalWidgetWrapper>(
+                                R.id.communal_widget_wrapper
+                            )
+                        var dirty = false
+
+                        if (oldView != null) {
+                            rootView.removeView(oldView)
+                            dirty = true
+                        }
+
+                        if (it != null) {
+                            rootView.addView(it)
+                            dirty = true
+                        }
+
+                        if (dirty) {
+                            keyguardBlueprintInteractor.refreshBlueprint()
+                        }
+                    }
+                }
+
+                launch { viewModel.alpha.collect { rootView.alpha = it } }
+            }
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/view/CommunalWidgetWrapper.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/view/CommunalWidgetWrapper.kt
new file mode 100644
index 0000000..560f4fa
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/view/CommunalWidgetWrapper.kt
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.communal.ui.view
+
+import android.content.Context
+import android.util.AttributeSet
+import android.widget.LinearLayout
+import com.android.systemui.R
+
+/** Wraps around a widget rendered in communal mode. */
+class CommunalWidgetWrapper(context: Context, attrs: AttributeSet? = null) :
+    LinearLayout(context, attrs) {
+    init {
+        id = R.id.communal_widget_wrapper
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/view/layout/blueprints/DefaultCommunalBlueprint.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/view/layout/blueprints/DefaultCommunalBlueprint.kt
new file mode 100644
index 0000000..c3369da
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/view/layout/blueprints/DefaultCommunalBlueprint.kt
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.communal.ui.view.layout.blueprints
+
+import androidx.constraintlayout.widget.ConstraintSet
+import com.android.systemui.communal.ui.view.layout.sections.DefaultCommunalWidgetSection
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyguard.data.repository.KeyguardBlueprint
+import javax.inject.Inject
+
+/** Blueprint for communal mode. */
+@SysUISingleton
+@JvmSuppressWildcards
+class DefaultCommunalBlueprint
+@Inject
+constructor(
+    private val defaultCommunalWidgetSection: DefaultCommunalWidgetSection,
+) : KeyguardBlueprint {
+    override val id: String = COMMUNAL
+
+    override fun apply(constraintSet: ConstraintSet) {
+        defaultCommunalWidgetSection.apply(constraintSet)
+    }
+
+    companion object {
+        const val COMMUNAL = "communal"
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/view/layout/sections/DefaultCommunalWidgetSection.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/view/layout/sections/DefaultCommunalWidgetSection.kt
new file mode 100644
index 0000000..b0e3132
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/view/layout/sections/DefaultCommunalWidgetSection.kt
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.communal.ui.view.layout.sections
+
+import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
+import androidx.constraintlayout.widget.ConstraintSet
+import androidx.constraintlayout.widget.ConstraintSet.BOTTOM
+import androidx.constraintlayout.widget.ConstraintSet.END
+import androidx.constraintlayout.widget.ConstraintSet.PARENT_ID
+import com.android.systemui.R
+import com.android.systemui.keyguard.data.repository.KeyguardSection
+import javax.inject.Inject
+
+class DefaultCommunalWidgetSection @Inject constructor() : KeyguardSection {
+    private val widgetAreaViewId = R.id.communal_widget_wrapper
+
+    override fun apply(constraintSet: ConstraintSet) {
+        constraintSet.apply {
+            constrainWidth(widgetAreaViewId, WRAP_CONTENT)
+            constrainHeight(widgetAreaViewId, WRAP_CONTENT)
+            connect(widgetAreaViewId, BOTTOM, PARENT_ID, BOTTOM)
+            connect(widgetAreaViewId, END, PARENT_ID, END)
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalWidgetViewModel.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalWidgetViewModel.kt
new file mode 100644
index 0000000..8fba342
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalWidgetViewModel.kt
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.communal.ui.viewmodel
+
+import com.android.systemui.communal.domain.interactor.CommunalInteractor
+import com.android.systemui.communal.shared.CommunalAppWidgetInfo
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyguard.ui.viewmodel.KeyguardBottomAreaViewModel
+import javax.inject.Inject
+import kotlinx.coroutines.flow.Flow
+
+@SysUISingleton
+class CommunalWidgetViewModel
+@Inject
+constructor(
+    communalInteractor: CommunalInteractor,
+    keyguardBottomAreaViewModel: KeyguardBottomAreaViewModel,
+) {
+    /** An observable for the alpha level for the communal widget area. */
+    val alpha: Flow<Float> = keyguardBottomAreaViewModel.alpha
+
+    /** A flow of info about the widget to be displayed, or null if widget is unavailable. */
+    val appWidgetInfo: Flow<CommunalAppWidgetInfo?> = communalInteractor.appWidgetInfo
+}
diff --git a/packages/SystemUI/src/com/android/systemui/contrast/ContrastDialog.kt b/packages/SystemUI/src/com/android/systemui/contrast/ContrastDialog.kt
index 6b1c85f..e627b68 100644
--- a/packages/SystemUI/src/com/android/systemui/contrast/ContrastDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/contrast/ContrastDialog.kt
@@ -66,9 +66,9 @@
 
         contrastButtons =
             mapOf(
-                CONTRAST_LEVEL_STANDARD to findViewById(R.id.contrast_button_standard),
-                CONTRAST_LEVEL_MEDIUM to findViewById(R.id.contrast_button_medium),
-                CONTRAST_LEVEL_HIGH to findViewById(R.id.contrast_button_high)
+                CONTRAST_LEVEL_STANDARD to requireViewById(R.id.contrast_button_standard),
+                CONTRAST_LEVEL_MEDIUM to requireViewById(R.id.contrast_button_medium),
+                CONTRAST_LEVEL_HIGH to requireViewById(R.id.contrast_button_high)
             )
 
         contrastButtons.forEach { (contrastLevel, contrastButton) ->
diff --git a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsControllerImpl.kt b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsControllerImpl.kt
index 7db5968..638da86 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsControllerImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsControllerImpl.kt
@@ -190,7 +190,7 @@
                     PREFS_CONTROLS_SEEDING_COMPLETED, mutableSetOf<String>())
                 val servicePackageSet = serviceInfoSet.map { it.packageName }
                 prefs.edit().putStringSet(PREFS_CONTROLS_SEEDING_COMPLETED,
-                    completedSeedingPackageSet.intersect(servicePackageSet)).apply()
+                    completedSeedingPackageSet?.intersect(servicePackageSet) ?: emptySet()).apply()
 
                 var changed = false
                 favoriteComponentSet.subtract(serviceInfoSet).forEach {
diff --git a/packages/SystemUI/src/com/android/systemui/controls/management/ControlsFavoritingActivity.kt b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsFavoritingActivity.kt
index 23721c9..8bae667 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/management/ControlsFavoritingActivity.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsFavoritingActivity.kt
@@ -193,7 +193,7 @@
 
                         ControlsAnimations.enterAnimation(pageIndicator).apply {
                             addListener(object : AnimatorListenerAdapter() {
-                                override fun onAnimationEnd(animation: Animator?) {
+                                override fun onAnimationEnd(animation: Animator) {
                                     // Position the tooltip if necessary after animations are complete
                                     // so we can get the position on screen. The tooltip is not
                                     // rooted in the layout root.
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ChallengeDialogs.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ChallengeDialogs.kt
index ff55b76d..a13f717 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ChallengeDialogs.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ChallengeDialogs.kt
@@ -106,10 +106,8 @@
                 }
             )
 
-            getWindow().apply {
-                setType(WINDOW_TYPE)
-                setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
-            }
+            window?.setType(WINDOW_TYPE)
+            window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
             setOnShowListener(DialogInterface.OnShowListener { _ ->
                 val editText = requireViewById<EditText>(R.id.controls_pin_input)
                 editText.setHint(instructions)
@@ -153,9 +151,7 @@
             )
         }
         return builder.create().apply {
-            getWindow().apply {
-                setType(WINDOW_TYPE)
-            }
+            window?.setType(WINDOW_TYPE)
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinator.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinator.kt
index 8029ba8..534832c0 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinator.kt
@@ -54,9 +54,10 @@
     /**
      * When a ToggleRange control is interacting with, a drag event is sent.
      *
+     * @param cvh [ControlViewHolder] for the control
      * @param isEdge did the drag event reach a control edge
      */
-    fun drag(isEdge: Boolean)
+    fun drag(cvh: ControlViewHolder, isEdge: Boolean)
 
     /**
      * Send a request to update the value of a device using the [FloatAction].
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinatorImpl.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinatorImpl.kt
index a7e9efd8..00d95c0 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinatorImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinatorImpl.kt
@@ -37,6 +37,8 @@
 import com.android.systemui.controls.settings.ControlsSettingsRepository
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags.ONE_WAY_HAPTICS_API_MIGRATION
 import com.android.systemui.plugins.ActivityStarter
 import com.android.systemui.statusbar.VibratorHelper
 import com.android.systemui.statusbar.policy.KeyguardStateController
@@ -57,6 +59,7 @@
         private val controlsMetricsLogger: ControlsMetricsLogger,
         private val vibrator: VibratorHelper,
         private val controlsSettingsRepository: ControlsSettingsRepository,
+        private val featureFlags: FeatureFlags,
 ) : ControlActionCoordinator {
     private var dialog: Dialog? = null
     private var pendingAction: Action? = null
@@ -119,11 +122,17 @@
         )
     }
 
-    override fun drag(isEdge: Boolean) {
-        if (isEdge) {
-            vibrate(Vibrations.rangeEdgeEffect)
+    override fun drag(cvh: ControlViewHolder, isEdge: Boolean) {
+        if (featureFlags.isEnabled(ONE_WAY_HAPTICS_API_MIGRATION)) {
+            val constant =
+                if (isEdge)
+                    HapticFeedbackConstants.SEGMENT_TICK
+                else
+                    HapticFeedbackConstants.SEGMENT_FREQUENT_TICK
+            vibrator.performHapticFeedback(cvh.layout, constant)
         } else {
-            vibrate(Vibrations.rangeMiddleEffect)
+            val effect = if (isEdge) Vibrations.rangeEdgeEffect else Vibrations.rangeMiddleEffect
+            vibrate(effect)
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
index c04bc87..abe3423 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
@@ -384,7 +384,7 @@
                 )
             }
             addListener(object : AnimatorListenerAdapter() {
-                override fun onAnimationEnd(animation: Animator?) {
+                override fun onAnimationEnd(animation: Animator) {
                     stateAnimator = null
                 }
             })
@@ -438,7 +438,7 @@
                 duration = 200L
                 interpolator = Interpolators.LINEAR
                 addListener(object : AnimatorListenerAdapter() {
-                    override fun onAnimationEnd(animation: Animator?) {
+                    override fun onAnimationEnd(animation: Animator) {
                         statusRowUpdater.invoke()
                     }
                 })
@@ -450,7 +450,7 @@
             statusAnimator = AnimatorSet().apply {
                 playSequentially(fadeOut, fadeIn)
                 addListener(object : AnimatorListenerAdapter() {
-                    override fun onAnimationEnd(animation: Animator?) {
+                    override fun onAnimationEnd(animation: Animator) {
                         status.alpha = STATUS_ALPHA_ENABLED
                         statusAnimator = null
                     }
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/DetailDialog.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/DetailDialog.kt
index be50a14..98f17f4 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/DetailDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/DetailDialog.kt
@@ -132,8 +132,8 @@
 
     init {
         // To pass touches to the task inside TaskView.
-        window.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL)
-        window.addPrivateFlags(WindowManager.LayoutParams.PRIVATE_FLAG_TRUSTED_OVERLAY)
+        window?.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL)
+        window?.addPrivateFlags(WindowManager.LayoutParams.PRIVATE_FLAG_TRUSTED_OVERLAY)
 
         setContentView(R.layout.controls_detail_dialog)
 
@@ -182,7 +182,7 @@
         }
 
         // consume all insets to achieve slide under effect
-        window.getDecorView().setOnApplyWindowInsetsListener {
+        checkNotNull(window).decorView.setOnApplyWindowInsetsListener {
             v: View, insets: WindowInsets ->
                 val l = v.getPaddingLeft()
                 val r = v.getPaddingRight()
@@ -202,7 +202,7 @@
     }
 
     fun getTaskViewBounds(): Rect {
-        val wm = context.getSystemService(WindowManager::class.java)
+        val wm = checkNotNull(context.getSystemService(WindowManager::class.java))
         val windowMetrics = wm.getCurrentWindowMetrics()
         val rect = windowMetrics.bounds
         val metricInsets = windowMetrics.windowInsets
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt
index ad2b785..dbbda9a 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt
@@ -67,7 +67,8 @@
                     iconMap.put(resourceId, icon)
                 }
             }
-            return RenderInfo(icon!!.constantState.newDrawable(context.resources), fg, bg)
+            return RenderInfo(
+                checkNotNull(icon?.constantState).newDrawable(context.resources), fg, bg)
         }
 
         fun registerComponentIcon(componentName: ComponentName, icon: Drawable) {
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/StatusBehavior.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/StatusBehavior.kt
index 84cda5a..3c2bfa0 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/StatusBehavior.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/StatusBehavior.kt
@@ -94,10 +94,8 @@
             )
         }
         cvh.visibleDialog = builder.create().apply {
-            getWindow().apply {
-                setType(WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY)
-                show()
-            }
+            window?.setType(WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY)
+            show()
         }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleRangeBehavior.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleRangeBehavior.kt
index 1461135..0d570d2 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleRangeBehavior.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleRangeBehavior.kt
@@ -235,7 +235,7 @@
         if (isDragging) {
             val isEdge = newLevel == MIN_LEVEL || newLevel == MAX_LEVEL
             if (clipLayer.level != newLevel) {
-                cvh.controlActionCoordinator.drag(isEdge)
+                cvh.controlActionCoordinator.drag(cvh, isEdge)
                 clipLayer.level = newLevel
             }
         } else if (newLevel != clipLayer.level) {
@@ -244,7 +244,7 @@
                     cvh.clipLayer.level = it.animatedValue as Int
                 }
                 addListener(object : AnimatorListenerAdapter() {
-                    override fun onAnimationEnd(animation: Animator?) {
+                    override fun onAnimationEnd(animation: Animator) {
                         rangeAnimator = null
                     }
                 })
@@ -335,7 +335,7 @@
         }
 
         override fun onScroll(
-            e1: MotionEvent,
+            e1: MotionEvent?,
             e2: MotionEvent,
             xDiff: Float,
             yDiff: Float
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/AndroidInternalsModule.java b/packages/SystemUI/src/com/android/systemui/dagger/AndroidInternalsModule.java
index 0992882..585c390 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/AndroidInternalsModule.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/AndroidInternalsModule.java
@@ -24,11 +24,11 @@
 import com.android.internal.util.NotificationMessagingUtil;
 import com.android.internal.widget.LockPatternUtils;
 
-import javax.inject.Singleton;
-
 import dagger.Module;
 import dagger.Provides;
 
+import javax.inject.Singleton;
+
 /**
  * Provides items imported from com.android.internal.
  */
@@ -51,7 +51,7 @@
     /** */
     @Provides
     public NotificationMessagingUtil provideNotificationMessagingUtil(Context context) {
-        return new NotificationMessagingUtil(context);
+        return new NotificationMessagingUtil(context, null);
     }
 
     /** Provides an instance of {@link com.android.internal.logging.UiEventLogger} */
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUICoreStartableModule.kt b/packages/SystemUI/src/com/android/systemui/dagger/SystemUICoreStartableModule.kt
index d9665c5b5..484be9c 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUICoreStartableModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUICoreStartableModule.kt
@@ -53,6 +53,7 @@
 import com.android.systemui.statusbar.phone.KeyguardLiftController
 import com.android.systemui.statusbar.phone.LockscreenWallpaper
 import com.android.systemui.statusbar.phone.ScrimController
+import com.android.systemui.statusbar.phone.StatusBarHeadsUpChangeListener
 import com.android.systemui.stylus.StylusUsiPowerStartable
 import com.android.systemui.temporarydisplay.chipbar.ChipbarCoordinator
 import com.android.systemui.theme.ThemeOverlayController
@@ -331,4 +332,11 @@
     @IntoMap
     @ClassKey(ScrimController::class)
     abstract fun bindScrimController(impl: ScrimController): CoreStartable
+
+    @Binds
+    @IntoMap
+    @ClassKey(StatusBarHeadsUpChangeListener::class)
+    abstract fun bindStatusBarHeadsUpChangeListener(
+        impl: StatusBarHeadsUpChangeListener
+    ): CoreStartable
 }
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
index 970d00b..3bf9cc8 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
@@ -107,6 +107,7 @@
 import com.android.systemui.statusbar.notification.row.dagger.NotificationShelfComponent;
 import com.android.systemui.statusbar.phone.CentralSurfaces;
 import com.android.systemui.statusbar.phone.LetterboxModule;
+import com.android.systemui.statusbar.phone.NotificationIconAreaControllerModule;
 import com.android.systemui.statusbar.phone.dagger.CentralSurfacesComponent;
 import com.android.systemui.statusbar.pipeline.dagger.StatusBarPipelineModule;
 import com.android.systemui.statusbar.policy.HeadsUpManager;
@@ -185,6 +186,7 @@
             MediaProjectionModule.class,
             MediaProjectionTaskSwitcherModule.class,
             MotionToolModule.class,
+            NotificationIconAreaControllerModule.class,
             PeopleHubModule.class,
             PeopleModule.class,
             PluginModule.class,
diff --git a/packages/SystemUI/src/com/android/systemui/decor/FaceScanningProviderFactory.kt b/packages/SystemUI/src/com/android/systemui/decor/FaceScanningProviderFactory.kt
index 4e62104..ac0d3c8 100644
--- a/packages/SystemUI/src/com/android/systemui/decor/FaceScanningProviderFactory.kt
+++ b/packages/SystemUI/src/com/android/systemui/decor/FaceScanningProviderFactory.kt
@@ -34,6 +34,7 @@
 import com.android.systemui.biometrics.AuthController
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.flags.FeatureFlags
 import com.android.systemui.log.ScreenDecorationsLogger
 import com.android.systemui.plugins.statusbar.StatusBarStateController
 import java.util.concurrent.Executor
@@ -47,6 +48,7 @@
     private val keyguardUpdateMonitor: KeyguardUpdateMonitor,
     @Main private val mainExecutor: Executor,
     private val logger: ScreenDecorationsLogger,
+    private val featureFlags: FeatureFlags,
 ) : DecorProviderFactory() {
     private val display = context.display
     private val displayInfo = DisplayInfo()
@@ -86,6 +88,7 @@
                                         keyguardUpdateMonitor,
                                         mainExecutor,
                                         logger,
+                                        featureFlags,
                                 )
                         )
                     }
@@ -110,6 +113,7 @@
     private val keyguardUpdateMonitor: KeyguardUpdateMonitor,
     private val mainExecutor: Executor,
     private val logger: ScreenDecorationsLogger,
+    private val featureFlags: FeatureFlags,
 ) : BoundDecorProvider() {
     override val viewId: Int = com.android.systemui.R.id.face_scanning_anim
 
@@ -144,6 +148,7 @@
                 mainExecutor,
                 logger,
                 authController,
+                featureFlags
         )
         view.id = viewId
         view.setColor(tintColor)
diff --git a/packages/SystemUI/src/com/android/systemui/display/data/repository/DisplayMetricsRepository.kt b/packages/SystemUI/src/com/android/systemui/display/data/repository/DisplayMetricsRepository.kt
index bcfeeb9e..cef45dc 100644
--- a/packages/SystemUI/src/com/android/systemui/display/data/repository/DisplayMetricsRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/display/data/repository/DisplayMetricsRepository.kt
@@ -51,7 +51,7 @@
                 val callback =
                     object : ConfigurationController.ConfigurationListener {
                         override fun onConfigChanged(newConfig: Configuration?) {
-                            context.display.getMetrics(displayMetricsHolder)
+                            context.display?.getMetrics(displayMetricsHolder)
                             trySend(displayMetricsHolder)
                         }
                     }
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeUi.java b/packages/SystemUI/src/com/android/systemui/doze/DozeUi.java
index 7c816ce..34a80e8 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeUi.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeUi.java
@@ -26,9 +26,9 @@
 import android.text.format.Formatter;
 import android.util.Log;
 
+import com.android.systemui.DejankUtils;
 import com.android.systemui.dagger.qualifiers.Main;
 import com.android.systemui.doze.dagger.DozeScope;
-import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.phone.DozeParameters;
 import com.android.systemui.util.AlarmTimeout;
 import com.android.systemui.util.wakelock.WakeLock;
@@ -52,15 +52,21 @@
     private final boolean mCanAnimateTransition;
     private final DozeParameters mDozeParameters;
     private final DozeLog mDozeLog;
-    private final StatusBarStateController mStatusBarStateController;
 
     private long mLastTimeTickElapsed = 0;
+    // If time tick is scheduled and there's not a pending runnable to cancel:
+    private boolean mTimeTickScheduled;
+    private final Runnable mCancelTimeTickerRunnable =  new Runnable() {
+        @Override
+        public void run() {
+            mTimeTicker.cancel();
+        }
+    };
 
     @Inject
     public DozeUi(Context context, AlarmManager alarmManager,
             WakeLock wakeLock, DozeHost host, @Main Handler handler,
             DozeParameters params,
-            StatusBarStateController statusBarStateController,
             DozeLog dozeLog) {
         mContext = context;
         mWakeLock = wakeLock;
@@ -70,7 +76,6 @@
         mDozeParameters = params;
         mTimeTicker = new AlarmTimeout(alarmManager, this::onTimeTick, "doze_time_tick", handler);
         mDozeLog = dozeLog;
-        mStatusBarStateController = statusBarStateController;
     }
 
     @Override
@@ -157,13 +162,15 @@
     }
 
     private void scheduleTimeTick() {
-        if (mTimeTicker.isScheduled()) {
+        if (mTimeTickScheduled) {
             return;
         }
+        mTimeTickScheduled = true;
+        DejankUtils.removeCallbacks(mCancelTimeTickerRunnable);
 
         long time = System.currentTimeMillis();
         long delta = roundToNextMinute(time) - System.currentTimeMillis();
-        boolean scheduled = mTimeTicker.schedule(delta, AlarmTimeout.MODE_IGNORE_IF_SCHEDULED);
+        boolean scheduled = mTimeTicker.schedule(delta, AlarmTimeout.MODE_RESCHEDULE_IF_SCHEDULED);
         if (scheduled) {
             mDozeLog.traceTimeTickScheduled(time, time + delta);
         }
@@ -171,11 +178,11 @@
     }
 
     private void unscheduleTimeTick() {
-        if (!mTimeTicker.isScheduled()) {
+        if (!mTimeTickScheduled) {
             return;
         }
-        verifyLastTimeTick();
-        mTimeTicker.cancel();
+        mTimeTickScheduled = false;
+        DejankUtils.postAfterTraversal(mCancelTimeTickerRunnable);
     }
 
     private void verifyLastTimeTick() {
@@ -205,6 +212,7 @@
         // Keep wakelock until a frame has been pushed.
         mHandler.post(mWakeLock.wrap(() -> {}));
 
+        mTimeTickScheduled = false;
         scheduleTimeTick();
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/conditions/AssistantAttentionCondition.java b/packages/SystemUI/src/com/android/systemui/dreams/conditions/AssistantAttentionCondition.java
index c889ac2..4dd97d5 100644
--- a/packages/SystemUI/src/com/android/systemui/dreams/conditions/AssistantAttentionCondition.java
+++ b/packages/SystemUI/src/com/android/systemui/dreams/conditions/AssistantAttentionCondition.java
@@ -16,10 +16,9 @@
 
 package com.android.systemui.dreams.conditions;
 
-import com.android.internal.app.AssistUtils;
-import com.android.internal.app.IVisualQueryDetectionAttentionListener;
+import com.android.systemui.assist.AssistManager;
+import com.android.systemui.assist.AssistManager.VisualQueryAttentionListener;
 import com.android.systemui.dagger.qualifiers.Application;
-import com.android.systemui.dreams.DreamOverlayStateController;
 import com.android.systemui.shared.condition.Condition;
 
 import javax.inject.Inject;
@@ -30,12 +29,10 @@
  * {@link AssistantAttentionCondition} provides a signal when assistant has the user's attention.
  */
 public class AssistantAttentionCondition extends Condition {
-    private final DreamOverlayStateController mDreamOverlayStateController;
-    private final AssistUtils mAssistUtils;
-    private boolean mEnabled;
+    private final AssistManager mAssistManager;
 
-    private final IVisualQueryDetectionAttentionListener mVisualQueryDetectionAttentionListener =
-            new IVisualQueryDetectionAttentionListener.Stub() {
+    private final VisualQueryAttentionListener mVisualQueryAttentionListener =
+            new VisualQueryAttentionListener() {
         @Override
         public void onAttentionGained() {
             updateCondition(true);
@@ -47,59 +44,26 @@
         }
     };
 
-    private final DreamOverlayStateController.Callback mCallback =
-            new DreamOverlayStateController.Callback() {
-        @Override
-        public void onStateChanged() {
-            if (mDreamOverlayStateController.isDreamOverlayStatusBarVisible()) {
-                enableVisualQueryDetection();
-            } else {
-                disableVisualQueryDetection();
-            }
-        }
-    };
-
     @Inject
     public AssistantAttentionCondition(
             @Application CoroutineScope scope,
-            DreamOverlayStateController dreamOverlayStateController,
-            AssistUtils assistUtils) {
+            AssistManager assistManager) {
         super(scope);
-        mDreamOverlayStateController = dreamOverlayStateController;
-        mAssistUtils = assistUtils;
+        mAssistManager = assistManager;
     }
 
     @Override
     protected void start() {
-        mDreamOverlayStateController.addCallback(mCallback);
+        mAssistManager.addVisualQueryAttentionListener(mVisualQueryAttentionListener);
     }
 
     @Override
     protected void stop() {
-        disableVisualQueryDetection();
-        mDreamOverlayStateController.removeCallback(mCallback);
+        mAssistManager.removeVisualQueryAttentionListener(mVisualQueryAttentionListener);
     }
 
     @Override
     protected int getStartStrategy() {
         return START_EAGERLY;
     }
-
-    private void enableVisualQueryDetection() {
-        if (mEnabled) {
-            return;
-        }
-        mEnabled = true;
-        mAssistUtils.enableVisualQueryDetection(mVisualQueryDetectionAttentionListener);
-    }
-
-    private void disableVisualQueryDetection() {
-        if (!mEnabled) {
-            return;
-        }
-        mEnabled = false;
-        mAssistUtils.disableVisualQueryDetection();
-        // Make sure the condition is set to false as well.
-        updateCondition(false);
-    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/dump/DumpHandler.kt b/packages/SystemUI/src/com/android/systemui/dump/DumpHandler.kt
index ae40f7e8..7150d69e 100644
--- a/packages/SystemUI/src/com/android/systemui/dump/DumpHandler.kt
+++ b/packages/SystemUI/src/com/android/systemui/dump/DumpHandler.kt
@@ -432,9 +432,11 @@
         }
 
         private inline fun PrintWriter.wrapSection(entry: DumpsysEntry, block: () -> Unit) {
+            Trace.beginSection(entry.name)
             preamble(entry)
             val dumpTime = measureTimeMillis(block)
             footer(entry, dumpTime)
+            Trace.endSection()
         }
 
         /**
diff --git a/packages/SystemUI/src/com/android/systemui/dump/DumpsysTableLogger.kt b/packages/SystemUI/src/com/android/systemui/dump/DumpsysTableLogger.kt
index f7e6b98..2e9d04b 100644
--- a/packages/SystemUI/src/com/android/systemui/dump/DumpsysTableLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/dump/DumpsysTableLogger.kt
@@ -16,6 +16,7 @@
 
 package com.android.systemui.dump
 
+import android.os.Trace
 import java.io.PrintWriter
 
 /**
@@ -83,31 +84,33 @@
 ) {
 
     fun printTableData(pw: PrintWriter) {
+        Trace.beginSection("DumpsysTableLogger#printTableData")
         printSectionStart(pw)
         printSchema(pw)
         printData(pw)
         printSectionEnd(pw)
+        Trace.endSection()
     }
 
     private fun printSectionStart(pw: PrintWriter) {
-        pw.println(HEADER_PREFIX + sectionName)
-        pw.println("version $VERSION")
+        pw.append(HEADER_PREFIX).println(sectionName)
+        pw.append("version ").println(VERSION)
     }
 
     private fun printSectionEnd(pw: PrintWriter) {
-        pw.println(FOOTER_PREFIX + sectionName)
+        pw.append(FOOTER_PREFIX).println(sectionName)
     }
 
     private fun printSchema(pw: PrintWriter) {
-        pw.println(columns.joinToString(separator = SEPARATOR))
+        columns.joinTo(pw, separator = SEPARATOR).println()
     }
 
     private fun printData(pw: PrintWriter) {
         val count = columns.size
-        rows
-            .filter { it.size == count }
-            .forEach { dataLine ->
-                pw.println(dataLine.joinToString(separator = SEPARATOR))
+        rows.forEach { dataLine ->
+            if (dataLine.size == count) {
+                dataLine.joinTo(pw, separator = SEPARATOR).println()
+            }
         }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebug.java b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebug.java
index 367a9b9..4c78e4c 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebug.java
+++ b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebug.java
@@ -93,8 +93,7 @@
                             shouldRestart = true;
                         }
                     } else if (mStringFlagCache.containsKey(flag.getName())) {
-                        String newValue = value == null ? "" : value;
-                        if (mStringFlagCache.get(flag.getName()) != value) {
+                        if (!mStringFlagCache.get(flag.getName()).equals(value)) {
                             shouldRestart = true;
                         }
                     } else if (mIntFlagCache.containsKey(flag.getName())) {
@@ -202,8 +201,7 @@
         String name = flag.getName();
         if (!mStringFlagCache.containsKey(name)) {
             mStringFlagCache.put(name,
-                    readFlagValueInternal(
-                            flag.getId(), name, flag.getDefault(), StringFlagSerializer.INSTANCE));
+                    readFlagValueInternal(name, flag.getDefault(), StringFlagSerializer.INSTANCE));
         }
 
         return mStringFlagCache.get(name);
@@ -215,36 +213,30 @@
         String name = flag.getName();
         if (!mStringFlagCache.containsKey(name)) {
             mStringFlagCache.put(name,
-                    readFlagValueInternal(
-                            flag.getId(), name, mResources.getString(flag.getResourceId()),
+                    readFlagValueInternal(name, mResources.getString(flag.getResourceId()),
                             StringFlagSerializer.INSTANCE));
         }
 
         return mStringFlagCache.get(name);
     }
 
-
-    @NonNull
     @Override
     public int getInt(@NonNull IntFlag flag) {
         String name = flag.getName();
         if (!mIntFlagCache.containsKey(name)) {
             mIntFlagCache.put(name,
-                    readFlagValueInternal(
-                            flag.getId(), name, flag.getDefault(), IntFlagSerializer.INSTANCE));
+                    readFlagValueInternal(name, flag.getDefault(), IntFlagSerializer.INSTANCE));
         }
 
         return mIntFlagCache.get(name);
     }
 
-    @NonNull
     @Override
     public int getInt(@NonNull ResourceIntFlag flag) {
         String name = flag.getName();
         if (!mIntFlagCache.containsKey(name)) {
             mIntFlagCache.put(name,
-                    readFlagValueInternal(
-                            flag.getId(), name, mResources.getInteger(flag.getResourceId()),
+                    readFlagValueInternal(name, mResources.getInteger(flag.getResourceId()),
                             IntFlagSerializer.INSTANCE));
         }
 
@@ -254,13 +246,6 @@
     /** Specific override for Boolean flags that checks against the teamfood list.*/
     private boolean readBooleanFlagInternal(Flag<Boolean> flag, boolean defaultValue) {
         Boolean result = readBooleanFlagOverride(flag.getName());
-        if (result == null) {
-            result = readBooleanFlagOverride(flag.getId());
-            if (result != null) {
-                // Move overrides from id to name
-                setFlagValueInternal(flag.getName(), result, BooleanFlagSerializer.INSTANCE);
-            }
-        }
         boolean hasServerOverride = mServerFlagReader.hasOverride(
                 flag.getNamespace(), flag.getName());
 
@@ -278,45 +263,22 @@
                 flag.getNamespace(), flag.getName(), defaultValue) : result;
     }
 
-    private Boolean readBooleanFlagOverride(int id) {
-        return readFlagValueInternal(id, BooleanFlagSerializer.INSTANCE);
-    }
 
     private Boolean readBooleanFlagOverride(String name) {
         return readFlagValueInternal(name, BooleanFlagSerializer.INSTANCE);
     }
 
-    // TODO(b/265188950): Remove id from this method once ids are fully deprecated.
     @NonNull
     private <T> T readFlagValueInternal(
-            int id, String name, @NonNull T defaultValue, FlagSerializer<T> serializer) {
+            String name, @NonNull T defaultValue, FlagSerializer<T> serializer) {
         requireNonNull(defaultValue, "defaultValue");
         T resultForName = readFlagValueInternal(name, serializer);
         if (resultForName == null) {
-            T resultForId = readFlagValueInternal(id, serializer);
-            if (resultForId == null) {
-                return defaultValue;
-            } else {
-                setFlagValue(name, resultForId, serializer);
-                return resultForId;
-            }
+            return defaultValue;
         }
         return resultForName;
     }
 
-
-    /** Returns the stored value or null if not set. */
-    // TODO(b/265188950): Remove method this once ids are fully deprecated.
-    @Nullable
-    private <T> T readFlagValueInternal(int id, FlagSerializer<T> serializer) {
-        try {
-            return mFlagManager.readFlagValue(id, serializer);
-        } catch (Exception e) {
-            eraseInternal(id);
-        }
-        return null;
-    }
-
     /** Returns the stored value or null if not set. */
     @Nullable
     private <T> T readFlagValueInternal(String name, FlagSerializer<T> serializer) {
@@ -384,15 +346,6 @@
     }
 
     /** Works just like {@link #eraseFlag(String)} except that it doesn't restart SystemUI. */
-    // TODO(b/265188950): Remove method this once ids are fully deprecated.
-    private void eraseInternal(int id) {
-        // We can't actually "erase" things from settings, but we can set them to empty!
-        mGlobalSettings.putStringForUser(mFlagManager.idToSettingsKey(id), "",
-                UserHandle.USER_CURRENT);
-        Log.i(TAG, "Erase name " + id);
-    }
-
-    /** Works just like {@link #eraseFlag(String)} except that it doesn't restart SystemUI. */
     private void eraseInternal(String name) {
         // We can't actually "erase" things from settings, but we can set them to empty!
         mGlobalSettings.putStringForUser(mFlagManager.nameToSettingsKey(name), "",
@@ -433,7 +386,7 @@
             setFlagValue(flag.getName(), value, BooleanFlagSerializer.INSTANCE);
         } else if (flag instanceof SysPropBooleanFlag) {
             // Store SysProp flags in SystemProperties where they can read by outside parties.
-            mSystemProperties.setBoolean(((SysPropBooleanFlag) flag).getName(), value);
+            mSystemProperties.setBoolean(flag.getName(), value);
             dispatchListenersAndMaybeRestart(
                     flag.getName(),
                     suppressRestart -> restartSystemUI(
@@ -526,7 +479,7 @@
                 }
             } catch (IllegalArgumentException e) {
                 Log.w(TAG,
-                        "Unable to set " + flag.getId() + " of type " + flag.getClass()
+                        "Unable to set " + flag.getName() + " of type " + flag.getClass()
                                 + " to value of type " + (value == null ? null : value.getClass()));
             }
         }
@@ -544,21 +497,18 @@
 
             if (f instanceof ReleasedFlag) {
                 enabled = isEnabled((ReleasedFlag) f);
-                overridden = readBooleanFlagOverride(f.getName()) != null
-                            || readBooleanFlagOverride(f.getId()) != null;
+                overridden = readBooleanFlagOverride(f.getName()) != null;
             } else if (f instanceof UnreleasedFlag) {
                 enabled = isEnabled((UnreleasedFlag) f);
-                overridden = readBooleanFlagOverride(f.getName()) != null
-                            || readBooleanFlagOverride(f.getId()) != null;
+                overridden = readBooleanFlagOverride(f.getName()) != null;
             } else if (f instanceof ResourceBooleanFlag) {
                 enabled = isEnabled((ResourceBooleanFlag) f);
-                overridden = readBooleanFlagOverride(f.getName()) != null
-                            || readBooleanFlagOverride(f.getId()) != null;
+                overridden = readBooleanFlagOverride(f.getName()) != null;
             } else if (f instanceof SysPropBooleanFlag) {
                 // TODO(b/223379190): Teamfood not supported for sysprop flags yet.
                 enabled = isEnabled((SysPropBooleanFlag) f);
                 teamfood = false;
-                overridden = !mSystemProperties.get(((SysPropBooleanFlag) f).getName()).isEmpty();
+                overridden = !mSystemProperties.get(f.getName()).isEmpty();
             } else {
                 // TODO: add support for other flag types.
                 Log.w(TAG, "Unsupported Flag Type. Please file a bug.");
@@ -566,11 +516,9 @@
             }
 
             if (enabled) {
-                return new ReleasedFlag(
-                        f.getId(), f.getName(), f.getNamespace(), teamfood, overridden);
+                return new ReleasedFlag(f.getName(), f.getNamespace(), teamfood, overridden);
             } else {
-                return new UnreleasedFlag(
-                        f.getId(), f.getName(), f.getNamespace(), teamfood, overridden);
+                return new UnreleasedFlag(f.getName(), f.getNamespace(), teamfood, overridden);
             }
         }
     };
diff --git a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsRelease.java b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsRelease.java
index 9d19a7d..e03b438 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsRelease.java
+++ b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsRelease.java
@@ -67,7 +67,7 @@
                         }
                     } else if (mStringCache.containsKey(flag.getName())) {
                         String newValue = value == null ? "" : value;
-                        if (mStringCache.get(flag.getName()) != newValue) {
+                        if (!mStringCache.get(flag.getName()).equals(newValue)) {
                             shouldRestart = true;
                         }
                     } else if (mIntCache.containsKey(flag.getName())) {
@@ -185,14 +185,12 @@
         return mStringCache.get(name);
     }
 
-    @NonNull
     @Override
     public int getInt(@NonNull IntFlag flag) {
         // Fill the cache.
         return getIntInternal(flag.getName(), flag.getDefault());
     }
 
-    @NonNull
     @Override
     public int getInt(@NonNull ResourceIntFlag flag) {
         // Fill the cache.
diff --git a/packages/SystemUI/src/com/android/systemui/flags/FlagCommand.java b/packages/SystemUI/src/com/android/systemui/flags/FlagCommand.java
index daf9429..bd0ed48 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/FlagCommand.java
+++ b/packages/SystemUI/src/com/android/systemui/flags/FlagCommand.java
@@ -219,17 +219,6 @@
         return 0;
     }
 
-    private int flagNameToId(String flagName) {
-        Map<String, Flag<?>> flagFields = FlagsFactory.INSTANCE.getKnownFlags();
-        for (String fieldName : flagFields.keySet()) {
-            if (flagName.equals(fieldName)) {
-                return flagFields.get(fieldName).getId();
-            }
-        }
-
-        return 0;
-    }
-
     private void printKnownFlags(PrintWriter pw) {
         Map<String, Flag<?>> fields = FlagsFactory.INSTANCE.getKnownFlags();
 
diff --git a/packages/SystemUI/src/com/android/systemui/flags/Flags.kt b/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
index a2fbd9c..2fc4574 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
+++ b/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
@@ -36,30 +36,29 @@
  * See [FeatureFlagsDebug] for instructions on flipping the flags via adb.
  */
 object Flags {
-    @JvmField val TEAMFOOD = unreleasedFlag(1, "teamfood")
+    @JvmField val TEAMFOOD = unreleasedFlag("teamfood")
 
     // 100 - notification
     // TODO(b/254512751): Tracking Bug
     val NOTIFICATION_PIPELINE_DEVELOPER_LOGGING =
-        unreleasedFlag(103, "notification_pipeline_developer_logging")
+        unreleasedFlag("notification_pipeline_developer_logging")
 
     // TODO(b/254512732): Tracking Bug
-    @JvmField val NSSL_DEBUG_LINES = unreleasedFlag(105, "nssl_debug_lines")
+    @JvmField val NSSL_DEBUG_LINES = unreleasedFlag("nssl_debug_lines")
 
     // TODO(b/254512505): Tracking Bug
-    @JvmField val NSSL_DEBUG_REMOVE_ANIMATION = unreleasedFlag(106, "nssl_debug_remove_animation")
+    @JvmField val NSSL_DEBUG_REMOVE_ANIMATION = unreleasedFlag("nssl_debug_remove_animation")
 
     // TODO(b/254512624): Tracking Bug
     @JvmField
     val NOTIFICATION_DRAG_TO_CONTENTS =
         resourceBooleanFlag(
-            108,
             R.bool.config_notificationToContents,
             "notification_drag_to_contents"
         )
 
     // TODO(b/254512538): Tracking Bug
-    val INSTANT_VOICE_REPLY = unreleasedFlag(111, "instant_voice_reply")
+    val INSTANT_VOICE_REPLY = unreleasedFlag("instant_voice_reply")
 
     /**
      * This flag controls whether we register a listener for StatsD notification memory reports.
@@ -67,48 +66,47 @@
      * enabled as well.
      */
     val NOTIFICATION_MEMORY_LOGGING_ENABLED =
-            releasedFlag(119, "notification_memory_logging_enabled")
+            releasedFlag("notification_memory_logging_enabled")
 
     // TODO(b/260335638): Tracking Bug
     @JvmField
     val NOTIFICATION_INLINE_REPLY_ANIMATION =
-        unreleasedFlag(174148361, "notification_inline_reply_animation")
+        unreleasedFlag("notification_inline_reply_animation")
 
     /** Makes sure notification panel is updated before the user switch is complete. */
     // TODO(b/278873737): Tracking Bug
     @JvmField
     val LOAD_NOTIFICATIONS_BEFORE_THE_USER_SWITCH_IS_COMPLETE =
-        releasedFlag(278873737, "load_notifications_before_the_user_switch_is_complete")
+        releasedFlag("load_notifications_before_the_user_switch_is_complete")
 
     // TODO(b/277338665): Tracking Bug
     @JvmField
     val NOTIFICATION_SHELF_REFACTOR =
-        unreleasedFlag(271161129, "notification_shelf_refactor", teamfood = true)
+        unreleasedFlag("notification_shelf_refactor", teamfood = true)
 
     // TODO(b/290787599): Tracking Bug
     @JvmField
     val NOTIFICATION_ICON_CONTAINER_REFACTOR =
-        unreleasedFlag(278765923, "notification_icon_container_refactor")
+        unreleasedFlag("notification_icon_container_refactor")
 
     // TODO(b/288326013): Tracking Bug
     @JvmField
     val NOTIFICATION_ASYNC_HYBRID_VIEW_INFLATION =
-        unreleasedFlag(288326013, "notification_async_hybrid_view_inflation", teamfood = false)
+        unreleasedFlag("notification_async_hybrid_view_inflation", teamfood = false)
 
     @JvmField
     val ANIMATED_NOTIFICATION_SHADE_INSETS =
-        releasedFlag(270682168, "animated_notification_shade_insets")
+        releasedFlag("animated_notification_shade_insets")
 
     // TODO(b/268005230): Tracking Bug
     @JvmField
-    val SENSITIVE_REVEAL_ANIM = unreleasedFlag(268005230, "sensitive_reveal_anim", teamfood = true)
+    val SENSITIVE_REVEAL_ANIM = unreleasedFlag("sensitive_reveal_anim", teamfood = true)
 
     // TODO(b/280783617): Tracking Bug
     @Keep
     @JvmField
     val BUILDER_EXTRAS_OVERRIDE =
         sysPropBooleanFlag(
-            128,
             "persist.sysui.notification.builder_extras_override",
             default = true
         )
@@ -117,27 +115,26 @@
     // TODO(b/292213543): Tracking Bug
     @JvmField
     val NOTIFICATION_GROUP_EXPANSION_CHANGE =
-            unreleasedFlag(292213543, "notification_group_expansion_change", teamfood = false)
+            unreleasedFlag("notification_group_expansion_change", teamfood = true)
 
     // 200 - keyguard/lockscreen
     // ** Flag retired **
     // public static final BooleanFlag KEYGUARD_LAYOUT =
-    //         new BooleanFlag(200, true);
+    //         new BooleanFlag(true);
 
     // TODO(b/254512750): Tracking Bug
-    val NEW_UNLOCK_SWIPE_ANIMATION = releasedFlag(202, "new_unlock_swipe_animation")
-    val CHARGING_RIPPLE = resourceBooleanFlag(203, R.bool.flag_charging_ripple, "charging_ripple")
+    val NEW_UNLOCK_SWIPE_ANIMATION = releasedFlag("new_unlock_swipe_animation")
+    val CHARGING_RIPPLE = resourceBooleanFlag(R.bool.flag_charging_ripple, "charging_ripple")
 
     // TODO(b/254512281): Tracking Bug
     @JvmField
     val BOUNCER_USER_SWITCHER =
-        resourceBooleanFlag(204, R.bool.config_enableBouncerUserSwitcher, "bouncer_user_switcher")
+        resourceBooleanFlag(R.bool.config_enableBouncerUserSwitcher, "bouncer_user_switcher")
 
     // TODO(b/254512676): Tracking Bug
     @JvmField
     val LOCKSCREEN_CUSTOM_CLOCKS =
         resourceBooleanFlag(
-            207,
             R.bool.config_enableLockScreenCustomClocks,
             "lockscreen_custom_clocks"
         )
@@ -145,28 +142,28 @@
     // TODO(b/275694445): Tracking Bug
     @JvmField
     val LOCKSCREEN_WITHOUT_SECURE_LOCK_WHEN_DREAMING =
-        releasedFlag(208, "lockscreen_without_secure_lock_when_dreaming")
+        releasedFlag("lockscreen_without_secure_lock_when_dreaming")
 
     // TODO(b/286092087): Tracking Bug
     @JvmField
-    val ENABLE_SYSTEM_UI_DREAM_CONTROLLER = unreleasedFlag(301, "enable_system_ui_dream_controller")
+    val ENABLE_SYSTEM_UI_DREAM_CONTROLLER = unreleasedFlag("enable_system_ui_dream_controller")
 
     // TODO(b/288287730): Tracking Bug
     @JvmField
-    val ENABLE_SYSTEM_UI_DREAM_HOSTING = unreleasedFlag(302, "enable_system_ui_dream_hosting")
+    val ENABLE_SYSTEM_UI_DREAM_HOSTING = unreleasedFlag("enable_system_ui_dream_hosting")
 
     /**
      * Whether the clock on a wide lock screen should use the new "stepping" animation for moving
      * the digits when the clock moves.
      */
-    @JvmField val STEP_CLOCK_ANIMATION = releasedFlag(212, "step_clock_animation")
+    @JvmField val STEP_CLOCK_ANIMATION = releasedFlag("step_clock_animation")
 
     /**
      * Migration from the legacy isDozing/dozeAmount paths to the new KeyguardTransitionRepository
      * will occur in stages. This is one stage of many to come.
      */
     // TODO(b/255607168): Tracking Bug
-    @JvmField val DOZING_MIGRATION_1 = unreleasedFlag(213, "dozing_migration_1")
+    @JvmField val DOZING_MIGRATION_1 = unreleasedFlag("dozing_migration_1")
 
     /**
      * Migrates control of the LightRevealScrim's reveal effect and amount from legacy code to the
@@ -174,80 +171,82 @@
      */
     // TODO(b/281655028): Tracking bug
     @JvmField
-    val LIGHT_REVEAL_MIGRATION = unreleasedFlag(218, "light_reveal_migration", teamfood = false)
+    val LIGHT_REVEAL_MIGRATION = unreleasedFlag("light_reveal_migration", teamfood = false)
 
     /** Flag to control the migration of face auth to modern architecture. */
     // TODO(b/262838215): Tracking bug
-    @JvmField val FACE_AUTH_REFACTOR = unreleasedFlag(220, "face_auth_refactor")
+    @JvmField val FACE_AUTH_REFACTOR = unreleasedFlag("face_auth_refactor")
 
     /** Flag to control the revamp of keyguard biometrics progress animation */
     // TODO(b/244313043): Tracking bug
-    @JvmField val BIOMETRICS_ANIMATION_REVAMP = unreleasedFlag(221, "biometrics_animation_revamp")
+    @JvmField val BIOMETRICS_ANIMATION_REVAMP = unreleasedFlag("biometrics_animation_revamp")
 
     // TODO(b/262780002): Tracking Bug
-    @JvmField val REVAMPED_WALLPAPER_UI = releasedFlag(222, "revamped_wallpaper_ui")
+    @JvmField val REVAMPED_WALLPAPER_UI = releasedFlag("revamped_wallpaper_ui")
 
     // flag for controlling auto pin confirmation and material u shapes in bouncer
     @JvmField
-    val AUTO_PIN_CONFIRMATION = releasedFlag(224, "auto_pin_confirmation", "auto_pin_confirmation")
+    val AUTO_PIN_CONFIRMATION = releasedFlag("auto_pin_confirmation", "auto_pin_confirmation")
 
     // TODO(b/262859270): Tracking Bug
-    @JvmField val FALSING_OFF_FOR_UNFOLDED = releasedFlag(225, "falsing_off_for_unfolded")
+    @JvmField val FALSING_OFF_FOR_UNFOLDED = releasedFlag("falsing_off_for_unfolded")
 
     /** Enables code to show contextual loyalty cards in wallet entrypoints */
     // TODO(b/294110497): Tracking Bug
     @JvmField
     val ENABLE_WALLET_CONTEXTUAL_LOYALTY_CARDS =
-        unreleasedFlag(226, "enable_wallet_contextual_loyalty_cards", teamfood = true)
+        releasedFlag("enable_wallet_contextual_loyalty_cards")
 
     // TODO(b/242908637): Tracking Bug
-    @JvmField val WALLPAPER_FULLSCREEN_PREVIEW = releasedFlag(227, "wallpaper_fullscreen_preview")
+    @JvmField val WALLPAPER_FULLSCREEN_PREVIEW = releasedFlag("wallpaper_fullscreen_preview")
 
     /** Whether the long-press gesture to open wallpaper picker is enabled. */
     // TODO(b/266242192): Tracking Bug
     @JvmField
-    val LOCK_SCREEN_LONG_PRESS_ENABLED = releasedFlag(228, "lock_screen_long_press_enabled")
+    val LOCK_SCREEN_LONG_PRESS_ENABLED = releasedFlag("lock_screen_long_press_enabled")
 
     /** Enables UI updates for AI wallpapers in the wallpaper picker. */
     // TODO(b/267722622): Tracking Bug
-    @JvmField val WALLPAPER_PICKER_UI_FOR_AIWP = releasedFlag(229, "wallpaper_picker_ui_for_aiwp")
+    @JvmField val WALLPAPER_PICKER_UI_FOR_AIWP = releasedFlag("wallpaper_picker_ui_for_aiwp")
 
     /** Whether to use a new data source for intents to run on keyguard dismissal. */
     // TODO(b/275069969): Tracking bug.
     @JvmField
-    val REFACTOR_KEYGUARD_DISMISS_INTENT = unreleasedFlag(231, "refactor_keyguard_dismiss_intent")
+    val REFACTOR_KEYGUARD_DISMISS_INTENT = unreleasedFlag("refactor_keyguard_dismiss_intent")
 
     /** Whether to allow long-press on the lock screen to directly open wallpaper picker. */
     // TODO(b/277220285): Tracking bug.
     @JvmField
     val LOCK_SCREEN_LONG_PRESS_DIRECT_TO_WPP =
-        unreleasedFlag(232, "lock_screen_long_press_directly_opens_wallpaper_picker")
+        unreleasedFlag("lock_screen_long_press_directly_opens_wallpaper_picker")
 
     /** Whether page transition animations in the wallpaper picker are enabled */
     // TODO(b/291710220): Tracking bug.
     @JvmField
     val WALLPAPER_PICKER_PAGE_TRANSITIONS =
-        unreleasedFlag(291710220, "wallpaper_picker_page_transitions")
+        unreleasedFlag("wallpaper_picker_page_transitions")
+
+    /** Add "Apply" button to wall paper picker's grid preview page. */
+    // TODO(b/294866904): Tracking bug.
+    @JvmField
+    val WALLPAPER_PICKER_GRID_APPLY_BUTTON =
+            unreleasedFlag("wallpaper_picker_grid_apply_button")
 
     /** Whether to run the new udfps keyguard refactor code. */
     // TODO(b/279440316): Tracking bug.
     @JvmField
-    val REFACTOR_UDFPS_KEYGUARD_VIEWS = unreleasedFlag(233, "refactor_udfps_keyguard_views")
+    val REFACTOR_UDFPS_KEYGUARD_VIEWS = unreleasedFlag("refactor_udfps_keyguard_views")
 
     /** Provide new auth messages on the bouncer. */
     // TODO(b/277961132): Tracking bug.
-    @JvmField val REVAMPED_BOUNCER_MESSAGES = unreleasedFlag(234, "revamped_bouncer_messages")
+    @JvmField val REVAMPED_BOUNCER_MESSAGES = unreleasedFlag("revamped_bouncer_messages")
 
     /** Whether to delay showing bouncer UI when face auth or active unlock are enrolled. */
     // TODO(b/279794160): Tracking bug.
-    @JvmField val DELAY_BOUNCER = releasedFlag(235, "delay_bouncer")
+    @JvmField val DELAY_BOUNCER = releasedFlag("delay_bouncer")
 
     /** Keyguard Migration */
 
-    /** Migrate the indication area to the new keyguard root view. */
-    // TODO(b/280067944): Tracking bug.
-    @JvmField val MIGRATE_INDICATION_AREA = releasedFlag(236, "migrate_indication_area")
-
     /**
      * Migrate the bottom area to the new keyguard root view. Because there is no such thing as a
      * "bottom area" after this, this also breaks it up into many smaller, modular pieces.
@@ -255,208 +254,233 @@
     // TODO(b/290652751): Tracking bug.
     @JvmField
     val MIGRATE_SPLIT_KEYGUARD_BOTTOM_AREA =
-        unreleasedFlag(290652751, "migrate_split_keyguard_bottom_area")
+        unreleasedFlag("migrate_split_keyguard_bottom_area")
 
     /** Whether to listen for fingerprint authentication over keyguard occluding activities. */
     // TODO(b/283260512): Tracking bug.
-    @JvmField val FP_LISTEN_OCCLUDING_APPS = unreleasedFlag(237, "fp_listen_occluding_apps",
-            teamfood = true)
+    @JvmField val FP_LISTEN_OCCLUDING_APPS = releasedFlag("fp_listen_occluding_apps")
 
     /** Flag meant to guard the talkback fix for the KeyguardIndicationTextView */
     // TODO(b/286563884): Tracking bug
-    @JvmField val KEYGUARD_TALKBACK_FIX = releasedFlag(238, "keyguard_talkback_fix")
+    @JvmField val KEYGUARD_TALKBACK_FIX = releasedFlag("keyguard_talkback_fix")
 
     // TODO(b/287268101): Tracking bug.
-    @JvmField val TRANSIT_CLOCK = releasedFlag(239, "lockscreen_custom_transit_clock")
+    @JvmField val TRANSIT_CLOCK = releasedFlag("lockscreen_custom_transit_clock")
 
     /** Migrate the lock icon view to the new keyguard root view. */
     // TODO(b/286552209): Tracking bug.
-    @JvmField val MIGRATE_LOCK_ICON = unreleasedFlag(240, "migrate_lock_icon")
+    @JvmField val MIGRATE_LOCK_ICON = unreleasedFlag("migrate_lock_icon")
 
     // TODO(b/288276738): Tracking bug.
-    @JvmField val WIDGET_ON_KEYGUARD = unreleasedFlag(241, "widget_on_keyguard")
+    @JvmField val WIDGET_ON_KEYGUARD = unreleasedFlag("widget_on_keyguard")
 
     /** Migrate the NSSL to the a sibling to both the panel and keyguard root view. */
     // TODO(b/288074305): Tracking bug.
-    @JvmField val MIGRATE_NSSL = unreleasedFlag(242, "migrate_nssl")
+    @JvmField val MIGRATE_NSSL = unreleasedFlag("migrate_nssl")
 
     /** Migrate the status view from the notification panel to keyguard root view. */
     // TODO(b/291767565): Tracking bug.
-    @JvmField val MIGRATE_KEYGUARD_STATUS_VIEW = unreleasedFlag(243, "migrate_keyguard_status_view")
+    @JvmField val MIGRATE_KEYGUARD_STATUS_VIEW = unreleasedFlag("migrate_keyguard_status_view")
 
     /** Enables preview loading animation in the wallpaper picker. */
     // TODO(b/274443705): Tracking Bug
     @JvmField
     val WALLPAPER_PICKER_PREVIEW_ANIMATION =
             unreleasedFlag(
-                    244,
-                    "wallpaper_picker_preview_animation"
+                    "wallpaper_picker_preview_animation",
+                teamfood = true
             )
 
+    /**
+     * TODO(b/278086361): Tracking bug
+     * Complete rewrite of the interactions between System UI and Window Manager involving keyguard
+     * state. When enabled, calls to ActivityTaskManagerService from System UI will exclusively
+     * occur from [WmLockscreenVisibilityManager] rather than the legacy KeyguardViewMediator.
+     *
+     * This flag is under development; some types of unlock may not animate properly if you enable
+     * it.
+     */
+    @JvmField
+    val KEYGUARD_WM_STATE_REFACTOR: UnreleasedFlag =
+            unreleasedFlag("keyguard_wm_state_refactor")
+
+    /** Stop running face auth when the display state changes to OFF. */
+    // TODO(b/294221702): Tracking bug.
+    @JvmField val STOP_FACE_AUTH_ON_DISPLAY_OFF = resourceBooleanFlag(
+            R.bool.flag_stop_face_auth_on_display_off, "stop_face_auth_on_display_off")
+
+    /** Flag to disable the face scanning animation pulsing. */
+    // TODO(b/295245791): Tracking bug.
+    @JvmField val STOP_PULSING_FACE_SCANNING_ANIMATION = resourceBooleanFlag(
+            R.bool.flag_stop_pulsing_face_scanning_animation,
+            "stop_pulsing_face_scanning_animation")
+
     // 300 - power menu
     // TODO(b/254512600): Tracking Bug
-    @JvmField val POWER_MENU_LITE = releasedFlag(300, "power_menu_lite")
+    @JvmField val POWER_MENU_LITE = releasedFlag("power_menu_lite")
 
     // 400 - smartspace
 
     // TODO(b/254513100): Tracking Bug
     val SMARTSPACE_SHARED_ELEMENT_TRANSITION_ENABLED =
-        releasedFlag(401, "smartspace_shared_element_transition_enabled")
+        releasedFlag("smartspace_shared_element_transition_enabled")
 
     // TODO(b/258517050): Clean up after the feature is launched.
     @JvmField
     val SMARTSPACE_DATE_WEATHER_DECOUPLED =
-        sysPropBooleanFlag(403, "persist.sysui.ss.dw_decoupled", default = true)
+        sysPropBooleanFlag("persist.sysui.ss.dw_decoupled", default = true)
 
     // TODO(b/270223352): Tracking Bug
     @JvmField
-    val HIDE_SMARTSPACE_ON_DREAM_OVERLAY = releasedFlag(404, "hide_smartspace_on_dream_overlay")
+    val HIDE_SMARTSPACE_ON_DREAM_OVERLAY = releasedFlag("hide_smartspace_on_dream_overlay")
 
     // TODO(b/271460958): Tracking Bug
     @JvmField
     val SHOW_WEATHER_COMPLICATION_ON_DREAM_OVERLAY =
-        releasedFlag(405, "show_weather_complication_on_dream_overlay")
+        releasedFlag("show_weather_complication_on_dream_overlay")
 
     // 500 - quick settings
 
-    val PEOPLE_TILE = resourceBooleanFlag(502, R.bool.flag_conversations, "people_tile")
+    val PEOPLE_TILE = resourceBooleanFlag(R.bool.flag_conversations, "people_tile")
 
     @JvmField
     val QS_USER_DETAIL_SHORTCUT =
         resourceBooleanFlag(
-            503,
             R.bool.flag_lockscreen_qs_user_detail_shortcut,
             "qs_user_detail_shortcut"
         )
 
     @JvmField
-    val QS_PIPELINE_NEW_HOST = unreleasedFlag(504, "qs_pipeline_new_host", teamfood = true)
+    val QS_PIPELINE_NEW_HOST = unreleasedFlag("qs_pipeline_new_host", teamfood = true)
 
     // TODO(b/278068252): Tracking Bug
     @JvmField
-    val QS_PIPELINE_AUTO_ADD = unreleasedFlag(505, "qs_pipeline_auto_add", teamfood = false)
+    val QS_PIPELINE_AUTO_ADD = unreleasedFlag("qs_pipeline_auto_add", teamfood = false)
 
     // TODO(b/254512383): Tracking Bug
     @JvmField
     val FULL_SCREEN_USER_SWITCHER =
         resourceBooleanFlag(
-            506,
             R.bool.config_enableFullscreenUserSwitcher,
             "full_screen_user_switcher"
         )
 
     // TODO(b/244064524): Tracking Bug
-    @JvmField val QS_SECONDARY_DATA_SUB_INFO = releasedFlag(508, "qs_secondary_data_sub_info")
+    @JvmField val QS_SECONDARY_DATA_SUB_INFO = releasedFlag("qs_secondary_data_sub_info")
 
     /** Enables Font Scaling Quick Settings tile */
     // TODO(b/269341316): Tracking Bug
-    @JvmField val ENABLE_FONT_SCALING_TILE = releasedFlag(509, "enable_font_scaling_tile")
+    @JvmField val ENABLE_FONT_SCALING_TILE = releasedFlag("enable_font_scaling_tile")
 
     /** Enables new QS Edit Mode visual refresh */
     // TODO(b/269787742): Tracking Bug
     @JvmField
-    val ENABLE_NEW_QS_EDIT_MODE = unreleasedFlag(510, "enable_new_qs_edit_mode", teamfood = false)
+    val ENABLE_NEW_QS_EDIT_MODE = unreleasedFlag("enable_new_qs_edit_mode", teamfood = false)
 
     // 600- status bar
 
     // TODO(b/265892345): Tracking Bug
-    val PLUG_IN_STATUS_BAR_CHIP = releasedFlag(265892345, "plug_in_status_bar_chip")
+    val PLUG_IN_STATUS_BAR_CHIP = releasedFlag("plug_in_status_bar_chip")
 
     // TODO(b/280426085): Tracking Bug
-    @JvmField val NEW_BLUETOOTH_REPOSITORY = releasedFlag(612, "new_bluetooth_repository")
+    @JvmField val NEW_BLUETOOTH_REPOSITORY = releasedFlag("new_bluetooth_repository")
 
     // TODO(b/292533677): Tracking Bug
-    val WIFI_TRACKER_LIB_FOR_WIFI_ICON =
-        unreleasedFlag(613, "wifi_tracker_lib_for_wifi_icon")
+    val WIFI_TRACKER_LIB_FOR_WIFI_ICON = releasedFlag("wifi_tracker_lib_for_wifi_icon")
 
     // TODO(b/293863612): Tracking Bug
     @JvmField val INCOMPATIBLE_CHARGING_BATTERY_ICON =
-        unreleasedFlag(614, "incompatible_charging_battery_icon")
+        releasedFlag("incompatible_charging_battery_icon")
+
+    // TODO(b/293585143): Tracking Bug
+    val INSTANT_TETHER = unreleasedFlag("instant_tether")
+
+    // TODO(b/294588085): Tracking Bug
+    val WIFI_SECONDARY_NETWORKS = releasedFlag("wifi_secondary_networks")
 
     // 700 - dialer/calls
     // TODO(b/254512734): Tracking Bug
-    val ONGOING_CALL_STATUS_BAR_CHIP = releasedFlag(700, "ongoing_call_status_bar_chip")
+    val ONGOING_CALL_STATUS_BAR_CHIP = releasedFlag("ongoing_call_status_bar_chip")
 
     // TODO(b/254512681): Tracking Bug
-    val ONGOING_CALL_IN_IMMERSIVE = releasedFlag(701, "ongoing_call_in_immersive")
+    val ONGOING_CALL_IN_IMMERSIVE = releasedFlag("ongoing_call_in_immersive")
 
     // TODO(b/254512753): Tracking Bug
-    val ONGOING_CALL_IN_IMMERSIVE_CHIP_TAP = releasedFlag(702, "ongoing_call_in_immersive_chip_tap")
+    val ONGOING_CALL_IN_IMMERSIVE_CHIP_TAP = releasedFlag("ongoing_call_in_immersive_chip_tap")
 
     // 800 - general visual/theme
-    @JvmField val MONET = resourceBooleanFlag(800, R.bool.flag_monet, "monet")
+    @JvmField val MONET = resourceBooleanFlag(R.bool.flag_monet, "monet")
 
     // 801 - region sampling
     // TODO(b/254512848): Tracking Bug
-    val REGION_SAMPLING = unreleasedFlag(801, "region_sampling")
+    val REGION_SAMPLING = unreleasedFlag("region_sampling")
 
     // 803 - screen contents translation
     // TODO(b/254513187): Tracking Bug
-    val SCREEN_CONTENTS_TRANSLATION = unreleasedFlag(803, "screen_contents_translation")
+    val SCREEN_CONTENTS_TRANSLATION = unreleasedFlag("screen_contents_translation")
 
     // 804 - monochromatic themes
-    @JvmField val MONOCHROMATIC_THEME = releasedFlag(804, "monochromatic")
+    @JvmField val MONOCHROMATIC_THEME = releasedFlag("monochromatic")
 
     // TODO(b/293380347): Tracking Bug
-    @JvmField val COLOR_FIDELITY = unreleasedFlag(805, "color_fidelity")
+    @JvmField val COLOR_FIDELITY = unreleasedFlag("color_fidelity")
 
     // 900 - media
     // TODO(b/254512697): Tracking Bug
-    val MEDIA_TAP_TO_TRANSFER = releasedFlag(900, "media_tap_to_transfer")
+    val MEDIA_TAP_TO_TRANSFER = releasedFlag("media_tap_to_transfer")
 
     // TODO(b/254512502): Tracking Bug
-    val MEDIA_SESSION_ACTIONS = unreleasedFlag(901, "media_session_actions")
+    val MEDIA_SESSION_ACTIONS = unreleasedFlag("media_session_actions")
 
     // TODO(b/254512654): Tracking Bug
-    @JvmField val DREAM_MEDIA_COMPLICATION = unreleasedFlag(905, "dream_media_complication")
+    @JvmField val DREAM_MEDIA_COMPLICATION = unreleasedFlag("dream_media_complication")
 
     // TODO(b/254512673): Tracking Bug
-    @JvmField val DREAM_MEDIA_TAP_TO_OPEN = unreleasedFlag(906, "dream_media_tap_to_open")
+    @JvmField val DREAM_MEDIA_TAP_TO_OPEN = unreleasedFlag("dream_media_tap_to_open")
 
     // TODO(b/254513168): Tracking Bug
-    @JvmField val UMO_SURFACE_RIPPLE = releasedFlag(907, "umo_surface_ripple")
+    @JvmField val UMO_SURFACE_RIPPLE = releasedFlag("umo_surface_ripple")
 
     // TODO(b/261734857): Tracking Bug
-    @JvmField val UMO_TURBULENCE_NOISE = releasedFlag(909, "umo_turbulence_noise")
+    @JvmField val UMO_TURBULENCE_NOISE = releasedFlag("umo_turbulence_noise")
 
     // TODO(b/263272731): Tracking Bug
-    val MEDIA_TTT_RECEIVER_SUCCESS_RIPPLE = releasedFlag(910, "media_ttt_receiver_success_ripple")
+    val MEDIA_TTT_RECEIVER_SUCCESS_RIPPLE = releasedFlag("media_ttt_receiver_success_ripple")
 
     // TODO(b/266157412): Tracking Bug
-    val MEDIA_RETAIN_SESSIONS = unreleasedFlag(913, "media_retain_sessions")
+    val MEDIA_RETAIN_SESSIONS = unreleasedFlag("media_retain_sessions")
 
     // TODO(b/267007629): Tracking Bug
-    val MEDIA_RESUME_PROGRESS = releasedFlag(915, "media_resume_progress")
+    val MEDIA_RESUME_PROGRESS = releasedFlag("media_resume_progress")
 
     // TODO(b/267166152) : Tracking Bug
-    val MEDIA_RETAIN_RECOMMENDATIONS = unreleasedFlag(916, "media_retain_recommendations")
+    val MEDIA_RETAIN_RECOMMENDATIONS = unreleasedFlag("media_retain_recommendations")
 
     // TODO(b/270437894): Tracking Bug
-    val MEDIA_REMOTE_RESUME = unreleasedFlag(917, "media_remote_resume")
+    val MEDIA_REMOTE_RESUME = unreleasedFlag("media_remote_resume")
 
     // 1000 - dock
-    val SIMULATE_DOCK_THROUGH_CHARGING = releasedFlag(1000, "simulate_dock_through_charging")
+    val SIMULATE_DOCK_THROUGH_CHARGING = releasedFlag("simulate_dock_through_charging")
 
     // TODO(b/254512758): Tracking Bug
-    @JvmField val ROUNDED_BOX_RIPPLE = releasedFlag(1002, "rounded_box_ripple")
+    @JvmField val ROUNDED_BOX_RIPPLE = releasedFlag("rounded_box_ripple")
 
     // TODO(b/273509374): Tracking Bug
     @JvmField
     val ALWAYS_SHOW_HOME_CONTROLS_ON_DREAMS =
-        releasedFlag(1006, "always_show_home_controls_on_dreams")
+        releasedFlag("always_show_home_controls_on_dreams")
 
     // 1100 - windowing
     @Keep
     @JvmField
     val WM_ENABLE_SHELL_TRANSITIONS =
-        sysPropBooleanFlag(1100, "persist.wm.debug.shell_transit", default = true)
+        sysPropBooleanFlag("persist.wm.debug.shell_transit", default = true)
 
     // TODO(b/254513207): Tracking Bug
     @Keep
     @JvmField
     val WM_ENABLE_PARTIAL_SCREEN_SHARING =
         unreleasedFlag(
-            1102,
             name = "record_task_content",
             namespace = DeviceConfig.NAMESPACE_WINDOW_MANAGER,
             teamfood = true
@@ -466,50 +490,44 @@
     @Keep
     @JvmField
     val HIDE_NAVBAR_WINDOW =
-        sysPropBooleanFlag(1103, "persist.wm.debug.hide_navbar_window", default = false)
+        sysPropBooleanFlag("persist.wm.debug.hide_navbar_window", default = false)
 
     @Keep
     @JvmField
     val WM_DESKTOP_WINDOWING =
-        sysPropBooleanFlag(1104, "persist.wm.debug.desktop_mode", default = false)
+        sysPropBooleanFlag("persist.wm.debug.desktop_mode", default = false)
 
     @Keep
     @JvmField
     val WM_CAPTION_ON_SHELL =
-        sysPropBooleanFlag(1105, "persist.wm.debug.caption_on_shell", default = true)
+        sysPropBooleanFlag("persist.wm.debug.caption_on_shell", default = true)
 
     @Keep
     @JvmField
     val ENABLE_FLING_TO_DISMISS_BUBBLE =
-        sysPropBooleanFlag(1108, "persist.wm.debug.fling_to_dismiss_bubble", default = true)
+        sysPropBooleanFlag("persist.wm.debug.fling_to_dismiss_bubble", default = true)
 
     @Keep
     @JvmField
     val ENABLE_FLING_TO_DISMISS_PIP =
-        sysPropBooleanFlag(1109, "persist.wm.debug.fling_to_dismiss_pip", default = true)
-
-    @Keep
-    @JvmField
-    val ENABLE_PIP_KEEP_CLEAR_ALGORITHM =
-        sysPropBooleanFlag(1110, "persist.wm.debug.enable_pip_keep_clear_algorithm", default = true)
+        sysPropBooleanFlag("persist.wm.debug.fling_to_dismiss_pip", default = true)
 
     // TODO(b/256873975): Tracking Bug
     @JvmField
     @Keep
-    val WM_BUBBLE_BAR = sysPropBooleanFlag(1111, "persist.wm.debug.bubble_bar", default = false)
+    val WM_BUBBLE_BAR = sysPropBooleanFlag("persist.wm.debug.bubble_bar", default = false)
 
     // TODO(b/260271148): Tracking bug
     @Keep
     @JvmField
     val WM_DESKTOP_WINDOWING_2 =
-        sysPropBooleanFlag(1112, "persist.wm.debug.desktop_mode_2", default = false)
+        sysPropBooleanFlag("persist.wm.debug.desktop_mode_2", default = false)
 
     // TODO(b/254513207): Tracking Bug to delete
     @Keep
     @JvmField
     val WM_ENABLE_PARTIAL_SCREEN_SHARING_ENTERPRISE_POLICIES =
         unreleasedFlag(
-            1113,
             name = "screen_record_enterprise_policies",
             namespace = DeviceConfig.NAMESPACE_WINDOW_MANAGER,
             teamfood = false
@@ -519,238 +537,250 @@
     @Keep
     @JvmField
     val ENABLE_PIP_SIZE_LARGE_SCREEN =
-        sysPropBooleanFlag(1114, "persist.wm.debug.enable_pip_size_large_screen", default = true)
+        sysPropBooleanFlag("persist.wm.debug.enable_pip_size_large_screen", default = true)
 
-    // TODO(b/265998256): Tracking bug
-    @Keep
+
+    // TODO(b/293252410) : Tracking Bug
     @JvmField
-    val ENABLE_PIP_APP_ICON_OVERLAY =
-        sysPropBooleanFlag(1115, "persist.wm.debug.enable_pip_app_icon_overlay", default = true)
+    val LOCKSCREEN_ENABLE_LANDSCAPE =
+            unreleasedFlag("lockscreen.enable_landscape")
 
     // TODO(b/273443374): Tracking Bug
     @Keep
     @JvmField
     val LOCKSCREEN_LIVE_WALLPAPER =
-        sysPropBooleanFlag(1117, "persist.wm.debug.lockscreen_live_wallpaper", default = true)
+        sysPropBooleanFlag("persist.wm.debug.lockscreen_live_wallpaper", default = true)
 
     // TODO(b/281648899): Tracking bug
     @Keep
     @JvmField
     val WALLPAPER_MULTI_CROP =
-        sysPropBooleanFlag(1118, "persist.wm.debug.wallpaper_multi_crop", default = false)
+        sysPropBooleanFlag("persist.wm.debug.wallpaper_multi_crop", default = false)
 
     // TODO(b/290220798): Tracking Bug
     @Keep
     @JvmField
     val ENABLE_PIP2_IMPLEMENTATION =
-        sysPropBooleanFlag(1119, "persist.wm.debug.enable_pip2_implementation", default = false)
+        sysPropBooleanFlag("persist.wm.debug.enable_pip2_implementation", default = false)
 
     // 1200 - predictive back
     @Keep
     @JvmField
     val WM_ENABLE_PREDICTIVE_BACK =
-        sysPropBooleanFlag(1200, "persist.wm.debug.predictive_back", default = true)
+        sysPropBooleanFlag("persist.wm.debug.predictive_back", default = true)
 
     @Keep
     @JvmField
     val WM_ENABLE_PREDICTIVE_BACK_ANIM =
-        sysPropBooleanFlag(1201, "persist.wm.debug.predictive_back_anim", default = true)
+        sysPropBooleanFlag("persist.wm.debug.predictive_back_anim", default = true)
 
     @Keep
     @JvmField
     val WM_ALWAYS_ENFORCE_PREDICTIVE_BACK =
-        sysPropBooleanFlag(1202, "persist.wm.debug.predictive_back_always_enforce", default = false)
+        sysPropBooleanFlag("persist.wm.debug.predictive_back_always_enforce", default = false)
 
     // TODO(b/254512728): Tracking Bug
-    @JvmField val NEW_BACK_AFFORDANCE = releasedFlag(1203, "new_back_affordance")
+    @JvmField val NEW_BACK_AFFORDANCE = releasedFlag("new_back_affordance")
 
     // TODO(b/255854141): Tracking Bug
     @JvmField
     val WM_ENABLE_PREDICTIVE_BACK_SYSUI =
-        unreleasedFlag(1204, "persist.wm.debug.predictive_back_sysui_enable", teamfood = true)
+        unreleasedFlag("persist.wm.debug.predictive_back_sysui_enable", teamfood = true)
 
     // TODO(b/270987164): Tracking Bug
-    @JvmField val TRACKPAD_GESTURE_FEATURES = releasedFlag(1205, "trackpad_gesture_features")
+    @JvmField val TRACKPAD_GESTURE_FEATURES = releasedFlag("trackpad_gesture_features")
 
     // TODO(b/263826204): Tracking Bug
     @JvmField
     val WM_ENABLE_PREDICTIVE_BACK_BOUNCER_ANIM =
-        unreleasedFlag(1206, "persist.wm.debug.predictive_back_bouncer_anim", teamfood = true)
+        unreleasedFlag("persist.wm.debug.predictive_back_bouncer_anim", teamfood = true)
 
     // TODO(b/238475428): Tracking Bug
     @JvmField
     val WM_SHADE_ALLOW_BACK_GESTURE =
-        sysPropBooleanFlag(1207, "persist.wm.debug.shade_allow_back_gesture", default = false)
+        sysPropBooleanFlag("persist.wm.debug.shade_allow_back_gesture", default = false)
 
     // TODO(b/238475428): Tracking Bug
     @JvmField
     val WM_SHADE_ANIMATE_BACK_GESTURE =
-        unreleasedFlag(1208, "persist.wm.debug.shade_animate_back_gesture", teamfood = false)
+        unreleasedFlag("persist.wm.debug.shade_animate_back_gesture", teamfood = false)
 
     // TODO(b/265639042): Tracking Bug
     @JvmField
     val WM_ENABLE_PREDICTIVE_BACK_QS_DIALOG_ANIM =
-        unreleasedFlag(1209, "persist.wm.debug.predictive_back_qs_dialog_anim", teamfood = true)
+        unreleasedFlag("persist.wm.debug.predictive_back_qs_dialog_anim", teamfood = true)
 
     // TODO(b/273800936): Tracking Bug
-    @JvmField val TRACKPAD_GESTURE_COMMON = releasedFlag(1210, "trackpad_gesture_common")
+    @JvmField val TRACKPAD_GESTURE_COMMON = releasedFlag("trackpad_gesture_common")
 
     // 1300 - screenshots
     // TODO(b/264916608): Tracking Bug
-    @JvmField val SCREENSHOT_METADATA = unreleasedFlag(1302, "screenshot_metadata")
+    @JvmField val SCREENSHOT_METADATA = unreleasedFlag("screenshot_metadata")
 
     // TODO(b/266955521): Tracking bug
-    @JvmField val SCREENSHOT_DETECTION = releasedFlag(1303, "screenshot_detection")
+    @JvmField val SCREENSHOT_DETECTION = releasedFlag("screenshot_detection")
 
     // TODO(b/251205791): Tracking Bug
-    @JvmField val SCREENSHOT_APP_CLIPS = releasedFlag(1304, "screenshot_app_clips")
+    @JvmField val SCREENSHOT_APP_CLIPS = releasedFlag("screenshot_app_clips")
 
     // 1400 - columbus
     // TODO(b/254512756): Tracking Bug
-    val QUICK_TAP_IN_PCC = releasedFlag(1400, "quick_tap_in_pcc")
+    val QUICK_TAP_IN_PCC = releasedFlag("quick_tap_in_pcc")
 
     // TODO(b/261979569): Tracking Bug
     val QUICK_TAP_FLOW_FRAMEWORK =
-        unreleasedFlag(1401, "quick_tap_flow_framework", teamfood = false)
+        unreleasedFlag("quick_tap_flow_framework", teamfood = false)
 
     // 1500 - chooser aka sharesheet
 
     // 1700 - clipboard
-    @JvmField val CLIPBOARD_REMOTE_BEHAVIOR = releasedFlag(1701, "clipboard_remote_behavior")
+    @JvmField val CLIPBOARD_REMOTE_BEHAVIOR = releasedFlag("clipboard_remote_behavior")
     // TODO(b/278714186) Tracking Bug
     @JvmField
-    val CLIPBOARD_IMAGE_TIMEOUT = unreleasedFlag(1702, "clipboard_image_timeout", teamfood = true)
+    val CLIPBOARD_IMAGE_TIMEOUT = unreleasedFlag("clipboard_image_timeout", teamfood = true)
     // TODO(b/279405451): Tracking Bug
     @JvmField
     val CLIPBOARD_SHARED_TRANSITIONS =
-            unreleasedFlag(1703, "clipboard_shared_transitions", teamfood = true)
+            unreleasedFlag("clipboard_shared_transitions", teamfood = true)
 
     // TODO(b/283300105): Tracking Bug
-    @JvmField val SCENE_CONTAINER = unreleasedFlag(1802, "scene_container")
+    @JvmField val SCENE_CONTAINER = unreleasedFlag("scene_container")
 
     // 1900
-    @JvmField val NOTE_TASKS = releasedFlag(1900, "keycode_flag")
+    @JvmField val NOTE_TASKS = releasedFlag("keycode_flag")
 
     // 2000 - device controls
-    @JvmField val APP_PANELS_ALL_APPS_ALLOWED = releasedFlag(2001, "app_panels_all_apps_allowed")
+    @JvmField val APP_PANELS_ALL_APPS_ALLOWED = releasedFlag("app_panels_all_apps_allowed")
 
     // 2200 - biometrics (udfps, sfps, BiometricPrompt, etc.)
     // TODO(b/259264861): Tracking Bug
-    @JvmField val UDFPS_NEW_TOUCH_DETECTION = releasedFlag(2200, "udfps_new_touch_detection")
-    @JvmField val UDFPS_ELLIPSE_DETECTION = releasedFlag(2201, "udfps_ellipse_detection")
+    @JvmField val UDFPS_NEW_TOUCH_DETECTION = releasedFlag("udfps_new_touch_detection")
+    @JvmField val UDFPS_ELLIPSE_DETECTION = releasedFlag("udfps_ellipse_detection")
     // TODO(b/278622168): Tracking Bug
-    @JvmField val BIOMETRIC_BP_STRONG = releasedFlag(2202, "biometric_bp_strong")
+    @JvmField val BIOMETRIC_BP_STRONG = releasedFlag("biometric_bp_strong")
 
     // 2300 - stylus
-    @JvmField val TRACK_STYLUS_EVER_USED = releasedFlag(2300, "track_stylus_ever_used")
-    @JvmField val ENABLE_STYLUS_CHARGING_UI = releasedFlag(2301, "enable_stylus_charging_ui")
+    @JvmField val TRACK_STYLUS_EVER_USED = releasedFlag("track_stylus_ever_used")
+    @JvmField val ENABLE_STYLUS_CHARGING_UI = releasedFlag("enable_stylus_charging_ui")
     @JvmField
-    val ENABLE_USI_BATTERY_NOTIFICATIONS = releasedFlag(2302, "enable_usi_battery_notifications")
-    @JvmField val ENABLE_STYLUS_EDUCATION = releasedFlag(2303, "enable_stylus_education")
+    val ENABLE_USI_BATTERY_NOTIFICATIONS = releasedFlag("enable_usi_battery_notifications")
+    @JvmField val ENABLE_STYLUS_EDUCATION = releasedFlag("enable_stylus_education")
 
     // 2400 - performance tools and debugging info
     // TODO(b/238923086): Tracking Bug
     @JvmField
     val WARN_ON_BLOCKING_BINDER_TRANSACTIONS =
-        unreleasedFlag(2400, "warn_on_blocking_binder_transactions")
+        unreleasedFlag("warn_on_blocking_binder_transactions")
 
     // TODO(b/283071711): Tracking bug
     @JvmField
     val TRIM_RESOURCES_WITH_BACKGROUND_TRIM_AT_LOCK =
-        unreleasedFlag(2401, "trim_resources_with_background_trim_on_lock")
+        unreleasedFlag("trim_resources_with_background_trim_on_lock")
 
     // TODO:(b/283203305): Tracking bug
-    @JvmField val TRIM_FONT_CACHES_AT_UNLOCK = unreleasedFlag(2402, "trim_font_caches_on_unlock")
+    @JvmField val TRIM_FONT_CACHES_AT_UNLOCK = unreleasedFlag("trim_font_caches_on_unlock")
 
     // 2700 - unfold transitions
     // TODO(b/265764985): Tracking Bug
     @Keep
     @JvmField
     val ENABLE_DARK_VIGNETTE_WHEN_FOLDING =
-        unreleasedFlag(2700, "enable_dark_vignette_when_folding")
+        unreleasedFlag("enable_dark_vignette_when_folding")
 
     // TODO(b/265764985): Tracking Bug
     @Keep
     @JvmField
     val ENABLE_UNFOLD_STATUS_BAR_ANIMATIONS =
-        unreleasedFlag(2701, "enable_unfold_status_bar_animations")
+        unreleasedFlag("enable_unfold_status_bar_animations")
 
     // TODO(b259590361): Tracking bug
-    val EXPERIMENTAL_FLAG = unreleasedFlag(2, "exp_flag_release")
+    val EXPERIMENTAL_FLAG = unreleasedFlag("exp_flag_release")
 
     // 2600 - keyboard
     // TODO(b/259352579): Tracking Bug
-    @JvmField val SHORTCUT_LIST_SEARCH_LAYOUT = releasedFlag(2600, "shortcut_list_search_layout")
+    @JvmField val SHORTCUT_LIST_SEARCH_LAYOUT = releasedFlag("shortcut_list_search_layout")
 
     // TODO(b/259428678): Tracking Bug
-    @JvmField val KEYBOARD_BACKLIGHT_INDICATOR = releasedFlag(2601, "keyboard_backlight_indicator")
+    @JvmField val KEYBOARD_BACKLIGHT_INDICATOR = releasedFlag("keyboard_backlight_indicator")
 
     // TODO(b/277192623): Tracking Bug
-    @JvmField val KEYBOARD_EDUCATION = unreleasedFlag(2603, "keyboard_education", teamfood = false)
+    @JvmField val KEYBOARD_EDUCATION = unreleasedFlag("keyboard_education", teamfood = false)
 
     // TODO(b/277201412): Tracking Bug
     @JvmField
-    val SPLIT_SHADE_SUBPIXEL_OPTIMIZATION = releasedFlag(2805, "split_shade_subpixel_optimization")
+    val SPLIT_SHADE_SUBPIXEL_OPTIMIZATION = releasedFlag("split_shade_subpixel_optimization")
 
     // TODO(b/288868056): Tracking Bug
     @JvmField
-    val PARTIAL_SCREEN_SHARING_TASK_SWITCHER = unreleasedFlag(288868056, "pss_task_switcher")
+    val PARTIAL_SCREEN_SHARING_TASK_SWITCHER = unreleasedFlag("pss_task_switcher")
 
     // TODO(b/278761837): Tracking Bug
-    @JvmField val USE_NEW_ACTIVITY_STARTER = releasedFlag(2801, name = "use_new_activity_starter")
+    @JvmField val USE_NEW_ACTIVITY_STARTER = releasedFlag(name = "use_new_activity_starter")
 
     // 2900 - Zero Jank fixes. Naming convention is: zj_<bug number>_<cuj name>
 
     // TODO:(b/285623104): Tracking bug
     @JvmField
     val ZJ_285570694_LOCKSCREEN_TRANSITION_FROM_AOD =
-        releasedFlag(2900, "zj_285570694_lockscreen_transition_from_aod")
+        releasedFlag("zj_285570694_lockscreen_transition_from_aod")
 
     // 3000 - dream
     // TODO(b/285059790) : Tracking Bug
     @JvmField
     val LOCKSCREEN_WALLPAPER_DREAM_ENABLED =
-        unreleasedFlag(3000, name = "enable_lockscreen_wallpaper_dream", teamfood = true)
+        unreleasedFlag(name = "enable_lockscreen_wallpaper_dream", teamfood = true)
 
     // TODO(b/283084712): Tracking Bug
-    @JvmField val IMPROVED_HUN_ANIMATIONS = unreleasedFlag(283084712, "improved_hun_animations")
+    @JvmField val IMPROVED_HUN_ANIMATIONS = unreleasedFlag("improved_hun_animations")
 
     // TODO(b/283447257): Tracking bug
     @JvmField
     val BIGPICTURE_NOTIFICATION_LAZY_LOADING =
-        unreleasedFlag(283447257, "bigpicture_notification_lazy_loading")
+        unreleasedFlag("bigpicture_notification_lazy_loading")
 
     // TODO(b/292062937): Tracking bug
     @JvmField
     val NOTIFICATION_CLEARABLE_REFACTOR =
-            unreleasedFlag(292062937, "notification_clearable_refactor")
+            unreleasedFlag("notification_clearable_refactor")
 
     // TODO(b/283740863): Tracking Bug
     @JvmField
     val ENABLE_NEW_PRIVACY_DIALOG =
-        unreleasedFlag(283740863, "enable_new_privacy_dialog", teamfood = true)
+        unreleasedFlag("enable_new_privacy_dialog", teamfood = true)
 
     // TODO(b/289573946): Tracking Bug
-    @JvmField val PRECOMPUTED_TEXT = unreleasedFlag(289573946, "precomputed_text")
+    @JvmField val PRECOMPUTED_TEXT = unreleasedFlag("precomputed_text")
 
     // 2900 - CentralSurfaces-related flags
 
     // TODO(b/285174336): Tracking Bug
     @JvmField
     val USE_REPOS_FOR_BOUNCER_SHOWING =
-        unreleasedFlag(2900, "use_repos_for_bouncer_showing", teamfood = true)
+        unreleasedFlag("use_repos_for_bouncer_showing", teamfood = true)
 
     // 3100 - Haptic interactions
 
     // TODO(b/290213663): Tracking Bug
     @JvmField
-    val ONE_WAY_HAPTICS_API_MIGRATION = unreleasedFlag(3100, "oneway_haptics_api_migration")
+    val ONE_WAY_HAPTICS_API_MIGRATION = unreleasedFlag("oneway_haptics_api_migration")
+
+    /** TODO(b/296223317): Enables the new keyguard presentation containing a clock. */
+    @JvmField
+    val ENABLE_CLOCK_KEYGUARD_PRESENTATION = unreleasedFlag("enable_clock_keyguard_presentation")
 
     /** Enable the Compose implementation of the PeopleSpaceActivity. */
     @JvmField
-    val COMPOSE_PEOPLE_SPACE = unreleasedFlag(293570761, "compose_people_space")
+    val COMPOSE_PEOPLE_SPACE = unreleasedFlag("compose_people_space")
 
     /** Enable the Compose implementation of the Quick Settings footer actions. */
     @JvmField
-    val COMPOSE_QS_FOOTER_ACTIONS = unreleasedFlag(293569320, "compose_qs_footer_actions")
+    val COMPOSE_QS_FOOTER_ACTIONS = unreleasedFlag("compose_qs_footer_actions")
+
+    /** Enable the share wifi button in Quick Settings internet dialog. */
+    @JvmField
+    val SHARE_WIFI_QS_BUTTON = unreleasedFlag("share_wifi_qs_button")
+
+    /** Enable haptic slider component in the brightness slider */
+    @JvmField
+    val HAPTIC_BRIGHTNESS_SLIDER = unreleasedFlag("haptic_brightness_slider")
 }
diff --git a/packages/SystemUI/src/com/android/systemui/keyboard/backlight/ui/view/KeyboardBacklightDialog.kt b/packages/SystemUI/src/com/android/systemui/keyboard/backlight/ui/view/KeyboardBacklightDialog.kt
index 7078341..b5b56b2 100644
--- a/packages/SystemUI/src/com/android/systemui/keyboard/backlight/ui/view/KeyboardBacklightDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyboard/backlight/ui/view/KeyboardBacklightDialog.kt
@@ -161,7 +161,7 @@
     }
 
     private fun updateIconTile() {
-        val iconTile = rootView.findViewById(BACKLIGHT_ICON_ID) as ImageView
+        val iconTile = rootView.requireViewById(BACKLIGHT_ICON_ID) as ImageView
         val backgroundDrawable = iconTile.background as ShapeDrawable
         if (currentLevel == 0) {
             iconTile.setColorFilter(dimmedIconColor)
diff --git a/packages/SystemUI/src/com/android/systemui/keyevent/domain/interactor/KeyEventInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyevent/domain/interactor/KeyEventInteractor.kt
new file mode 100644
index 0000000..3f2f67d
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyevent/domain/interactor/KeyEventInteractor.kt
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyevent.domain.interactor
+
+import android.view.KeyEvent
+import com.android.systemui.back.domain.interactor.BackActionInteractor
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyguard.domain.interactor.KeyguardKeyEventInteractor
+import javax.inject.Inject
+
+/**
+ * Sends key events to the appropriate interactors and then acts upon key events that haven't
+ * already been handled but should be handled by SystemUI.
+ */
+@SysUISingleton
+class KeyEventInteractor
+@Inject
+constructor(
+    private val backActionInteractor: BackActionInteractor,
+    private val keyguardKeyEventInteractor: KeyguardKeyEventInteractor,
+) {
+    fun dispatchKeyEvent(event: KeyEvent): Boolean {
+        if (keyguardKeyEventInteractor.dispatchKeyEvent(event)) {
+            return true
+        }
+
+        when (event.keyCode) {
+            KeyEvent.KEYCODE_BACK -> {
+                if (event.handleAction()) {
+                    backActionInteractor.onBackRequested()
+                }
+                return true
+            }
+        }
+        return false
+    }
+
+    fun interceptMediaKey(event: KeyEvent): Boolean {
+        return keyguardKeyEventInteractor.interceptMediaKey(event)
+    }
+
+    fun dispatchKeyEventPreIme(event: KeyEvent): Boolean {
+        return keyguardKeyEventInteractor.dispatchKeyEventPreIme(event)
+    }
+
+    companion object {
+        // Most actions shouldn't be handled on the down event and instead handled on subsequent
+        // key events like ACTION_UP.
+        fun KeyEvent.handleAction(): Boolean {
+            return action != KeyEvent.ACTION_DOWN
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
index e6053fb..9d2771e 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
@@ -73,6 +73,14 @@
 import com.android.internal.policy.IKeyguardStateCallback;
 import com.android.keyguard.mediator.ScreenOnCoordinator;
 import com.android.systemui.SystemUIApplication;
+import com.android.systemui.dagger.qualifiers.Application;
+import com.android.systemui.flags.FeatureFlags;
+import com.android.systemui.flags.Flags;
+import com.android.systemui.keyguard.ui.binder.KeyguardSurfaceBehindParamsApplier;
+import com.android.systemui.keyguard.ui.binder.KeyguardSurfaceBehindViewBinder;
+import com.android.systemui.keyguard.ui.binder.WindowManagerLockscreenVisibilityViewBinder;
+import com.android.systemui.keyguard.ui.viewmodel.KeyguardSurfaceBehindViewModel;
+import com.android.systemui.keyguard.ui.viewmodel.WindowManagerLockscreenVisibilityViewModel;
 import com.android.systemui.settings.DisplayTracker;
 import com.android.wm.shell.transition.ShellTransitions;
 import com.android.wm.shell.transition.Transitions;
@@ -85,10 +93,13 @@
 
 import javax.inject.Inject;
 
+import kotlinx.coroutines.CoroutineScope;
+
 public class KeyguardService extends Service {
     static final String TAG = "KeyguardService";
     static final String PERMISSION = android.Manifest.permission.CONTROL_KEYGUARD;
 
+    private final FeatureFlags mFlags;
     private final KeyguardViewMediator mKeyguardViewMediator;
     private final KeyguardLifecyclesDispatcher mKeyguardLifecyclesDispatcher;
     private final ScreenOnCoordinator mScreenOnCoordinator;
@@ -291,13 +302,33 @@
                            KeyguardLifecyclesDispatcher keyguardLifecyclesDispatcher,
                            ScreenOnCoordinator screenOnCoordinator,
                            ShellTransitions shellTransitions,
-                           DisplayTracker displayTracker) {
+                           DisplayTracker displayTracker,
+                           WindowManagerLockscreenVisibilityViewModel
+                                   wmLockscreenVisibilityViewModel,
+                           WindowManagerLockscreenVisibilityManager wmLockscreenVisibilityManager,
+                           KeyguardSurfaceBehindViewModel keyguardSurfaceBehindViewModel,
+                           KeyguardSurfaceBehindParamsApplier keyguardSurfaceBehindAnimator,
+                           @Application CoroutineScope scope,
+                           FeatureFlags featureFlags) {
         super();
         mKeyguardViewMediator = keyguardViewMediator;
         mKeyguardLifecyclesDispatcher = keyguardLifecyclesDispatcher;
         mScreenOnCoordinator = screenOnCoordinator;
         mShellTransitions = shellTransitions;
         mDisplayTracker = displayTracker;
+        mFlags = featureFlags;
+
+        if (mFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+            WindowManagerLockscreenVisibilityViewBinder.bind(
+                    wmLockscreenVisibilityViewModel,
+                    wmLockscreenVisibilityManager,
+                    scope);
+
+            KeyguardSurfaceBehindViewBinder.bind(
+                    keyguardSurfaceBehindViewModel,
+                    keyguardSurfaceBehindAnimator,
+                    scope);
+        }
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt
index 489d2ab..ff74050 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt
@@ -403,7 +403,9 @@
      * the device.
      */
     fun canPerformInWindowLauncherAnimations(): Boolean {
-        return isNexusLauncherUnderneath() &&
+        // TODO(b/278086361): Refactor in-window animations.
+        return !featureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR) &&
+                isNexusLauncherUnderneath() &&
                 // If the launcher is underneath, but we're about to launch an activity, don't do
                 // the animations since they won't be visible.
                 !notificationShadeWindowController.isLaunchingActivity &&
@@ -847,54 +849,57 @@
         }
 
         surfaceBehindRemoteAnimationTargets?.forEach { surfaceBehindRemoteAnimationTarget ->
-            val surfaceHeight: Int = surfaceBehindRemoteAnimationTarget.screenSpaceBounds.height()
+            if (!featureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                val surfaceHeight: Int =
+                        surfaceBehindRemoteAnimationTarget.screenSpaceBounds.height()
 
-            var scaleFactor = (SURFACE_BEHIND_START_SCALE_FACTOR +
-                    (1f - SURFACE_BEHIND_START_SCALE_FACTOR) *
-                    MathUtils.clamp(amount, 0f, 1f))
+                var scaleFactor = (SURFACE_BEHIND_START_SCALE_FACTOR +
+                        (1f - SURFACE_BEHIND_START_SCALE_FACTOR) *
+                        MathUtils.clamp(amount, 0f, 1f))
 
-            // If we're dismissing via swipe to the Launcher, we'll play in-window scale animations,
-            // so don't also scale the window.
-            if (keyguardStateController.isDismissingFromSwipe &&
-                    willUnlockWithInWindowLauncherAnimations) {
-                scaleFactor = 1f
-            }
-
-            // Translate up from the bottom.
-            surfaceBehindMatrix.setTranslate(
-                    surfaceBehindRemoteAnimationTarget.screenSpaceBounds.left.toFloat(),
-                    surfaceBehindRemoteAnimationTarget.screenSpaceBounds.top.toFloat() +
-                            surfaceHeight * SURFACE_BEHIND_START_TRANSLATION_Y * (1f - amount)
-            )
-
-            // Scale up from a point at the center-bottom of the surface.
-            surfaceBehindMatrix.postScale(
-                    scaleFactor,
-                    scaleFactor,
-                    keyguardViewController.viewRootImpl.width / 2f,
-                    surfaceHeight * SURFACE_BEHIND_SCALE_PIVOT_Y
-            )
-
-            // SyncRtSurfaceTransactionApplier cannot apply transaction when the target view is
-            // unable to draw
-            val sc: SurfaceControl? = surfaceBehindRemoteAnimationTarget.leash
-            if (keyguardViewController.viewRootImpl.view?.visibility != View.VISIBLE &&
-                    sc?.isValid == true) {
-                with(SurfaceControl.Transaction()) {
-                    setMatrix(sc, surfaceBehindMatrix, tmpFloat)
-                    setCornerRadius(sc, roundedCornerRadius)
-                    setAlpha(sc, animationAlpha)
-                    apply()
+                // If we're dismissing via swipe to the Launcher, we'll play in-window scale
+                // animations, so don't also scale the window.
+                if (keyguardStateController.isDismissingFromSwipe &&
+                        willUnlockWithInWindowLauncherAnimations) {
+                    scaleFactor = 1f
                 }
-            } else {
-                applyParamsToSurface(
-                        SyncRtSurfaceTransactionApplier.SurfaceParams.Builder(
-                            surfaceBehindRemoteAnimationTarget.leash)
-                            .withMatrix(surfaceBehindMatrix)
-                            .withCornerRadius(roundedCornerRadius)
-                            .withAlpha(animationAlpha)
-                            .build()
+
+                // Translate up from the bottom.
+                surfaceBehindMatrix.setTranslate(
+                        surfaceBehindRemoteAnimationTarget.screenSpaceBounds.left.toFloat(),
+                        surfaceBehindRemoteAnimationTarget.screenSpaceBounds.top.toFloat() +
+                                surfaceHeight * SURFACE_BEHIND_START_TRANSLATION_Y * (1f - amount)
                 )
+
+                // Scale up from a point at the center-bottom of the surface.
+                surfaceBehindMatrix.postScale(
+                        scaleFactor,
+                        scaleFactor,
+                        keyguardViewController.viewRootImpl.width / 2f,
+                        surfaceHeight * SURFACE_BEHIND_SCALE_PIVOT_Y
+                )
+
+                // SyncRtSurfaceTransactionApplier cannot apply transaction when the target view is
+                // unable to draw
+                val sc: SurfaceControl? = surfaceBehindRemoteAnimationTarget.leash
+                if (keyguardViewController.viewRootImpl.view?.visibility != View.VISIBLE &&
+                        sc?.isValid == true) {
+                    with(SurfaceControl.Transaction()) {
+                        setMatrix(sc, surfaceBehindMatrix, tmpFloat)
+                        setCornerRadius(sc, roundedCornerRadius)
+                        setAlpha(sc, animationAlpha)
+                        apply()
+                    }
+                } else {
+                    applyParamsToSurface(
+                            SyncRtSurfaceTransactionApplier.SurfaceParams.Builder(
+                                    surfaceBehindRemoteAnimationTarget.leash)
+                                    .withMatrix(surfaceBehindMatrix)
+                                    .withCornerRadius(roundedCornerRadius)
+                                    .withAlpha(animationAlpha)
+                                    .build()
+                    )
+                }
             }
         }
 
@@ -929,28 +934,41 @@
 
     /**
      * Called by [KeyguardViewMediator] to let us know that the remote animation has finished, and
-     * we should clean up all of our state.
+     * we should clean up all of our state. [showKeyguard] will tell us which surface should be
+     * visible after the animation has been completed or canceled.
      *
      * This is generally triggered by us, calling
      * [KeyguardViewMediator.finishSurfaceBehindRemoteAnimation].
      */
-    fun notifyFinishedKeyguardExitAnimation(cancelled: Boolean) {
+    fun notifyFinishedKeyguardExitAnimation(showKeyguard: Boolean) {
         // Cancel any pending actions.
         handler.removeCallbacksAndMessages(null)
 
-        // Make sure we made the surface behind fully visible, just in case. It should already be
-        // fully visible. The exit animation is finished, and we should not hold the leash anymore,
-        // so forcing it to 1f.
-        surfaceBehindAlpha = 1f
-        setSurfaceBehindAppearAmount(1f)
+        // The lockscreen surface is gone, so it is now safe to re-show the smartspace.
+        if (lockscreenSmartspace?.visibility == View.INVISIBLE) {
+            lockscreenSmartspace?.visibility = View.VISIBLE
+        }
+
+        if (!showKeyguard) {
+            // Make sure we made the surface behind fully visible, just in case. It should already be
+            // fully visible. The exit animation is finished, and we should not hold the leash anymore,
+            // so forcing it to 1f.
+            surfaceBehindAlpha = 1f
+            setSurfaceBehindAppearAmount(1f)
+
+            try {
+                launcherUnlockController?.setUnlockAmount(1f, false /* forceIfAnimating */)
+            } catch (e: RemoteException) {
+                Log.e(TAG, "Remote exception in notifyFinishedKeyguardExitAnimation", e)
+            }
+        }
+
+        listeners.forEach { it.onUnlockAnimationFinished() }
+
+        // Reset all state
         surfaceBehindAlphaAnimator.cancel()
         surfaceBehindEntryAnimator.cancel()
         wallpaperCannedUnlockAnimator.cancel()
-        try {
-            launcherUnlockController?.setUnlockAmount(1f, false /* forceIfAnimating */)
-        } catch (e: RemoteException) {
-            Log.e(TAG, "Remote exception in notifyFinishedKeyguardExitAnimation", e)
-        }
 
         // That target is no longer valid since the animation finished, null it out.
         surfaceBehindRemoteAnimationTargets = null
@@ -960,13 +978,6 @@
         dismissAmountThresholdsReached = false
         willUnlockWithInWindowLauncherAnimations = false
         willUnlockWithSmartspaceTransition = false
-
-        // The lockscreen surface is gone, so it is now safe to re-show the smartspace.
-        if (lockscreenSmartspace?.visibility == View.INVISIBLE) {
-            lockscreenSmartspace?.visibility = View.VISIBLE
-        }
-
-        listeners.forEach { it.onUnlockAnimationFinished() }
     }
 
     /**
@@ -977,10 +988,12 @@
         if (keyguardStateController.isShowing) {
             // Hide the keyguard, with no fade out since we animated it away during the unlock.
 
-            keyguardViewController.hide(
-                surfaceBehindRemoteAnimationStartTime,
-                0 /* fadeOutDuration */
-            )
+            if (!featureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                keyguardViewController.hide(
+                        surfaceBehindRemoteAnimationStartTime,
+                        0 /* fadeOutDuration */
+                )
+            }
         } else {
             Log.i(TAG, "#hideKeyguardViewAfterRemoteAnimation called when keyguard view is not " +
                     "showing. Ignoring...")
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewConfigurator.kt b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewConfigurator.kt
index 6213265c..9b323ee 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewConfigurator.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewConfigurator.kt
@@ -20,11 +20,17 @@
 import android.content.res.Configuration
 import android.view.View
 import android.view.ViewGroup
+import com.android.keyguard.KeyguardStatusViewController
+import com.android.keyguard.dagger.KeyguardStatusViewComponent
 import com.android.systemui.CoreStartable
 import com.android.systemui.R
+import com.android.systemui.communal.ui.adapter.CommunalWidgetViewAdapter
+import com.android.systemui.communal.ui.binder.CommunalWidgetViewBinder
+import com.android.systemui.communal.ui.viewmodel.CommunalWidgetViewModel
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.flags.FeatureFlags
 import com.android.systemui.flags.Flags
+import com.android.systemui.keyguard.domain.interactor.KeyguardBlueprintInteractor
 import com.android.systemui.keyguard.ui.binder.KeyguardAmbientIndicationAreaViewBinder
 import com.android.systemui.keyguard.ui.binder.KeyguardBlueprintViewBinder
 import com.android.systemui.keyguard.ui.binder.KeyguardIndicationAreaBinder
@@ -80,6 +86,10 @@
     private val chipbarCoordinator: ChipbarCoordinator,
     private val keyguardBlueprintCommandListener: KeyguardBlueprintCommandListener,
     private val keyguardBlueprintViewModel: KeyguardBlueprintViewModel,
+    private val keyguardStatusViewComponentFactory: KeyguardStatusViewComponent.Factory,
+    private val keyguardBlueprintInteractor: KeyguardBlueprintInteractor,
+    private val communalWidgetViewModel: CommunalWidgetViewModel,
+    private val communalWidgetViewAdapter: CommunalWidgetViewAdapter,
 ) : CoreStartable {
 
     private var rootViewHandle: DisposableHandle? = null
@@ -88,6 +98,7 @@
     private var rightShortcutHandle: KeyguardQuickAffordanceViewBinder.Binding? = null
     private var ambientIndicationAreaHandle: KeyguardAmbientIndicationAreaViewBinder.Binding? = null
     private var settingsPopupMenuHandle: DisposableHandle? = null
+    private var keyguardStatusViewController: KeyguardStatusViewController? = null
 
     override fun start() {
         bindKeyguardRootView()
@@ -96,11 +107,13 @@
         unbindKeyguardBottomArea(notificationPanel)
         bindIndicationArea()
         bindLockIconView(notificationPanel)
+        bindKeyguardStatusView(notificationPanel)
         setupNotificationStackScrollLayout(notificationPanel)
         bindLeftShortcut()
         bindRightShortcut()
         bindAmbientIndicationArea()
         bindSettingsPopupMenu()
+        bindCommunalWidgetArea()
 
         KeyguardBlueprintViewBinder.bind(keyguardRootView, keyguardBlueprintViewModel)
         keyguardBlueprintCommandListener.start()
@@ -117,7 +130,7 @@
             sharedNotificationContainer.addNotificationStackScrollLayout(nssl)
             SharedNotificationContainerBinder.bind(
                 sharedNotificationContainer,
-                sharedNotificationContainerViewModel
+                sharedNotificationContainerViewModel,
             )
         }
     }
@@ -132,9 +145,7 @@
     fun bindIndicationArea() {
         indicationAreaHandle?.dispose()
 
-        // At startup, 2 views with the ID `R.id.keyguard_indication_area` will be available.
-        // Disable one of them
-        if (!featureFlags.isEnabled(Flags.MIGRATE_INDICATION_AREA)) {
+        if (!featureFlags.isEnabled(Flags.MIGRATE_SPLIT_KEYGUARD_BOTTOM_AREA)) {
             keyguardRootView.findViewById<View?>(R.id.keyguard_indication_area)?.let {
                 keyguardRootView.removeView(it)
             }
@@ -255,4 +266,44 @@
             }
         }
     }
+
+    fun bindKeyguardStatusView(legacyParent: ViewGroup) {
+        // At startup, 2 views with the ID `R.id.keyguard_status_view` will be available.
+        // Disable one of them
+        if (featureFlags.isEnabled(Flags.MIGRATE_KEYGUARD_STATUS_VIEW)) {
+            legacyParent.findViewById<View>(R.id.keyguard_status_view)?.let {
+                legacyParent.removeView(it)
+            }
+
+            val keyguardStatusView = keyguardRootView.addStatusView()
+            val statusViewComponent = keyguardStatusViewComponentFactory.build(keyguardStatusView)
+            val controller = statusViewComponent.getKeyguardStatusViewController()
+            controller.init()
+            keyguardStatusViewController = controller
+        } else {
+            keyguardRootView.findViewById<View?>(R.id.keyguard_status_view)?.let {
+                keyguardRootView.removeView(it)
+            }
+        }
+    }
+
+    private fun bindCommunalWidgetArea() {
+        if (!featureFlags.isEnabled(Flags.WIDGET_ON_KEYGUARD)) {
+            return
+        }
+
+        CommunalWidgetViewBinder.bind(
+            keyguardRootView,
+            communalWidgetViewModel,
+            communalWidgetViewAdapter,
+            keyguardBlueprintInteractor,
+        )
+    }
+
+    /**
+     * Temporary, to allow NotificationPanelViewController to use the same instance while code is
+     * migrated: b/288242803
+     */
+    fun getKeyguardStatusViewController() = keyguardStatusViewController
+    fun getKeyguardRootView() = keyguardRootView
 }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index 66de371..fd15853 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -171,8 +171,6 @@
 import com.android.systemui.wallpapers.data.repository.WallpaperRepository;
 import com.android.wm.shell.keyguard.KeyguardTransitions;
 
-import dagger.Lazy;
-
 import java.io.PrintWriter;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -182,6 +180,7 @@
 import java.util.concurrent.Executor;
 import java.util.function.Consumer;
 
+import dagger.Lazy;
 import kotlinx.coroutines.CoroutineDispatcher;
 
 /**
@@ -1035,12 +1034,19 @@
                 IRemoteAnimationFinishedCallback finishedCallback) {
             Trace.beginSection("mExitAnimationRunner.onAnimationStart#startKeyguardExitAnimation");
             startKeyguardExitAnimation(transit, apps, wallpapers, nonApps, finishedCallback);
+            if (mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                mWmLockscreenVisibilityManager.get().onKeyguardGoingAwayRemoteAnimationStart(
+                        transit, apps, wallpapers, nonApps, finishedCallback);
+            }
             Trace.endSection();
         }
 
         @Override // Binder interface
         public void onAnimationCancelled() {
             cancelKeyguardExitAnimation();
+            if (mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                mWmLockscreenVisibilityManager.get().onKeyguardGoingAwayRemoteAnimationCancelled();
+            }
         }
     };
 
@@ -1106,7 +1112,7 @@
 
                         mOccludeByDreamAnimator = ValueAnimator.ofFloat(0f, 1f);
                         mOccludeByDreamAnimator.setDuration(mDreamOpenAnimationDuration);
-                        mOccludeByDreamAnimator.setInterpolator(Interpolators.LINEAR);
+                        //mOccludeByDreamAnimator.setInterpolator(Interpolators.LINEAR);
                         mOccludeByDreamAnimator.addUpdateListener(
                                 animation -> {
                                     SyncRtSurfaceTransactionApplier.SurfaceParams.Builder
@@ -1336,6 +1342,8 @@
             mDreamingToLockscreenTransitionViewModel;
     private RemoteAnimationTarget mRemoteAnimationTarget;
 
+    private Lazy<WindowManagerLockscreenVisibilityManager> mWmLockscreenVisibilityManager;
+
     /**
      * Injected constructor. See {@link KeyguardModule}.
      */
@@ -1379,7 +1387,8 @@
             SystemClock systemClock,
             @Main CoroutineDispatcher mainDispatcher,
             Lazy<DreamingToLockscreenTransitionViewModel> dreamingToLockscreenTransitionViewModel,
-            SystemPropertiesHelper systemPropertiesHelper) {
+            SystemPropertiesHelper systemPropertiesHelper,
+            Lazy<WindowManagerLockscreenVisibilityManager> wmLockscreenVisibilityManager) {
         mContext = context;
         mUserTracker = userTracker;
         mFalsingCollector = falsingCollector;
@@ -1446,8 +1455,9 @@
         mUiEventLogger = uiEventLogger;
         mSessionTracker = sessionTracker;
 
-        mMainDispatcher = mainDispatcher;
         mDreamingToLockscreenTransitionViewModel = dreamingToLockscreenTransitionViewModel;
+        mWmLockscreenVisibilityManager = wmLockscreenVisibilityManager;
+        mMainDispatcher = mainDispatcher;
     }
 
     public void userActivity() {
@@ -2561,7 +2571,7 @@
         } else if (mSurfaceBehindRemoteAnimationRunning) {
             // We're already running the keyguard exit animation, likely due to an in-progress swipe
             // to unlock.
-           exitKeyguardAndFinishSurfaceBehindRemoteAnimation(false /* cancelled */);
+            exitKeyguardAndFinishSurfaceBehindRemoteAnimation(false /* showKeyguard */);
         } else if (!mHideAnimationRun) {
             if (DEBUG) Log.d(TAG, "tryKeyguardDone: starting pre-hide animation");
             mHideAnimationRun = true;
@@ -2685,6 +2695,12 @@
             if (DEBUG) {
                 Log.d(TAG, "updateActivityLockScreenState(" + showing + ", " + aodShowing + ")");
             }
+
+            if (mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                // Handled in WmLockscreenVisibilityManager if flag is enabled.
+                return;
+            }
+
             try {
                 mActivityTaskManagerService.setLockScreenShown(showing, aodShowing);
             } catch (RemoteException e) {
@@ -2724,7 +2740,11 @@
             }
             mHiding = false;
 
-            mKeyguardViewControllerLazy.get().show(options);
+            if (!mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                // Handled directly in StatusBarKeyguardViewManager if enabled.
+                mKeyguardViewControllerLazy.get().show(options);
+            }
+
             resetKeyguardDonePendingLocked();
             mHideAnimationRun = false;
             adjustStatusBarLocked();
@@ -2795,19 +2815,22 @@
             mUpdateMonitor.setKeyguardGoingAway(true);
             mKeyguardViewControllerLazy.get().setKeyguardGoingAwayState(true);
 
-            // Don't actually hide the Keyguard at the moment, wait for window
-            // manager until it tells us it's safe to do so with
-            // startKeyguardExitAnimation.
-            // Posting to mUiOffloadThread to ensure that calls to ActivityTaskManager will be in
-            // order.
-            final int keyguardFlag = flags;
-            mUiBgExecutor.execute(() -> {
-                try {
-                    mActivityTaskManagerService.keyguardGoingAway(keyguardFlag);
-                } catch (RemoteException e) {
-                    Log.e(TAG, "Error while calling WindowManager", e);
-                }
-            });
+            // Handled in WmLockscreenVisibilityManager if flag is enabled.
+            if (!mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                    // Don't actually hide the Keyguard at the moment, wait for window manager 
+                    // until it tells us it's safe to do so with startKeyguardExitAnimation.
+		    // Posting to mUiOffloadThread to ensure that calls to ActivityTaskManager 
+		    // will be in order.
+		    final int keyguardFlag = flags;
+		    mUiBgExecutor.execute(() -> {
+		        try {
+		            mActivityTaskManagerService.keyguardGoingAway(keyguardFlag);
+		        } catch (RemoteException e) {
+		            Log.e(TAG, "Error while calling WindowManager", e);
+		        }
+		    });
+            }
+
             Trace.endSection();
         }
     };
@@ -2919,7 +2942,10 @@
             if (!mHiding
                     && !mSurfaceBehindRemoteAnimationRequested
                     && !mKeyguardStateController.isFlingingToDismissKeyguardDuringSwipeGesture()) {
-                if (finishedCallback != null) {
+                // If the flag is enabled, remote animation state is handled in
+                // WmLockscreenVisibilityManager.
+                if (finishedCallback != null
+                        && !mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
                     // There will not execute animation, send a finish callback to ensure the remote
                     // animation won't hang there.
                     try {
@@ -2945,10 +2971,12 @@
                         new IRemoteAnimationFinishedCallback() {
                             @Override
                             public void onAnimationFinished() throws RemoteException {
-                                try {
-                                    finishedCallback.onAnimationFinished();
-                                } catch (RemoteException e) {
-                                    Slog.w(TAG, "Failed to call onAnimationFinished", e);
+                                if (!mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                                    try {
+                                        finishedCallback.onAnimationFinished();
+                                    } catch (RemoteException e) {
+                                        Slog.w(TAG, "Failed to call onAnimationFinished", e);
+                                    }
                                 }
                                 onKeyguardExitFinished();
                                 mKeyguardViewControllerLazy.get().hide(0 /* startTime */,
@@ -2975,7 +3003,11 @@
             // it will dismiss the panel in that case.
             } else if (!mStatusBarStateController.leaveOpenOnKeyguardHide()
                     && apps != null && apps.length > 0) {
-                mSurfaceBehindRemoteAnimationFinishedCallback = finishedCallback;
+                if (!mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                    // Handled in WmLockscreenVisibilityManager. Other logic in this class will
+                    // short circuit when this is null.
+                    mSurfaceBehindRemoteAnimationFinishedCallback = finishedCallback;
+                }
                 mSurfaceBehindRemoteAnimationRunning = true;
 
                 mInteractionJankMonitor.begin(
@@ -2995,7 +3027,10 @@
                         createInteractionJankMonitorConf(
                                 CUJ_LOCKSCREEN_UNLOCK_ANIMATION, "RemoteAnimationDisabled"));
 
-                mKeyguardViewControllerLazy.get().hide(startTime, fadeoutDuration);
+                if (!mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                    // Handled directly in StatusBarKeyguardViewManager if enabled.
+                    mKeyguardViewControllerLazy.get().hide(startTime, fadeoutDuration);
+                }
 
                 // TODO(bc-animation): When remote animation is enabled for keyguard exit animation,
                 // apps, wallpapers and finishedCallback are set to non-null. nonApps is not yet
@@ -3003,19 +3038,23 @@
                 mContext.getMainExecutor().execute(() -> {
                     if (finishedCallback == null) {
                         mKeyguardUnlockAnimationControllerLazy.get()
-                                .notifyFinishedKeyguardExitAnimation(false /* cancelled */);
+                                .notifyFinishedKeyguardExitAnimation(false /* showKeyguard */);
                         mInteractionJankMonitor.end(CUJ_LOCKSCREEN_UNLOCK_ANIMATION);
                         return;
                     }
                     if (apps == null || apps.length == 0) {
                         Slog.e(TAG, "Keyguard exit without a corresponding app to show.");
+
                         try {
-                            finishedCallback.onAnimationFinished();
+                            if (!mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                                finishedCallback.onAnimationFinished();
+                            }
                         } catch (RemoteException e) {
                             Slog.e(TAG, "RemoteException");
                         } finally {
                             mInteractionJankMonitor.end(CUJ_LOCKSCREEN_UNLOCK_ANIMATION);
                         }
+
                         return;
                     }
 
@@ -3039,7 +3078,9 @@
                         @Override
                         public void onAnimationEnd(Animator animation) {
                             try {
-                                finishedCallback.onAnimationFinished();
+                                if (!mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                                    finishedCallback.onAnimationFinished();
+                                }
                             } catch (RemoteException e) {
                                 Slog.e(TAG, "RemoteException");
                             } finally {
@@ -3050,7 +3091,9 @@
                         @Override
                         public void onAnimationCancel(Animator animation) {
                             try {
-                                finishedCallback.onAnimationFinished();
+                                if (!mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                                    finishedCallback.onAnimationFinished();
+                                }
                             } catch (RemoteException e) {
                                 Slog.e(TAG, "RemoteException");
                             } finally {
@@ -3120,7 +3163,7 @@
             // A lock is pending, meaning the keyguard exit animation was cancelled because we're
             // re-locking. We should just end the surface-behind animation without exiting the
             // keyguard. The pending lock will be handled by onFinishedGoingToSleep().
-            finishSurfaceBehindRemoteAnimation(true);
+            finishSurfaceBehindRemoteAnimation(true /* showKeyguard */);
             maybeHandlePendingLock();
         } else {
             Log.d(TAG, "#handleCancelKeyguardExitAnimation: keyguard exit animation cancelled. "
@@ -3129,7 +3172,7 @@
             // No lock is pending, so the animation was cancelled during the unlock sequence, but
             // we should end up unlocked. Show the surface and exit the keyguard.
             showSurfaceBehindKeyguard();
-            exitKeyguardAndFinishSurfaceBehindRemoteAnimation(true /* cancelled */);
+            exitKeyguardAndFinishSurfaceBehindRemoteAnimation(false /* showKeyguard */);
         }
     }
 
@@ -3140,12 +3183,13 @@
      * with the RemoteAnimation, actually hide the keyguard, and clean up state related to the
      * keyguard exit animation.
      *
-     * @param cancelled {@code true} if the animation was cancelled before it finishes.
+     * @param showKeyguard {@code true} if the animation was cancelled and keyguard should remain
+     *                        visible
      */
-    public void exitKeyguardAndFinishSurfaceBehindRemoteAnimation(boolean cancelled) {
+    public void exitKeyguardAndFinishSurfaceBehindRemoteAnimation(boolean showKeyguard) {
         Log.d(TAG, "onKeyguardExitRemoteAnimationFinished");
         if (!mSurfaceBehindRemoteAnimationRunning && !mSurfaceBehindRemoteAnimationRequested) {
-            Log.d(TAG, "skip onKeyguardExitRemoteAnimationFinished cancelled=" + cancelled
+            Log.d(TAG, "skip onKeyguardExitRemoteAnimationFinished showKeyguard=" + showKeyguard
                     + " surfaceAnimationRunning=" + mSurfaceBehindRemoteAnimationRunning
                     + " surfaceAnimationRequested=" + mSurfaceBehindRemoteAnimationRequested);
             return;
@@ -3170,9 +3214,7 @@
                         + " wasShowing=" + wasShowing);
             }
 
-            mKeyguardUnlockAnimationControllerLazy.get()
-                    .notifyFinishedKeyguardExitAnimation(cancelled);
-            finishSurfaceBehindRemoteAnimation(cancelled);
+            finishSurfaceBehindRemoteAnimation(showKeyguard);
 
             // Dispatch the callback on animation finishes.
             mUpdateMonitor.dispatchKeyguardDismissAnimationFinished();
@@ -3200,7 +3242,11 @@
                 flags |= KEYGUARD_GOING_AWAY_FLAG_TO_LAUNCHER_CLEAR_SNAPSHOT;
             }
 
-            mActivityTaskManagerService.keyguardGoingAway(flags);
+            if (!mFeatureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                // Handled in WmLockscreenVisibilityManager.
+                mActivityTaskManagerService.keyguardGoingAway(flags);
+            }
+
             mKeyguardStateController.notifyKeyguardGoingAway(true);
         } catch (RemoteException e) {
             mSurfaceBehindRemoteAnimationRequested = false;
@@ -3236,7 +3282,10 @@
      * This does not set keyguard state to either locked or unlocked, it simply ends the remote
      * animation on the surface behind the keyguard. This can be called by
      */
-    void finishSurfaceBehindRemoteAnimation(boolean cancelled) {
+    void finishSurfaceBehindRemoteAnimation(boolean showKeyguard) {
+        mKeyguardUnlockAnimationControllerLazy.get()
+                .notifyFinishedKeyguardExitAnimation(showKeyguard);
+
         mSurfaceBehindRemoteAnimationRequested = false;
         mSurfaceBehindRemoteAnimationRunning = false;
         mKeyguardStateController.notifyKeyguardGoingAway(false);
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/WindowManagerLockscreenVisibilityManager.kt b/packages/SystemUI/src/com/android/systemui/keyguard/WindowManagerLockscreenVisibilityManager.kt
new file mode 100644
index 0000000..75677f2
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/WindowManagerLockscreenVisibilityManager.kt
@@ -0,0 +1,206 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard
+
+import android.app.IActivityTaskManager
+import android.util.Log
+import android.view.IRemoteAnimationFinishedCallback
+import android.view.RemoteAnimationTarget
+import android.view.WindowManager
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.keyguard.ui.binder.KeyguardSurfaceBehindParamsApplier
+import com.android.systemui.statusbar.policy.KeyguardStateController
+import java.util.concurrent.Executor
+import javax.inject.Inject
+
+/**
+ * Manages lockscreen and AOD visibility state via the [IActivityTaskManager], and keeps track of
+ * remote animations related to changes in lockscreen visibility.
+ */
+@SysUISingleton
+class WindowManagerLockscreenVisibilityManager
+@Inject
+constructor(
+    @Main private val executor: Executor,
+    private val activityTaskManagerService: IActivityTaskManager,
+    private val keyguardStateController: KeyguardStateController,
+    private val keyguardSurfaceBehindAnimator: KeyguardSurfaceBehindParamsApplier,
+) {
+
+    /**
+     * Whether the lockscreen is showing, which we pass to [IActivityTaskManager.setLockScreenShown]
+     * in order to show the lockscreen and hide the surface behind the keyguard (or the inverse).
+     */
+    private var isLockscreenShowing = true
+
+    /**
+     * Whether AOD is showing, which we pass to [IActivityTaskManager.setLockScreenShown] in order
+     * to show AOD when the lockscreen is visible.
+     */
+    private var isAodVisible = false
+
+    /**
+     * Whether the keyguard is currently "going away", which we triggered via a call to
+     * [IActivityTaskManager.keyguardGoingAway]. When we tell WM that the keyguard is going away,
+     * the app/launcher surface behind the keyguard is made visible, and WM calls
+     * [onKeyguardGoingAwayRemoteAnimationStart] with a RemoteAnimationTarget so that we can animate
+     * it.
+     *
+     * Going away does not inherently result in [isLockscreenShowing] being set to false; we need to
+     * do that ourselves once we are done animating the surface.
+     *
+     * THIS IS THE ONLY PLACE 'GOING AWAY' TERMINOLOGY SHOULD BE USED. 'Going away' is a WM concept
+     * and we have gotten into trouble using it to mean various different things in the past. Unlock
+     * animations may still be visible when the keyguard is NOT 'going away', for example, when we
+     * play in-window animations, we set the surface to alpha=1f and end the animation immediately.
+     * The remainder of the animation occurs in-window, so while you might expect that the keyguard
+     * is still 'going away' because unlock animations are playing, it's actually not.
+     *
+     * If you want to know if the keyguard is 'going away', you probably want to check if we have
+     * STARTED but not FINISHED a transition to GONE.
+     *
+     * The going away animation will run until:
+     * - We manually call [endKeyguardGoingAwayAnimation] after we're done animating.
+     * - We call [setLockscreenShown] = true, which cancels the going away animation.
+     * - WM calls [onKeyguardGoingAwayRemoteAnimationCancelled] for another reason (such as the 10
+     *   second timeout).
+     */
+    private var isKeyguardGoingAway = false
+        private set(value) {
+            // TODO(b/278086361): Extricate the keyguard state controller.
+            keyguardStateController.notifyKeyguardGoingAway(value)
+            field = value
+        }
+
+    /** Callback provided by WM to call once we're done with the going away animation. */
+    private var goingAwayRemoteAnimationFinishedCallback: IRemoteAnimationFinishedCallback? = null
+
+    /**
+     * Set the visibility of the surface behind the keyguard, making the appropriate calls to Window
+     * Manager to effect the change.
+     */
+    fun setSurfaceBehindVisibility(visible: Boolean) {
+        if (isKeyguardGoingAway == visible) {
+            Log.d(TAG, "WmLockscreenVisibilityManager#setVisibility -> already visible=$visible")
+            return
+        }
+
+        // The surface behind is always visible if the lockscreen is not showing, so we're already
+        // visible.
+        if (visible && !isLockscreenShowing) {
+            Log.d(TAG, "#setVisibility -> already visible since the lockscreen isn't showing")
+            return
+        }
+
+        if (visible) {
+            // Make the surface visible behind the keyguard by calling keyguardGoingAway. The
+            // lockscreen is still showing as well, allowing us to animate unlocked.
+            Log.d(TAG, "ActivityTaskManagerService#keyguardGoingAway()")
+            activityTaskManagerService.keyguardGoingAway(0)
+            isKeyguardGoingAway = true
+        } else {
+            // Hide the surface by setting the lockscreen showing.
+            setLockscreenShown(true)
+        }
+    }
+
+    fun setAodVisible(aodVisible: Boolean) {
+        setWmLockscreenState(aodVisible = aodVisible)
+    }
+
+    /** Sets the visibility of the lockscreen. */
+    fun setLockscreenShown(lockscreenShown: Boolean) {
+        setWmLockscreenState(lockscreenShowing = lockscreenShown)
+    }
+
+    fun onKeyguardGoingAwayRemoteAnimationStart(
+        @WindowManager.TransitionOldType transit: Int,
+        apps: Array<RemoteAnimationTarget>,
+        wallpapers: Array<RemoteAnimationTarget>,
+        nonApps: Array<RemoteAnimationTarget>,
+        finishedCallback: IRemoteAnimationFinishedCallback
+    ) {
+        goingAwayRemoteAnimationFinishedCallback = finishedCallback
+        keyguardSurfaceBehindAnimator.applyParamsToSurface(apps[0])
+    }
+
+    fun onKeyguardGoingAwayRemoteAnimationCancelled() {
+        // If WM cancelled the animation, we need to end immediately even if we're still using the
+        // animation.
+        endKeyguardGoingAwayAnimation()
+    }
+
+    /**
+     * Whether the going away remote animation target is in-use, which means we're animating it or
+     * intend to animate it.
+     *
+     * Some unlock animations (such as the translation spring animation) are non-deterministic and
+     * might end after the transition to GONE ends. In that case, we want to keep the remote
+     * animation running until the spring ends.
+     */
+    fun setUsingGoingAwayRemoteAnimation(usingTarget: Boolean) {
+        if (!usingTarget) {
+            endKeyguardGoingAwayAnimation()
+        }
+    }
+
+    private fun setWmLockscreenState(
+        lockscreenShowing: Boolean = this.isLockscreenShowing,
+        aodVisible: Boolean = this.isAodVisible
+    ) {
+        Log.d(
+            TAG,
+            "#setWmLockscreenState(" +
+                "isLockscreenShowing=$lockscreenShowing, " +
+                "aodVisible=$aodVisible)."
+        )
+
+        if (this.isLockscreenShowing == lockscreenShowing && this.isAodVisible == aodVisible) {
+            return
+        }
+
+        activityTaskManagerService.setLockScreenShown(lockscreenShowing, aodVisible)
+        this.isLockscreenShowing = lockscreenShowing
+        this.isAodVisible = aodVisible
+    }
+
+    private fun endKeyguardGoingAwayAnimation() {
+        if (!isKeyguardGoingAway) {
+            Log.d(
+                TAG,
+                "#endKeyguardGoingAwayAnimation() called when isKeyguardGoingAway=false. " +
+                    "Short-circuiting."
+            )
+            return
+        }
+
+        executor.execute {
+            Log.d(TAG, "Finishing remote animation.")
+            goingAwayRemoteAnimationFinishedCallback?.onAnimationFinished()
+            goingAwayRemoteAnimationFinishedCallback = null
+
+            isKeyguardGoingAway = false
+
+            keyguardSurfaceBehindAnimator.notifySurfaceReleased()
+        }
+    }
+
+    companion object {
+        private val TAG = this::class.java.simpleName
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java b/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java
index a5ac7c7..13dfe24 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java
@@ -37,6 +37,7 @@
 import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.classifier.FalsingCollector;
 import com.android.systemui.classifier.FalsingModule;
+import com.android.systemui.communal.data.repository.CommunalWidgetRepositoryModule;
 import com.android.systemui.dagger.SysUISingleton;
 import com.android.systemui.dagger.qualifiers.Main;
 import com.android.systemui.dagger.qualifiers.UiBackground;
@@ -47,6 +48,7 @@
 import com.android.systemui.keyguard.DismissCallbackRegistry;
 import com.android.systemui.keyguard.KeyguardUnlockAnimationController;
 import com.android.systemui.keyguard.KeyguardViewMediator;
+import com.android.systemui.keyguard.WindowManagerLockscreenVisibilityManager;
 import com.android.systemui.keyguard.data.quickaffordance.KeyguardDataQuickAffordanceModule;
 import com.android.systemui.keyguard.data.repository.KeyguardFaceAuthModule;
 import com.android.systemui.keyguard.data.repository.KeyguardRepositoryModule;
@@ -91,6 +93,7 @@
         KeyguardStatusViewComponent.class,
         KeyguardUserSwitcherComponent.class},
         includes = {
+            CommunalWidgetRepositoryModule.class,
             FalsingModule.class,
             KeyguardDataQuickAffordanceModule.class,
             KeyguardRepositoryModule.class,
@@ -146,7 +149,8 @@
             SystemClock systemClock,
             @Main CoroutineDispatcher mainDispatcher,
             Lazy<DreamingToLockscreenTransitionViewModel> dreamingToLockscreenTransitionViewModel,
-            SystemPropertiesHelper systemPropertiesHelper) {
+            SystemPropertiesHelper systemPropertiesHelper,
+            Lazy<WindowManagerLockscreenVisibilityManager> wmLockscreenVisibilityManager) {
         return new KeyguardViewMediator(
                 context,
                 uiEventLogger,
@@ -189,7 +193,8 @@
                 systemClock,
                 mainDispatcher,
                 dreamingToLockscreenTransitionViewModel,
-                systemPropertiesHelper);
+                systemPropertiesHelper,
+                wmLockscreenVisibilityManager);
     }
 
     /** */
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/QrCodeScannerKeyguardQuickAffordanceConfig.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/QrCodeScannerKeyguardQuickAffordanceConfig.kt
index 20ed549..45277b8 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/QrCodeScannerKeyguardQuickAffordanceConfig.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/QrCodeScannerKeyguardQuickAffordanceConfig.kt
@@ -78,16 +78,8 @@
 
     override suspend fun getPickerScreenState(): KeyguardQuickAffordanceConfig.PickerScreenState {
         return when {
-            !controller.isAvailableOnDevice ->
+            !isEnabledForPickerStateOption() ->
                 KeyguardQuickAffordanceConfig.PickerScreenState.UnavailableOnDevice
-            !controller.isAbleToOpenCameraApp -> {
-                KeyguardQuickAffordanceConfig.PickerScreenState.Disabled(
-                    explanation =
-                        context.getString(
-                            R.string.qr_scanner_quick_affordance_unavailable_explanation
-                        ),
-                )
-            }
             else -> KeyguardQuickAffordanceConfig.PickerScreenState.Default()
         }
     }
@@ -118,6 +110,11 @@
         }
     }
 
+    /** Returns whether QR scanner be shown as one of available lockscreen shortcut option. */
+    private fun isEnabledForPickerStateOption(): Boolean {
+        return controller.isAbleToLaunchScannerActivity && controller.isAllowedOnLockScreen
+    }
+
     companion object {
         private const val TAG = "QrCodeScannerKeyguardQuickAffordanceConfig"
     }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/QuickAccessWalletKeyguardQuickAffordanceConfig.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/QuickAccessWalletKeyguardQuickAffordanceConfig.kt
index c019d21..5d7a3d4 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/QuickAccessWalletKeyguardQuickAffordanceConfig.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/QuickAccessWalletKeyguardQuickAffordanceConfig.kt
@@ -59,7 +59,7 @@
         conflatedCallbackFlow {
             val callback =
                 object : QuickAccessWalletClient.OnWalletCardsRetrievedCallback {
-                    override fun onWalletCardsRetrieved(response: GetWalletCardsResponse?) {
+                    override fun onWalletCardsRetrieved(response: GetWalletCardsResponse) {
                         val hasCards = response?.walletCards?.isNotEmpty() == true
                         trySendWithFailureLogging(
                             state(
@@ -71,7 +71,7 @@
                         )
                     }
 
-                    override fun onWalletCardRetrievalError(error: GetWalletCardsError?) {
+                    override fun onWalletCardRetrievalError(error: GetWalletCardsError) {
                         Log.e(TAG, "Wallet card retrieval error, message: \"${error?.message}\"")
                         trySendWithFailureLogging(
                             KeyguardQuickAffordanceConfig.LockScreenState.Hidden,
@@ -133,13 +133,13 @@
         return suspendCancellableCoroutine { continuation ->
             val callback =
                 object : QuickAccessWalletClient.OnWalletCardsRetrievedCallback {
-                    override fun onWalletCardsRetrieved(response: GetWalletCardsResponse?) {
+                    override fun onWalletCardsRetrieved(response: GetWalletCardsResponse) {
                         continuation.resumeWith(
                             Result.success(response?.walletCards ?: emptyList())
                         )
                     }
 
-                    override fun onWalletCardRetrievalError(error: GetWalletCardsError?) {
+                    override fun onWalletCardRetrievalError(error: GetWalletCardsError) {
                         continuation.resumeWith(Result.success(emptyList()))
                     }
                 }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/BiometricSettingsRepository.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/BiometricSettingsRepository.kt
index ff3e77c..682e841 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/BiometricSettingsRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/BiometricSettingsRepository.kt
@@ -28,6 +28,9 @@
 import com.android.systemui.Dumpable
 import com.android.systemui.R
 import com.android.systemui.biometrics.AuthController
+import com.android.systemui.biometrics.data.repository.FacePropertyRepository
+import com.android.systemui.biometrics.data.repository.FingerprintPropertyRepository
+import com.android.systemui.biometrics.shared.model.SensorStrength
 import com.android.systemui.broadcast.BroadcastDispatcher
 import com.android.systemui.common.coroutine.ChannelExt.trySendWithFailureLogging
 import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow
@@ -68,34 +71,32 @@
  * upstream changes.
  */
 interface BiometricSettingsRepository {
-    /** Whether any fingerprints are enrolled for the current user. */
-    val isFingerprintEnrolled: StateFlow<Boolean>
-
-    /** Whether face authentication is enrolled for the current user. */
-    val isFaceEnrolled: Flow<Boolean>
+    /**
+     * If the current user can enter the device using fingerprint. This is true if user has enrolled
+     * fingerprints and fingerprint auth is not disabled through settings/device policy
+     */
+    val isFingerprintEnrolledAndEnabled: StateFlow<Boolean>
 
     /**
-     * Whether face authentication is enabled/disabled based on system settings like device policy,
-     * biometrics setting.
+     * If the current user can enter the device using fingerprint, right now.
+     *
+     * This returns true if there are no strong auth flags that restrict the user from using
+     * fingerprint and [isFingerprintEnrolledAndEnabled] is true
      */
-    val isFaceAuthenticationEnabled: Flow<Boolean>
+    val isFingerprintAuthCurrentlyAllowed: StateFlow<Boolean>
 
     /**
-     * Whether the current user is allowed to use a strong biometric for device entry based on
-     * Android Security policies. If false, the user may be able to use primary authentication for
-     * device entry.
+     * If the current user can use face auth to enter the device. This is true when the user has
+     * face auth enrolled, and is enabled in settings/device policy.
      */
-    val isStrongBiometricAllowed: StateFlow<Boolean>
+    val isFaceAuthEnrolledAndEnabled: Flow<Boolean>
 
     /**
-     * Whether the current user is allowed to use a convenience biometric for device entry based on
-     * Android Security policies. If false, the user may be able to use strong biometric or primary
-     * authentication for device entry.
+     * If the current user can use face auth to enter the device right now. This is true when
+     * [isFaceAuthEnrolledAndEnabled] is true and strong auth settings allow face auth to run and
+     * face auth is supported by the current device posture.
      */
-    val isNonStrongBiometricAllowed: StateFlow<Boolean>
-
-    /** Whether fingerprint feature is enabled for the current user by the DevicePolicy */
-    val isFingerprintEnabledByDevicePolicy: StateFlow<Boolean>
+    val isFaceAuthCurrentlyAllowed: Flow<Boolean>
 
     /**
      * Whether face authentication is supported for the current device posture. Face auth can be
@@ -130,6 +131,8 @@
     @Background backgroundDispatcher: CoroutineDispatcher,
     biometricManager: BiometricManager?,
     devicePostureRepository: DevicePostureRepository,
+    facePropertyRepository: FacePropertyRepository,
+    fingerprintPropertyRepository: FingerprintPropertyRepository,
     dumpManager: DumpManager,
 ) : BiometricSettingsRepository, Dumpable {
 
@@ -165,7 +168,9 @@
     }
 
     override fun dump(pw: PrintWriter, args: Array<String?>) {
-        pw.println("isFingerprintEnrolled=${isFingerprintEnrolled.value}")
+        pw.println("isFingerprintEnrolledAndEnabled=${isFingerprintEnrolledAndEnabled.value}")
+        pw.println("isFingerprintAuthCurrentlyAllowed=${isFingerprintAuthCurrentlyAllowed.value}")
+        pw.println("isNonStrongBiometricAllowed=${isNonStrongBiometricAllowed.value}")
         pw.println("isStrongBiometricAllowed=${isStrongBiometricAllowed.value}")
         pw.println("isFingerprintEnabledByDevicePolicy=${isFingerprintEnabledByDevicePolicy.value}")
     }
@@ -180,7 +185,7 @@
             user = UserHandle.ALL
         )
 
-    override val isFingerprintEnrolled: StateFlow<Boolean> =
+    private val isFingerprintEnrolled: Flow<Boolean> =
         selectedUserId
             .flatMapLatest { currentUserId ->
                 conflatedCallbackFlow {
@@ -211,7 +216,7 @@
                     authController.isFingerprintEnrolled(userRepository.getSelectedUserInfo().id)
             )
 
-    override val isFaceEnrolled: Flow<Boolean> =
+    private val isFaceEnrolled: Flow<Boolean> =
         selectedUserId.flatMapLatest { selectedUserId: Int ->
             conflatedCallbackFlow {
                 val callback =
@@ -245,14 +250,6 @@
             isFaceEnabledByBiometricsManager.map { biometricsEnabledForUser[userInfo.id] ?: false }
         }
 
-    override val isFaceAuthenticationEnabled: Flow<Boolean>
-        get() =
-            combine(isFaceEnabledByBiometricsManagerForCurrentUser, isFaceEnabledByDevicePolicy) {
-                biometricsManagerSetting,
-                devicePolicySetting ->
-                biometricsManagerSetting && devicePolicySetting
-            }
-
     private val isFaceEnabledByDevicePolicy: Flow<Boolean> =
         combine(selectedUserId, devicePolicyChangedForAllUsers) { userId, _ ->
                 devicePolicyManager.isFaceDisabled(userId)
@@ -263,6 +260,13 @@
             .flowOn(backgroundDispatcher)
             .distinctUntilChanged()
 
+    private val isFaceAuthenticationEnabled: Flow<Boolean> =
+        combine(isFaceEnabledByBiometricsManagerForCurrentUser, isFaceEnabledByDevicePolicy) {
+            biometricsManagerSetting,
+            devicePolicySetting ->
+            biometricsManagerSetting && devicePolicySetting
+        }
+
     private val isFaceEnabledByBiometricsManager: Flow<Pair<Int, Boolean>> =
         conflatedCallbackFlow {
                 val callback =
@@ -283,7 +287,7 @@
             // being registered.
             .stateIn(scope, SharingStarted.Eagerly, Pair(0, false))
 
-    override val isStrongBiometricAllowed: StateFlow<Boolean> =
+    private val isStrongBiometricAllowed: StateFlow<Boolean> =
         strongAuthTracker.isStrongBiometricAllowed.stateIn(
             scope,
             SharingStarted.Eagerly,
@@ -293,7 +297,7 @@
             )
         )
 
-    override val isNonStrongBiometricAllowed: StateFlow<Boolean> =
+    private val isNonStrongBiometricAllowed: StateFlow<Boolean> =
         strongAuthTracker.isNonStrongBiometricAllowed.stateIn(
             scope,
             SharingStarted.Eagerly,
@@ -303,7 +307,19 @@
             )
         )
 
-    override val isFingerprintEnabledByDevicePolicy: StateFlow<Boolean> =
+    private val isFingerprintBiometricAllowed: Flow<Boolean> =
+        fingerprintPropertyRepository.strength.flatMapLatest {
+            if (it == SensorStrength.STRONG) isStrongBiometricAllowed
+            else isNonStrongBiometricAllowed
+        }
+
+    private val isFaceBiometricsAllowed: Flow<Boolean> =
+        facePropertyRepository.sensorInfo.flatMapLatest {
+            if (it?.strength == SensorStrength.STRONG) isStrongBiometricAllowed
+            else isNonStrongBiometricAllowed
+        }
+
+    private val isFingerprintEnabledByDevicePolicy: StateFlow<Boolean> =
         selectedUserId
             .flatMapLatest { userId ->
                 devicePolicyChangedForAllUsers
@@ -319,6 +335,25 @@
                         userRepository.getSelectedUserInfo().id
                     )
             )
+
+    override val isFingerprintEnrolledAndEnabled: StateFlow<Boolean> =
+        isFingerprintEnrolled
+            .and(isFingerprintEnabledByDevicePolicy)
+            .stateIn(scope, SharingStarted.Eagerly, false)
+
+    override val isFingerprintAuthCurrentlyAllowed: StateFlow<Boolean> =
+        isFingerprintEnrolledAndEnabled
+            .and(isFingerprintBiometricAllowed)
+            .stateIn(scope, SharingStarted.Eagerly, false)
+
+    override val isFaceAuthEnrolledAndEnabled: Flow<Boolean>
+        get() = isFaceAuthenticationEnabled.and(isFaceEnrolled)
+
+    override val isFaceAuthCurrentlyAllowed: Flow<Boolean>
+        get() =
+            isFaceAuthEnrolledAndEnabled
+                .and(isFaceBiometricsAllowed)
+                .and(isFaceAuthSupportedInCurrentPosture)
 }
 
 @OptIn(ExperimentalCoroutinesApi::class)
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/DeviceEntryFaceAuthRepository.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/DeviceEntryFaceAuthRepository.kt
index 30f8f3e..93eb103 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/DeviceEntryFaceAuthRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/DeviceEntryFaceAuthRepository.kt
@@ -26,8 +26,6 @@
 import com.android.keyguard.FaceAuthUiEvent
 import com.android.systemui.Dumpable
 import com.android.systemui.R
-import com.android.systemui.biometrics.data.repository.FacePropertyRepository
-import com.android.systemui.biometrics.shared.model.SensorStrength
 import com.android.systemui.bouncer.domain.interactor.AlternateBouncerInteractor
 import com.android.systemui.common.coroutine.ChannelExt.trySendWithFailureLogging
 import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow
@@ -46,6 +44,7 @@
 import com.android.systemui.keyguard.shared.model.FaceDetectionStatus
 import com.android.systemui.keyguard.shared.model.FailedFaceAuthenticationStatus
 import com.android.systemui.keyguard.shared.model.HelpFaceAuthenticationStatus
+import com.android.systemui.keyguard.shared.model.KeyguardState
 import com.android.systemui.keyguard.shared.model.SuccessFaceAuthenticationStatus
 import com.android.systemui.keyguard.shared.model.TransitionState
 import com.android.systemui.log.FaceAuthenticationLogger
@@ -71,7 +70,6 @@
 import kotlinx.coroutines.flow.distinctUntilChanged
 import kotlinx.coroutines.flow.filter
 import kotlinx.coroutines.flow.filterNotNull
-import kotlinx.coroutines.flow.flatMapLatest
 import kotlinx.coroutines.flow.flowOf
 import kotlinx.coroutines.flow.launchIn
 import kotlinx.coroutines.flow.map
@@ -160,8 +158,7 @@
     @FaceDetectTableLog private val faceDetectLog: TableLogBuffer,
     @FaceAuthTableLog private val faceAuthLog: TableLogBuffer,
     private val keyguardTransitionInteractor: KeyguardTransitionInteractor,
-    featureFlags: FeatureFlags,
-    facePropertyRepository: FacePropertyRepository,
+    private val featureFlags: FeatureFlags,
     dumpManager: DumpManager,
 ) : DeviceEntryFaceAuthRepository, Dumpable {
     private var authCancellationSignal: CancellationSignal? = null
@@ -181,13 +178,6 @@
     override val detectionStatus: Flow<FaceDetectionStatus>
         get() = _detectionStatus.filterNotNull()
 
-    private val isFaceBiometricsAllowed: Flow<Boolean> =
-        facePropertyRepository.sensorInfo.flatMapLatest {
-            if (it?.strength == SensorStrength.STRONG)
-                biometricSettingsRepository.isStrongBiometricAllowed
-            else biometricSettingsRepository.isNonStrongBiometricAllowed
-        }
-
     private val _isLockedOut = MutableStateFlow(false)
     override val isLockedOut: StateFlow<Boolean> = _isLockedOut
 
@@ -286,8 +276,12 @@
         // starts going to sleep.
         merge(
                 keyguardRepository.wakefulness.map { it.isStartingToSleepOrAsleep() },
-                keyguardRepository.isKeyguardGoingAway,
-                userRepository.userSwitchingInProgress
+                if (featureFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+                    keyguardTransitionInteractor.isInTransitionToState(KeyguardState.GONE)
+                } else {
+                    keyguardRepository.isKeyguardGoingAway
+                },
+                userRepository.userSwitchingInProgress,
             )
             .onEach { anyOfThemIsTrue ->
                 if (anyOfThemIsTrue) {
@@ -308,8 +302,10 @@
                 canFaceAuthOrDetectRun(faceDetectLog),
                 logAndObserve(isBypassEnabled, "isBypassEnabled", faceDetectLog),
                 logAndObserve(
-                    isFaceBiometricsAllowed.isFalse().or(trustRepository.isCurrentUserTrusted),
-                    "biometricIsNotAllowedOrCurrentUserIsTrusted",
+                    biometricSettingsRepository.isFaceAuthCurrentlyAllowed
+                        .isFalse()
+                        .or(trustRepository.isCurrentUserTrusted),
+                    "faceAuthIsNotCurrentlyAllowedOrCurrentUserIsTrusted",
                     faceDetectLog
                 ),
                 // We don't want to run face detect if fingerprint can be used to unlock the device
@@ -341,13 +337,8 @@
     private fun canFaceAuthOrDetectRun(tableLogBuffer: TableLogBuffer): Flow<Boolean> {
         return listOf(
                 logAndObserve(
-                    biometricSettingsRepository.isFaceEnrolled,
-                    "isFaceEnrolled",
-                    tableLogBuffer
-                ),
-                logAndObserve(
-                    biometricSettingsRepository.isFaceAuthenticationEnabled,
-                    "isFaceAuthenticationEnabled",
+                    biometricSettingsRepository.isFaceAuthEnrolledAndEnabled,
+                    "isFaceAuthEnrolledAndEnabled",
                     tableLogBuffer
                 ),
                 logAndObserve(faceAuthPaused.isFalse(), "faceAuthIsNotPaused", tableLogBuffer),
@@ -401,7 +392,11 @@
                     "currentUserIsNotTrusted",
                     faceAuthLog
                 ),
-                logAndObserve(isFaceBiometricsAllowed, "isFaceBiometricsAllowed", faceAuthLog),
+                logAndObserve(
+                    biometricSettingsRepository.isFaceAuthCurrentlyAllowed,
+                    "isFaceAuthCurrentlyAllowed",
+                    faceAuthLog
+                ),
                 logAndObserve(isAuthenticated.isFalse(), "faceNotAuthenticated", faceAuthLog),
             )
             .reduce(::and)
@@ -581,7 +576,7 @@
             // We always want to invoke face detect in the main thread.
             faceAuthLogger.faceDetectionStarted()
             faceManager?.detectFace(
-                detectCancellationSignal,
+                checkNotNull(detectCancellationSignal),
                 detectionCallback,
                 FaceAuthenticateOptions.Builder().setUserId(currentUserId).build()
             )
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardRepository.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardRepository.kt
index f1b3441..42cd3a5 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardRepository.kt
@@ -99,7 +99,16 @@
     /** Is an activity showing over the keyguard? */
     val isKeyguardOccluded: Flow<Boolean>
 
-    /** Observable for the signal that keyguard is about to go away. */
+    /**
+     * Observable for the signal that keyguard is about to go away.
+     *
+     * TODO(b/278086361): Remove once KEYGUARD_WM_STATE_REFACTOR flag is removed.
+     */
+    @Deprecated(
+        "Use KeyguardTransitionInteractor flows instead. The closest match for 'going " +
+            "away' is isInTransitionToState(GONE), but consider using more specific flows " +
+            "whenever possible."
+    )
     val isKeyguardGoingAway: Flow<Boolean>
 
     /** Is the always-on display available to be used? */
@@ -199,13 +208,16 @@
     fun setAnimateDozingTransitions(animate: Boolean)
 
     /** Sets the current amount of alpha that should be used for rendering the bottom area. */
-    @Deprecated("Deprecated as part of b/278057014")
-    fun setBottomAreaAlpha(alpha: Float)
+    @Deprecated("Deprecated as part of b/278057014") fun setBottomAreaAlpha(alpha: Float)
 
     /** Sets the current amount of alpha that should be used for rendering the keyguard. */
     fun setKeyguardAlpha(alpha: Float)
 
-    fun setKeyguardVisibility(statusBarState: Int, goingToFullShade: Boolean, occlusionTransitionRunning: Boolean)
+    fun setKeyguardVisibility(
+        statusBarState: Int,
+        goingToFullShade: Boolean,
+        occlusionTransitionRunning: Boolean
+    )
 
     /**
      * Sets the relative offset of the lock-screen clock from its natural position on the screen.
@@ -362,10 +374,11 @@
 
                 awaitClose { keyguardStateController.removeCallback(callback) }
             }
+            .distinctUntilChanged()
             .stateIn(
-                scope = scope,
-                started = SharingStarted.WhileSubscribed(),
-                initialValue = keyguardStateController.isUnlocked,
+                scope,
+                SharingStarted.Eagerly,
+                initialValue = false,
             )
 
     override val isKeyguardGoingAway: Flow<Boolean> = conflatedCallbackFlow {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardRepositoryModule.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardRepositoryModule.kt
index 246ee33..2f80106 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardRepositoryModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardRepositoryModule.kt
@@ -32,6 +32,11 @@
     @Binds fun keyguardRepository(impl: KeyguardRepositoryImpl): KeyguardRepository
 
     @Binds
+    fun keyguardSurfaceBehindRepository(
+        impl: KeyguardSurfaceBehindRepositoryImpl
+    ): KeyguardSurfaceBehindRepository
+
+    @Binds
     fun keyguardTransitionRepository(
         impl: KeyguardTransitionRepositoryImpl
     ): KeyguardTransitionRepository
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardSurfaceBehindRepository.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardSurfaceBehindRepository.kt
new file mode 100644
index 0000000..014b7fa
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardSurfaceBehindRepository.kt
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.data.repository
+
+import com.android.systemui.dagger.SysUISingleton
+import javax.inject.Inject
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/**
+ * State related to SysUI's handling of the surface behind the keyguard (typically an app or the
+ * launcher). We manipulate this surface during unlock animations.
+ */
+interface KeyguardSurfaceBehindRepository {
+
+    /** Whether we're running animations on the surface. */
+    val isAnimatingSurface: Flow<Boolean>
+
+    /** Set whether we're running animations on the surface. */
+    fun setAnimatingSurface(animating: Boolean)
+}
+
+@SysUISingleton
+class KeyguardSurfaceBehindRepositoryImpl @Inject constructor() : KeyguardSurfaceBehindRepository {
+    private val _isAnimatingSurface = MutableStateFlow(false)
+    override val isAnimatingSurface = _isAnimatingSurface.asStateFlow()
+
+    override fun setAnimatingSurface(animating: Boolean) {
+        _isAnimatingSurface.value = animating
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepository.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepository.kt
index 6a2511f..1c0b73f 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepository.kt
@@ -163,12 +163,13 @@
 
     private fun constructCircleRevealFromPoint(point: Point): LightRevealEffect {
         return with(point) {
+            val display = checkNotNull(context.display)
             CircleReveal(
                 x,
                 y,
                 startRadius = 0,
                 endRadius =
-                    max(max(x, context.display.width - x), max(y, context.display.height - y)),
+                    max(max(x, display.width - x), max(y, display.height - y)),
             )
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAlternateBouncerTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAlternateBouncerTransitionInteractor.kt
index 8f0b91b..b050890 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAlternateBouncerTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAlternateBouncerTransitionInteractor.kt
@@ -17,7 +17,6 @@
 package com.android.systemui.keyguard.domain.interactor
 
 import android.animation.ValueAnimator
-import com.android.app.animation.Interpolators
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
 import com.android.systemui.keyguard.data.repository.KeyguardTransitionRepository
@@ -26,6 +25,7 @@
 import com.android.systemui.util.kotlin.Utils.Companion.toQuad
 import com.android.systemui.util.kotlin.Utils.Companion.toQuint
 import com.android.systemui.util.kotlin.sample
+import com.android.wm.shell.animation.Interpolators
 import javax.inject.Inject
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.delay
@@ -50,6 +50,7 @@
         listenForAlternateBouncerToGone()
         listenForAlternateBouncerToLockscreenAodOrDozing()
         listenForAlternateBouncerToPrimaryBouncer()
+        listenForTransitionToCamera(scope, keyguardInteractor)
     }
 
     private fun listenForAlternateBouncerToLockscreenAodOrDozing() {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAodTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAodTransitionInteractor.kt
index 888f746..518ae2f 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAodTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromAodTransitionInteractor.kt
@@ -47,6 +47,7 @@
     override fun start() {
         listenForAodToLockscreenOrOccluded()
         listenForAodToGone()
+        listenForTransitionToCamera(scope, keyguardInteractor)
     }
 
     private fun listenForAodToLockscreenOrOccluded() {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDozingTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDozingTransitionInteractor.kt
index 76d9893..712215f 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDozingTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDozingTransitionInteractor.kt
@@ -47,6 +47,7 @@
     override fun start() {
         listenForDozingToLockscreenOrOccluded()
         listenForDozingToGone()
+        listenForTransitionToCamera(scope, keyguardInteractor)
     }
 
     private fun listenForDozingToLockscreenOrOccluded() {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDreamingTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDreamingTransitionInteractor.kt
index 954ff6f..75aa4b60f 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDreamingTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDreamingTransitionInteractor.kt
@@ -51,6 +51,7 @@
         listenForDreamingToOccluded()
         listenForDreamingToGone()
         listenForDreamingToDozing()
+        listenForTransitionToCamera(scope, keyguardInteractor)
     }
 
     fun startToLockscreenTransition() {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractor.kt
index 6b28b27..9c6a1b1 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractor.kt
@@ -20,8 +20,11 @@
 import com.android.app.animation.Interpolators
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
 import com.android.systemui.keyguard.data.repository.KeyguardTransitionRepository
 import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.keyguard.shared.model.KeyguardSurfaceBehindModel
 import com.android.systemui.keyguard.shared.model.StatusBarState.KEYGUARD
 import com.android.systemui.keyguard.shared.model.TransitionInfo
 import com.android.systemui.keyguard.shared.model.TransitionState
@@ -34,7 +37,11 @@
 import javax.inject.Inject
 import kotlin.time.Duration.Companion.milliseconds
 import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onStart
 import kotlinx.coroutines.launch
 
 @SysUISingleton
@@ -45,6 +52,7 @@
     override val transitionInteractor: KeyguardTransitionInteractor,
     @Application private val scope: CoroutineScope,
     private val keyguardInteractor: KeyguardInteractor,
+    private val flags: FeatureFlags,
     private val shadeRepository: ShadeRepository,
 ) :
     TransitionInteractor(
@@ -53,13 +61,75 @@
 
     override fun start() {
         listenForLockscreenToGone()
+        listenForLockscreenToGoneDragging()
         listenForLockscreenToOccluded()
-        listenForLockscreenToCamera()
         listenForLockscreenToAodOrDozing()
         listenForLockscreenToPrimaryBouncer()
         listenForLockscreenToDreaming()
         listenForLockscreenToPrimaryBouncerDragging()
         listenForLockscreenToAlternateBouncer()
+        listenForLockscreenTransitionToCamera()
+    }
+
+    /**
+     * Whether we want the surface behind the keyguard visible for the transition from LOCKSCREEN,
+     * or null if we don't care and should just use a reasonable default.
+     *
+     * [KeyguardSurfaceBehindInteractor] will switch to this flow whenever a transition from
+     * LOCKSCREEN is running.
+     */
+    val surfaceBehindVisibility: Flow<Boolean?> =
+        transitionInteractor.startedKeyguardTransitionStep
+            .map { startedStep ->
+                if (startedStep.to != KeyguardState.GONE) {
+                    // LOCKSCREEN to anything but GONE does not require any special surface
+                    // visibility handling.
+                    return@map null
+                }
+
+                true // TODO(b/278086361): Implement continuous swipe to unlock.
+            }
+            .onStart {
+                // Default to null ("don't care, use a reasonable default").
+                emit(null)
+            }
+            .distinctUntilChanged()
+
+    /**
+     * The surface behind view params to use for the transition from LOCKSCREEN, or null if we don't
+     * care and should use a reasonable default.
+     */
+    val surfaceBehindModel: Flow<KeyguardSurfaceBehindModel?> =
+        combine(
+                transitionInteractor.startedKeyguardTransitionStep,
+                transitionInteractor.transitionStepsFromState(KeyguardState.LOCKSCREEN)
+            ) { startedStep, fromLockscreenStep ->
+                if (startedStep.to != KeyguardState.GONE) {
+                    // Only LOCKSCREEN -> GONE has specific surface params (for the unlock
+                    // animation).
+                    return@combine null
+                } else if (fromLockscreenStep.value > 0.5f) {
+                    // Start the animation once we're 50% transitioned to GONE.
+                    KeyguardSurfaceBehindModel(
+                        animateFromAlpha = 0f,
+                        alpha = 1f,
+                        animateFromTranslationY = 500f,
+                        translationY = 0f
+                    )
+                } else {
+                    KeyguardSurfaceBehindModel(
+                        alpha = 0f,
+                    )
+                }
+            }
+            .onStart {
+                // Default to null ("don't care, use a reasonable default").
+                emit(null)
+            }
+            .distinctUntilChanged()
+
+    private fun listenForLockscreenTransitionToCamera() {
+        listenForTransitionToCamera(scope, keyguardInteractor)
     }
 
     private fun listenForLockscreenToDreaming() {
@@ -169,7 +239,8 @@
                             }
 
                             // If canceled, just put the state back
-                            // TODO: This logic should happen in FromPrimaryBouncerInteractor.
+                            // TODO(b/278086361): This logic should happen in
+                            //  FromPrimaryBouncerInteractor.
                             if (nextState == TransitionState.CANCELED) {
                                 transitionRepository.startTransition(
                                     TransitionInfo(
@@ -201,7 +272,32 @@
         }
     }
 
+    fun dismissKeyguard() {
+        startTransitionTo(KeyguardState.GONE)
+    }
+
     private fun listenForLockscreenToGone() {
+        if (flags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+            return
+        }
+
+        scope.launch {
+            keyguardInteractor.isKeyguardGoingAway
+                .sample(transitionInteractor.startedKeyguardTransitionStep, ::Pair)
+                .collect { pair ->
+                    val (isKeyguardGoingAway, lastStartedStep) = pair
+                    if (isKeyguardGoingAway && lastStartedStep.to == KeyguardState.LOCKSCREEN) {
+                        startTransitionTo(KeyguardState.GONE)
+                    }
+                }
+        }
+    }
+
+    private fun listenForLockscreenToGoneDragging() {
+        if (flags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+            return
+        }
+
         scope.launch {
             keyguardInteractor.isKeyguardGoingAway
                 .sample(transitionInteractor.startedKeyguardTransitionStep, ::Pair)
@@ -219,7 +315,7 @@
             keyguardInteractor.isKeyguardOccluded
                 .sample(
                     combine(
-                        transitionInteractor.finishedKeyguardState,
+                        transitionInteractor.startedKeyguardState,
                         keyguardInteractor.isDreaming,
                         ::Pair
                     ),
@@ -233,27 +329,6 @@
         }
     }
 
-    /** This signal may come in before the occlusion signal, and can provide a custom transition */
-    private fun listenForLockscreenToCamera() {
-        scope.launch {
-            keyguardInteractor.onCameraLaunchDetected
-                .sample(transitionInteractor.startedKeyguardTransitionStep, ::Pair)
-                .collect { (_, lastStartedStep) ->
-                    // DREAMING/AOD/OFF may trigger on the first power button push, so include this
-                    // state in order to cancel and correct the transition
-                    if (
-                        lastStartedStep.to == KeyguardState.LOCKSCREEN ||
-                            lastStartedStep.to == KeyguardState.DREAMING ||
-                            lastStartedStep.to == KeyguardState.DOZING ||
-                            lastStartedStep.to == KeyguardState.AOD ||
-                            lastStartedStep.to == KeyguardState.OFF
-                    ) {
-                        startTransitionTo(KeyguardState.OCCLUDED)
-                    }
-                }
-        }
-    }
-
     private fun listenForLockscreenToAodOrDozing() {
         scope.launch {
             keyguardInteractor.wakefulnessModel
@@ -291,7 +366,7 @@
     }
 
     companion object {
-        private val DEFAULT_DURATION = 500.milliseconds
+        private val DEFAULT_DURATION = 400.milliseconds
         val TO_DREAMING_DURATION = 933.milliseconds
         val TO_OCCLUDED_DURATION = 450.milliseconds
     }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractor.kt
index 9142d1f..143be1d 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractor.kt
@@ -17,23 +17,28 @@
 package com.android.systemui.keyguard.domain.interactor
 
 import android.animation.ValueAnimator
-import com.android.app.animation.Interpolators
 import com.android.keyguard.KeyguardSecurityModel
-import com.android.keyguard.KeyguardSecurityModel.SecurityMode.Password
 import com.android.keyguard.KeyguardUpdateMonitor
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
 import com.android.systemui.keyguard.data.repository.KeyguardTransitionRepository
 import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.keyguard.shared.model.KeyguardSurfaceBehindModel
 import com.android.systemui.keyguard.shared.model.WakefulnessState
 import com.android.systemui.util.kotlin.Utils.Companion.toQuad
 import com.android.systemui.util.kotlin.Utils.Companion.toQuint
 import com.android.systemui.util.kotlin.Utils.Companion.toTriple
 import com.android.systemui.util.kotlin.sample
+import com.android.wm.shell.animation.Interpolators
 import javax.inject.Inject
 import kotlin.time.Duration.Companion.milliseconds
 import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.onStart
 import kotlinx.coroutines.launch
 
 @SysUISingleton
@@ -44,6 +49,7 @@
     override val transitionInteractor: KeyguardTransitionInteractor,
     @Application private val scope: CoroutineScope,
     private val keyguardInteractor: KeyguardInteractor,
+    private val flags: FeatureFlags,
     private val keyguardSecurityModel: KeyguardSecurityModel,
 ) :
     TransitionInteractor(
@@ -55,6 +61,58 @@
         listenForPrimaryBouncerToAodOrDozing()
         listenForPrimaryBouncerToLockscreenOrOccluded()
         listenForPrimaryBouncerToDreamingLockscreenHosted()
+        listenForTransitionToCamera(scope, keyguardInteractor)
+    }
+
+    val surfaceBehindVisibility: Flow<Boolean?> =
+        combine(
+                transitionInteractor.startedKeyguardTransitionStep,
+                transitionInteractor.transitionStepsFromState(KeyguardState.PRIMARY_BOUNCER)
+            ) { startedStep, fromBouncerStep ->
+                if (startedStep.to != KeyguardState.GONE) {
+                    return@combine null
+                }
+
+                fromBouncerStep.value > 0.5f
+            }
+            .onStart {
+                // Default to null ("don't care, use a reasonable default").
+                emit(null)
+            }
+            .distinctUntilChanged()
+
+    val surfaceBehindModel: Flow<KeyguardSurfaceBehindModel?> =
+        combine(
+                transitionInteractor.startedKeyguardTransitionStep,
+                transitionInteractor.transitionStepsFromState(KeyguardState.PRIMARY_BOUNCER)
+            ) { startedStep, fromBouncerStep ->
+                if (startedStep.to != KeyguardState.GONE) {
+                    // BOUNCER to anything but GONE does not require any special surface
+                    // visibility handling.
+                    return@combine null
+                }
+
+                if (fromBouncerStep.value > 0.5f) {
+                    KeyguardSurfaceBehindModel(
+                        animateFromAlpha = 0f,
+                        alpha = 1f,
+                        animateFromTranslationY = 500f,
+                        translationY = 0f,
+                    )
+                } else {
+                    KeyguardSurfaceBehindModel(
+                        alpha = 0f,
+                    )
+                }
+            }
+            .onStart {
+                // Default to null ("don't care, use a reasonable default").
+                emit(null)
+            }
+            .distinctUntilChanged()
+
+    fun dismissPrimaryBouncer() {
+        startTransitionTo(KeyguardState.GONE)
     }
 
     private fun listenForPrimaryBouncerToLockscreenOrOccluded() {
@@ -124,28 +182,34 @@
     private fun listenForPrimaryBouncerToDreamingLockscreenHosted() {
         scope.launch {
             keyguardInteractor.primaryBouncerShowing
-                .sample(
-                    combine(
-                        keyguardInteractor.isActiveDreamLockscreenHosted,
-                        transitionInteractor.startedKeyguardTransitionStep,
-                        ::Pair
-                    ),
-                    ::toTriple
-                )
-                .collect {
-                    (isBouncerShowing, isActiveDreamLockscreenHosted, lastStartedTransitionStep) ->
-                    if (
-                        !isBouncerShowing &&
-                            isActiveDreamLockscreenHosted &&
-                            lastStartedTransitionStep.to == KeyguardState.PRIMARY_BOUNCER
-                    ) {
-                        startTransitionTo(KeyguardState.DREAMING_LOCKSCREEN_HOSTED)
+                    .sample(
+                            combine(
+                                    keyguardInteractor.isActiveDreamLockscreenHosted,
+                                    transitionInteractor.startedKeyguardTransitionStep,
+                                    ::Pair
+                            ),
+                            ::toTriple
+                    )
+                    .collect { (isBouncerShowing, isActiveDreamLockscreenHosted, lastStartedTransitionStep) ->
+                        if (
+                                !isBouncerShowing &&
+                                isActiveDreamLockscreenHosted &&
+                                lastStartedTransitionStep.to == KeyguardState.PRIMARY_BOUNCER
+                        ) {
+                            startTransitionTo(KeyguardState.DREAMING_LOCKSCREEN_HOSTED)
+                        }
                     }
-                }
         }
     }
 
     private fun listenForPrimaryBouncerToGone() {
+        if (flags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+            // This is handled in KeyguardSecurityContainerController and
+            // StatusBarKeyguardViewManager, which calls the transition interactor to kick off a
+            // transition vs. listening to legacy state flags.
+            return
+        }
+
         scope.launch {
             keyguardInteractor.isKeyguardGoingAway
                 .sample(transitionInteractor.startedKeyguardTransitionStep, ::Pair)
@@ -160,7 +224,7 @@
                             )
                         // IME for password requires a slightly faster animation
                         val duration =
-                            if (securityMode == Password) {
+                            if (securityMode == KeyguardSecurityModel.SecurityMode.Password) {
                                 TO_GONE_SHORT_DURATION
                             } else {
                                 TO_GONE_DURATION
@@ -188,7 +252,7 @@
 
     companion object {
         private val DEFAULT_DURATION = 300.milliseconds
-        val TO_GONE_DURATION = 250.milliseconds
+        val TO_GONE_DURATION = 500.milliseconds
         val TO_GONE_SHORT_DURATION = 200.milliseconds
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardInteractor.kt
index 53d3c07..ed84884 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardInteractor.kt
@@ -34,6 +34,7 @@
 import com.android.systemui.keyguard.shared.model.DozeStateModel.Companion.isDozeOff
 import com.android.systemui.keyguard.shared.model.DozeTransitionModel
 import com.android.systemui.keyguard.shared.model.KeyguardRootViewVisibilityState
+import com.android.systemui.keyguard.shared.model.KeyguardState
 import com.android.systemui.keyguard.shared.model.ScreenModel
 import com.android.systemui.keyguard.shared.model.StatusBarState
 import com.android.systemui.keyguard.shared.model.WakefulnessModel
@@ -43,7 +44,6 @@
 import kotlinx.coroutines.channels.awaitClose
 import kotlinx.coroutines.delay
 import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.flow.combine
 import kotlinx.coroutines.flow.distinctUntilChanged
@@ -67,18 +67,6 @@
     bouncerRepository: KeyguardBouncerRepository,
     configurationRepository: ConfigurationRepository,
 ) {
-
-    data class PreviewMode(
-        val isInPreviewMode: Boolean = false,
-        val shouldHighlightSelectedAffordance: Boolean = false,
-    )
-
-    /**
-     * Whether this view-model instance is powering the preview experience that renders exclusively
-     * in the wallpaper picker application. This should _always_ be `false` for the real lock screen
-     * experience.
-     */
-    val previewMode = MutableStateFlow(PreviewMode())
     /**
      * The amount of doze the system is in, where `1.0` is fully dozing and `0.0` is not dozing at
      * all.
@@ -264,7 +252,26 @@
         repository.setAnimateDozingTransitions(animate)
     }
 
+    fun isKeyguardDismissable(): Boolean {
+        return repository.isKeyguardUnlocked.value
+    }
+
     companion object {
         private const val TAG = "KeyguardInteractor"
+
+        fun isKeyguardVisibleInState(state: KeyguardState): Boolean {
+            return when (state) {
+                KeyguardState.OFF -> true
+                KeyguardState.DOZING -> true
+                KeyguardState.DREAMING -> true
+                KeyguardState.AOD -> true
+                KeyguardState.ALTERNATE_BOUNCER -> true
+                KeyguardState.PRIMARY_BOUNCER -> true
+                KeyguardState.LOCKSCREEN -> true
+                KeyguardState.GONE -> false
+                KeyguardState.OCCLUDED -> true
+                KeyguardState.DREAMING_LOCKSCREEN_HOSTED -> false
+            }
+        }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractor.kt
new file mode 100644
index 0000000..635961b
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractor.kt
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.domain.interactor
+
+import android.content.Context
+import android.media.AudioManager
+import android.view.KeyEvent
+import com.android.systemui.back.domain.interactor.BackActionInteractor
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyevent.domain.interactor.KeyEventInteractor.Companion.handleAction
+import com.android.systemui.media.controls.util.MediaSessionLegacyHelperWrapper
+import com.android.systemui.plugins.statusbar.StatusBarStateController
+import com.android.systemui.shade.ShadeController
+import com.android.systemui.statusbar.StatusBarState
+import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager
+import javax.inject.Inject
+
+/** Handles key events arriving when the keyguard is showing or device is dozing. */
+@SysUISingleton
+class KeyguardKeyEventInteractor
+@Inject
+constructor(
+    private val context: Context,
+    private val statusBarStateController: StatusBarStateController,
+    private val keyguardInteractor: KeyguardInteractor,
+    private val statusBarKeyguardViewManager: StatusBarKeyguardViewManager,
+    private val shadeController: ShadeController,
+    private val mediaSessionLegacyHelperWrapper: MediaSessionLegacyHelperWrapper,
+    private val backActionInteractor: BackActionInteractor,
+) {
+
+    fun dispatchKeyEvent(event: KeyEvent): Boolean {
+        if (statusBarStateController.isDozing) {
+            when (event.keyCode) {
+                KeyEvent.KEYCODE_VOLUME_DOWN,
+                KeyEvent.KEYCODE_VOLUME_UP -> return dispatchVolumeKeyEvent(event)
+            }
+        }
+
+        if (event.handleAction()) {
+            when (event.keyCode) {
+                KeyEvent.KEYCODE_MENU -> return dispatchMenuKeyEvent()
+                KeyEvent.KEYCODE_SPACE -> return dispatchSpaceEvent()
+            }
+        }
+        return false
+    }
+
+    /**
+     * While IME is active and a BACK event is detected, check with {@link
+     * StatusBarKeyguardViewManager#dispatchBackKeyEventPreIme()} to see if the event should be
+     * handled before routing to IME, in order to prevent the user from having to hit back twice to
+     * exit bouncer.
+     */
+    fun dispatchKeyEventPreIme(event: KeyEvent): Boolean {
+        when (event.keyCode) {
+            KeyEvent.KEYCODE_BACK ->
+                if (
+                    statusBarStateController.state == StatusBarState.KEYGUARD &&
+                        statusBarKeyguardViewManager.dispatchBackKeyEventPreIme()
+                ) {
+                    return backActionInteractor.onBackRequested()
+                }
+        }
+        return false
+    }
+
+    fun interceptMediaKey(event: KeyEvent): Boolean {
+        return statusBarStateController.state == StatusBarState.KEYGUARD &&
+            statusBarKeyguardViewManager.interceptMediaKey(event)
+    }
+
+    private fun dispatchMenuKeyEvent(): Boolean {
+        val shouldUnlockOnMenuPressed =
+            isDeviceInteractive() &&
+                (statusBarStateController.state != StatusBarState.SHADE) &&
+                statusBarKeyguardViewManager.shouldDismissOnMenuPressed()
+        if (shouldUnlockOnMenuPressed) {
+            shadeController.animateCollapseShadeForced()
+            return true
+        }
+        return false
+    }
+
+    private fun dispatchSpaceEvent(): Boolean {
+        if (isDeviceInteractive() && statusBarStateController.state != StatusBarState.SHADE) {
+            shadeController.animateCollapseShadeForced()
+            return true
+        }
+        return false
+    }
+
+    private fun dispatchVolumeKeyEvent(event: KeyEvent): Boolean {
+        mediaSessionLegacyHelperWrapper
+            .getHelper(context)
+            .sendVolumeKeyEvent(event, AudioManager.USE_DEFAULT_STREAM_TYPE, true)
+        return true
+    }
+
+    private fun isDeviceInteractive(): Boolean {
+        return keyguardInteractor.wakefulnessModel.value.isDeviceInteractive()
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardSurfaceBehindInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardSurfaceBehindInteractor.kt
new file mode 100644
index 0000000..bf04f8f
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardSurfaceBehindInteractor.kt
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.domain.interactor
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyguard.data.repository.KeyguardSurfaceBehindRepository
+import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.keyguard.shared.model.KeyguardSurfaceBehindModel
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.map
+import javax.inject.Inject
+
+@SysUISingleton
+class KeyguardSurfaceBehindInteractor
+@Inject
+constructor(
+    private val repository: KeyguardSurfaceBehindRepository,
+    private val fromLockscreenInteractor: FromLockscreenTransitionInteractor,
+    private val fromPrimaryBouncerInteractor: FromPrimaryBouncerTransitionInteractor,
+    transitionInteractor: KeyguardTransitionInteractor,
+) {
+
+    @OptIn(ExperimentalCoroutinesApi::class)
+    val viewParams: Flow<KeyguardSurfaceBehindModel> =
+        transitionInteractor.isInTransitionToAnyState
+            .flatMapLatest { isInTransition ->
+                if (!isInTransition) {
+                    defaultParams
+                } else {
+                    combine(
+                        transitionSpecificViewParams,
+                        defaultParams,
+                    ) { transitionParams, defaultParams ->
+                        transitionParams ?: defaultParams
+                    }
+                }
+            }
+
+    val isAnimatingSurface = repository.isAnimatingSurface
+
+    private val defaultParams =
+        transitionInteractor.finishedKeyguardState.map { state ->
+            KeyguardSurfaceBehindModel(
+                alpha =
+                    if (WindowManagerLockscreenVisibilityInteractor.isSurfaceVisible(state)) 1f
+                    else 0f
+            )
+        }
+
+    /**
+     * View params provided by the transition interactor for the most recently STARTED transition.
+     * This is used to run transition-specific animations on the surface.
+     *
+     * If null, there are no transition-specific view params needed for this transition and we will
+     * use a reasonable default.
+     */
+    @OptIn(ExperimentalCoroutinesApi::class)
+    private val transitionSpecificViewParams: Flow<KeyguardSurfaceBehindModel?> =
+        transitionInteractor.startedKeyguardTransitionStep.flatMapLatest { startedStep ->
+            when (startedStep.from) {
+                KeyguardState.LOCKSCREEN -> fromLockscreenInteractor.surfaceBehindModel
+                KeyguardState.PRIMARY_BOUNCER -> fromPrimaryBouncerInteractor.surfaceBehindModel
+                // Return null for other states, where no transition specific params are needed.
+                else -> flowOf(null)
+            }
+        }
+
+    fun setAnimatingSurface(animating: Boolean) {
+        repository.setAnimatingSurface(animating)
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionAuditLogger.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionAuditLogger.kt
index 4f7abd4..0dc16e9 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionAuditLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionAuditLogger.kt
@@ -95,5 +95,11 @@
                 logger.log(TAG, VERBOSE, "Doze transition", it)
             }
         }
+
+        scope.launch {
+            keyguardInteractor.onCameraLaunchDetected.collect {
+                logger.log(TAG, VERBOSE, "onCameraLaunchDetected", it)
+            }
+        }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractor.kt
index 8c4c7ae..9382618 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractor.kt
@@ -17,17 +17,20 @@
 
 package com.android.systemui.keyguard.domain.interactor
 
+import android.util.Log
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
 import com.android.systemui.keyguard.data.repository.KeyguardTransitionRepository
 import com.android.systemui.keyguard.shared.model.KeyguardState
 import com.android.systemui.keyguard.shared.model.KeyguardState.ALTERNATE_BOUNCER
 import com.android.systemui.keyguard.shared.model.KeyguardState.AOD
+import com.android.systemui.keyguard.shared.model.KeyguardState.DOZING
 import com.android.systemui.keyguard.shared.model.KeyguardState.DREAMING
 import com.android.systemui.keyguard.shared.model.KeyguardState.DREAMING_LOCKSCREEN_HOSTED
 import com.android.systemui.keyguard.shared.model.KeyguardState.GONE
 import com.android.systemui.keyguard.shared.model.KeyguardState.LOCKSCREEN
 import com.android.systemui.keyguard.shared.model.KeyguardState.OCCLUDED
+import com.android.systemui.keyguard.shared.model.KeyguardState.OFF
 import com.android.systemui.keyguard.shared.model.KeyguardState.PRIMARY_BOUNCER
 import com.android.systemui.keyguard.shared.model.TransitionState
 import com.android.systemui.keyguard.shared.model.TransitionStep
@@ -36,6 +39,7 @@
 import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.SharingStarted
 import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.combine
 import kotlinx.coroutines.flow.filter
 import kotlinx.coroutines.flow.map
 import kotlinx.coroutines.flow.merge
@@ -46,8 +50,12 @@
 class KeyguardTransitionInteractor
 @Inject
 constructor(
-    private val repository: KeyguardTransitionRepository,
     @Application val scope: CoroutineScope,
+    private val repository: KeyguardTransitionRepository,
+    private val keyguardInteractor: dagger.Lazy<KeyguardInteractor>,
+    private val fromLockscreenTransitionInteractor: dagger.Lazy<FromLockscreenTransitionInteractor>,
+    private val fromPrimaryBouncerTransitionInteractor:
+        dagger.Lazy<FromPrimaryBouncerTransitionInteractor>,
 ) {
     private val TAG = this::class.simpleName
 
@@ -128,12 +136,11 @@
         repository.transition(PRIMARY_BOUNCER, GONE)
 
     /** OFF->LOCKSCREEN transition information. */
-    val offToLockscreenTransition: Flow<TransitionStep> =
-        repository.transition(KeyguardState.OFF, LOCKSCREEN)
+    val offToLockscreenTransition: Flow<TransitionStep> = repository.transition(OFF, LOCKSCREEN)
 
     /** DOZING->LOCKSCREEN transition information. */
     val dozingToLockscreenTransition: Flow<TransitionStep> =
-        repository.transition(KeyguardState.DOZING, LOCKSCREEN)
+        repository.transition(DOZING, LOCKSCREEN)
 
     /**
      * AOD<->LOCKSCREEN transition information, mapped to dozeAmount range of AOD (1f) <->
@@ -157,17 +164,30 @@
     val finishedKeyguardTransitionStep: Flow<TransitionStep> =
         repository.transitions.filter { step -> step.transitionState == TransitionState.FINISHED }
 
-    /** The destination state of the last started transition */
+    /** The destination state of the last started transition. */
     val startedKeyguardState: StateFlow<KeyguardState> =
         startedKeyguardTransitionStep
             .map { step -> step.to }
-            .stateIn(scope, SharingStarted.Eagerly, KeyguardState.OFF)
+            .stateIn(scope, SharingStarted.Eagerly, OFF)
 
     /** The last completed [KeyguardState] transition */
     val finishedKeyguardState: StateFlow<KeyguardState> =
         finishedKeyguardTransitionStep
             .map { step -> step.to }
             .stateIn(scope, SharingStarted.Eagerly, LOCKSCREEN)
+
+    /**
+     * Whether we're currently in a transition to a new [KeyguardState] and haven't yet completed
+     * it.
+     */
+    val isInTransitionToAnyState =
+            combine(
+                    startedKeyguardTransitionStep,
+                    finishedKeyguardState,
+            ) { startedStep, finishedState ->
+                startedStep.to != finishedState
+            }
+
     /**
      * The amount of transition into or out of the given [KeyguardState].
      *
@@ -187,4 +207,41 @@
                 }
             }
     }
+
+    fun transitionStepsFromState(fromState: KeyguardState): Flow<TransitionStep> {
+        return repository.transitions.filter { step -> step.from == fromState }
+    }
+
+    fun transitionStepsToState(toState: KeyguardState): Flow<TransitionStep> {
+        return repository.transitions.filter { step -> step.to == toState }
+    }
+
+    /**
+     * Called to start a transition that will ultimately dismiss the keyguard from the current
+     * state.
+     */
+    fun startDismissKeyguardTransition() {
+        when (startedKeyguardState.value) {
+            LOCKSCREEN -> fromLockscreenTransitionInteractor.get().dismissKeyguard()
+            PRIMARY_BOUNCER -> fromPrimaryBouncerTransitionInteractor.get().dismissPrimaryBouncer()
+            else ->
+                Log.e(
+                    "KeyguardTransitionInteractor",
+                    "We don't know how to dismiss keyguard from state " +
+                        "${startedKeyguardState.value}"
+                )
+        }
+    }
+
+    /** Whether we're in a transition to the given [KeyguardState], but haven't yet completed it. */
+    fun isInTransitionToState(
+            state: KeyguardState,
+    ): Flow<Boolean> {
+        return combine(
+                startedKeyguardTransitionStep,
+                finishedKeyguardState,
+        ) { startedStep, finishedState ->
+            startedStep.to == state && finishedState != state
+        }
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/LockscreenSceneInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/LockscreenSceneInteractor.kt
deleted file mode 100644
index 278c68d..0000000
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/LockscreenSceneInteractor.kt
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.domain.interactor
-
-import com.android.systemui.authentication.domain.interactor.AuthenticationInteractor
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
-import com.android.systemui.bouncer.domain.interactor.BouncerInteractor
-import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.dagger.qualifiers.Application
-import javax.inject.Inject
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.flow.SharingStarted
-import kotlinx.coroutines.flow.StateFlow
-import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.flow.stateIn
-
-/** Hosts business and application state accessing logic for the lockscreen scene. */
-@SysUISingleton
-class LockscreenSceneInteractor
-@Inject
-constructor(
-    @Application applicationScope: CoroutineScope,
-    private val authenticationInteractor: AuthenticationInteractor,
-    private val bouncerInteractor: BouncerInteractor,
-) {
-    /** Whether the device is currently locked. */
-    val isDeviceLocked: StateFlow<Boolean> =
-        authenticationInteractor.isUnlocked
-            .map { !it }
-            .stateIn(
-                scope = applicationScope,
-                started = SharingStarted.WhileSubscribed(),
-                initialValue = !authenticationInteractor.isUnlocked.value,
-            )
-
-    /** Whether it's currently possible to swipe up to dismiss the lockscreen. */
-    val isSwipeToDismissEnabled: StateFlow<Boolean> =
-        authenticationInteractor.isUnlocked
-            .map { isUnlocked ->
-                !isUnlocked &&
-                    authenticationInteractor.getAuthenticationMethod() is
-                        AuthenticationMethodModel.Swipe
-            }
-            .stateIn(
-                scope = applicationScope,
-                started = SharingStarted.WhileSubscribed(),
-                initialValue = false,
-            )
-
-    /** Attempts to dismiss the lockscreen. This will cause the bouncer to show, if needed. */
-    fun dismissLockscreen() {
-        bouncerInteractor.showOrUnlockDevice()
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/OccludingAppDeviceEntryInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/OccludingAppDeviceEntryInteractor.kt
index ff8d5c9..3ec660a 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/OccludingAppDeviceEntryInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/OccludingAppDeviceEntryInteractor.kt
@@ -22,10 +22,14 @@
 import com.android.systemui.bouncer.domain.interactor.PrimaryBouncerInteractor
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
 import com.android.systemui.keyguard.data.repository.DeviceEntryFingerprintAuthRepository
 import com.android.systemui.keyguard.shared.model.ErrorFingerprintAuthenticationStatus
 import com.android.systemui.keyguard.shared.model.SuccessFingerprintAuthenticationStatus
 import com.android.systemui.plugins.ActivityStarter
+import com.android.systemui.power.domain.interactor.PowerInteractor
+import com.android.systemui.util.kotlin.sample
 import javax.inject.Inject
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -55,6 +59,8 @@
     @Application scope: CoroutineScope,
     private val context: Context,
     activityStarter: ActivityStarter,
+    powerInteractor: PowerInteractor,
+    featureFlags: FeatureFlags,
 ) {
     private val keyguardOccludedByApp: Flow<Boolean> =
         combine(
@@ -87,29 +93,37 @@
             .ifKeyguardOccludedByApp(/* elseFlow */ flowOf(null))
 
     init {
-        scope.launch {
-            // On fingerprint success, go to the home screen
-            fingerprintUnlockSuccessEvents.collect { goToHomeScreen() }
-        }
+        if (featureFlags.isEnabled(Flags.FP_LISTEN_OCCLUDING_APPS)) {
+            scope.launch {
+                // On fingerprint success when the screen is on, go to the home screen
+                fingerprintUnlockSuccessEvents.sample(powerInteractor.isInteractive).collect {
+                    if (it) {
+                        goToHomeScreen()
+                    }
+                    // don't go to the home screen if the authentication is from AOD/dozing/off
+                }
+            }
 
-        scope.launch {
-            // On device fingerprint lockout, request the bouncer with a runnable to
-            // go to the home screen. Without this, the bouncer won't proceed to the home screen.
-            fingerprintLockoutEvents.collect {
-                activityStarter.dismissKeyguardThenExecute(
-                    object : ActivityStarter.OnDismissAction {
-                        override fun onDismiss(): Boolean {
-                            goToHomeScreen()
-                            return false
-                        }
+            scope.launch {
+                // On device fingerprint lockout, request the bouncer with a runnable to
+                // go to the home screen. Without this, the bouncer won't proceed to the home
+                // screen.
+                fingerprintLockoutEvents.collect {
+                    activityStarter.dismissKeyguardThenExecute(
+                        object : ActivityStarter.OnDismissAction {
+                            override fun onDismiss(): Boolean {
+                                goToHomeScreen()
+                                return false
+                            }
 
-                        override fun willRunAnimationOnKeyguard(): Boolean {
-                            return false
-                        }
-                    },
-                    /* cancel= */ null,
-                    /* afterKeyguardGone */ false
-                )
+                            override fun willRunAnimationOnKeyguard(): Boolean {
+                                return false
+                            }
+                        },
+                        /* cancel= */ null,
+                        /* afterKeyguardGone */ false
+                    )
+                }
             }
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/TransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/TransitionInteractor.kt
index 0dda625..54c6d5f 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/TransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/TransitionInteractor.kt
@@ -21,7 +21,10 @@
 import com.android.systemui.keyguard.data.repository.KeyguardTransitionRepository
 import com.android.systemui.keyguard.shared.model.KeyguardState
 import com.android.systemui.keyguard.shared.model.TransitionInfo
+import com.android.systemui.util.kotlin.sample
 import java.util.UUID
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.launch
 
 /**
  * Each TransitionInteractor is responsible for determining under which conditions to notify
@@ -46,7 +49,7 @@
     fun startTransitionTo(
         toState: KeyguardState,
         animator: ValueAnimator? = getDefaultAnimatorForTransitionsToState(toState),
-        resetIfCancelled: Boolean = false
+        resetIfCancelled: Boolean = false,
     ): UUID? {
         if (
             fromState != transitionInteractor.startedKeyguardState.value &&
@@ -75,6 +78,27 @@
         )
     }
 
+    /** This signal may come in before the occlusion signal, and can provide a custom transition */
+    fun listenForTransitionToCamera(
+        scope: CoroutineScope,
+        keyguardInteractor: KeyguardInteractor,
+    ) {
+        scope.launch {
+            keyguardInteractor.onCameraLaunchDetected
+                .sample(transitionInteractor.finishedKeyguardState)
+                .collect { finishedKeyguardState ->
+                    // Other keyguard state transitions may trigger on the first power button push,
+                    // so use the last finishedKeyguardState to determine the overriding FROM state
+                    if (finishedKeyguardState == fromState) {
+                        startTransitionTo(
+                            KeyguardState.OCCLUDED,
+                            resetIfCancelled = true,
+                        )
+                    }
+                }
+        }
+    }
+
     /**
      * Returns a ValueAnimator to be used for transitions to [toState], if one is not explicitly
      * passed to [startTransitionTo].
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractor.kt
new file mode 100644
index 0000000..96bfdc6
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractor.kt
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.domain.interactor
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyguard.shared.model.BiometricUnlockModel
+import com.android.systemui.keyguard.shared.model.KeyguardState
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.map
+import javax.inject.Inject
+
+@SysUISingleton
+class WindowManagerLockscreenVisibilityInteractor
+@Inject
+constructor(
+    keyguardInteractor: KeyguardInteractor,
+    transitionInteractor: KeyguardTransitionInteractor,
+    surfaceBehindInteractor: KeyguardSurfaceBehindInteractor,
+    fromLockscreenInteractor: FromLockscreenTransitionInteractor,
+    fromBouncerInteractor: FromPrimaryBouncerTransitionInteractor,
+) {
+    private val defaultSurfaceBehindVisibility =
+        transitionInteractor.finishedKeyguardState.map(::isSurfaceVisible)
+
+    /**
+     * Surface visibility provided by the From*TransitionInteractor responsible for the currently
+     * RUNNING transition, or null if the current transition does not require special surface
+     * visibility handling.
+     *
+     * An example of transition-specific visibility is swipe to unlock, where the surface should
+     * only be visible after swiping 20% of the way up the screen, and should become invisible again
+     * if the user swipes back down.
+     */
+    @OptIn(ExperimentalCoroutinesApi::class)
+    private val transitionSpecificSurfaceBehindVisibility: Flow<Boolean?> =
+        transitionInteractor.startedKeyguardTransitionStep
+            .flatMapLatest { startedStep ->
+                when (startedStep.from) {
+                    KeyguardState.LOCKSCREEN -> {
+                        fromLockscreenInteractor.surfaceBehindVisibility
+                    }
+                    KeyguardState.PRIMARY_BOUNCER -> {
+                        fromBouncerInteractor.surfaceBehindVisibility
+                    }
+                    else -> flowOf(null)
+                }
+            }
+            .distinctUntilChanged()
+
+    /**
+     * Surface visibility, which is either determined by the default visibility in the FINISHED
+     * KeyguardState, or the transition-specific visibility used during certain RUNNING transitions.
+     */
+    @OptIn(ExperimentalCoroutinesApi::class)
+    val surfaceBehindVisibility: Flow<Boolean> =
+        transitionInteractor
+                .isInTransitionToAnyState
+            .flatMapLatest { isInTransition ->
+                if (!isInTransition) {
+                    defaultSurfaceBehindVisibility
+                } else {
+                    combine(
+                        transitionSpecificSurfaceBehindVisibility,
+                        defaultSurfaceBehindVisibility,
+                    ) { transitionVisibility, defaultVisibility ->
+                        // Defer to the transition-specific visibility since we're RUNNING a
+                        // transition, but fall back to the default visibility if the current
+                        // transition's interactor did not specify a visibility.
+                        transitionVisibility ?: defaultVisibility
+                    }
+                }
+            }
+            .distinctUntilChanged()
+
+    /**
+     * Whether we're animating, or intend to animate, the surface behind the keyguard via remote
+     * animation. This is used to keep the RemoteAnimationTarget alive until we're done using it.
+     */
+    val usingKeyguardGoingAwayAnimation: Flow<Boolean> =
+        combine(
+                transitionInteractor.isInTransitionToState(KeyguardState.GONE),
+                transitionInteractor.finishedKeyguardState,
+                surfaceBehindInteractor.isAnimatingSurface
+            ) { isInTransitionToGone, finishedState, isAnimatingSurface ->
+                // We may still be animating the surface after the keyguard is fully GONE, since
+                // some animations (like the translation spring) are not tied directly to the
+                // transition step amount.
+                isInTransitionToGone || (finishedState == KeyguardState.GONE && isAnimatingSurface)
+            }
+            .distinctUntilChanged()
+
+    /**
+     * Whether the lockscreen is visible, from the Window Manager (WM) perspective.
+     *
+     * Note: This may briefly be true even if the lockscreen UI has animated out (alpha = 0f), as we
+     * only inform WM once we're done with the keyguard and we're fully GONE. Don't use this if you
+     * want to know if the AOD/clock/notifs/etc. are visible.
+     */
+    val lockscreenVisibility: Flow<Boolean> =
+        combine(
+                transitionInteractor.startedKeyguardTransitionStep,
+                transitionInteractor.finishedKeyguardState,
+            ) { startedStep, finishedState ->
+                // If we finished the transition, use the finished state. If we're running a
+                // transition, use the state we're transitioning FROM. This can be different from
+                // the last finished state if a transition is interrupted. For example, if we were
+                // transitioning from GONE to AOD and then started AOD -> LOCKSCREEN mid-transition,
+                // we want to immediately use the visibility for AOD (lockscreenVisibility=true)
+                // even though the lastFinishedState is still GONE (lockscreenVisibility=false).
+                if (finishedState == startedStep.to) finishedState else startedStep.from
+            }
+            .map(::isLockscreenVisible)
+            .distinctUntilChanged()
+
+    /**
+     * Whether always-on-display (AOD) is visible when the lockscreen is visible, from window
+     * manager's perspective.
+     *
+     * Note: This may be true even if AOD is not user-visible, such as when the light sensor
+     * indicates the device is in the user's pocket. Don't use this if you want to know if the AOD
+     * clock/smartspace/notif icons are visible.
+     */
+    val aodVisibility: Flow<Boolean> =
+        combine(
+                keyguardInteractor.isDozing,
+                keyguardInteractor.biometricUnlockState,
+            ) { isDozing, biometricUnlockState ->
+                // AOD is visible if we're dozing, unless we are wake and unlocking (where we go
+                // directly from AOD to unlocked while dozing).
+                isDozing && !BiometricUnlockModel.isWakeAndUnlock(biometricUnlockState)
+            }
+            .distinctUntilChanged()
+
+    companion object {
+        fun isSurfaceVisible(state: KeyguardState): Boolean {
+            return !isLockscreenVisible(state)
+        }
+
+        fun isLockscreenVisible(state: KeyguardState): Boolean {
+            return state != KeyguardState.GONE
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/shared/model/KeyguardSurfaceBehindModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/shared/model/KeyguardSurfaceBehindModel.kt
new file mode 100644
index 0000000..7fb5cfd
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/shared/model/KeyguardSurfaceBehindModel.kt
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.shared.model
+
+/**
+ * Models the appearance of the surface behind the keyguard, and (optionally) how it should be
+ * animating.
+ *
+ * This is intended to be an atomic, high-level description of the surface's appearance and related
+ * animations, which we can derive from the STARTED/FINISHED transition states rather than the
+ * individual TransitionSteps.
+ *
+ * For example, if we're transitioning from LOCKSCREEN to GONE, that means we should be
+ * animatingFromAlpha 0f -> 1f and animatingFromTranslationY 500f -> 0f.
+ * KeyguardSurfaceBehindAnimator can decide how best to implement this, depending on previously
+ * running animations, spring momentum, and other state.
+ */
+data class KeyguardSurfaceBehindModel(
+    val alpha: Float = 1f,
+
+    /**
+     * If provided, animate from this value to [alpha] unless an animation is already running, in
+     * which case we'll animate from the current value to [alpha].
+     */
+    val animateFromAlpha: Float = alpha,
+    val translationY: Float = 0f,
+
+    /**
+     * If provided, animate from this value to [translationY] unless an animation is already
+     * running, in which case we'll animate from the current value to [translationY].
+     */
+    val animateFromTranslationY: Float = translationY,
+) {
+    fun willAnimateAlpha(): Boolean {
+        return animateFromAlpha != alpha
+    }
+
+    fun willAnimateTranslationY(): Boolean {
+        return animateFromTranslationY != translationY
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardAmbientIndicationAreaViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardAmbientIndicationAreaViewBinder.kt
index d6883dd..5c072fb 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardAmbientIndicationAreaViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardAmbientIndicationAreaViewBinder.kt
@@ -67,14 +67,15 @@
                 repeatOnLifecycle(Lifecycle.State.STARTED) {
                     launch {
                         keyguardRootViewModel.alpha.collect { alpha ->
-                            view.importantForAccessibility =
-                                if (alpha == 0f) {
-                                    View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
-                                } else {
-                                    View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
-                                }
-
-                            ambientIndicationArea?.alpha = alpha
+                            ambientIndicationArea?.apply {
+                                this.importantForAccessibility =
+                                    if (alpha == 0f) {
+                                        View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
+                                    } else {
+                                        View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
+                                    }
+                                this.alpha = alpha
+                            }
                         }
                     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBlueprintViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBlueprintViewBinder.kt
index 23b80b0..ed4dd6a 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBlueprintViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBlueprintViewBinder.kt
@@ -19,10 +19,10 @@
 
 import android.os.Trace
 import android.util.Log
+import androidx.constraintlayout.widget.ConstraintLayout
 import androidx.constraintlayout.widget.ConstraintSet
 import androidx.lifecycle.Lifecycle
 import androidx.lifecycle.repeatOnLifecycle
-import com.android.systemui.keyguard.ui.view.KeyguardRootView
 import com.android.systemui.keyguard.ui.viewmodel.KeyguardBlueprintViewModel
 import com.android.systemui.lifecycle.repeatWhenAttached
 import kotlinx.coroutines.launch
@@ -31,19 +31,19 @@
     companion object {
         private const val TAG = "KeyguardBlueprintViewBinder"
 
-        fun bind(keyguardRootView: KeyguardRootView, viewModel: KeyguardBlueprintViewModel) {
-            keyguardRootView.repeatWhenAttached {
+        fun bind(constraintLayout: ConstraintLayout, viewModel: KeyguardBlueprintViewModel) {
+            constraintLayout.repeatWhenAttached {
                 repeatOnLifecycle(Lifecycle.State.CREATED) {
                     launch {
                         viewModel.blueprint.collect { blueprint ->
                             Trace.beginSection("KeyguardBlueprintController#applyBlueprint")
                             Log.d(TAG, "applying blueprint: $blueprint")
                             ConstraintSet().apply {
-                                clone(keyguardRootView)
+                                clone(constraintLayout)
                                 val emptyLayout = ConstraintSet.Layout()
                                 knownIds.forEach { getConstraint(it).layout.copyFrom(emptyLayout) }
                                 blueprint?.apply(this)
-                                applyTo(keyguardRootView)
+                                applyTo(constraintLayout)
                             }
                             Trace.endSection()
                         }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBottomAreaViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBottomAreaViewBinder.kt
index a0a2abe..44acf4f 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBottomAreaViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBottomAreaViewBinder.kt
@@ -176,14 +176,15 @@
 
                     launch {
                         viewModel.alpha.collect { alpha ->
-                            view.importantForAccessibility =
-                                if (alpha == 0f) {
-                                    View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
-                                } else {
-                                    View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
-                                }
-
-                            ambientIndicationArea?.alpha = alpha
+                            ambientIndicationArea?.apply {
+                                this.importantForAccessibility =
+                                    if (alpha == 0f) {
+                                        View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
+                                    } else {
+                                        View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
+                                    }
+                                this.alpha = alpha
+                            }
                         }
                     }
 
@@ -471,7 +472,7 @@
             return true
         }
 
-        override fun onLongClickUseDefaultHapticFeedback(view: View?) = false
+        override fun onLongClickUseDefaultHapticFeedback(view: View) = false
     }
 
     @Deprecated("Deprecated as part of b/278057014")
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardIndicationAreaBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardIndicationAreaBinder.kt
index a385a0e..dc51944 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardIndicationAreaBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardIndicationAreaBinder.kt
@@ -73,25 +73,27 @@
                     launch {
                         if (featureFlags.isEnabled(Flags.MIGRATE_SPLIT_KEYGUARD_BOTTOM_AREA)) {
                             keyguardRootViewModel.alpha.collect { alpha ->
-                                view.importantForAccessibility =
-                                    if (alpha == 0f) {
-                                        View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
-                                    } else {
-                                        View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
-                                    }
-
-                                indicationArea.alpha = alpha
+                                indicationArea.apply {
+                                    this.importantForAccessibility =
+                                        if (alpha == 0f) {
+                                            View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
+                                        } else {
+                                            View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
+                                        }
+                                    this.alpha = alpha
+                                }
                             }
                         } else {
                             viewModel.alpha.collect { alpha ->
-                                view.importantForAccessibility =
-                                    if (alpha == 0f) {
-                                        View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
-                                    } else {
-                                        View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
-                                    }
-
-                                indicationArea.alpha = alpha
+                                indicationArea.apply {
+                                    this.importantForAccessibility =
+                                        if (alpha == 0f) {
+                                            View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
+                                        } else {
+                                            View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
+                                        }
+                                    this.alpha = alpha
+                                }
                             }
                         }
                     }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardQuickAffordanceViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardQuickAffordanceViewBinder.kt
index 63a6791..83b5463 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardQuickAffordanceViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardQuickAffordanceViewBinder.kt
@@ -304,7 +304,7 @@
             return true
         }
 
-        override fun onLongClickUseDefaultHapticFeedback(view: View?) = false
+        override fun onLongClickUseDefaultHapticFeedback(view: View) = false
 
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardSettingsViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardSettingsViewBinder.kt
index 162c109..82610e6 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardSettingsViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardSettingsViewBinder.kt
@@ -43,7 +43,7 @@
         vibratorHelper: VibratorHelper,
         activityStarter: ActivityStarter
     ): DisposableHandle {
-        val view = parentView.findViewById<LaunchableLinearLayout>(R.id.keyguard_settings_button)
+        val view = parentView.requireViewById<LaunchableLinearLayout>(R.id.keyguard_settings_button)
 
         val disposableHandle =
             view.repeatWhenAttached {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindParamsApplier.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindParamsApplier.kt
new file mode 100644
index 0000000..a5b00e0
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindParamsApplier.kt
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.ui.binder
+
+import android.animation.Animator
+import android.animation.AnimatorListenerAdapter
+import android.animation.ValueAnimator
+import android.graphics.Matrix
+import android.util.Log
+import android.view.RemoteAnimationTarget
+import android.view.SurfaceControl
+import android.view.SyncRtSurfaceTransactionApplier
+import android.view.View
+import androidx.dynamicanimation.animation.FloatValueHolder
+import androidx.dynamicanimation.animation.SpringAnimation
+import androidx.dynamicanimation.animation.SpringForce
+import com.android.keyguard.KeyguardViewController
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.keyguard.TAG
+import com.android.systemui.keyguard.domain.interactor.KeyguardSurfaceBehindInteractor
+import com.android.systemui.keyguard.shared.model.KeyguardSurfaceBehindModel
+import com.android.wm.shell.animation.Interpolators
+import java.util.concurrent.Executor
+import javax.inject.Inject
+
+/**
+ * Applies [KeyguardSurfaceBehindViewParams] to a RemoteAnimationTarget, starting and managing
+ * animations as needed.
+ */
+@SysUISingleton
+class KeyguardSurfaceBehindParamsApplier
+@Inject
+constructor(
+    @Main private val executor: Executor,
+    private val keyguardViewController: KeyguardViewController,
+    private val interactor: KeyguardSurfaceBehindInteractor,
+) {
+    private var surfaceBehind: RemoteAnimationTarget? = null
+    private val surfaceTransactionApplier: SyncRtSurfaceTransactionApplier
+        get() = SyncRtSurfaceTransactionApplier(keyguardViewController.viewRootImpl.view)
+
+    private val matrix = Matrix()
+    private val tmpFloat = FloatArray(9)
+
+    private var animatedTranslationY = FloatValueHolder()
+    private val translateYSpring =
+        SpringAnimation(animatedTranslationY).apply {
+            spring =
+                SpringForce().apply {
+                    stiffness = 200f
+                    dampingRatio = 1f
+                }
+            addUpdateListener { _, _, _ -> applyToSurfaceBehind() }
+            addEndListener { _, _, _, _ -> 
+                try {
+                    updateIsAnimatingSurface()
+                } catch (e: NullPointerException) {
+                    // TODO(b/291645410): Remove when we can isolate DynamicAnimations.
+                    e.printStackTrace()
+                }
+            }
+        }
+
+    private var animatedAlpha = 0f
+    private var alphaAnimator =
+        ValueAnimator.ofFloat(0f, 1f).apply {
+            duration = 500
+            interpolator = Interpolators.ALPHA_IN
+            addUpdateListener {
+                animatedAlpha = it.animatedValue as Float
+                applyToSurfaceBehind()
+            }
+            addListener(
+                object : AnimatorListenerAdapter() {
+                    override fun onAnimationEnd(animation: Animator?) {
+                        updateIsAnimatingSurface()
+                    }
+                }
+            )
+        }
+
+    /**
+     * ViewParams to apply to the surface provided to [applyParamsToSurface]. If the surface is null
+     * these will be applied once someone gives us a surface via [applyParamsToSurface].
+     */
+    var viewParams: KeyguardSurfaceBehindModel = KeyguardSurfaceBehindModel()
+        set(newParams) {
+            field = newParams
+            startOrUpdateAnimators()
+            applyToSurfaceBehind()
+        }
+
+    /**
+     * Provides us with a surface to animate. We'll apply the [viewParams] to this surface and start
+     * any necessary animations.
+     */
+    fun applyParamsToSurface(surface: RemoteAnimationTarget) {
+        this.surfaceBehind = surface
+        startOrUpdateAnimators()
+    }
+
+    /**
+     * Notifies us that the [RemoteAnimationTarget] has been released, one way or another.
+     * Attempting to animate a released target will cause a crash.
+     *
+     * This can be called either because we finished animating the surface naturally, or by WM
+     * because external factors cancelled the remote animation (timeout, re-lock, etc). If it's the
+     * latter, cancel any outstanding animations we have.
+     */
+    fun notifySurfaceReleased() {
+        surfaceBehind = null
+
+        if (alphaAnimator.isRunning) {
+            alphaAnimator.cancel()
+        }
+
+        if (translateYSpring.isRunning) {
+            translateYSpring.cancel()
+        }
+    }
+
+    private fun startOrUpdateAnimators() {
+        if (surfaceBehind == null) {
+            return
+        }
+
+        if (viewParams.willAnimateAlpha()) {
+            var fromAlpha = viewParams.animateFromAlpha
+
+            if (alphaAnimator.isRunning) {
+                alphaAnimator.cancel()
+                fromAlpha = animatedAlpha
+            }
+
+            alphaAnimator.setFloatValues(fromAlpha, viewParams.alpha)
+            alphaAnimator.start()
+        }
+
+        if (viewParams.willAnimateTranslationY()) {
+            if (!translateYSpring.isRunning) {
+                // If the spring isn't running yet, set the start value. Otherwise, respect the
+                // current position.
+                animatedTranslationY.value = viewParams.animateFromTranslationY
+            }
+
+            translateYSpring.animateToFinalPosition(viewParams.translationY)
+        }
+
+        updateIsAnimatingSurface()
+    }
+
+    private fun updateIsAnimatingSurface() {
+        interactor.setAnimatingSurface(translateYSpring.isRunning || alphaAnimator.isRunning)
+    }
+
+    private fun applyToSurfaceBehind() {
+        surfaceBehind?.leash?.let { sc ->
+            executor.execute {
+                if (surfaceBehind == null) {
+                    Log.d(
+                        TAG,
+                        "Attempting to modify params of surface that isn't " +
+                            "animating. Ignoring."
+                    )
+                    matrix.set(Matrix.IDENTITY_MATRIX)
+                    return@execute
+                }
+
+                val translationY =
+                    if (translateYSpring.isRunning) animatedTranslationY.value
+                    else viewParams.translationY
+
+                val alpha =
+                    if (alphaAnimator.isRunning) {
+                        animatedAlpha
+                    } else {
+                        viewParams.alpha
+                    }
+
+                if (
+                    keyguardViewController.viewRootImpl.view?.visibility != View.VISIBLE &&
+                        sc.isValid
+                ) {
+                    with(SurfaceControl.Transaction()) {
+                        setMatrix(
+                            sc,
+                            matrix.apply { setTranslate(/* dx= */ 0f, translationY) },
+                            tmpFloat
+                        )
+                        setAlpha(sc, alpha)
+                        apply()
+                    }
+                } else {
+                    surfaceTransactionApplier.scheduleApply(
+                        SyncRtSurfaceTransactionApplier.SurfaceParams.Builder(sc)
+                            .withMatrix(matrix.apply { setTranslate(/* dx= */ 0f, translationY) })
+                            .withAlpha(alpha)
+                            .build()
+                    )
+                }
+            }
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindViewBinder.kt
new file mode 100644
index 0000000..599f69f
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindViewBinder.kt
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.ui.binder
+
+import com.android.systemui.keyguard.WindowManagerLockscreenVisibilityManager
+import com.android.systemui.keyguard.ui.viewmodel.KeyguardSurfaceBehindViewModel
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.launch
+
+/**
+ * Binds the [WindowManagerLockscreenVisibilityManager] "view", which manages the visibility of the
+ * surface behind the keyguard.
+ */
+object KeyguardSurfaceBehindViewBinder {
+    @JvmStatic
+    fun bind(
+        viewModel: KeyguardSurfaceBehindViewModel,
+        applier: KeyguardSurfaceBehindParamsApplier,
+        scope: CoroutineScope
+    ) {
+        scope.launch { viewModel.surfaceBehindViewParams.collect { applier.viewParams = it } }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/UdfpsKeyguardInternalViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/UdfpsKeyguardInternalViewBinder.kt
index b568a9a..3bb01f2 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/UdfpsKeyguardInternalViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/UdfpsKeyguardInternalViewBinder.kt
@@ -42,13 +42,13 @@
         view.accessibilityDelegate = viewModel.accessibilityDelegate
 
         // bind child views
-        UdfpsAodFingerprintViewBinder.bind(view.findViewById(R.id.udfps_aod_fp), aodViewModel)
+        UdfpsAodFingerprintViewBinder.bind(view.requireViewById(R.id.udfps_aod_fp), aodViewModel)
         UdfpsFingerprintViewBinder.bind(
-            view.findViewById(R.id.udfps_lockscreen_fp),
+            view.requireViewById(R.id.udfps_lockscreen_fp),
             fingerprintViewModel
         )
         UdfpsBackgroundViewBinder.bind(
-            view.findViewById(R.id.udfps_keyguard_fp_bg),
+            view.requireViewById(R.id.udfps_keyguard_fp_bg),
             backgroundViewModel
         )
     }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/WindowManagerLockscreenVisibilityViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/WindowManagerLockscreenVisibilityViewBinder.kt
new file mode 100644
index 0000000..fc0c78a
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/WindowManagerLockscreenVisibilityViewBinder.kt
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.ui.binder
+
+import com.android.systemui.keyguard.WindowManagerLockscreenVisibilityManager
+import com.android.systemui.keyguard.ui.viewmodel.WindowManagerLockscreenVisibilityViewModel
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.launch
+
+/**
+ * Binds the [WindowManagerLockscreenVisibilityManager] "view", which manages the visibility of the
+ * surface behind the keyguard.
+ */
+object WindowManagerLockscreenVisibilityViewBinder {
+    @JvmStatic
+    fun bind(
+        viewModel: WindowManagerLockscreenVisibilityViewModel,
+        lockscreenVisibilityManager: WindowManagerLockscreenVisibilityManager,
+        scope: CoroutineScope
+    ) {
+        scope.launch {
+            viewModel.surfaceBehindVisibility.collect {
+                lockscreenVisibilityManager.setSurfaceBehindVisibility(it)
+            }
+        }
+
+        scope.launch {
+            viewModel.lockscreenVisibility.collect {
+                lockscreenVisibilityManager.setLockscreenShown(it)
+            }
+        }
+
+        scope.launch {
+            viewModel.aodVisibility.collect { lockscreenVisibilityManager.setAodVisible(it) }
+        }
+
+        scope.launch {
+            viewModel.surfaceBehindAnimating.collect {
+                lockscreenVisibilityManager.setUsingGoingAwayRemoteAnimation(it)
+            }
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/preview/KeyguardPreviewRenderer.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/preview/KeyguardPreviewRenderer.kt
index cf96458..41c1c96 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/preview/KeyguardPreviewRenderer.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/preview/KeyguardPreviewRenderer.kt
@@ -49,6 +49,7 @@
 import com.android.systemui.keyguard.ui.binder.KeyguardPreviewClockViewBinder
 import com.android.systemui.keyguard.ui.binder.KeyguardPreviewSmartspaceViewBinder
 import com.android.systemui.keyguard.ui.binder.KeyguardQuickAffordanceViewBinder
+import com.android.systemui.keyguard.ui.binder.KeyguardRootViewBinder
 import com.android.systemui.keyguard.ui.view.KeyguardRootView
 import com.android.systemui.keyguard.ui.viewmodel.KeyguardBlueprintViewModel
 import com.android.systemui.keyguard.ui.viewmodel.KeyguardBottomAreaViewModel
@@ -56,25 +57,31 @@
 import com.android.systemui.keyguard.ui.viewmodel.KeyguardPreviewSmartspaceViewModel
 import com.android.systemui.keyguard.ui.viewmodel.KeyguardQuickAffordancesCombinedViewModel
 import com.android.systemui.keyguard.ui.viewmodel.KeyguardRootViewModel
+import com.android.systemui.keyguard.ui.viewmodel.OccludingAppDeviceEntryMessageViewModel
 import com.android.systemui.monet.ColorScheme
 import com.android.systemui.plugins.ClockController
 import com.android.systemui.plugins.FalsingManager
 import com.android.systemui.shared.clocks.ClockRegistry
 import com.android.systemui.shared.clocks.DefaultClockController
 import com.android.systemui.shared.clocks.shared.model.ClockPreviewConstants
+import com.android.systemui.shared.keyguard.shared.model.KeyguardQuickAffordanceSlots
 import com.android.systemui.shared.quickaffordance.shared.model.KeyguardPreviewConstants
 import com.android.systemui.statusbar.KeyguardIndicationController
 import com.android.systemui.statusbar.VibratorHelper
 import com.android.systemui.statusbar.lockscreen.LockscreenSmartspaceController
 import com.android.systemui.statusbar.phone.KeyguardBottomAreaView
+import com.android.systemui.statusbar.policy.KeyguardStateController
+import com.android.systemui.temporarydisplay.chipbar.ChipbarCoordinator
 import dagger.assisted.Assisted
 import dagger.assisted.AssistedInject
 import kotlinx.coroutines.CoroutineDispatcher
 import kotlinx.coroutines.DisposableHandle
+import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.runBlocking
 
 /** Renders the preview of the lock screen. */
 class KeyguardPreviewRenderer
+@OptIn(ExperimentalCoroutinesApi::class)
 @AssistedInject
 constructor(
     @Application private val context: Context,
@@ -99,6 +106,9 @@
     @Assisted bundle: Bundle,
     private val keyguardBlueprintViewModel: KeyguardBlueprintViewModel,
     private val keyguardBlueprintInteractor: KeyguardBlueprintInteractor,
+    private val occludingAppDeviceEntryMessageViewModel: OccludingAppDeviceEntryMessageViewModel,
+    private val chipbarCoordinator: ChipbarCoordinator,
+    private val keyguardStateController: KeyguardStateController,
 ) {
 
     val hostToken: IBinder? = bundle.getBinder(KEY_HOST_TOKEN)
@@ -117,7 +127,7 @@
     private var host: SurfaceControlViewHost
 
     val surfacePackage: SurfaceControlViewHost.SurfacePackage
-        get() = host.surfacePackage
+        get() = checkNotNull(host.surfacePackage)
 
     private lateinit var largeClockHostView: FrameLayout
     private lateinit var smallClockHostView: FrameLayout
@@ -130,19 +140,21 @@
 
     init {
         if (featureFlags.isEnabled(Flags.MIGRATE_SPLIT_KEYGUARD_BOTTOM_AREA)) {
-            keyguardRootViewModel.enablePreviewMode(
+            keyguardRootViewModel.enablePreviewMode()
+            quickAffordancesCombinedViewModel.enablePreviewMode(
                 initiallySelectedSlotId =
-                bundle.getString(
-                    KeyguardPreviewConstants.KEY_INITIALLY_SELECTED_SLOT_ID,
-                ),
+                    bundle.getString(
+                        KeyguardPreviewConstants.KEY_INITIALLY_SELECTED_SLOT_ID,
+                    )
+                        ?: KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START,
                 shouldHighlightSelectedAffordance = shouldHighlightSelectedAffordance,
             )
         } else {
             bottomAreaViewModel.enablePreviewMode(
                 initiallySelectedSlotId =
-                bundle.getString(
-                    KeyguardPreviewConstants.KEY_INITIALLY_SELECTED_SLOT_ID,
-                ),
+                    bundle.getString(
+                        KeyguardPreviewConstants.KEY_INITIALLY_SELECTED_SLOT_ID,
+                    ),
                 shouldHighlightSelectedAffordance = shouldHighlightSelectedAffordance,
             )
         }
@@ -163,17 +175,8 @@
             val rootView = FrameLayout(context)
 
             if (featureFlags.isEnabled(Flags.MIGRATE_SPLIT_KEYGUARD_BOTTOM_AREA)) {
-                val keyguardRootView = KeyguardRootView(context, null)
-                rootView.addView(
-                    keyguardRootView,
-                    FrameLayout.LayoutParams(
-                        FrameLayout.LayoutParams.MATCH_PARENT,
-                        FrameLayout.LayoutParams.MATCH_PARENT,
-                    ),
-                )
-                setupShortcuts(keyguardRootView)
-                KeyguardBlueprintViewBinder.bind(keyguardRootView, keyguardBlueprintViewModel)
-                keyguardBlueprintInteractor.refreshBlueprint()
+                setupKeyguardRootView(rootView)
+                setupShortcuts(rootView)
             } else {
                 setUpBottomArea(rootView)
             }
@@ -314,7 +317,7 @@
                     false,
                 ) as KeyguardBottomAreaView
         bottomAreaView.init(
-                viewModel = bottomAreaViewModel,
+            viewModel = bottomAreaViewModel,
         )
         parentView.addView(
             bottomAreaView,
@@ -325,10 +328,34 @@
         )
     }
 
-    private fun setupShortcuts(keyguardRootView: KeyguardRootView) {
+    @OptIn(ExperimentalCoroutinesApi::class)
+    private fun setupKeyguardRootView(rootView: FrameLayout) {
+        val keyguardRootView = KeyguardRootView(context, null)
+        disposables.add(
+            KeyguardRootViewBinder.bind(
+                keyguardRootView,
+                keyguardRootViewModel,
+                featureFlags,
+                occludingAppDeviceEntryMessageViewModel,
+                chipbarCoordinator,
+                keyguardStateController,
+            )
+        )
+        rootView.addView(
+            keyguardRootView,
+            FrameLayout.LayoutParams(
+                FrameLayout.LayoutParams.MATCH_PARENT,
+                FrameLayout.LayoutParams.MATCH_PARENT,
+            ),
+        )
+        KeyguardBlueprintViewBinder.bind(keyguardRootView, keyguardBlueprintViewModel)
+        keyguardBlueprintInteractor.refreshBlueprint()
+    }
+
+    private fun setupShortcuts(rootView: FrameLayout) {
         shortcutsBindings.add(
             KeyguardQuickAffordanceViewBinder.bind(
-                keyguardRootView.requireViewById(R.id.start_button),
+                rootView.requireViewById(R.id.start_button),
                 quickAffordancesCombinedViewModel.startButton,
                 keyguardRootViewModel.alpha,
                 falsingManager,
@@ -340,7 +367,7 @@
 
         shortcutsBindings.add(
             KeyguardQuickAffordanceViewBinder.bind(
-                keyguardRootView.requireViewById(R.id.end_button),
+                rootView.requireViewById(R.id.end_button),
                 quickAffordancesCombinedViewModel.endButton,
                 keyguardRootViewModel.alpha,
                 falsingManager,
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/KeyguardRootView.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/KeyguardRootView.kt
index e60901f..a948741 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/KeyguardRootView.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/KeyguardRootView.kt
@@ -24,6 +24,7 @@
 import android.widget.ImageView
 import androidx.constraintlayout.widget.ConstraintLayout
 import androidx.core.content.res.ResourcesCompat
+import com.android.keyguard.KeyguardStatusView
 import com.android.keyguard.LockIconView
 import com.android.systemui.R
 import com.android.systemui.animation.view.LaunchableImageView
@@ -38,6 +39,8 @@
         attrs,
     ) {
 
+    private var statusView: KeyguardStatusView? = null
+
     init {
         addIndicationTextArea()
         addLockIconView()
@@ -45,6 +48,7 @@
         addLeftShortcut()
         addRightShortcut()
         addSettingsPopupMenu()
+        addStatusView()
     }
 
     private fun addIndicationTextArea() {
@@ -119,4 +123,19 @@
                 }
         addView(view)
     }
+
+    fun addStatusView(): KeyguardStatusView {
+        // StatusView may need to be rebuilt on config changes. Remove and reinflate
+        statusView?.let { removeView(it) }
+        val view =
+            (LayoutInflater.from(context).inflate(R.layout.keyguard_status_view, this, false)
+                    as KeyguardStatusView)
+                .apply {
+                    setClipChildren(false)
+                    statusView = this
+                }
+
+        addView(view)
+        return view
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/DefaultKeyguardBlueprint.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/DefaultKeyguardBlueprint.kt
index 5538fe7..518df07 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/DefaultKeyguardBlueprint.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/DefaultKeyguardBlueprint.kt
@@ -25,6 +25,8 @@
 import com.android.systemui.keyguard.ui.view.layout.sections.DefaultLockIconSection
 import com.android.systemui.keyguard.ui.view.layout.sections.DefaultSettingsPopupMenuSection
 import com.android.systemui.keyguard.ui.view.layout.sections.DefaultShortcutsSection
+import com.android.systemui.keyguard.ui.view.layout.sections.DefaultStatusViewSection
+import com.android.systemui.keyguard.ui.view.layout.sections.SplitShadeGuidelines
 import javax.inject.Inject
 
 /**
@@ -42,6 +44,8 @@
     private val defaultShortcutsSection: DefaultShortcutsSection,
     private val defaultAmbientIndicationAreaSection: DefaultAmbientIndicationAreaSection,
     private val defaultSettingsPopupMenuSection: DefaultSettingsPopupMenuSection,
+    private val defaultStatusViewSection: DefaultStatusViewSection,
+    private val splitShadeGuidelines: SplitShadeGuidelines,
 ) : KeyguardBlueprint {
     override val id: String = DEFAULT
 
@@ -51,6 +55,8 @@
         defaultShortcutsSection.apply(constraintSet)
         defaultAmbientIndicationAreaSection.apply(constraintSet)
         defaultSettingsPopupMenuSection.apply(constraintSet)
+        defaultStatusViewSection.apply(constraintSet)
+        splitShadeGuidelines.apply(constraintSet)
     }
 
     companion object {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/KeyguardBlueprintModule.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/KeyguardBlueprintModule.kt
index fefe679..07f316b 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/KeyguardBlueprintModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/KeyguardBlueprintModule.kt
@@ -17,6 +17,7 @@
 
 package com.android.systemui.keyguard.ui.view.layout.blueprints
 
+import com.android.systemui.communal.ui.view.layout.blueprints.DefaultCommunalBlueprint
 import com.android.systemui.keyguard.data.repository.KeyguardBlueprint
 import dagger.Binds
 import dagger.Module
@@ -35,4 +36,10 @@
     abstract fun bindShortcutsBesideUdfpsLockscreenBlueprint(
         shortcutsBesideUdfpsLockscreenBlueprint: ShortcutsBesideUdfpsKeyguardBlueprint
     ): KeyguardBlueprint
+
+    @Binds
+    @IntoSet
+    abstract fun bindDefaultCommunalBlueprint(
+        defaultCommunalBlueprint: DefaultCommunalBlueprint
+    ): KeyguardBlueprint
 }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/ShortcutsBesideUdfpsKeyguardBlueprint.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/ShortcutsBesideUdfpsKeyguardBlueprint.kt
index 19410e4..54c2796 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/ShortcutsBesideUdfpsKeyguardBlueprint.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/blueprints/ShortcutsBesideUdfpsKeyguardBlueprint.kt
@@ -27,6 +27,8 @@
 import com.android.systemui.keyguard.ui.view.layout.sections.DefaultLockIconSection
 import com.android.systemui.keyguard.ui.view.layout.sections.DefaultSettingsPopupMenuSection
 import com.android.systemui.keyguard.ui.view.layout.sections.DefaultShortcutsSection
+import com.android.systemui.keyguard.ui.view.layout.sections.DefaultStatusViewSection
+import com.android.systemui.keyguard.ui.view.layout.sections.SplitShadeGuidelines
 import javax.inject.Inject
 
 /** Vertically aligns the shortcuts with the udfps. */
@@ -41,6 +43,8 @@
     private val defaultSettingsPopupMenuSection: DefaultSettingsPopupMenuSection,
     private val alignShortcutsToUdfpsSection: AlignShortcutsToUdfpsSection,
     private val defaultShortcutsSection: DefaultShortcutsSection,
+    private val defaultStatusViewSection: DefaultStatusViewSection,
+    private val splitShadeGuidelines: SplitShadeGuidelines,
 ) : KeyguardBlueprint {
     override val id: String = SHORTCUTS_BESIDE_UDFPS
 
@@ -54,6 +58,8 @@
         } else {
             defaultShortcutsSection.apply(constraintSet)
         }
+        defaultStatusViewSection.apply(constraintSet)
+        splitShadeGuidelines.apply(constraintSet)
     }
 
     companion object {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/DefaultStatusViewSection.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/DefaultStatusViewSection.kt
new file mode 100644
index 0000000..3f319ba
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/DefaultStatusViewSection.kt
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.ui.view.layout.sections
+
+import android.content.Context
+import android.view.ViewGroup
+import androidx.constraintlayout.widget.ConstraintSet
+import com.android.systemui.R
+import com.android.systemui.keyguard.data.repository.KeyguardSection
+import javax.inject.Inject
+import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
+import androidx.constraintlayout.widget.ConstraintSet.MATCH_CONSTRAINT
+import androidx.constraintlayout.widget.ConstraintSet.PARENT_ID
+import androidx.constraintlayout.widget.ConstraintSet.START
+import androidx.constraintlayout.widget.ConstraintSet.TOP
+import androidx.constraintlayout.widget.ConstraintSet.END
+
+class DefaultStatusViewSection @Inject constructor(private val context: Context) :
+    KeyguardSection {
+    private val statusViewId = R.id.keyguard_status_view
+
+    override fun apply(constraintSet: ConstraintSet) {
+        constraintSet.apply {
+            constrainWidth(statusViewId, MATCH_CONSTRAINT)
+            constrainHeight(statusViewId, WRAP_CONTENT)
+            connect(statusViewId, TOP, PARENT_ID, TOP)
+            connect(statusViewId, START, PARENT_ID, START)
+            connect(statusViewId, END, PARENT_ID, END)
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/SplitShadeGuidelines.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/SplitShadeGuidelines.kt
new file mode 100644
index 0000000..668b17f
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/SplitShadeGuidelines.kt
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.ui.view.layout.sections
+
+import android.content.Context
+import android.view.ViewGroup
+import androidx.constraintlayout.widget.ConstraintSet
+import com.android.systemui.R
+import com.android.systemui.keyguard.data.repository.KeyguardSection
+import javax.inject.Inject
+import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
+import androidx.constraintlayout.widget.ConstraintSet.MATCH_CONSTRAINT
+import androidx.constraintlayout.widget.ConstraintSet.PARENT_ID
+import androidx.constraintlayout.widget.ConstraintSet.START
+import androidx.constraintlayout.widget.ConstraintSet.TOP
+import androidx.constraintlayout.widget.ConstraintSet.END
+import androidx.constraintlayout.widget.ConstraintSet.VERTICAL
+
+class SplitShadeGuidelines @Inject constructor(private val context: Context) :
+    KeyguardSection {
+
+    override fun apply(constraintSet: ConstraintSet) {
+        constraintSet.apply {
+            // For use on large screens, it will provide a guideline vertically in the center to
+            // enable items to be aligned on the left or right sides
+            create(R.id.split_shade_guideline, VERTICAL)
+            setGuidelinePercent(R.id.split_shade_guideline, 0.5f)
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordancesCombinedViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordancesCombinedViewModel.kt
index 56a98455..02ea550 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordancesCombinedViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordancesCombinedViewModel.kt
@@ -18,22 +18,20 @@
 package com.android.systemui.keyguard.ui.viewmodel
 
 import androidx.annotation.VisibleForTesting
-import com.android.systemui.keyguard.domain.interactor.KeyguardBottomAreaInteractor
 import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor
 import com.android.systemui.keyguard.domain.interactor.KeyguardQuickAffordanceInteractor
 import com.android.systemui.keyguard.domain.model.KeyguardQuickAffordanceModel
 import com.android.systemui.keyguard.shared.quickaffordance.ActivationState
 import com.android.systemui.keyguard.shared.quickaffordance.KeyguardQuickAffordancePosition
 import com.android.systemui.shared.keyguard.shared.model.KeyguardQuickAffordanceSlots
+import javax.inject.Inject
 import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.combine
 import kotlinx.coroutines.flow.distinctUntilChanged
 import kotlinx.coroutines.flow.flatMapLatest
-import kotlinx.coroutines.flow.flowOf
 import kotlinx.coroutines.flow.map
-import javax.inject.Inject
 
 @OptIn(ExperimentalCoroutinesApi::class)
 class KeyguardQuickAffordancesCombinedViewModel
@@ -43,6 +41,18 @@
     private val keyguardInteractor: KeyguardInteractor,
 ) {
 
+    data class PreviewMode(
+        val isInPreviewMode: Boolean = false,
+        val shouldHighlightSelectedAffordance: Boolean = false,
+    )
+
+    /**
+     * Whether this view-model instance is powering the preview experience that renders exclusively
+     * in the wallpaper picker application. This should _always_ be `false` for the real lock screen
+     * experience.
+     */
+    private val previewMode = MutableStateFlow(PreviewMode())
+
     /**
      * ID of the slot that's currently selected in the preview that renders exclusively in the
      * wallpaper picker application. This is ignored for the actual, real lock screen experience.
@@ -85,39 +95,63 @@
         selectedPreviewSlotId.value = slotId
     }
 
+    /**
+     * Puts this view-model in "preview mode", which means it's being used for UI that is rendering
+     * the lock screen preview in wallpaper picker / settings and not the real experience on the
+     * lock screen.
+     *
+     * @param initiallySelectedSlotId The ID of the initial slot to render as the selected one.
+     * @param shouldHighlightSelectedAffordance Whether the selected quick affordance should be
+     *   highlighted (while all others are dimmed to make the selected one stand out).
+     */
+    fun enablePreviewMode(
+        initiallySelectedSlotId: String?,
+        shouldHighlightSelectedAffordance: Boolean,
+    ) {
+        val newPreviewMode =
+            PreviewMode(
+                isInPreviewMode = true,
+                shouldHighlightSelectedAffordance = shouldHighlightSelectedAffordance,
+            )
+        onPreviewSlotSelected(
+            initiallySelectedSlotId ?: KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START
+        )
+        previewMode.value = newPreviewMode
+    }
+
     private fun button(
         position: KeyguardQuickAffordancePosition
     ): Flow<KeyguardQuickAffordanceViewModel> {
-        return keyguardInteractor.previewMode.flatMapLatest { previewMode ->
+        return previewMode.flatMapLatest { previewMode ->
             combine(
-                if (previewMode.isInPreviewMode) {
-                    quickAffordanceInteractor.quickAffordanceAlwaysVisible(position = position)
-                } else {
-                    quickAffordanceInteractor.quickAffordance(position = position)
-                },
-                keyguardInteractor.animateDozingTransitions.distinctUntilChanged(),
-                areQuickAffordancesFullyOpaque,
-                selectedPreviewSlotId,
-                quickAffordanceInteractor.useLongPress(),
-            ) { model, animateReveal, isFullyOpaque, selectedPreviewSlotId, useLongPress ->
-                val slotId = position.toSlotId()
-                val isSelected = selectedPreviewSlotId == slotId
-                model.toViewModel(
-                    animateReveal = !previewMode.isInPreviewMode && animateReveal,
-                    isClickable = isFullyOpaque && !previewMode.isInPreviewMode,
-                    isSelected =
-                    previewMode.isInPreviewMode &&
-                        previewMode.shouldHighlightSelectedAffordance &&
-                        isSelected,
-                    isDimmed =
-                    previewMode.isInPreviewMode &&
-                        previewMode.shouldHighlightSelectedAffordance &&
-                        !isSelected,
-                    forceInactive = previewMode.isInPreviewMode,
-                    slotId = slotId,
-                    useLongPress = useLongPress,
-                )
-            }
+                    if (previewMode.isInPreviewMode) {
+                        quickAffordanceInteractor.quickAffordanceAlwaysVisible(position = position)
+                    } else {
+                        quickAffordanceInteractor.quickAffordance(position = position)
+                    },
+                    keyguardInteractor.animateDozingTransitions.distinctUntilChanged(),
+                    areQuickAffordancesFullyOpaque,
+                    selectedPreviewSlotId,
+                    quickAffordanceInteractor.useLongPress(),
+                ) { model, animateReveal, isFullyOpaque, selectedPreviewSlotId, useLongPress ->
+                    val slotId = position.toSlotId()
+                    val isSelected = selectedPreviewSlotId == slotId
+                    model.toViewModel(
+                        animateReveal = !previewMode.isInPreviewMode && animateReveal,
+                        isClickable = isFullyOpaque && !previewMode.isInPreviewMode,
+                        isSelected =
+                            previewMode.isInPreviewMode &&
+                                previewMode.shouldHighlightSelectedAffordance &&
+                                isSelected,
+                        isDimmed =
+                            previewMode.isInPreviewMode &&
+                                previewMode.shouldHighlightSelectedAffordance &&
+                                !isSelected,
+                        forceInactive = previewMode.isInPreviewMode,
+                        slotId = slotId,
+                        useLongPress = useLongPress,
+                    )
+                }
                 .distinctUntilChanged()
         }
     }
@@ -167,8 +201,6 @@
         // time, we don't want the number to be too close to 1.0 such that there is a chance that we
         // never treat the affordance UI as "fully opaque" as that would risk making it forever not
         // clickable.
-        @VisibleForTesting
-        const val AFFORDANCE_FULLY_OPAQUE_ALPHA_THRESHOLD = 0.95f
+        @VisibleForTesting const val AFFORDANCE_FULLY_OPAQUE_ALPHA_THRESHOLD = 0.95f
     }
-
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt
index 316ca77..92b9ee4 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt
@@ -19,29 +19,37 @@
 
 import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor
 import com.android.systemui.keyguard.shared.model.KeyguardRootViewVisibilityState
-import com.android.systemui.shared.keyguard.shared.model.KeyguardQuickAffordanceSlots
+import javax.inject.Inject
 import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.distinctUntilChanged
 import kotlinx.coroutines.flow.flatMapLatest
 import kotlinx.coroutines.flow.flowOf
-import javax.inject.Inject
 
 @OptIn(ExperimentalCoroutinesApi::class)
 class KeyguardRootViewModel
 @Inject
 constructor(
     private val keyguardInteractor: KeyguardInteractor,
-    private val keyguardQuickAffordancesCombinedViewModel: KeyguardQuickAffordancesCombinedViewModel
-)
-{
+) {
+
+    data class PreviewMode(val isInPreviewMode: Boolean = false)
+
+    /**
+     * Whether this view-model instance is powering the preview experience that renders exclusively
+     * in the wallpaper picker application. This should _always_ be `false` for the real lock screen
+     * experience.
+     */
+    private val previewMode = MutableStateFlow(PreviewMode())
+
     /** Represents the current state of the KeyguardRootView visibility */
     val keyguardRootViewVisibilityState: Flow<KeyguardRootViewVisibilityState> =
         keyguardInteractor.keyguardRootViewVisibilityState
 
     /** An observable for the alpha level for the entire keyguard root view. */
     val alpha: Flow<Float> =
-        keyguardInteractor.previewMode.flatMapLatest {
+        previewMode.flatMapLatest {
             if (it.isInPreviewMode) {
                 flowOf(1f)
             } else {
@@ -53,23 +61,9 @@
      * Puts this view-model in "preview mode", which means it's being used for UI that is rendering
      * the lock screen preview in wallpaper picker / settings and not the real experience on the
      * lock screen.
-     *
-     * @param initiallySelectedSlotId The ID of the initial slot to render as the selected one.
-     * @param shouldHighlightSelectedAffordance Whether the selected quick affordance should be
-     *   highlighted (while all others are dimmed to make the selected one stand out).
      */
-    fun enablePreviewMode(
-        initiallySelectedSlotId: String?,
-        shouldHighlightSelectedAffordance: Boolean,
-    ) {
-        keyguardInteractor.previewMode.value =
-            KeyguardInteractor.PreviewMode(
-                isInPreviewMode = true,
-                shouldHighlightSelectedAffordance = shouldHighlightSelectedAffordance,
-            )
-        keyguardQuickAffordancesCombinedViewModel.onPreviewSlotSelected(
-            initiallySelectedSlotId ?: KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START
-        )
+    fun enablePreviewMode() {
+        val newPreviewMode = PreviewMode(true)
+        previewMode.value = newPreviewMode
     }
-
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardSurfaceBehindViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardSurfaceBehindViewModel.kt
new file mode 100644
index 0000000..4f52962
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardSurfaceBehindViewModel.kt
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.ui.viewmodel
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyguard.domain.interactor.KeyguardSurfaceBehindInteractor
+import javax.inject.Inject
+
+@SysUISingleton
+class KeyguardSurfaceBehindViewModel
+@Inject
+constructor(interactor: KeyguardSurfaceBehindInteractor) {
+    val surfaceBehindViewParams = interactor.viewParams
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModel.kt
index abd178c..6d3b7f1 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModel.kt
@@ -17,14 +17,16 @@
 package com.android.systemui.keyguard.ui.viewmodel
 
 import com.android.systemui.R
+import com.android.systemui.authentication.domain.interactor.AuthenticationInteractor
+import com.android.systemui.bouncer.domain.interactor.BouncerInteractor
 import com.android.systemui.common.shared.model.ContentDescription
 import com.android.systemui.common.shared.model.Icon
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
-import com.android.systemui.keyguard.domain.interactor.LockscreenSceneInteractor
 import com.android.systemui.scene.shared.model.SceneKey
 import javax.inject.Inject
 import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.SharingStarted
 import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.flow.map
@@ -36,63 +38,58 @@
 @Inject
 constructor(
     @Application applicationScope: CoroutineScope,
-    private val interactor: LockscreenSceneInteractor,
+    authenticationInteractor: AuthenticationInteractor,
+    private val bouncerInteractor: BouncerInteractor,
 ) {
     /** The icon for the "lock" button on the lockscreen. */
     val lockButtonIcon: StateFlow<Icon> =
-        interactor.isDeviceLocked
-            .map { isLocked -> lockIcon(isLocked = isLocked) }
+        authenticationInteractor.isUnlocked
+            .map { isUnlocked -> lockIcon(isUnlocked = isUnlocked) }
             .stateIn(
                 scope = applicationScope,
                 started = SharingStarted.WhileSubscribed(),
-                initialValue = lockIcon(isLocked = interactor.isDeviceLocked.value),
+                initialValue = lockIcon(isUnlocked = authenticationInteractor.isUnlocked.value),
             )
 
     /** The key of the scene we should switch to when swiping up. */
-    val upDestinationSceneKey: StateFlow<SceneKey> =
-        interactor.isSwipeToDismissEnabled
-            .map { isSwipeToUnlockEnabled -> upDestinationSceneKey(isSwipeToUnlockEnabled) }
-            .stateIn(
-                scope = applicationScope,
-                started = SharingStarted.WhileSubscribed(),
-                initialValue = upDestinationSceneKey(interactor.isSwipeToDismissEnabled.value),
-            )
+    val upDestinationSceneKey: Flow<SceneKey> =
+        authenticationInteractor.isUnlocked.map { isUnlocked ->
+            if (isUnlocked) {
+                SceneKey.Gone
+            } else {
+                SceneKey.Bouncer
+            }
+        }
 
     /** Notifies that the lock button on the lock screen was clicked. */
     fun onLockButtonClicked() {
-        interactor.dismissLockscreen()
+        bouncerInteractor.showOrUnlockDevice()
     }
 
     /** Notifies that some content on the lock screen was clicked. */
     fun onContentClicked() {
-        interactor.dismissLockscreen()
+        bouncerInteractor.showOrUnlockDevice()
     }
 
     private fun upDestinationSceneKey(
-        isSwipeToUnlockEnabled: Boolean,
+        canSwipeToDismiss: Boolean,
     ): SceneKey {
-        return if (isSwipeToUnlockEnabled) SceneKey.Gone else SceneKey.Bouncer
+        return if (canSwipeToDismiss) SceneKey.Gone else SceneKey.Bouncer
     }
 
     private fun lockIcon(
-        isLocked: Boolean,
+        isUnlocked: Boolean,
     ): Icon {
-        return Icon.Resource(
-            res =
-                if (isLocked) {
-                    R.drawable.ic_device_lock_on
-                } else {
-                    R.drawable.ic_device_lock_off
-                },
-            contentDescription =
-                ContentDescription.Resource(
-                    res =
-                        if (isLocked) {
-                            R.string.accessibility_lock_icon
-                        } else {
-                            R.string.accessibility_unlock_button
-                        }
-                )
-        )
+        return if (isUnlocked) {
+            Icon.Resource(
+                R.drawable.ic_device_lock_off,
+                ContentDescription.Resource(R.string.accessibility_unlock_button)
+            )
+        } else {
+            Icon.Resource(
+                R.drawable.ic_device_lock_on,
+                ContentDescription.Resource(R.string.accessibility_lock_icon)
+            )
+        }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/WindowManagerLockscreenVisibilityViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/WindowManagerLockscreenVisibilityViewModel.kt
new file mode 100644
index 0000000..f797640
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/WindowManagerLockscreenVisibilityViewModel.kt
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.ui.viewmodel
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyguard.domain.interactor.WindowManagerLockscreenVisibilityInteractor
+import javax.inject.Inject
+
+@SysUISingleton
+class WindowManagerLockscreenVisibilityViewModel
+@Inject
+constructor(interactor: WindowManagerLockscreenVisibilityInteractor) {
+    val surfaceBehindVisibility = interactor.surfaceBehindVisibility
+    val surfaceBehindAnimating = interactor.usingKeyguardGoingAwayAnimation
+    val lockscreenVisibility = interactor.lockscreenVisibility
+    val aodVisibility = interactor.aodVisibility
+}
diff --git a/packages/SystemUI/src/com/android/systemui/lifecycle/RepeatWhenAttached.kt b/packages/SystemUI/src/com/android/systemui/lifecycle/RepeatWhenAttached.kt
index e064839..5f7991e 100644
--- a/packages/SystemUI/src/com/android/systemui/lifecycle/RepeatWhenAttached.kt
+++ b/packages/SystemUI/src/com/android/systemui/lifecycle/RepeatWhenAttached.kt
@@ -70,7 +70,7 @@
     var lifecycleOwner: ViewLifecycleOwner? = null
     val onAttachListener =
         object : View.OnAttachStateChangeListener {
-            override fun onViewAttachedToWindow(v: View?) {
+            override fun onViewAttachedToWindow(v: View) {
                 Assert.isMainThread()
                 lifecycleOwner?.onDestroy()
                 lifecycleOwner =
@@ -81,7 +81,7 @@
                     )
             }
 
-            override fun onViewDetachedFromWindow(v: View?) {
+            override fun onViewDetachedFromWindow(v: View) {
                 lifecycleOwner?.onDestroy()
                 lifecycleOwner = null
             }
diff --git a/core/java/android/view/selectiontoolbar/WidgetInfo.aidl b/packages/SystemUI/src/com/android/systemui/log/dagger/CommunalLog.kt
similarity index 64%
copy from core/java/android/view/selectiontoolbar/WidgetInfo.aidl
copy to packages/SystemUI/src/com/android/systemui/log/dagger/CommunalLog.kt
index 1057c51..afb18f1 100644
--- a/core/java/android/view/selectiontoolbar/WidgetInfo.aidl
+++ b/packages/SystemUI/src/com/android/systemui/log/dagger/CommunalLog.kt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2021 The Android Open Source Project
+ * Copyright (C) 2023 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,9 +14,9 @@
  * limitations under the License.
  */
 
-package android.view.selectiontoolbar;
+package com.android.systemui.log.dagger
 
-/**
- * @hide
- */
-parcelable WidgetInfo;
+import javax.inject.Qualifier
+
+/** A [com.android.systemui.log.LogBuffer] for communal-related logging. */
+@Qualifier @MustBeDocumented @Retention(AnnotationRetention.RUNTIME) annotation class CommunalLog
diff --git a/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java b/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java
index cc1504a..5127d14 100644
--- a/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java
+++ b/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java
@@ -120,6 +120,14 @@
         return factory.create("ShadeLog", 500, false);
     }
 
+    /** Provides a logging buffer for Shade messages. */
+    @Provides
+    @SysUISingleton
+    @ShadeTouchLog
+    public static LogBuffer provideShadeTouchLogBuffer(LogBufferFactory factory) {
+        return factory.create("ShadeTouchLog", 500, false);
+    }
+
     /** Provides a logging buffer for all logs related to managing notification sections. */
     @Provides
     @SysUISingleton
@@ -489,6 +497,16 @@
         return factory.create("DreamLog", 250);
     }
 
+    /**
+     * Provides a {@link LogBuffer} for communal-related logs.
+     */
+    @Provides
+    @SysUISingleton
+    @CommunalLog
+    public static LogBuffer provideCommunalLogBuffer(LogBufferFactory factory) {
+        return factory.create("CommunalLog", 250);
+    }
+
     /** Provides a {@link LogBuffer} for display metrics related logs. */
     @Provides
     @SysUISingleton
diff --git a/packages/SystemUI/src/com/android/systemui/log/dagger/ShadeTouchLog.java b/packages/SystemUI/src/com/android/systemui/log/dagger/ShadeTouchLog.java
new file mode 100644
index 0000000..b13667e
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/log/dagger/ShadeTouchLog.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.dagger;
+
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import com.android.systemui.log.LogBuffer;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+
+import javax.inject.Qualifier;
+
+/** A {@link LogBuffer} for tracking touches in various shade child views. */
+@Qualifier
+@Documented
+@Retention(RUNTIME)
+public @interface ShadeTouchLog {
+}
diff --git a/packages/SystemUI/src/com/android/systemui/log/table/TableLogBuffer.kt b/packages/SystemUI/src/com/android/systemui/log/table/TableLogBuffer.kt
index 67a985e..a7ffc5f 100644
--- a/packages/SystemUI/src/com/android/systemui/log/table/TableLogBuffer.kt
+++ b/packages/SystemUI/src/com/android/systemui/log/table/TableLogBuffer.kt
@@ -302,14 +302,14 @@
 
     @Synchronized
     override fun dump(pw: PrintWriter, args: Array<out String>) {
-        pw.println(HEADER_PREFIX + name)
-        pw.println("version $VERSION")
+        pw.append(HEADER_PREFIX).println(name)
+        pw.append("version ").println(VERSION)
 
         lastEvictedValues.values.sortedBy { it.timestamp }.forEach { it.dump(pw) }
         for (i in 0 until buffer.size) {
             buffer[i].dump(pw)
         }
-        pw.println(FOOTER_PREFIX + name)
+        pw.append(FOOTER_PREFIX).println(name)
     }
 
     /** Dumps an individual [TableChange]. */
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/models/player/SeekBarViewModel.kt b/packages/SystemUI/src/com/android/systemui/media/controls/models/player/SeekBarViewModel.kt
index 35f5a8c..a91917a 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/models/player/SeekBarViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/models/player/SeekBarViewModel.kt
@@ -514,7 +514,7 @@
          * Returns true when the down event of the scroll hits within the target box of the thumb.
          */
         override fun onScroll(
-            eventStart: MotionEvent,
+            eventStart: MotionEvent?,
             event: MotionEvent,
             distanceX: Float,
             distanceY: Float
@@ -528,7 +528,7 @@
          * Gestures that include a fling are considered a false gesture on the seek bar.
          */
         override fun onFling(
-            eventStart: MotionEvent,
+            eventStart: MotionEvent?,
             event: MotionEvent,
             velocityX: Float,
             velocityY: Float
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataFilter.kt b/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataFilter.kt
index 207df6b..a1291a4 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataFilter.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataFilter.kt
@@ -149,11 +149,7 @@
         // Check if smartspace has explicitly specified whether to re-activate resumable media.
         // The default behavior is to trigger if the smartspace data is active.
         val shouldTriggerResume =
-            if (data.cardAction?.extras?.containsKey(EXTRA_KEY_TRIGGER_RESUME) == true) {
-                data.cardAction.extras.getBoolean(EXTRA_KEY_TRIGGER_RESUME, true)
-            } else {
-                true
-            }
+            data.cardAction?.extras?.getBoolean(EXTRA_KEY_TRIGGER_RESUME, true) ?: true
         val shouldReactivate =
             shouldTriggerResume && !hasActiveMedia() && hasAnyMedia() && data.isActive
 
@@ -269,9 +265,7 @@
                     "Cannot create dismiss action click action: extras missing dismiss_intent."
                 )
             } else if (
-                dismissIntent.getComponent() != null &&
-                    dismissIntent.getComponent().getClassName() ==
-                        EXPORTED_SMARTSPACE_TRAMPOLINE_ACTIVITY_NAME
+                dismissIntent.component?.className == EXPORTED_SMARTSPACE_TRAMPOLINE_ACTIVITY_NAME
             ) {
                 // Dismiss the card Smartspace data through Smartspace trampoline activity.
                 context.startActivity(dismissIntent)
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataManager.kt b/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataManager.kt
index 55dcd88..dddbeda 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataManager.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataManager.kt
@@ -22,6 +22,7 @@
 import android.app.Notification.EXTRA_SUBSTITUTE_APP_NAME
 import android.app.PendingIntent
 import android.app.StatusBarManager
+import android.app.smartspace.SmartspaceAction
 import android.app.smartspace.SmartspaceConfig
 import android.app.smartspace.SmartspaceManager
 import android.app.smartspace.SmartspaceSession
@@ -1623,20 +1624,18 @@
      *   SmartspaceTarget's data is invalid.
      */
     private fun toSmartspaceMediaData(target: SmartspaceTarget): SmartspaceMediaData {
-        var dismissIntent: Intent? = null
-        if (target.baseAction != null && target.baseAction.extras != null) {
-            dismissIntent =
-                target.baseAction.extras.getParcelable(EXTRAS_SMARTSPACE_DISMISS_INTENT_KEY)
-                    as Intent?
-        }
+        val baseAction: SmartspaceAction? = target.baseAction
+        val dismissIntent =
+            baseAction?.extras?.getParcelable(EXTRAS_SMARTSPACE_DISMISS_INTENT_KEY) as Intent?
 
         val isActive =
             when {
                 !mediaFlags.isPersistentSsCardEnabled() -> true
-                target.baseAction == null -> true
-                else ->
-                    target.baseAction.extras.getString(EXTRA_KEY_TRIGGER_SOURCE) !=
-                        EXTRA_VALUE_TRIGGER_PERIODIC
+                baseAction == null -> true
+                else -> {
+                    val triggerSource = baseAction.extras?.getString(EXTRA_KEY_TRIGGER_SOURCE)
+                    triggerSource != EXTRA_VALUE_TRIGGER_PERIODIC
+                }
             }
 
         packageName(target)?.let {
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaSessionBasedFilter.kt b/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaSessionBasedFilter.kt
index d6f941d..6a8ffb7 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaSessionBasedFilter.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaSessionBasedFilter.kt
@@ -65,7 +65,7 @@
 
     private val sessionListener =
         object : MediaSessionManager.OnActiveSessionsChangedListener {
-            override fun onActiveSessionsChanged(controllers: List<MediaController>) {
+            override fun onActiveSessionsChanged(controllers: List<MediaController>?) {
                 handleControllersChanged(controllers)
             }
         }
@@ -190,16 +190,18 @@
         }
     }
 
-    private fun handleControllersChanged(controllers: List<MediaController>) {
+    private fun handleControllersChanged(controllers: List<MediaController>?) {
         packageControllers.clear()
-        controllers.forEach { controller ->
+        controllers?.forEach { controller ->
             packageControllers.get(controller.packageName)?.let { tokens -> tokens.add(controller) }
                 ?: run {
                     val tokens = mutableListOf(controller)
                     packageControllers.put(controller.packageName, tokens)
                 }
         }
-        tokensWithNotifications.retainAll(controllers.map { TokenId(it.sessionToken) })
+        controllers?.map { TokenId(it.sessionToken) }?.let {
+            tokensWithNotifications.retainAll(it)
+        }
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/ui/IlluminationDrawable.kt b/packages/SystemUI/src/com/android/systemui/media/controls/ui/IlluminationDrawable.kt
index b46ebb2..b9cc772 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/ui/IlluminationDrawable.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/ui/IlluminationDrawable.kt
@@ -195,7 +195,7 @@
                 }
                 addListener(
                     object : AnimatorListenerAdapter() {
-                        override fun onAnimationEnd(animation: Animator?) {
+                        override fun onAnimationEnd(animation: Animator) {
                             backgroundAnimation = null
                         }
                     }
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/ui/LightSourceDrawable.kt b/packages/SystemUI/src/com/android/systemui/media/controls/ui/LightSourceDrawable.kt
index 937a618..646d1d0 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/ui/LightSourceDrawable.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/ui/LightSourceDrawable.kt
@@ -98,11 +98,11 @@
                         addListener(
                             object : AnimatorListenerAdapter() {
                                 var cancelled = false
-                                override fun onAnimationCancel(animation: Animator?) {
+                                override fun onAnimationCancel(animation: Animator) {
                                     cancelled = true
                                 }
 
-                                override fun onAnimationEnd(animation: Animator?) {
+                                override fun onAnimationEnd(animation: Animator) {
                                     if (cancelled) {
                                         return
                                     }
@@ -226,7 +226,7 @@
                 )
                 addListener(
                     object : AnimatorListenerAdapter() {
-                        override fun onAnimationEnd(animation: Animator?) {
+                        override fun onAnimationEnd(animation: Animator) {
                             rippleData.progress = 0f
                             rippleAnimation = null
                             invalidateSelf()
@@ -270,11 +270,8 @@
         return bounds
     }
 
-    override fun onStateChange(stateSet: IntArray?): Boolean {
+    override fun onStateChange(stateSet: IntArray): Boolean {
         val changed = super.onStateChange(stateSet)
-        if (stateSet == null) {
-            return changed
-        }
 
         val wasPressed = pressed
         var enabled = false
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaCarouselScrollHandler.kt b/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaCarouselScrollHandler.kt
index 1ace316..ce50a11 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaCarouselScrollHandler.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaCarouselScrollHandler.kt
@@ -127,19 +127,19 @@
         object : GestureDetector.SimpleOnGestureListener() {
             override fun onFling(
                 eStart: MotionEvent?,
-                eCurrent: MotionEvent?,
+                eCurrent: MotionEvent,
                 vX: Float,
                 vY: Float
             ) = onFling(vX, vY)
 
             override fun onScroll(
                 down: MotionEvent?,
-                lastMotion: MotionEvent?,
+                lastMotion: MotionEvent,
                 distanceX: Float,
                 distanceY: Float
-            ) = onScroll(down!!, lastMotion!!, distanceX)
+            ) = onScroll(down!!, lastMotion, distanceX)
 
-            override fun onDown(e: MotionEvent?): Boolean {
+            override fun onDown(e: MotionEvent): Boolean {
                 if (falsingProtectionNeeded) {
                     falsingCollector.onNotificationStartDismissing()
                 }
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaHierarchyManager.kt b/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaHierarchyManager.kt
index fe8ebaf..c1c757e 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaHierarchyManager.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaHierarchyManager.kt
@@ -180,20 +180,20 @@
                 object : AnimatorListenerAdapter() {
                     private var cancelled: Boolean = false
 
-                    override fun onAnimationCancel(animation: Animator?) {
+                    override fun onAnimationCancel(animation: Animator) {
                         cancelled = true
                         animationPending = false
                         rootView?.removeCallbacks(startAnimation)
                     }
 
-                    override fun onAnimationEnd(animation: Animator?) {
+                    override fun onAnimationEnd(animation: Animator) {
                         isCrossFadeAnimatorRunning = false
                         if (!cancelled) {
                             applyTargetStateIfNotAnimating()
                         }
                     }
 
-                    override fun onAnimationStart(animation: Animator?) {
+                    override fun onAnimationStart(animation: Animator) {
                         cancelled = false
                         animationPending = false
                     }
@@ -606,7 +606,7 @@
         val viewHost = UniqueObjectHostView(context)
         viewHost.addOnAttachStateChangeListener(
             object : View.OnAttachStateChangeListener {
-                override fun onViewAttachedToWindow(p0: View?) {
+                override fun onViewAttachedToWindow(p0: View) {
                     if (rootOverlay == null) {
                         rootView = viewHost.viewRootImpl.view
                         rootOverlay = (rootView!!.overlay as ViewGroupOverlay)
@@ -614,7 +614,7 @@
                     viewHost.removeOnAttachStateChangeListener(this)
                 }
 
-                override fun onViewDetachedFromWindow(p0: View?) {}
+                override fun onViewDetachedFromWindow(p0: View) {}
             }
         )
         return viewHost
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaHost.kt b/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaHost.kt
index be570b4..631a0b8 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaHost.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/ui/MediaHost.kt
@@ -144,12 +144,12 @@
         setListeningToMediaData(true)
         hostView.addOnAttachStateChangeListener(
             object : OnAttachStateChangeListener {
-                override fun onViewAttachedToWindow(v: View?) {
+                override fun onViewAttachedToWindow(v: View) {
                     setListeningToMediaData(true)
                     updateViewVisibility()
                 }
 
-                override fun onViewDetachedFromWindow(v: View?) {
+                override fun onViewDetachedFromWindow(v: View) {
                     setListeningToMediaData(false)
                 }
             }
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/ui/SquigglyProgress.kt b/packages/SystemUI/src/com/android/systemui/media/controls/ui/SquigglyProgress.kt
index 583c626..16dfc21 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/ui/SquigglyProgress.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/ui/SquigglyProgress.kt
@@ -117,7 +117,7 @@
                     }
                     addListener(
                         object : AnimatorListenerAdapter() {
-                            override fun onAnimationEnd(animation: Animator?) {
+                            override fun onAnimationEnd(animation: Animator) {
                                 heightAnimator = null
                             }
                         }
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaSessionLegacyHelperWrapper.kt b/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaSessionLegacyHelperWrapper.kt
new file mode 100644
index 0000000..9924369
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaSessionLegacyHelperWrapper.kt
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.media.controls.util
+
+import android.content.Context
+import android.media.session.MediaSessionLegacyHelper
+import com.android.systemui.dagger.SysUISingleton
+import javax.inject.Inject
+
+/** Injectable wrapper around `MediaSessionLegacyHelper` functions */
+@SysUISingleton
+class MediaSessionLegacyHelperWrapper @Inject constructor() {
+    fun getHelper(context: Context): MediaSessionLegacyHelper {
+        return MediaSessionLegacyHelper.getHelper(context)
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseAdapter.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseAdapter.java
index b88eba9..d8824983 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseAdapter.java
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseAdapter.java
@@ -157,6 +157,7 @@
         private String mDeviceId;
         private ValueAnimator mCornerAnimator;
         private ValueAnimator mVolumeAnimator;
+        private int mLatestUpdateVolume = -1;
 
         MediaDeviceBaseViewHolder(View view) {
             super(view);
@@ -314,7 +315,11 @@
             mSeekBar.setMaxVolume(device.getMaxVolume());
             final int currentVolume = device.getCurrentVolume();
             if (!mIsDragging) {
-                if (mSeekBar.getVolume() != currentVolume) {
+                if (mSeekBar.getVolume() != currentVolume && (mLatestUpdateVolume == -1
+                        || currentVolume == mLatestUpdateVolume)) {
+                    // Update only if volume of device and value of volume bar doesn't match.
+                    // Check if response volume match with the latest request, to ignore obsolete
+                    // response
                     if (isCurrentSeekbarInvisible && !mIsInitVolumeFirstTime) {
                         updateTitleIcon(currentVolume == 0 ? R.drawable.media_output_icon_volume_off
                                         : R.drawable.media_output_icon_volume,
@@ -330,12 +335,16 @@
                                 updateUnmutedVolumeIcon();
                             }
                             mSeekBar.setVolume(currentVolume);
+                            mLatestUpdateVolume = -1;
                         }
                     }
                 } else if (currentVolume == 0) {
                     mSeekBar.resetVolume();
                     updateMutedVolumeIcon();
                 }
+                if (currentVolume == mLatestUpdateVolume) {
+                    mLatestUpdateVolume = -1;
+                }
             }
             if (mIsInitVolumeFirstTime) {
                 mIsInitVolumeFirstTime = false;
@@ -360,6 +369,7 @@
                         mStartFromMute = false;
                     }
                     if (progressToVolume != deviceVolume) {
+                        mLatestUpdateVolume = progressToVolume;
                         mController.adjustVolume(device, progressToVolume);
                     }
                 }
@@ -505,11 +515,13 @@
             mSeekBar.setOnTouchListener((v, event) -> false);
             updateIconAreaClickListener((v) -> {
                 if (device.getCurrentVolume() == 0) {
+                    mController.logInteractionUnmuteDevice(device);
                     mSeekBar.setVolume(UNMUTE_DEFAULT_VOLUME);
                     mController.adjustVolume(device, UNMUTE_DEFAULT_VOLUME);
                     updateUnmutedVolumeIcon();
                     mIconAreaLayout.setOnTouchListener(((iconV, event) -> false));
                 } else {
+                    mController.logInteractionMuteDevice(device);
                     mSeekBar.resetVolume();
                     mController.adjustVolume(device, 0);
                     updateMutedVolumeIcon();
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseDialog.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseDialog.java
index 7712690..3a1d8b0 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseDialog.java
@@ -296,7 +296,10 @@
 
     @Override
     public void stop() {
-        if (isBroadcastSupported() && mIsLeBroadcastCallbackRegistered) {
+        // unregister broadcast callback should only depend on profile and registered flag
+        // rather than remote device or broadcast state
+        // otherwise it might have risks of leaking registered callback handle
+        if (mMediaOutputController.isBroadcastSupported() && mIsLeBroadcastCallbackRegistered) {
             mMediaOutputController.unregisterLeBroadcastServiceCallback(mBroadcastCallback);
             mIsLeBroadcastCallbackRegistered = false;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java
index d281f50..bb0e9d1 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java
@@ -837,6 +837,14 @@
         mMetricLogger.logInteractionAdjustVolume(device);
     }
 
+    void logInteractionMuteDevice(MediaDevice device) {
+        mMetricLogger.logInteractionMute(device);
+    }
+
+    void logInteractionUnmuteDevice(MediaDevice device) {
+        mMetricLogger.logInteractionUnmute(device);
+    }
+
     String getPackageName() {
         return mPackageName;
     }
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialog.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialog.java
index f3865f5..e5a6bb5 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialog.java
@@ -104,11 +104,16 @@
     @Override
     public boolean isBroadcastSupported() {
         boolean isBluetoothLeDevice = false;
+        boolean isBroadcastEnabled = false;
         if (FeatureFlagUtils.isEnabled(mContext,
                 FeatureFlagUtils.SETTINGS_NEED_CONNECTED_BLE_DEVICE_FOR_BROADCAST)) {
             if (mMediaOutputController.getCurrentConnectedMediaDevice() != null) {
                 isBluetoothLeDevice = mMediaOutputController.isBluetoothLeDevice(
                     mMediaOutputController.getCurrentConnectedMediaDevice());
+                // if broadcast is active, broadcast should be considered as supported
+                // there could be a valid case that broadcast is ongoing
+                // without active LEA device connected
+                isBroadcastEnabled = mMediaOutputController.isBluetoothLeBroadcastEnabled();
             }
         } else {
             // To decouple LE Audio Broadcast and Unicast, it always displays the button when there
@@ -116,7 +121,8 @@
             isBluetoothLeDevice = true;
         }
 
-        return mMediaOutputController.isBroadcastSupported() && isBluetoothLeDevice;
+        return mMediaOutputController.isBroadcastSupported()
+                && (isBluetoothLeDevice || isBroadcastEnabled);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java
index 39d4e6e..ffd626a 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java
@@ -56,6 +56,7 @@
      * Update the endpoints of a content switching operation.
      * This method should be called before a switching operation, so the metric logger can track
      * source and target devices.
+     *
      * @param source the current connected media device
      * @param target the target media device for content switching to
      */
@@ -72,37 +73,9 @@
 
     /**
      * Do the metric logging of content switching success.
+     *
      * @param selectedDeviceType string representation of the target media device
-     * @param deviceList media device list for device count updating
-     */
-    public void logOutputSuccess(String selectedDeviceType, List<MediaDevice> deviceList) {
-        if (DEBUG) {
-            Log.d(TAG, "logOutputSuccess - selected device: " + selectedDeviceType);
-        }
-
-        if (mSourceDevice == null && mTargetDevice == null) {
-            return;
-        }
-
-        updateLoggingDeviceCount(deviceList);
-
-        SysUiStatsLog.write(
-                SysUiStatsLog.MEDIAOUTPUT_OP_SWITCH_REPORTED,
-                getLoggingDeviceType(mSourceDevice, true),
-                getLoggingDeviceType(mTargetDevice, false),
-                SysUiStatsLog.MEDIA_OUTPUT_OP_SWITCH_REPORTED__RESULT__OK,
-                SysUiStatsLog.MEDIA_OUTPUT_OP_SWITCH_REPORTED__SUBRESULT__NO_ERROR,
-                getLoggingPackageName(),
-                mWiredDeviceCount,
-                mConnectedBluetoothDeviceCount,
-                mRemoteDeviceCount,
-                mAppliedDeviceCountWithinRemoteGroup);
-    }
-
-    /**
-     * Do the metric logging of content switching success.
-     * @param selectedDeviceType string representation of the target media device
-     * @param deviceItemList media item list for device count updating
+     * @param deviceItemList     media item list for device count updating
      */
     public void logOutputItemSuccess(String selectedDeviceType, List<MediaItem> deviceItemList) {
         if (DEBUG) {
@@ -125,11 +98,14 @@
                 mWiredDeviceCount,
                 mConnectedBluetoothDeviceCount,
                 mRemoteDeviceCount,
-                mAppliedDeviceCountWithinRemoteGroup);
+                mAppliedDeviceCountWithinRemoteGroup,
+                mTargetDevice.isSuggestedDevice(),
+                mTargetDevice.hasOngoingSession());
     }
 
     /**
      * Do the metric logging of volume adjustment.
+     *
      * @param source the device been adjusted
      */
     public void logInteractionAdjustVolume(MediaDevice source) {
@@ -141,7 +117,8 @@
                 SysUiStatsLog.MEDIAOUTPUT_OP_INTERACTION_REPORT,
                 SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__INTERACTION_TYPE__ADJUST_VOLUME,
                 getInteractionDeviceType(source),
-                getLoggingPackageName());
+                getLoggingPackageName(),
+                source.isSuggestedDevice());
     }
 
     /**
@@ -156,7 +133,8 @@
                 SysUiStatsLog.MEDIAOUTPUT_OP_INTERACTION_REPORT,
                 SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__INTERACTION_TYPE__STOP_CASTING,
                 SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__TARGET__UNKNOWN_TYPE,
-                getLoggingPackageName());
+                getLoggingPackageName(),
+                /*isSuggestedDevice = */false);
     }
 
     /**
@@ -171,42 +149,47 @@
                 SysUiStatsLog.MEDIAOUTPUT_OP_INTERACTION_REPORT,
                 SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__INTERACTION_TYPE__EXPANSION,
                 getInteractionDeviceType(source),
-                getLoggingPackageName());
+                getLoggingPackageName(),
+                source.isSuggestedDevice());
     }
 
     /**
-     * Do the metric logging of content switching failure.
-     * @param deviceList media device list for device count updating
-     * @param reason the reason of content switching failure
+     * Do the metric logging of muting device.
      */
-    public void logOutputFailure(List<MediaDevice> deviceList, int reason) {
+    public void logInteractionMute(MediaDevice source) {
         if (DEBUG) {
-            Log.e(TAG, "logRequestFailed - " + reason);
+            Log.d(TAG, "logInteraction - Mute");
         }
 
-        if (mSourceDevice == null && mTargetDevice == null) {
-            return;
-        }
-
-        updateLoggingDeviceCount(deviceList);
-
         SysUiStatsLog.write(
-                SysUiStatsLog.MEDIAOUTPUT_OP_SWITCH_REPORTED,
-                getLoggingDeviceType(mSourceDevice, true),
-                getLoggingDeviceType(mTargetDevice, false),
-                SysUiStatsLog.MEDIA_OUTPUT_OP_SWITCH_REPORTED__RESULT__ERROR,
-                getLoggingSwitchOpSubResult(reason),
+                SysUiStatsLog.MEDIAOUTPUT_OP_INTERACTION_REPORT,
+                SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__INTERACTION_TYPE__MUTE,
+                getInteractionDeviceType(source),
                 getLoggingPackageName(),
-                mWiredDeviceCount,
-                mConnectedBluetoothDeviceCount,
-                mRemoteDeviceCount,
-                mAppliedDeviceCountWithinRemoteGroup);
+                source.isSuggestedDevice());
+    }
+
+    /**
+     * Do the metric logging of unmuting device.
+     */
+    public void logInteractionUnmute(MediaDevice source) {
+        if (DEBUG) {
+            Log.d(TAG, "logInteraction - Unmute");
+        }
+
+        SysUiStatsLog.write(
+                SysUiStatsLog.MEDIAOUTPUT_OP_INTERACTION_REPORT,
+                SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__INTERACTION_TYPE__UNMUTE,
+                getInteractionDeviceType(source),
+                getLoggingPackageName(),
+                source.isSuggestedDevice());
     }
 
     /**
      * Do the metric logging of content switching failure.
+     *
      * @param deviceItemList media item list for device count updating
-     * @param reason the reason of content switching failure
+     * @param reason         the reason of content switching failure
      */
     public void logOutputItemFailure(List<MediaItem> deviceItemList, int reason) {
         if (DEBUG) {
@@ -229,7 +212,9 @@
                 mWiredDeviceCount,
                 mConnectedBluetoothDeviceCount,
                 mRemoteDeviceCount,
-                mAppliedDeviceCountWithinRemoteGroup);
+                mAppliedDeviceCountWithinRemoteGroup,
+                mTargetDevice.isSuggestedDevice(),
+                mTargetDevice.hasOngoingSession());
     }
 
     private void updateLoggingDeviceCount(List<MediaDevice> deviceList) {
@@ -266,7 +251,7 @@
         mWiredDeviceCount = mConnectedBluetoothDeviceCount = mRemoteDeviceCount = 0;
         mAppliedDeviceCountWithinRemoteGroup = 0;
 
-        for (MediaItem mediaItem: deviceItemList) {
+        for (MediaItem mediaItem : deviceItemList) {
             if (mediaItem.getMediaDevice().isPresent()
                     && mediaItem.getMediaDevice().get().isConnected()) {
                 switch (mediaItem.getMediaDevice().get().getDeviceType()) {
@@ -326,6 +311,10 @@
                 return isSourceDevice
                         ? SysUiStatsLog.MEDIA_OUTPUT_OP_SWITCH_REPORTED__SOURCE__REMOTE_GROUP
                         : SysUiStatsLog.MEDIA_OUTPUT_OP_SWITCH_REPORTED__TARGET__REMOTE_GROUP;
+            case MediaDevice.MediaDeviceType.TYPE_REMOTE_AUDIO_VIDEO_RECEIVER:
+                return isSourceDevice
+                        ? SysUiStatsLog.MEDIA_OUTPUT_OP_SWITCH_REPORTED__SOURCE__AVR
+                        : SysUiStatsLog.MEDIA_OUTPUT_OP_SWITCH_REPORTED__TARGET__AVR;
             default:
                 return isSourceDevice
                         ? SysUiStatsLog.MEDIA_OUTPUT_OP_SWITCH_REPORTED__SOURCE__UNKNOWN_TYPE
diff --git a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttChipControllerReceiver.kt b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttChipControllerReceiver.kt
index bbd3d33..da8e106 100644
--- a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttChipControllerReceiver.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttChipControllerReceiver.kt
@@ -201,13 +201,13 @@
     }
 
     override fun updateView(newInfo: ChipReceiverInfo, currentView: ViewGroup) {
-        val packageName = newInfo.routeInfo.clientPackageName
+        val packageName: String? = newInfo.routeInfo.clientPackageName
         var iconInfo = MediaTttUtils.getIconInfoFromPackageName(
             context,
             packageName,
             isReceiver = true,
         ) {
-            logger.logPackageNotFound(packageName)
+            packageName?.let { logger.logPackageNotFound(it) }
         }
 
         if (newInfo.appNameOverride != null) {
diff --git a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttReceiverRippleController.kt b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttReceiverRippleController.kt
index 5013802..fbf7e25 100644
--- a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttReceiverRippleController.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttReceiverRippleController.kt
@@ -68,9 +68,9 @@
         )
         rippleView.addOnAttachStateChangeListener(
             object : View.OnAttachStateChangeListener {
-                override fun onViewDetachedFromWindow(view: View?) {}
+                override fun onViewDetachedFromWindow(view: View) {}
 
-                override fun onViewAttachedToWindow(view: View?) {
+                override fun onViewAttachedToWindow(view: View) {
                     if (view == null) {
                         return
                     }
diff --git a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/ReceiverChipRippleView.kt b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/ReceiverChipRippleView.kt
index 0b0535d..35018f1 100644
--- a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/ReceiverChipRippleView.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/ReceiverChipRippleView.kt
@@ -54,7 +54,7 @@
         // Reset all listeners to animator.
         animator.removeAllListeners()
         animator.addListener(object : AnimatorListenerAdapter() {
-            override fun onAnimationEnd(animation: Animator?) {
+            override fun onAnimationEnd(animation: Animator) {
                 onAnimationEnd?.run()
                 isStarted = false
             }
@@ -86,7 +86,7 @@
             invalidate()
         }
         animator.addListener(object : AnimatorListenerAdapter() {
-            override fun onAnimationEnd(animation: Animator?) {
+            override fun onAnimationEnd(animation: Animator) {
                 animation?.let { visibility = GONE }
                 onAnimationEnd?.run()
                 isStarted = false
diff --git a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/sender/MediaTttSenderCoordinator.kt b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/sender/MediaTttSenderCoordinator.kt
index f75f8b9..87d0098 100644
--- a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/sender/MediaTttSenderCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/sender/MediaTttSenderCoordinator.kt
@@ -162,7 +162,7 @@
         logger: MediaTttSenderLogger,
         instanceId: InstanceId,
     ): ChipbarInfo {
-        val packageName = routeInfo.clientPackageName
+        val packageName = checkNotNull(routeInfo.clientPackageName)
         val otherDeviceName =
             if (routeInfo.name.isBlank()) {
                 context.getString(R.string.media_ttt_default_device_type)
diff --git a/packages/SystemUI/src/com/android/systemui/mediaprojection/appselector/view/MediaProjectionRecentsViewController.kt b/packages/SystemUI/src/com/android/systemui/mediaprojection/appselector/view/MediaProjectionRecentsViewController.kt
index c816446..64de9bd 100644
--- a/packages/SystemUI/src/com/android/systemui/mediaprojection/appselector/view/MediaProjectionRecentsViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/mediaprojection/appselector/view/MediaProjectionRecentsViewController.kt
@@ -88,7 +88,7 @@
                 .inflate(R.layout.media_projection_recent_tasks, parent, /* attachToRoot= */ false)
                 as ViewGroup
 
-        val container = recentsRoot.findViewById<View>(R.id.media_projection_recent_tasks_container)
+        val container = recentsRoot.requireViewById<View>(R.id.media_projection_recent_tasks_container)
         container.setTaskHeightSize()
 
         val progress = recentsRoot.requireViewById<View>(R.id.media_projection_recent_tasks_loader)
diff --git a/packages/SystemUI/src/com/android/systemui/mediaprojection/taskswitcher/data/repository/MediaProjectionManagerRepository.kt b/packages/SystemUI/src/com/android/systemui/mediaprojection/taskswitcher/data/repository/MediaProjectionManagerRepository.kt
index 38d4e69..6480a47 100644
--- a/packages/SystemUI/src/com/android/systemui/mediaprojection/taskswitcher/data/repository/MediaProjectionManagerRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/mediaprojection/taskswitcher/data/repository/MediaProjectionManagerRepository.kt
@@ -81,8 +81,8 @@
             return MediaProjectionState.EntireScreen
         }
         val matchingTask =
-            tasksRepository.findRunningTaskFromWindowContainerToken(session.tokenToRecord)
-                ?: return MediaProjectionState.EntireScreen
+            tasksRepository.findRunningTaskFromWindowContainerToken(
+                checkNotNull(session.tokenToRecord)) ?: return MediaProjectionState.EntireScreen
         return MediaProjectionState.SingleTask(matchingTask)
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/navigationbar/NavigationBar.java b/packages/SystemUI/src/com/android/systemui/navigationbar/NavigationBar.java
index e134f7c..ae0ab84 100644
--- a/packages/SystemUI/src/com/android/systemui/navigationbar/NavigationBar.java
+++ b/packages/SystemUI/src/com/android/systemui/navigationbar/NavigationBar.java
@@ -25,6 +25,7 @@
 import static android.app.StatusBarManager.WindowVisibleState;
 import static android.app.StatusBarManager.windowStateToString;
 import static android.app.WindowConfiguration.ROTATION_UNDEFINED;
+import static android.inputmethodservice.InputMethodService.ENABLE_HIDE_IME_CAPTION_BAR;
 import static android.view.InsetsSource.FLAG_SUPPRESS_SCRIM;
 import static android.view.WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE;
 import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
@@ -1714,10 +1715,12 @@
 
     private InsetsFrameProvider[] getInsetsFrameProvider(int insetsHeight, Context userContext) {
         final InsetsFrameProvider navBarProvider =
-                new InsetsFrameProvider(mInsetsSourceOwner, 0, WindowInsets.Type.navigationBars())
-                        .setInsetsSizeOverrides(new InsetsFrameProvider.InsetsSizeOverride[] {
-                                new InsetsFrameProvider.InsetsSizeOverride(
-                                        TYPE_INPUT_METHOD, null)});
+                new InsetsFrameProvider(mInsetsSourceOwner, 0, WindowInsets.Type.navigationBars());
+        if (!ENABLE_HIDE_IME_CAPTION_BAR) {
+            navBarProvider.setInsetsSizeOverrides(new InsetsFrameProvider.InsetsSizeOverride[] {
+                    new InsetsFrameProvider.InsetsSizeOverride(TYPE_INPUT_METHOD, null)
+            });
+        }
         if (insetsHeight != -1 && !mEdgeBackGestureHandler.isButtonForcedVisible()) {
             navBarProvider.setInsetsSize(Insets.of(0, 0, 0, insetsHeight));
         }
diff --git a/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskRoleManagerExt.kt b/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskRoleManagerExt.kt
index 4d30634..63d4634 100644
--- a/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskRoleManagerExt.kt
+++ b/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskRoleManagerExt.kt
@@ -77,8 +77,13 @@
             .build()
     }
 
-    private fun PackageManager.getApplicationLabel(packageName: String?): String? =
-        runCatching { getApplicationInfo(packageName, /* flags= */ 0)!! }
+    private fun PackageManager.getApplicationLabel(packageName: String?): String? {
+        if (packageName == null) {
+            return null
+        }
+
+        return runCatching { getApplicationInfo(packageName, /* flags= */ 0)!! }
             .getOrNull()
             ?.let { info -> getApplicationLabel(info).toString() }
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/people/PeopleSpaceActivity.java b/packages/SystemUI/src/com/android/systemui/people/PeopleSpaceActivity.java
deleted file mode 100644
index d1d3e3d..0000000
--- a/packages/SystemUI/src/com/android/systemui/people/PeopleSpaceActivity.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.people;
-
-import static android.appwidget.AppWidgetManager.EXTRA_APPWIDGET_ID;
-import static android.appwidget.AppWidgetManager.INVALID_APPWIDGET_ID;
-
-import android.content.Intent;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.ViewGroup;
-
-import androidx.activity.ComponentActivity;
-import androidx.lifecycle.ViewModelProvider;
-
-import com.android.systemui.compose.ComposeFacade;
-import com.android.systemui.flags.FeatureFlags;
-import com.android.systemui.flags.Flags;
-import com.android.systemui.people.ui.view.PeopleViewBinder;
-import com.android.systemui.people.ui.viewmodel.PeopleViewModel;
-
-import javax.inject.Inject;
-
-import kotlin.Unit;
-import kotlin.jvm.functions.Function1;
-
-/** People Tile Widget configuration activity that shows the user their conversation tiles. */
-public class PeopleSpaceActivity extends ComponentActivity {
-
-    private static final String TAG = "PeopleSpaceActivity";
-    private static final boolean DEBUG = PeopleSpaceUtils.DEBUG;
-
-    private final PeopleViewModel.Factory mViewModelFactory;
-    private final FeatureFlags mFeatureFlags;
-
-    @Inject
-    public PeopleSpaceActivity(PeopleViewModel.Factory viewModelFactory,
-            FeatureFlags featureFlags) {
-        super();
-        mViewModelFactory = viewModelFactory;
-        mFeatureFlags = featureFlags;
-    }
-
-    @Override
-    protected void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        setResult(RESULT_CANCELED);
-
-        PeopleViewModel viewModel = new ViewModelProvider(this, mViewModelFactory).get(
-                PeopleViewModel.class);
-
-        // Update the widget ID coming from the intent.
-        int widgetId = getIntent().getIntExtra(EXTRA_APPWIDGET_ID, INVALID_APPWIDGET_ID);
-        viewModel.onWidgetIdChanged(widgetId);
-
-        Function1<PeopleViewModel.Result, Unit> onResult = (result) -> {
-            finishActivity(result);
-            return null;
-        };
-
-        if (mFeatureFlags.isEnabled(Flags.COMPOSE_PEOPLE_SPACE)
-                && ComposeFacade.INSTANCE.isComposeAvailable()) {
-            Log.d(TAG, "Using the Compose implementation of the PeopleSpaceActivity");
-            ComposeFacade.INSTANCE.setPeopleSpaceActivityContent(this, viewModel, onResult);
-        } else {
-            Log.d(TAG, "Using the View implementation of the PeopleSpaceActivity");
-            ViewGroup view = PeopleViewBinder.create(this);
-            PeopleViewBinder.bind(view, viewModel, /* lifecycleOwner= */ this, onResult);
-            setContentView(view);
-        }
-    }
-
-    private void finishActivity(PeopleViewModel.Result result) {
-        if (result instanceof PeopleViewModel.Result.Success) {
-            if (DEBUG) Log.d(TAG, "Widget added!");
-            Intent data = ((PeopleViewModel.Result.Success) result).getData();
-            setResult(RESULT_OK, data);
-        } else {
-            if (DEBUG) Log.d(TAG, "Activity dismissed with no widgets added!");
-            setResult(RESULT_CANCELED);
-        }
-        finish();
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/people/PeopleSpaceActivity.kt b/packages/SystemUI/src/com/android/systemui/people/PeopleSpaceActivity.kt
new file mode 100644
index 0000000..5b7eb45
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/people/PeopleSpaceActivity.kt
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.people
+
+import android.appwidget.AppWidgetManager
+import android.os.Bundle
+import android.util.Log
+import androidx.activity.ComponentActivity
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.ViewModelProvider
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.repeatOnLifecycle
+import com.android.systemui.compose.ComposeFacade.isComposeAvailable
+import com.android.systemui.compose.ComposeFacade.setPeopleSpaceActivityContent
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
+import com.android.systemui.people.ui.view.PeopleViewBinder
+import com.android.systemui.people.ui.view.PeopleViewBinder.bind
+import com.android.systemui.people.ui.viewmodel.PeopleViewModel
+import javax.inject.Inject
+import kotlinx.coroutines.launch
+
+/** People Tile Widget configuration activity that shows the user their conversation tiles. */
+class PeopleSpaceActivity
+@Inject
+constructor(
+    private val viewModelFactory: PeopleViewModel.Factory,
+    private val featureFlags: FeatureFlags,
+) : ComponentActivity() {
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+        setResult(RESULT_CANCELED)
+
+        // Update the widget ID coming from the intent.
+        val viewModel = ViewModelProvider(this, viewModelFactory)[PeopleViewModel::class.java]
+        val widgetId =
+            intent.getIntExtra(
+                AppWidgetManager.EXTRA_APPWIDGET_ID,
+                AppWidgetManager.INVALID_APPWIDGET_ID,
+            )
+        viewModel.onWidgetIdChanged(widgetId)
+
+        // Make sure to refresh the tiles/conversations when the lifecycle is resumed, so that it
+        // updates them when going back to the Activity after leaving it.
+        // Note that we do this here instead of inside an effect in the PeopleScreen() composable
+        // because otherwise onTileRefreshRequested() will be called after the first composition,
+        // which will trigger a new recomposition and redraw, affecting the GPU memory (see
+        // b/276871425).
+        lifecycleScope.launch {
+            repeatOnLifecycle(Lifecycle.State.RESUMED) { viewModel.onTileRefreshRequested() }
+        }
+
+        // Set the content of the activity, using either the View or Compose implementation.
+        if (featureFlags.isEnabled(Flags.COMPOSE_PEOPLE_SPACE) && isComposeAvailable()) {
+            Log.d(TAG, "Using the Compose implementation of the PeopleSpaceActivity")
+            setPeopleSpaceActivityContent(
+                activity = this,
+                viewModel,
+                onResult = { finishActivity(it) },
+            )
+        } else {
+            Log.d(TAG, "Using the View implementation of the PeopleSpaceActivity")
+            val view = PeopleViewBinder.create(this)
+            bind(view, viewModel, lifecycleOwner = this, onResult = { finishActivity(it) })
+            setContentView(view)
+        }
+    }
+
+    private fun finishActivity(result: PeopleViewModel.Result) {
+        if (result is PeopleViewModel.Result.Success) {
+            if (DEBUG) Log.d(TAG, "Widget added!")
+            setResult(RESULT_OK, result.data)
+        } else {
+            if (DEBUG) Log.d(TAG, "Activity dismissed with no widgets added!")
+            setResult(RESULT_CANCELED)
+        }
+
+        finish()
+    }
+
+    companion object {
+        private const val TAG = "PeopleSpaceActivity"
+        private const val DEBUG = PeopleSpaceUtils.DEBUG
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/people/ui/view/PeopleViewBinder.kt b/packages/SystemUI/src/com/android/systemui/people/ui/view/PeopleViewBinder.kt
index d8a429e..46c8d35 100644
--- a/packages/SystemUI/src/com/android/systemui/people/ui/view/PeopleViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/people/ui/view/PeopleViewBinder.kt
@@ -109,14 +109,6 @@
                     }
             }
         }
-
-        // Make sure to refresh the tiles/conversations when the Activity is resumed, so that it
-        // updates them when going back to the Activity after leaving it.
-        lifecycleOwner.lifecycleScope.launch {
-            lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
-                viewModel.onTileRefreshRequested()
-            }
-        }
     }
 
     private fun setNoConversationsContent(view: ViewGroup, onGotItClicked: () -> Unit) {
@@ -140,13 +132,13 @@
             LayoutInflater.from(context)
                 .inflate(R.layout.people_space_activity_no_conversations, /* root= */ view)
 
-        noConversationsView.findViewById<View>(R.id.got_it_button).setOnClickListener {
+        noConversationsView.requireViewById<View>(R.id.got_it_button).setOnClickListener {
             onGotItClicked()
         }
 
         // The Tile preview has colorBackground as its background. Change it so it's different than
         // the activity's background.
-        val item = noConversationsView.findViewById<LinearLayout>(android.R.id.background)
+        val item = noConversationsView.requireViewById<LinearLayout>(android.R.id.background)
         val shape = item.background as GradientDrawable
         val ta =
             context.theme.obtainStyledAttributes(
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/AppOpsPrivacyItemMonitor.kt b/packages/SystemUI/src/com/android/systemui/privacy/AppOpsPrivacyItemMonitor.kt
index 88b8676..fedbdec 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/AppOpsPrivacyItemMonitor.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/AppOpsPrivacyItemMonitor.kt
@@ -53,11 +53,14 @@
 
     @VisibleForTesting
     companion object {
-        val OPS_MIC_CAMERA = intArrayOf(AppOpsManager.OP_CAMERA,
-                AppOpsManager.OP_PHONE_CALL_CAMERA, AppOpsManager.OP_RECORD_AUDIO,
+        val OPS_MIC_CAMERA = intArrayOf(
+                AppOpsManager.OP_CAMERA,
+                AppOpsManager.OP_PHONE_CALL_CAMERA,
+                AppOpsManager.OP_RECORD_AUDIO,
                 AppOpsManager.OP_PHONE_CALL_MICROPHONE,
                 AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO,
-                AppOpsManager.OP_RECEIVE_EXPLICIT_USER_INTERACTION_AUDIO)
+                AppOpsManager.OP_RECEIVE_EXPLICIT_USER_INTERACTION_AUDIO,
+                AppOpsManager.OP_RECEIVE_SANDBOX_TRIGGER_AUDIO)
         val OPS_LOCATION = intArrayOf(
                 AppOpsManager.OP_COARSE_LOCATION,
                 AppOpsManager.OP_FINE_LOCATION)
@@ -212,6 +215,7 @@
             AppOpsManager.OP_PHONE_CALL_MICROPHONE,
             AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO,
             AppOpsManager.OP_RECEIVE_EXPLICIT_USER_INTERACTION_AUDIO,
+            AppOpsManager.OP_RECEIVE_SANDBOX_TRIGGER_AUDIO,
             AppOpsManager.OP_RECORD_AUDIO -> PrivacyType.TYPE_MICROPHONE
             else -> return null
         }
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogV2.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogV2.kt
index f4aa27d..c202f14 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogV2.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogV2.kt
@@ -192,7 +192,7 @@
             return null
         }
         val closeAppButton =
-            window.layoutInflater.inflate(
+            checkNotNull(window).layoutInflater.inflate(
                 R.layout.privacy_dialog_card_button,
                 expandedLayout,
                 false
@@ -248,7 +248,7 @@
 
     private fun configureManageButton(element: PrivacyElement, expandedLayout: ViewGroup): View {
         val manageButton =
-            window.layoutInflater.inflate(
+            checkNotNull(window).layoutInflater.inflate(
                 R.layout.privacy_dialog_card_button,
                 expandedLayout,
                 false
diff --git a/packages/SystemUI/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerController.java b/packages/SystemUI/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerController.java
index fa3f878f..2d460a0 100644
--- a/packages/SystemUI/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerController.java
+++ b/packages/SystemUI/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerController.java
@@ -120,6 +120,7 @@
         mUserTracker = userTracker;
         mConfigEnableLockScreenButton = mContext.getResources().getBoolean(
             android.R.bool.config_enableQrCodeScannerOnLockScreen);
+        mExecutor.execute(this::updateQRCodeScannerActivityDetails);
     }
 
     /**
@@ -158,18 +159,18 @@
      * Returns true if lock screen entry point for QR Code Scanner is to be enabled.
      */
     public boolean isEnabledForLockScreenButton() {
-        return mQRCodeScannerEnabled && isAbleToOpenCameraApp() && isAvailableOnDevice();
+        return mQRCodeScannerEnabled && isAbleToLaunchScannerActivity() && isAllowedOnLockScreen();
     }
 
-    /** Returns whether the feature is available on the device. */
-    public boolean isAvailableOnDevice() {
+    /** Returns whether the QR scanner button is allowed on lockscreen. */
+    public boolean isAllowedOnLockScreen() {
         return mConfigEnableLockScreenButton;
     }
 
     /**
-     * Returns true if the feature can open a camera app on the device.
+     * Returns true if the feature can open the configured QR scanner activity.
      */
-    public boolean isAbleToOpenCameraApp() {
+    public boolean isAbleToLaunchScannerActivity() {
         return mIntent != null && isActivityCallable(mIntent);
     }
 
@@ -355,9 +356,6 @@
 
         // Reset cached values to default as we are no longer listening
         mOnDefaultQRCodeScannerChangedListener = null;
-        mQRCodeScannerActivity = null;
-        mIntent = null;
-        mComponentName = null;
     }
 
     private void notifyQRCodeScannerActivityChanged() {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java b/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
index 7523d6e..ddd9463 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
@@ -7,6 +7,7 @@
 import android.animation.AnimatorSet;
 import android.animation.ObjectAnimator;
 import android.animation.PropertyValuesHolder;
+import android.app.ActivityManager;
 import android.content.Context;
 import android.content.res.Configuration;
 import android.os.Bundle;
@@ -549,10 +550,8 @@
         return mPages.get(0).mRecords.size();
     }
 
-    public void startTileReveal(Set<String> tileSpecs, final Runnable postAnimation) {
-        if (tileSpecs.isEmpty() || mPages.size() < 2 || getScrollX() != 0 || !beginFakeDrag()) {
-            // Do not start the reveal animation unless there are tiles to animate, multiple
-            // TileLayouts available and the user has not already started dragging.
+    public void startTileReveal(Set<String> tilesToReveal, final Runnable postAnimation) {
+        if (shouldNotRunAnimation(tilesToReveal)) {
             return;
         }
 
@@ -560,13 +559,13 @@
         final TileLayout lastPage = mPages.get(lastPageNumber);
         final ArrayList<Animator> bounceAnims = new ArrayList<>();
         for (TileRecord tr : lastPage.mRecords) {
-            if (tileSpecs.contains(tr.tile.getTileSpec())) {
+            if (tilesToReveal.contains(tr.tile.getTileSpec())) {
                 bounceAnims.add(setupBounceAnimator(tr.tileView, bounceAnims.size()));
             }
         }
 
         if (bounceAnims.isEmpty()) {
-            // All tileSpecs are on the first page. Nothing to do.
+            // All tilesToReveal are on the first page. Nothing to do.
             // TODO: potentially show a bounce animation for first page QS tiles
             endFakeDrag();
             return;
@@ -588,6 +587,16 @@
         postInvalidateOnAnimation();
     }
 
+    private boolean shouldNotRunAnimation(Set<String> tilesToReveal) {
+        boolean noAnimationNeeded = tilesToReveal.isEmpty() || mPages.size() < 2;
+        boolean scrollingInProgress = getScrollX() != 0 || !beginFakeDrag();
+        // isRunningInTestHarness() to disable animation in functional testing as it caused
+        // flakiness and is not needed there. Alternative solutions were more complex and would
+        // still be either potentially flaky or modify internal data.
+        // For more info see b/253493927 and b/293234595
+        return noAnimationNeeded || scrollingInProgress || ActivityManager.isRunningInTestHarness();
+    }
+
     private int sanitizePageAction(int action) {
         int pageLeftId = AccessibilityNodeInfo.AccessibilityAction.ACTION_PAGE_LEFT.getId();
         int pageRightId = AccessibilityNodeInfo.AccessibilityAction.ACTION_PAGE_RIGHT.getId();
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSContainerImpl.java b/packages/SystemUI/src/com/android/systemui/qs/QSContainerImpl.java
index 1afc885..d2eac45 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSContainerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSContainerImpl.java
@@ -23,12 +23,14 @@
 import android.graphics.Path;
 import android.graphics.PointF;
 import android.util.AttributeSet;
+import android.view.MotionEvent;
 import android.view.View;
 import android.widget.FrameLayout;
 
 import com.android.systemui.Dumpable;
 import com.android.systemui.R;
 import com.android.systemui.qs.customize.QSCustomizer;
+import com.android.systemui.shade.TouchLogger;
 import com.android.systemui.util.LargeScreenUtils;
 
 import java.io.PrintWriter;
@@ -129,6 +131,11 @@
     }
 
     @Override
+    public boolean dispatchTouchEvent(MotionEvent ev) {
+        return TouchLogger.logDispatchTouch("QS", ev, super.dispatchTouchEvent(ev));
+    }
+
+    @Override
     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
         super.onLayout(changed, left, top, right, bottom);
         updateExpansion();
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSHostAdapter.kt b/packages/SystemUI/src/com/android/systemui/qs/QSHostAdapter.kt
index 67927a4..cb87e3c 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSHostAdapter.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSHostAdapter.kt
@@ -22,13 +22,12 @@
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
 import com.android.systemui.dump.DumpManager
-import com.android.systemui.flags.FeatureFlags
-import com.android.systemui.flags.Flags
 import com.android.systemui.plugins.qs.QSTile
 import com.android.systemui.plugins.qs.QSTileView
 import com.android.systemui.qs.external.TileServiceRequestController
 import com.android.systemui.qs.pipeline.data.repository.TileSpecRepository.Companion.POSITION_AT_END
 import com.android.systemui.qs.pipeline.domain.interactor.CurrentTilesInteractor
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository
 import com.android.systemui.qs.pipeline.shared.TileSpec
 import javax.inject.Inject
 import kotlinx.coroutines.CoroutineScope
@@ -37,10 +36,11 @@
 
 /**
  * Adapter to determine what real class to use for classes that depend on [QSHost].
- * * When [Flags.QS_PIPELINE_NEW_HOST] is off, all calls will be routed to [QSTileHost].
- * * When [Flags.QS_PIPELINE_NEW_HOST] is on, calls regarding the current set of tiles will be
- *   routed to [CurrentTilesInteractor]. Other calls (like [createTileView]) will still be routed to
+ * * When [QSPipelineFlagsRepository.pipelineHostEnabled] is false, all calls will be routed to
  *   [QSTileHost].
+ * * When [QSPipelineFlagsRepository.pipelineHostEnabled] is true, calls regarding the current set
+ *   of tiles will be routed to [CurrentTilesInteractor]. Other calls (like [createTileView]) will
+ *   still be routed to [QSTileHost].
  *
  * This routing also includes dumps.
  */
@@ -53,7 +53,7 @@
     private val context: Context,
     private val tileServiceRequestControllerBuilder: TileServiceRequestController.Builder,
     @Application private val scope: CoroutineScope,
-    private val featureFlags: FeatureFlags,
+    flags: QSPipelineFlagsRepository,
     dumpManager: DumpManager,
 ) : QSHost {
 
@@ -61,7 +61,7 @@
         private const val TAG = "QSTileHost"
     }
 
-    private val useNewHost = featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)
+    private val useNewHost = flags.pipelineHostEnabled
 
     @GuardedBy("callbacksMap") private val callbacksMap = mutableMapOf<QSHost.Callback, Job>()
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java b/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java
index 432147f..e57db56 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java
@@ -35,8 +35,6 @@
 import com.android.systemui.dagger.SysUISingleton;
 import com.android.systemui.dagger.qualifiers.Main;
 import com.android.systemui.dump.nano.SystemUIProtoDump;
-import com.android.systemui.flags.FeatureFlags;
-import com.android.systemui.flags.Flags;
 import com.android.systemui.plugins.PluginListener;
 import com.android.systemui.plugins.PluginManager;
 import com.android.systemui.plugins.qs.QSFactory;
@@ -50,6 +48,7 @@
 import com.android.systemui.qs.nano.QsTileState;
 import com.android.systemui.qs.pipeline.data.repository.CustomTileAddedRepository;
 import com.android.systemui.qs.pipeline.domain.interactor.PanelInteractor;
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository;
 import com.android.systemui.settings.UserFileManager;
 import com.android.systemui.settings.UserTracker;
 import com.android.systemui.shade.ShadeController;
@@ -119,7 +118,7 @@
 
     private TileLifecycleManager.Factory mTileLifeCycleManagerFactory;
 
-    private final FeatureFlags mFeatureFlags;
+    private final QSPipelineFlagsRepository mFeatureFlags;
 
     @Inject
     public QSTileHost(Context context,
@@ -135,7 +134,7 @@
             CustomTileStatePersister customTileStatePersister,
             TileLifecycleManager.Factory tileLifecycleManagerFactory,
             UserFileManager userFileManager,
-            FeatureFlags featureFlags
+            QSPipelineFlagsRepository featureFlags
     ) {
         mContext = context;
         mUserContext = context;
@@ -162,7 +161,7 @@
             // finishes before creating any tiles.
             tunerService.addTunable(this, TILES_SETTING);
             // AutoTileManager can modify mTiles so make sure mTiles has already been initialized.
-            if (!mFeatureFlags.isEnabled(Flags.QS_PIPELINE_AUTO_ADD)) {
+            if (!mFeatureFlags.getPipelineAutoAddEnabled()) {
                 mAutoTiles = autoTiles.get();
             }
         });
@@ -283,7 +282,7 @@
             }
         }
         // Do not process tiles if the flag is enabled.
-        if (mFeatureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)) {
+        if (mFeatureFlags.getPipelineHostEnabled()) {
             return;
         }
         if (newValue == null && UserManager.isDeviceInDemoMode(mContext)) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/TEST_MAPPING b/packages/SystemUI/src/com/android/systemui/qs/TEST_MAPPING
index 2d45c5b2..86ef7ef 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/TEST_MAPPING
+++ b/packages/SystemUI/src/com/android/systemui/qs/TEST_MAPPING
@@ -10,6 +10,17 @@
           "exclude-annotation": "androidx.test.filters.FlakyTest"
         }
       ]
+    },
+    {
+      "name": "QuickSettingsDeviceResetTests",
+      "options": [
+          {
+            "exclude-annotation": "org.junit.Ignore"
+          },
+          {
+            "exclude-annotation": "androidx.test.filters.FlakyTest"
+          }
+      ]
     }
   ]
 }
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/qs/dagger/QSHostModule.kt b/packages/SystemUI/src/com/android/systemui/qs/dagger/QSHostModule.kt
index 1f63f5d..b2111d7 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/dagger/QSHostModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/dagger/QSHostModule.kt
@@ -16,8 +16,6 @@
 
 package com.android.systemui.qs.dagger
 
-import com.android.systemui.flags.FeatureFlags
-import com.android.systemui.flags.Flags
 import com.android.systemui.qs.QSHost
 import com.android.systemui.qs.QSHostAdapter
 import com.android.systemui.qs.QSTileHost
@@ -27,6 +25,7 @@
 import com.android.systemui.qs.pipeline.data.repository.CustomTileAddedSharedPrefsRepository
 import com.android.systemui.qs.pipeline.domain.interactor.PanelInteractor
 import com.android.systemui.qs.pipeline.domain.interactor.PanelInteractorImpl
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository
 import dagger.Binds
 import dagger.Module
 import dagger.Provides
@@ -45,11 +44,11 @@
         @Provides
         @JvmStatic
         fun providePanelInteractor(
-            featureFlags: FeatureFlags,
+            featureFlags: QSPipelineFlagsRepository,
             qsHost: QSTileHost,
             panelInteractorImpl: PanelInteractorImpl
         ): PanelInteractor {
-            return if (featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)) {
+            return if (featureFlags.pipelineHostEnabled) {
                 panelInteractorImpl
             } else {
                 qsHost
@@ -59,11 +58,11 @@
         @Provides
         @JvmStatic
         fun provideCustomTileAddedRepository(
-            featureFlags: FeatureFlags,
+            featureFlags: QSPipelineFlagsRepository,
             qsHost: QSTileHost,
             customTileAddedRepository: CustomTileAddedSharedPrefsRepository
         ): CustomTileAddedRepository {
-            return if (featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)) {
+            return if (featureFlags.pipelineHostEnabled) {
                 customTileAddedRepository
             } else {
                 qsHost
diff --git a/packages/SystemUI/src/com/android/systemui/qs/pipeline/data/repository/TileSpecRepository.kt b/packages/SystemUI/src/com/android/systemui/qs/pipeline/data/repository/TileSpecRepository.kt
index a162d11..18f59b1 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/pipeline/data/repository/TileSpecRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/pipeline/data/repository/TileSpecRepository.kt
@@ -20,6 +20,7 @@
 import android.content.res.Resources
 import android.database.ContentObserver
 import android.provider.Settings
+import android.util.SparseArray
 import com.android.systemui.R
 import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow
 import com.android.systemui.dagger.SysUISingleton
@@ -107,6 +108,7 @@
 ) : TileSpecRepository {
 
     private val mutex = Mutex()
+    private val tileSpecsPerUser = SparseArray<List<TileSpec>>()
 
     private val retailModeTiles by lazy {
         resources
@@ -142,10 +144,12 @@
                 awaitClose { secureSettings.unregisterContentObserver(observer) }
             }
             .onStart { emit(Unit) }
-            .map { secureSettings.getStringForUser(SETTING, userId) ?: "" }
-            .distinctUntilChanged()
+            .map { loadTiles(userId) }
             .onEach { logger.logTilesChangedInSettings(it, userId) }
-            .map { parseTileSpecs(it, userId) }
+            .distinctUntilChanged()
+            .map { parseTileSpecs(it, userId).also { storeTiles(userId, it) } }
+            .distinctUntilChanged()
+            .onEach { mutex.withLock { tileSpecsPerUser.put(userId, it) } }
             .flowOn(backgroundDispatcher)
     }
 
@@ -154,7 +158,7 @@
             if (tile == TileSpec.Invalid) {
                 return
             }
-            val tilesList = loadTiles(userId).toMutableList()
+            val tilesList = tileSpecsPerUser.get(userId, emptyList()).toMutableList()
             if (tile !in tilesList) {
                 if (position < 0 || position >= tilesList.size) {
                     tilesList.add(tile)
@@ -162,6 +166,7 @@
                     tilesList.add(position, tile)
                 }
                 storeTiles(userId, tilesList)
+                tileSpecsPerUser.put(userId, tilesList)
             }
         }
 
@@ -170,9 +175,10 @@
             if (tiles.all { it == TileSpec.Invalid }) {
                 return
             }
-            val tilesList = loadTiles(userId).toMutableList()
+            val tilesList = tileSpecsPerUser.get(userId, emptyList()).toMutableList()
             if (tilesList.removeAll(tiles)) {
                 storeTiles(userId, tilesList.toList())
+                tileSpecsPerUser.put(userId, tilesList)
             }
         }
 
@@ -181,18 +187,10 @@
             val filtered = tiles.filter { it != TileSpec.Invalid }
             if (filtered.isNotEmpty()) {
                 storeTiles(userId, filtered)
+                tileSpecsPerUser.put(userId, tiles)
             }
         }
 
-    private suspend fun loadTiles(@UserIdInt forUser: Int): List<TileSpec> {
-        return withContext(backgroundDispatcher) {
-            (secureSettings.getStringForUser(SETTING, forUser) ?: "")
-                .split(DELIMITER)
-                .map(TileSpec::create)
-                .filter { it !is TileSpec.Invalid }
-        }
-    }
-
     private suspend fun storeTiles(@UserIdInt forUser: Int, tiles: List<TileSpec>) {
         if (retailModeRepository.inRetailMode) {
             // No storing tiles when in retail mode
@@ -214,6 +212,12 @@
         }
     }
 
+    private suspend fun loadTiles(userId: Int): String {
+        return withContext(backgroundDispatcher) {
+            secureSettings.getStringForUser(SETTING, userId) ?: ""
+        }
+    }
+
     private fun parseTileSpecs(tilesFromSettings: String, user: Int): List<TileSpec> {
         val fromSettings =
             tilesFromSettings.split(DELIMITER).map(TileSpec::create).filter {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractor.kt b/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractor.kt
index ff881f7..5a5e47a 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractor.kt
@@ -27,8 +27,6 @@
 import com.android.systemui.dagger.qualifiers.Background
 import com.android.systemui.dagger.qualifiers.Main
 import com.android.systemui.dump.nano.SystemUIProtoDump
-import com.android.systemui.flags.FeatureFlags
-import com.android.systemui.flags.Flags
 import com.android.systemui.plugins.qs.QSFactory
 import com.android.systemui.plugins.qs.QSTile
 import com.android.systemui.qs.external.CustomTile
@@ -39,6 +37,7 @@
 import com.android.systemui.qs.pipeline.data.repository.InstalledTilesComponentRepository
 import com.android.systemui.qs.pipeline.data.repository.TileSpecRepository
 import com.android.systemui.qs.pipeline.domain.model.TileModel
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository
 import com.android.systemui.qs.pipeline.shared.TileSpec
 import com.android.systemui.qs.pipeline.shared.logging.QSPipelineLogger
 import com.android.systemui.qs.toProto
@@ -56,6 +55,8 @@
 import kotlinx.coroutines.flow.collectLatest
 import kotlinx.coroutines.flow.combine
 import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.filter
+import kotlinx.coroutines.flow.first
 import kotlinx.coroutines.flow.flatMapLatest
 import kotlinx.coroutines.flow.flowOn
 import kotlinx.coroutines.flow.map
@@ -137,7 +138,7 @@
     @Background private val backgroundDispatcher: CoroutineDispatcher,
     @Application private val scope: CoroutineScope,
     private val logger: QSPipelineLogger,
-    featureFlags: FeatureFlags,
+    featureFlags: QSPipelineFlagsRepository,
 ) : CurrentTilesInteractor {
 
     private val _currentSpecsAndTiles: MutableStateFlow<List<TileModel>> =
@@ -169,7 +170,7 @@
         }
 
     init {
-        if (featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)) {
+        if (featureFlags.pipelineHostEnabled) {
             startTileCollection()
         }
     }
@@ -273,7 +274,9 @@
     }
 
     override fun addTile(spec: TileSpec, position: Int) {
-        scope.launch {
+        scope.launch(backgroundDispatcher) {
+            // Block until the list is not empty
+            currentTiles.filter { it.isNotEmpty() }.first()
             tileSpecRepository.addTile(userRepository.getSelectedUserInfo().id, spec, position)
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/startable/QSPipelineCoreStartable.kt b/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/startable/QSPipelineCoreStartable.kt
index 224fc1a..0743ba0 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/startable/QSPipelineCoreStartable.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/startable/QSPipelineCoreStartable.kt
@@ -18,10 +18,9 @@
 
 import com.android.systemui.CoreStartable
 import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.flags.FeatureFlags
-import com.android.systemui.flags.Flags
 import com.android.systemui.qs.pipeline.domain.interactor.AutoAddInteractor
 import com.android.systemui.qs.pipeline.domain.interactor.CurrentTilesInteractor
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository
 import javax.inject.Inject
 
 @SysUISingleton
@@ -30,14 +29,11 @@
 constructor(
     private val currentTilesInteractor: CurrentTilesInteractor,
     private val autoAddInteractor: AutoAddInteractor,
-    private val featureFlags: FeatureFlags,
+    private val featureFlags: QSPipelineFlagsRepository,
 ) : CoreStartable {
 
     override fun start() {
-        if (
-            featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST) &&
-                featureFlags.isEnabled(Flags.QS_PIPELINE_AUTO_ADD)
-        ) {
+        if (featureFlags.pipelineAutoAddEnabled) {
             autoAddInteractor.init(currentTilesInteractor)
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepository.kt b/packages/SystemUI/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepository.kt
new file mode 100644
index 0000000..551b0f4
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepository.kt
@@ -0,0 +1,23 @@
+package com.android.systemui.qs.pipeline.shared
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
+import javax.inject.Inject
+
+/** Encapsulate the different QS pipeline flags and their dependencies */
+@SysUISingleton
+class QSPipelineFlagsRepository
+@Inject
+constructor(
+    private val featureFlags: FeatureFlags,
+) {
+
+    /** @see Flags.QS_PIPELINE_NEW_HOST */
+    val pipelineHostEnabled: Boolean
+        get() = featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)
+
+    /** @see Flags.QS_PIPELINE_AUTO_ADD */
+    val pipelineAutoAddEnabled: Boolean
+        get() = pipelineHostEnabled && featureFlags.isEnabled(Flags.QS_PIPELINE_AUTO_ADD)
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/QRCodeScannerTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/QRCodeScannerTile.java
index 9e365d3..1ba377b 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/QRCodeScannerTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/QRCodeScannerTile.java
@@ -120,7 +120,7 @@
         state.label = mContext.getString(R.string.qr_code_scanner_title);
         state.contentDescription = state.label;
         state.icon = ResourceIcon.get(R.drawable.ic_qr_code_scanner);
-        state.state = mQRCodeScannerController.isAbleToOpenCameraApp() ? Tile.STATE_INACTIVE
+        state.state = mQRCodeScannerController.isAbleToLaunchScannerActivity() ? Tile.STATE_INACTIVE
                 : Tile.STATE_UNAVAILABLE;
         // The assumption is that if the OEM has the QR code scanner module enabled then the scanner
         // would go to "Unavailable" state only when GMS core is updating.
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/WorkModeTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/WorkModeTile.java
index 8f9cf4b..21da596 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/WorkModeTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/WorkModeTile.java
@@ -142,6 +142,9 @@
         state.contentDescription = state.label;
         state.expandedAccessibilityClassName = Switch.class.getName();
         state.state = state.value ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE;
+        state.secondaryLabel = state.value
+                ? ""
+                : mContext.getString(R.string.quick_settings_work_mode_paused_state);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/qs/ui/viewmodel/QuickSettingsSceneViewModel.kt b/packages/SystemUI/src/com/android/systemui/qs/ui/viewmodel/QuickSettingsSceneViewModel.kt
index 5e6a44b..4c6281e 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/ui/viewmodel/QuickSettingsSceneViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/ui/viewmodel/QuickSettingsSceneViewModel.kt
@@ -16,19 +16,17 @@
 
 package com.android.systemui.qs.ui.viewmodel
 
+import com.android.systemui.bouncer.domain.interactor.BouncerInteractor
 import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.keyguard.domain.interactor.LockscreenSceneInteractor
 import javax.inject.Inject
 
 /** Models UI state and handles user input for the quick settings scene. */
 @SysUISingleton
 class QuickSettingsSceneViewModel
 @Inject
-constructor(
-    private val lockscreenSceneInteractor: LockscreenSceneInteractor,
-) {
+constructor(private val bouncerInteractor: BouncerInteractor) {
     /** Notifies that some content in quick settings was clicked. */
     fun onContentClicked() {
-        lockscreenSceneInteractor.dismissLockscreen()
+        bouncerInteractor.showOrUnlockDevice()
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/scene/data/repository/SceneContainerRepository.kt b/packages/SystemUI/src/com/android/systemui/scene/data/repository/SceneContainerRepository.kt
index fee3960..350fa38 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/data/repository/SceneContainerRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/data/repository/SceneContainerRepository.kt
@@ -18,50 +18,49 @@
 
 package com.android.systemui.scene.data.repository
 
+import com.android.systemui.dagger.qualifiers.Application
 import com.android.systemui.scene.shared.model.ObservableTransitionState
 import com.android.systemui.scene.shared.model.SceneContainerConfig
 import com.android.systemui.scene.shared.model.SceneKey
 import com.android.systemui.scene.shared.model.SceneModel
-import com.android.systemui.scene.shared.model.SceneTransitionModel
 import javax.inject.Inject
+import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharingStarted
 import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.flow.asStateFlow
 import kotlinx.coroutines.flow.flatMapLatest
 import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.stateIn
 
 /** Source of truth for scene framework application state. */
 class SceneContainerRepository
 @Inject
 constructor(
+    @Application applicationScope: CoroutineScope,
     private val config: SceneContainerConfig,
 ) {
+    private val _desiredScene = MutableStateFlow(SceneModel(config.initialSceneKey))
+    val desiredScene: StateFlow<SceneModel> = _desiredScene.asStateFlow()
 
     private val _isVisible = MutableStateFlow(true)
     val isVisible: StateFlow<Boolean> = _isVisible.asStateFlow()
 
-    private val _currentScene = MutableStateFlow(SceneModel(config.initialSceneKey))
-    val currentScene: StateFlow<SceneModel> = _currentScene.asStateFlow()
-
-    private val transitionState = MutableStateFlow<Flow<ObservableTransitionState>?>(null)
-    val transitionProgress: Flow<Float> =
-        transitionState.flatMapLatest { observableTransitionStateFlow ->
-            observableTransitionStateFlow?.flatMapLatest { observableTransitionState ->
-                when (observableTransitionState) {
-                    is ObservableTransitionState.Idle -> flowOf(1f)
-                    is ObservableTransitionState.Transition -> observableTransitionState.progress
-                }
-            }
-                ?: flowOf(1f)
-        }
-
-    private val _transitions = MutableStateFlow<SceneTransitionModel?>(null)
-    val transitions: StateFlow<SceneTransitionModel?> = _transitions.asStateFlow()
+    private val defaultTransitionState = ObservableTransitionState.Idle(config.initialSceneKey)
+    private val _transitionState = MutableStateFlow<Flow<ObservableTransitionState>?>(null)
+    val transitionState: StateFlow<ObservableTransitionState> =
+        _transitionState
+            .flatMapLatest { innerFlowOrNull -> innerFlowOrNull ?: flowOf(defaultTransitionState) }
+            .stateIn(
+                scope = applicationScope,
+                started = SharingStarted.Eagerly,
+                initialValue = defaultTransitionState,
+            )
 
     /**
-     * Returns the keys to all scenes in the container with the given name.
+     * Returns the keys to all scenes in the container.
      *
      * The scenes will be sorted in z-order such that the last one is the one that should be
      * rendered on top of all previous ones.
@@ -70,40 +69,19 @@
         return config.sceneKeys
     }
 
-    /** Sets the current scene in the container with the given name. */
-    fun setCurrentScene(scene: SceneModel) {
+    fun setDesiredScene(scene: SceneModel) {
         check(allSceneKeys().contains(scene.key)) {
             """
-                Cannot set current scene key to "${scene.key}". The configuration does not contain a
-                scene with that key.
+                Cannot set the desired scene key to "${scene.key}". The configuration does not
+                contain a scene with that key.
             """
                 .trimIndent()
         }
 
-        _currentScene.value = scene
+        _desiredScene.value = scene
     }
 
-    /** Sets the scene transition in the container with the given name. */
-    fun setSceneTransition(from: SceneKey, to: SceneKey) {
-        check(allSceneKeys().contains(from)) {
-            """
-                Cannot set current scene key to "$from". The configuration does not contain a scene
-                with that key.
-            """
-                .trimIndent()
-        }
-        check(allSceneKeys().contains(to)) {
-            """
-                Cannot set current scene key to "$to". The configuration does not contain a scene
-                with that key.
-            """
-                .trimIndent()
-        }
-
-        _transitions.value = SceneTransitionModel(from = from, to = to)
-    }
-
-    /** Sets whether the container with the given name is visible. */
+    /** Sets whether the container is visible. */
     fun setVisible(isVisible: Boolean) {
         _isVisible.value = isVisible
     }
@@ -114,6 +92,6 @@
      * Note that you must call is with `null` when the UI is done or risk a memory leak.
      */
     fun setTransitionState(transitionState: Flow<ObservableTransitionState>?) {
-        this.transitionState.value = transitionState
+        _transitionState.value = transitionState
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/scene/domain/interactor/SceneInteractor.kt b/packages/SystemUI/src/com/android/systemui/scene/domain/interactor/SceneInteractor.kt
index 64715bc..a7434c6 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/domain/interactor/SceneInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/domain/interactor/SceneInteractor.kt
@@ -17,18 +17,19 @@
 package com.android.systemui.scene.domain.interactor
 
 import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dagger.qualifiers.Application
 import com.android.systemui.scene.data.repository.SceneContainerRepository
 import com.android.systemui.scene.shared.logger.SceneLogger
 import com.android.systemui.scene.shared.model.ObservableTransitionState
-import com.android.systemui.scene.shared.model.RemoteUserInput
 import com.android.systemui.scene.shared.model.SceneKey
 import com.android.systemui.scene.shared.model.SceneModel
-import com.android.systemui.scene.shared.model.SceneTransitionModel
 import javax.inject.Inject
+import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharingStarted
 import kotlinx.coroutines.flow.StateFlow
-import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.stateIn
 
 /**
  * Generic business logic and app state accessors for the scene framework.
@@ -41,12 +42,72 @@
 class SceneInteractor
 @Inject
 constructor(
+    @Application applicationScope: CoroutineScope,
     private val repository: SceneContainerRepository,
     private val logger: SceneLogger,
 ) {
 
     /**
-     * Returns the keys of all scenes in the container with the given name.
+     * The currently *desired* scene.
+     *
+     * **Important:** this value will _commonly be different_ from what is being rendered in the UI,
+     * by design.
+     *
+     * There are two intended sources for this value:
+     * 1. Programmatic requests to transition to another scene (calls to [changeScene]).
+     * 2. Reports from the UI about completing a transition to another scene (calls to
+     *    [onSceneChanged]).
+     *
+     * Both the sources above cause the value of this flow to change; however, they cause mismatches
+     * in different ways.
+     *
+     * **Updates from programmatic transitions**
+     *
+     * When an external bit of code asks the framework to switch to another scene, the value here
+     * will update immediately. Downstream, the UI will detect this change and initiate the
+     * transition animation. As the transition animation progresses, a threshold will be reached, at
+     * which point the UI and the state here will match each other.
+     *
+     * **Updates from the UI**
+     *
+     * When the user interacts with the UI, the UI runs a transition animation that tracks the user
+     * pointer (for example, the user's finger). During this time, the state value here and what the
+     * UI shows will likely not match. Once/if a threshold is met, the UI reports it and commits the
+     * change, making the value here match the UI again.
+     */
+    val desiredScene: StateFlow<SceneModel> = repository.desiredScene
+
+    /**
+     * The current state of the transition.
+     *
+     * Consumers should use this state to know:
+     * 1. Whether there is an ongoing transition or if the system is at rest.
+     * 2. When transitioning, which scenes are being transitioned between.
+     * 3. When transitioning, what the progress of the transition is.
+     */
+    val transitionState: StateFlow<ObservableTransitionState> = repository.transitionState
+
+    /**
+     * The key of the scene that the UI is currently transitioning to or `null` if there is no
+     * active transition at the moment.
+     *
+     * This is a convenience wrapper around [transitionState], meant for flow-challenged consumers
+     * like Java code.
+     */
+    val transitioningTo: StateFlow<SceneKey?> =
+        transitionState
+            .map { state -> (state as? ObservableTransitionState.Transition)?.toScene }
+            .stateIn(
+                scope = applicationScope,
+                started = SharingStarted.WhileSubscribed(),
+                initialValue = null,
+            )
+
+    /** Whether the scene container is visible. */
+    val isVisible: StateFlow<Boolean> = repository.isVisible
+
+    /**
+     * Returns the keys of all scenes in the container.
      *
      * The scenes will be sorted in z-order such that the last one is the one that should be
      * rendered on top of all previous ones.
@@ -55,26 +116,20 @@
         return repository.allSceneKeys()
     }
 
-    /** Sets the scene in the container with the given name. */
-    fun setCurrentScene(scene: SceneModel, loggingReason: String) {
-        val currentSceneKey = repository.currentScene.value.key
-        if (currentSceneKey == scene.key) {
-            return
-        }
-
-        logger.logSceneChange(
-            from = currentSceneKey,
-            to = scene.key,
-            reason = loggingReason,
-        )
-        repository.setCurrentScene(scene)
-        repository.setSceneTransition(from = currentSceneKey, to = scene.key)
+    /**
+     * Requests a scene change to the given scene.
+     *
+     * The change is animated. Therefore, while the value in [desiredScene] will update immediately,
+     * it will be some time before the UI will switch to the desired scene. The scene change
+     * requested is remembered here but served by the UI layer, which will start a transition
+     * animation. Once enough of the transition has occurred, the system will come into agreement
+     * between the [desiredScene] and the UI.
+     */
+    fun changeScene(scene: SceneModel, loggingReason: String) {
+        updateDesiredScene(scene, loggingReason, logger::logSceneChangeRequested)
     }
 
-    /** The current scene in the container with the given name. */
-    val currentScene: StateFlow<SceneModel> = repository.currentScene
-
-    /** Sets the visibility of the container with the given name. */
+    /** Sets the visibility of the container. */
     fun setVisible(isVisible: Boolean, loggingReason: String) {
         val wasVisible = repository.isVisible.value
         if (wasVisible == isVisible) {
@@ -89,9 +144,6 @@
         return repository.setVisible(isVisible)
     }
 
-    /** Whether the container with the given name is visible. */
-    val isVisible: StateFlow<Boolean> = repository.isVisible
-
     /**
      * Binds the given flow so the system remembers it.
      *
@@ -101,23 +153,33 @@
         repository.setTransitionState(transitionState)
     }
 
-    /** Progress of the transition into the current scene in the container with the given name. */
-    val transitionProgress: Flow<Float> = repository.transitionProgress
-
     /**
-     * Scene transitions as pairs of keys. A new value is emitted exactly once, each time a scene
-     * transition occurs. The flow begins with a `null` value at first, because the initial scene is
-     * not something that we transition to from another scene.
+     * Notifies that the UI has transitioned sufficiently to the given scene.
+     *
+     * *Not intended for external use!*
+     *
+     * Once a transition between one scene and another passes a threshold, the UI invokes this
+     * method to report it, updating the value in [desiredScene] to match what the UI shows.
      */
-    val transitions: StateFlow<SceneTransitionModel?> = repository.transitions
+    internal fun onSceneChanged(scene: SceneModel, loggingReason: String) {
+        updateDesiredScene(scene, loggingReason, logger::logSceneChangeCommitted)
+    }
 
-    private val _remoteUserInput: MutableStateFlow<RemoteUserInput?> = MutableStateFlow(null)
+    private fun updateDesiredScene(
+        scene: SceneModel,
+        loggingReason: String,
+        log: (from: SceneKey, to: SceneKey, loggingReason: String) -> Unit,
+    ) {
+        val currentSceneKey = desiredScene.value.key
+        if (currentSceneKey == scene.key) {
+            return
+        }
 
-    /** A flow of motion events originating from outside of the scene framework. */
-    val remoteUserInput: StateFlow<RemoteUserInput?> = _remoteUserInput.asStateFlow()
-
-    /** Handles a remote user input. */
-    fun onRemoteUserInput(input: RemoteUserInput) {
-        _remoteUserInput.value = input
+        log(
+            /* from= */ currentSceneKey,
+            /* to= */ scene.key,
+            /* loggingReason= */ loggingReason,
+        )
+        repository.setDesiredScene(scene)
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/scene/domain/startable/SceneContainerStartable.kt b/packages/SystemUI/src/com/android/systemui/scene/domain/startable/SceneContainerStartable.kt
index 20ee393..1747099 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/domain/startable/SceneContainerStartable.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/domain/startable/SceneContainerStartable.kt
@@ -18,6 +18,7 @@
 
 import com.android.systemui.CoreStartable
 import com.android.systemui.authentication.domain.interactor.AuthenticationInteractor
+import com.android.systemui.authentication.domain.model.AuthenticationMethodModel
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
 import com.android.systemui.dagger.qualifiers.DisplayId
@@ -29,6 +30,7 @@
 import com.android.systemui.model.updateFlags
 import com.android.systemui.scene.domain.interactor.SceneInteractor
 import com.android.systemui.scene.shared.logger.SceneLogger
+import com.android.systemui.scene.shared.model.ObservableTransitionState
 import com.android.systemui.scene.shared.model.SceneKey
 import com.android.systemui.scene.shared.model.SceneModel
 import com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_BOUNCER_SHOWING
@@ -39,8 +41,8 @@
 import javax.inject.Inject
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.flow.distinctUntilChanged
-import kotlinx.coroutines.flow.filterNotNull
 import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.mapNotNull
 import kotlinx.coroutines.launch
 
 /**
@@ -72,14 +74,31 @@
         }
     }
 
-    /** Updates the visibility of the scene container based on the current scene. */
+    /** Updates the visibility of the scene container. */
     private fun hydrateVisibility() {
         applicationScope.launch {
-            sceneInteractor.currentScene
-                .map { it.key }
+            sceneInteractor.transitionState
+                .mapNotNull { state ->
+                    when (state) {
+                        is ObservableTransitionState.Idle -> {
+                            if (state.scene != SceneKey.Gone) {
+                                true to "scene is not Gone"
+                            } else {
+                                false to "scene is Gone"
+                            }
+                        }
+                        is ObservableTransitionState.Transition -> {
+                            if (state.fromScene == SceneKey.Gone) {
+                                true to "scene transitioning away from Gone"
+                            } else {
+                                null
+                            }
+                        }
+                    }
+                }
                 .distinctUntilChanged()
-                .collect { sceneKey ->
-                    sceneInteractor.setVisible(sceneKey != SceneKey.Gone, "scene is $sceneKey")
+                .collect { (isVisible, loggingReason) ->
+                    sceneInteractor.setVisible(isVisible, loggingReason)
                 }
         }
     }
@@ -88,43 +107,55 @@
     private fun automaticallySwitchScenes() {
         applicationScope.launch {
             authenticationInteractor.isUnlocked
-                .map { isUnlocked ->
-                    val currentSceneKey = sceneInteractor.currentScene.value.key
+                .mapNotNull { isUnlocked ->
+                    val renderedScenes =
+                        when (val transitionState = sceneInteractor.transitionState.value) {
+                            is ObservableTransitionState.Idle -> setOf(transitionState.scene)
+                            is ObservableTransitionState.Transition ->
+                                setOf(
+                                    transitionState.progress,
+                                    transitionState.toScene,
+                                )
+                        }
                     val isBypassEnabled = authenticationInteractor.isBypassEnabled()
                     when {
                         isUnlocked ->
-                            when (currentSceneKey) {
+                            when {
                                 // When the device becomes unlocked in Bouncer, go to Gone.
-                                is SceneKey.Bouncer ->
+                                renderedScenes.contains(SceneKey.Bouncer) ->
                                     SceneKey.Gone to "device unlocked in Bouncer scene"
+
                                 // When the device becomes unlocked in Lockscreen, go to Gone if
                                 // bypass is enabled.
-                                is SceneKey.Lockscreen ->
+                                renderedScenes.contains(SceneKey.Lockscreen) ->
                                     if (isBypassEnabled) {
                                         SceneKey.Gone to
                                             "device unlocked in Lockscreen scene with bypass"
                                     } else {
                                         null
                                     }
+
                                 // We got unlocked while on a scene that's not Lockscreen or
                                 // Bouncer, no need to change scenes.
                                 else -> null
                             }
+
                         // When the device becomes locked, to Lockscreen.
                         !isUnlocked ->
-                            when (currentSceneKey) {
+                            when {
                                 // Already on lockscreen or bouncer, no need to change scenes.
-                                is SceneKey.Lockscreen,
-                                is SceneKey.Bouncer -> null
+                                renderedScenes.contains(SceneKey.Lockscreen) ||
+                                    renderedScenes.contains(SceneKey.Bouncer) -> null
+
                                 // We got locked while on a scene that's not Lockscreen or Bouncer,
                                 // go to Lockscreen.
                                 else ->
-                                    SceneKey.Lockscreen to "device locked in $currentSceneKey scene"
+                                    SceneKey.Lockscreen to
+                                        "device locked in non-Lockscreen and non-Bouncer scene"
                             }
                         else -> null
                     }
                 }
-                .filterNotNull()
                 .collect { (targetSceneKey, loggingReason) ->
                     switchToScene(
                         targetSceneKey = targetSceneKey,
@@ -135,22 +166,39 @@
 
         applicationScope.launch {
             keyguardInteractor.wakefulnessModel
-                .map { it.state == WakefulnessState.ASLEEP }
+                .map { wakefulnessModel -> wakefulnessModel.state }
                 .distinctUntilChanged()
-                .collect { isAsleep ->
-                    if (isAsleep) {
-                        // When the device goes to sleep, reset the current scene.
-                        val isUnlocked = authenticationInteractor.isUnlocked.value
-                        val (targetSceneKey, loggingReason) =
-                            if (isUnlocked) {
-                                SceneKey.Gone to "device is asleep while unlocked"
-                            } else {
-                                SceneKey.Lockscreen to "device is asleep while locked"
+                .collect { wakefulnessState ->
+                    when (wakefulnessState) {
+                        WakefulnessState.STARTING_TO_SLEEP -> {
+                            switchToScene(
+                                targetSceneKey = SceneKey.Lockscreen,
+                                loggingReason = "device is starting to sleep",
+                            )
+                        }
+                        WakefulnessState.STARTING_TO_WAKE -> {
+                            val authMethod = authenticationInteractor.getAuthenticationMethod()
+                            val isUnlocked = authenticationInteractor.isUnlocked.value
+                            when {
+                                authMethod == AuthenticationMethodModel.None -> {
+                                    switchToScene(
+                                        targetSceneKey = SceneKey.Gone,
+                                        loggingReason =
+                                            "device is starting to wake up while auth method is" +
+                                                " none",
+                                    )
+                                }
+                                authMethod.isSecure && isUnlocked -> {
+                                    switchToScene(
+                                        targetSceneKey = SceneKey.Gone,
+                                        loggingReason =
+                                            "device is starting to wake up while unlocked with a" +
+                                                " secure auth method",
+                                    )
+                                }
                             }
-                        switchToScene(
-                            targetSceneKey = targetSceneKey,
-                            loggingReason = loggingReason,
-                        )
+                        }
+                        else -> Unit
                     }
                 }
         }
@@ -159,8 +207,9 @@
     /** Keeps [SysUiState] up-to-date */
     private fun hydrateSystemUiState() {
         applicationScope.launch {
-            sceneInteractor.currentScene
-                .map { it.key }
+            sceneInteractor.transitionState
+                .mapNotNull { it as? ObservableTransitionState.Idle }
+                .map { it.scene }
                 .distinctUntilChanged()
                 .collect { sceneKey ->
                     sysUiState.updateFlags(
@@ -177,7 +226,7 @@
     }
 
     private fun switchToScene(targetSceneKey: SceneKey, loggingReason: String) {
-        sceneInteractor.setCurrentScene(
+        sceneInteractor.changeScene(
             scene = SceneModel(targetSceneKey),
             loggingReason = loggingReason,
         )
diff --git a/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt b/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt
index 0adbd5a..62136dc 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt
@@ -37,7 +37,7 @@
         )
     }
 
-    fun logSceneChange(
+    fun logSceneChangeRequested(
         from: SceneKey,
         to: SceneKey,
         reason: String,
@@ -50,7 +50,24 @@
                 str2 = to.toString()
                 str3 = reason
             },
-            messagePrinter = { "$str1 → $str2, reason: $str3" },
+            messagePrinter = { "Scene change requested: $str1 → $str2, reason: $str3" },
+        )
+    }
+
+    fun logSceneChangeCommitted(
+        from: SceneKey,
+        to: SceneKey,
+        reason: String,
+    ) {
+        logBuffer.log(
+            tag = TAG,
+            level = LogLevel.INFO,
+            messageInitializer = {
+                str1 = from.toString()
+                str2 = to.toString()
+                str3 = reason
+            },
+            messagePrinter = { "Scene change committed: $str1 → $str2, reason: $str3" },
         )
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/scene/shared/model/RemoteUserInput.kt b/packages/SystemUI/src/com/android/systemui/scene/shared/model/RemoteUserInput.kt
deleted file mode 100644
index 680de59..0000000
--- a/packages/SystemUI/src/com/android/systemui/scene/shared/model/RemoteUserInput.kt
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.android.systemui.scene.shared.model
-
-import android.view.MotionEvent
-
-/** A representation of user input that is used by the scene framework. */
-data class RemoteUserInput(
-    val x: Float,
-    val y: Float,
-    val action: RemoteUserInputAction,
-) {
-    companion object {
-        fun translateMotionEvent(event: MotionEvent): RemoteUserInput {
-            return RemoteUserInput(
-                x = event.x,
-                y = event.y,
-                action =
-                    when (event.actionMasked) {
-                        MotionEvent.ACTION_DOWN -> RemoteUserInputAction.DOWN
-                        MotionEvent.ACTION_MOVE -> RemoteUserInputAction.MOVE
-                        MotionEvent.ACTION_UP -> RemoteUserInputAction.UP
-                        MotionEvent.ACTION_CANCEL -> RemoteUserInputAction.CANCEL
-                        else -> RemoteUserInputAction.UNKNOWN
-                    }
-            )
-        }
-    }
-}
-
-enum class RemoteUserInputAction {
-    DOWN,
-    MOVE,
-    UP,
-    CANCEL,
-    UNKNOWN,
-}
diff --git a/packages/SystemUI/src/com/android/systemui/scene/ui/view/SceneWindowRootView.kt b/packages/SystemUI/src/com/android/systemui/scene/ui/view/SceneWindowRootView.kt
index 8601b3d..cdf50ba 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/ui/view/SceneWindowRootView.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/ui/view/SceneWindowRootView.kt
@@ -2,7 +2,6 @@
 
 import android.content.Context
 import android.util.AttributeSet
-import android.view.MotionEvent
 import android.view.View
 import com.android.systemui.scene.shared.model.Scene
 import com.android.systemui.scene.shared.model.SceneContainerConfig
@@ -39,14 +38,6 @@
         )
     }
 
-    override fun onTouchEvent(event: MotionEvent?): Boolean {
-        return event?.let {
-            viewModel.onRemoteUserInput(event)
-            true
-        }
-            ?: false
-    }
-
     override fun setVisibility(visibility: Int) {
         // Do nothing. We don't want external callers to invoke this. Instead, we drive our own
         // visibility from our view-binder.
diff --git a/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt b/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt
index b4ebaec..5c16fb5 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt
@@ -16,11 +16,9 @@
 
 package com.android.systemui.scene.ui.viewmodel
 
-import android.view.MotionEvent
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.scene.domain.interactor.SceneInteractor
 import com.android.systemui.scene.shared.model.ObservableTransitionState
-import com.android.systemui.scene.shared.model.RemoteUserInput
 import com.android.systemui.scene.shared.model.SceneKey
 import com.android.systemui.scene.shared.model.SceneModel
 import javax.inject.Inject
@@ -34,9 +32,6 @@
 constructor(
     private val interactor: SceneInteractor,
 ) {
-    /** A flow of motion events originating from outside of the scene framework. */
-    val remoteUserInput: StateFlow<RemoteUserInput?> = interactor.remoteUserInput
-
     /**
      * Keys of all scenes in the container.
      *
@@ -45,15 +40,15 @@
      */
     val allSceneKeys: List<SceneKey> = interactor.allSceneKeys()
 
-    /** The current scene. */
-    val currentScene: StateFlow<SceneModel> = interactor.currentScene
+    /** The scene that should be rendered. */
+    val currentScene: StateFlow<SceneModel> = interactor.desiredScene
 
     /** Whether the container is visible. */
     val isVisible: StateFlow<Boolean> = interactor.isVisible
 
-    /** Requests a transition to the scene with the given key. */
-    fun setCurrentScene(scene: SceneModel) {
-        interactor.setCurrentScene(
+    /** Notifies that the UI has transitioned sufficiently to the given scene. */
+    fun onSceneChanged(scene: SceneModel) {
+        interactor.onSceneChanged(
             scene = scene,
             loggingReason = SCENE_TRANSITION_LOGGING_REASON,
         )
@@ -68,11 +63,6 @@
         interactor.setTransitionState(transitionState)
     }
 
-    /** Handles a [MotionEvent] representing remote user input. */
-    fun onRemoteUserInput(event: MotionEvent) {
-        interactor.onRemoteUserInput(RemoteUserInput.translateMotionEvent(event))
-    }
-
     companion object {
         private const val SCENE_TRANSITION_LOGGING_REASON = "user input"
     }
diff --git a/packages/SystemUI/src/com/android/systemui/screenrecord/BaseScreenSharePermissionDialog.kt b/packages/SystemUI/src/com/android/systemui/screenrecord/BaseScreenSharePermissionDialog.kt
index b340043..23894a3 100644
--- a/packages/SystemUI/src/com/android/systemui/screenrecord/BaseScreenSharePermissionDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/screenrecord/BaseScreenSharePermissionDialog.kt
@@ -50,22 +50,20 @@
 
     public override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
-        window.apply {
-            addPrivateFlags(WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS)
-            setGravity(Gravity.CENTER)
-        }
+        window?.addPrivateFlags(WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS)
+        window?.setGravity(Gravity.CENTER)
         setContentView(R.layout.screen_share_dialog)
-        dialogTitle = findViewById(R.id.screen_share_dialog_title)
-        warning = findViewById(R.id.text_warning)
-        startButton = findViewById(android.R.id.button1)
-        cancelButton = findViewById(android.R.id.button2)
+        dialogTitle = requireViewById(R.id.screen_share_dialog_title)
+        warning = requireViewById(R.id.text_warning)
+        startButton = requireViewById(android.R.id.button1)
+        cancelButton = requireViewById(android.R.id.button2)
         updateIcon()
         initScreenShareOptions()
         createOptionsView(getOptionsViewLayoutId())
     }
 
     private fun updateIcon() {
-        val icon = findViewById<ImageView>(R.id.screen_share_dialog_icon)
+        val icon = requireViewById<ImageView>(R.id.screen_share_dialog_icon)
         if (dialogIconTint != null) {
             icon.setColorFilter(context.getColor(dialogIconTint))
         }
@@ -92,7 +90,7 @@
                 options
             )
         adapter.setDropDownViewResource(R.layout.screen_share_dialog_spinner_item_text)
-        screenShareModeSpinner = findViewById(R.id.screen_share_mode_spinner)
+        screenShareModeSpinner = requireViewById(R.id.screen_share_mode_spinner)
         screenShareModeSpinner.adapter = adapter
         screenShareModeSpinner.onItemSelectedListener = this
     }
diff --git a/packages/SystemUI/src/com/android/systemui/screenrecord/ScreenRecordPermissionDialog.kt b/packages/SystemUI/src/com/android/systemui/screenrecord/ScreenRecordPermissionDialog.kt
index 604d449..fb99775 100644
--- a/packages/SystemUI/src/com/android/systemui/screenrecord/ScreenRecordPermissionDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/screenrecord/ScreenRecordPermissionDialog.kt
@@ -63,6 +63,7 @@
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         setDialogTitle(R.string.screenrecord_permission_dialog_title)
+        setTitle(R.string.screenrecord_title)
         setStartButtonText(R.string.screenrecord_permission_dialog_continue)
         setStartButtonOnClickListener { v: View? ->
             onStartRecordingClicked?.run()
@@ -100,11 +101,11 @@
     @LayoutRes override fun getOptionsViewLayoutId(): Int = R.layout.screen_record_options
 
     private fun initRecordOptionsView() {
-        audioSwitch = findViewById(R.id.screenrecord_audio_switch)
-        tapsSwitch = findViewById(R.id.screenrecord_taps_switch)
-        tapsView = findViewById(R.id.show_taps)
+        audioSwitch = requireViewById(R.id.screenrecord_audio_switch)
+        tapsSwitch = requireViewById(R.id.screenrecord_taps_switch)
+        tapsView = requireViewById(R.id.show_taps)
         updateTapsViewVisibility()
-        options = findViewById(R.id.screen_recording_options)
+        options = requireViewById(R.id.screen_recording_options)
         val a: ArrayAdapter<*> =
             ScreenRecordingAdapter(context, android.R.layout.simple_spinner_dropdown_item, MODES)
         a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentCreator.kt b/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentCreator.kt
index 76d0f6e..ab2a8d9 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentCreator.kt
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentCreator.kt
@@ -19,6 +19,7 @@
 import android.content.ClipData
 import android.content.ClipDescription
 import android.content.ComponentName
+import android.content.ContentProvider
 import android.content.Context
 import android.content.Intent
 import android.net.Uri
@@ -36,7 +37,9 @@
     fun createShareWithText(uri: Uri, extraText: String): Intent =
         createShare(uri, text = extraText)
 
-    private fun createShare(uri: Uri, subject: String? = null, text: String? = null): Intent {
+    private fun createShare(rawUri: Uri, subject: String? = null, text: String? = null): Intent {
+        val uri = uriWithoutUserId(rawUri)
+
         // Create a share intent, this will always go through the chooser activity first
         // which should not trigger auto-enter PiP
         val sharingIntent =
@@ -68,7 +71,8 @@
      * @return an ACTION_EDIT intent for the given URI, directed to config_screenshotEditor if
      *   available.
      */
-    fun createEditIntent(uri: Uri, context: Context): Intent {
+    fun createEdit(rawUri: Uri, context: Context): Intent {
+        val uri = uriWithoutUserId(rawUri)
         val editIntent = Intent(Intent.ACTION_EDIT)
 
         val editor = context.getString(R.string.config_screenshotEditor)
@@ -78,9 +82,22 @@
 
         return editIntent
             .setDataAndType(uri, "image/png")
+            .putExtra(EXTRA_EDIT_SOURCE, EDIT_SOURCE_SCREENSHOT)
             .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
             .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
             .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
             .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
     }
+
+    private const val EXTRA_EDIT_SOURCE = "edit_source"
+    private const val EDIT_SOURCE_SCREENSHOT = "screenshot"
+}
+
+/**
+ * URIs here are passed only via Intent which are sent to the target user via Intent. Because of
+ * this, the userId component can be removed to prevent compatibility issues when an app attempts
+ * valid a URI containing a userId within the authority.
+ */
+private fun uriWithoutUserId(uri: Uri): Uri {
+    return ContentProvider.getUriWithoutUserId(uri)
 }
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentExecutor.kt b/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentExecutor.kt
index ecd4568..aa6bfc3 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentExecutor.kt
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/ActionIntentExecutor.kt
@@ -83,7 +83,7 @@
         if (overrideTransition) {
             val runner = RemoteAnimationAdapter(SCREENSHOT_REMOTE_RUNNER, 0, 0)
             try {
-                WindowManagerGlobal.getWindowManagerService()
+                checkNotNull(WindowManagerGlobal.getWindowManagerService())
                     .overridePendingAppTransitionRemote(runner, displayTracker.defaultDisplayId)
             } catch (e: Exception) {
                 Log.e(TAG, "Error overriding screenshot app transition", e)
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/DraggableConstraintLayout.java b/packages/SystemUI/src/com/android/systemui/screenshot/DraggableConstraintLayout.java
index 0b4b7c6..bdbc470 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/DraggableConstraintLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/DraggableConstraintLayout.java
@@ -43,6 +43,7 @@
  */
 public class DraggableConstraintLayout extends ConstraintLayout
         implements ViewTreeObserver.OnComputeInternalInsetsListener {
+    public static final int SWIPE_PADDING_DP = 12; // extra padding around views to allow swipe
 
     private static final float VELOCITY_DP_PER_MS = 1;
     private static final int MAXIMUM_DISMISS_DISTANCE_DP = 400;
@@ -179,8 +180,13 @@
         Region r = new Region();
         Rect rect = new Rect();
         for (int i = 0; i < getChildCount(); i++) {
-            getChildAt(i).getGlobalVisibleRect(rect);
-            r.op(rect, Region.Op.UNION);
+            View child = getChildAt(i);
+            if (child.getVisibility() == View.VISIBLE) {
+                child.getGlobalVisibleRect(rect);
+                rect.inset((int) FloatingWindowUtil.dpToPx(mDisplayMetrics, -SWIPE_PADDING_DP),
+                        (int) FloatingWindowUtil.dpToPx(mDisplayMetrics, -SWIPE_PADDING_DP));
+                r.op(rect, Region.Op.UNION);
+            }
         }
         inoutInfo.setTouchableInsets(ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION);
         inoutInfo.touchableRegion.set(r);
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/LongScreenshotActivity.java b/packages/SystemUI/src/com/android/systemui/screenshot/LongScreenshotActivity.java
index 010658b..53dbe76 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/LongScreenshotActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/LongScreenshotActivity.java
@@ -334,7 +334,7 @@
         if (mScreenshotUserHandle != Process.myUserHandle()) {
             // TODO: Fix transition for work profile. Omitting it in the meantime.
             mActionExecutor.launchIntentAsync(
-                    ActionIntentCreator.INSTANCE.createEditIntent(uri, this),
+                    ActionIntentCreator.INSTANCE.createEdit(uri, this),
                     null,
                     mScreenshotUserHandle, false);
         } else {
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java
index 204b5e6..03e1e15 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java
@@ -68,7 +68,6 @@
 import android.view.LayoutInflater;
 import android.view.MotionEvent;
 import android.view.ScrollCaptureResponse;
-import android.view.TouchDelegate;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.ViewTreeObserver;
@@ -123,7 +122,6 @@
     public static final long SCREENSHOT_ACTIONS_EXPANSION_DURATION_MS = 400;
     private static final long SCREENSHOT_ACTIONS_ALPHA_DURATION_MS = 100;
     private static final float SCREENSHOT_ACTIONS_START_SCALE_X = .7f;
-    private static final int SWIPE_PADDING_DP = 12; // extra padding around views to allow swipe
 
     private final Resources mResources;
     private final Interpolator mFastOutSlowIn;
@@ -284,17 +282,22 @@
         Region swipeRegion = new Region();
 
         final Rect tmpRect = new Rect();
+        int swipePadding = (int) FloatingWindowUtil.dpToPx(
+                mDisplayMetrics, DraggableConstraintLayout.SWIPE_PADDING_DP * -1);
         mScreenshotPreview.getBoundsOnScreen(tmpRect);
-        tmpRect.inset((int) FloatingWindowUtil.dpToPx(mDisplayMetrics, -SWIPE_PADDING_DP),
-                (int) FloatingWindowUtil.dpToPx(mDisplayMetrics, -SWIPE_PADDING_DP));
+        tmpRect.inset(swipePadding, swipePadding);
         swipeRegion.op(tmpRect, Region.Op.UNION);
         mActionsContainerBackground.getBoundsOnScreen(tmpRect);
-        tmpRect.inset((int) FloatingWindowUtil.dpToPx(mDisplayMetrics, -SWIPE_PADDING_DP),
-                (int) FloatingWindowUtil.dpToPx(mDisplayMetrics, -SWIPE_PADDING_DP));
+        tmpRect.inset(swipePadding, swipePadding);
         swipeRegion.op(tmpRect, Region.Op.UNION);
         mDismissButton.getBoundsOnScreen(tmpRect);
         swipeRegion.op(tmpRect, Region.Op.UNION);
 
+        View messageContainer = findViewById(R.id.screenshot_message_container);
+        if (messageContainer != null) {
+            messageContainer.getBoundsOnScreen(tmpRect);
+            swipeRegion.op(tmpRect, Region.Op.UNION);
+        }
         View messageDismiss = findViewById(R.id.message_dismiss_button);
         if (messageDismiss != null) {
             messageDismiss.getBoundsOnScreen(tmpRect);
@@ -378,16 +381,6 @@
         mEditChip = requireNonNull(mActionsContainer.findViewById(R.id.screenshot_edit_chip));
         mScrollChip = requireNonNull(mActionsContainer.findViewById(R.id.screenshot_scroll_chip));
 
-        int swipePaddingPx = (int) FloatingWindowUtil.dpToPx(mDisplayMetrics, SWIPE_PADDING_DP);
-        TouchDelegate previewDelegate = new TouchDelegate(
-                new Rect(swipePaddingPx, swipePaddingPx, swipePaddingPx, swipePaddingPx),
-                mScreenshotPreview);
-        mScreenshotPreview.setTouchDelegate(previewDelegate);
-        TouchDelegate actionsDelegate = new TouchDelegate(
-                new Rect(swipePaddingPx, swipePaddingPx, swipePaddingPx, swipePaddingPx),
-                mActionsContainerBackground);
-        mActionsContainerBackground.setTouchDelegate(actionsDelegate);
-
         setFocusable(true);
         mActionsContainer.setScrollX(0);
 
@@ -815,7 +808,7 @@
             mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_EDIT_TAPPED, 0, mPackageName);
             prepareSharedTransition();
             mActionExecutor.launchIntentAsync(
-                    ActionIntentCreator.INSTANCE.createEditIntent(imageData.uri, mContext),
+                    ActionIntentCreator.INSTANCE.createEdit(imageData.uri, mContext),
                     imageData.editTransition.get().bundle,
                     imageData.owner, true);
         });
@@ -823,7 +816,7 @@
             mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_PREVIEW_TAPPED, 0, mPackageName);
             prepareSharedTransition();
             mActionExecutor.launchIntentAsync(
-                    ActionIntentCreator.INSTANCE.createEditIntent(imageData.uri, mContext),
+                    ActionIntentCreator.INSTANCE.createEdit(imageData.uri, mContext),
                     imageData.editTransition.get().bundle,
                     imageData.owner, true);
         });
diff --git a/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java b/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java
index fc89a9e..f4d19dc 100644
--- a/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java
+++ b/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java
@@ -30,6 +30,7 @@
 import android.graphics.drawable.Drawable;
 import android.os.Looper;
 import android.util.AttributeSet;
+import android.view.MotionEvent;
 import android.view.View;
 
 import androidx.annotation.Nullable;
@@ -38,6 +39,7 @@
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.colorextraction.ColorExtractor;
+import com.android.systemui.shade.TouchLogger;
 import com.android.systemui.util.LargeScreenUtils;
 
 import java.util.concurrent.Executor;
@@ -59,6 +61,7 @@
     private float mViewAlpha = 1.0f;
     private Drawable mDrawable;
     private PorterDuffColorFilter mColorFilter;
+    private String mScrimName;
     private int mTintColor;
     private boolean mBlendWithMainColor = true;
     private Runnable mChangeRunnable;
@@ -336,6 +339,15 @@
         }
     }
 
+    public void setScrimName(String scrimName) {
+        mScrimName = scrimName;
+    }
+
+    @Override
+    public boolean dispatchTouchEvent(MotionEvent ev) {
+        return TouchLogger.logDispatchTouch(mScrimName, ev, super.dispatchTouchEvent(ev));
+    }
+
     /**
      * The position of the bottom of the scrim, used for clipping.
      * @see #enableBottomEdgeConcave(boolean)
diff --git a/packages/SystemUI/src/com/android/systemui/sensorprivacy/SensorUseStartedActivity.kt b/packages/SystemUI/src/com/android/systemui/sensorprivacy/SensorUseStartedActivity.kt
index d33d113..2f0fc51 100644
--- a/packages/SystemUI/src/com/android/systemui/sensorprivacy/SensorUseStartedActivity.kt
+++ b/packages/SystemUI/src/com/android/systemui/sensorprivacy/SensorUseStartedActivity.kt
@@ -228,6 +228,8 @@
     }
 
     override fun onDismiss(dialog: DialogInterface?) {
-        finish()
+        if (!isChangingConfigurations) {
+            finish()
+        }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/settings/DisplayTracker.kt b/packages/SystemUI/src/com/android/systemui/settings/DisplayTracker.kt
index 468a75d..e7ee961 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/DisplayTracker.kt
+++ b/packages/SystemUI/src/com/android/systemui/settings/DisplayTracker.kt
@@ -48,6 +48,9 @@
     /** Remove a [Callback] previously added. */
     fun removeCallback(callback: Callback)
 
+    /** Gets the Display with the given displayId */
+    fun getDisplay(displayId: Int): Display
+
     /** Ćallback for notifying of changes. */
     interface Callback {
 
diff --git a/packages/SystemUI/src/com/android/systemui/settings/DisplayTrackerImpl.kt b/packages/SystemUI/src/com/android/systemui/settings/DisplayTrackerImpl.kt
index 5169f88..68cc483 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/DisplayTrackerImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/settings/DisplayTrackerImpl.kt
@@ -115,6 +115,10 @@
         }
     }
 
+    override fun getDisplay(displayId: Int): Display {
+        return displayManager.getDisplay(displayId)
+    }
+
     @WorkerThread
     private fun onDisplayAdded(displayId: Int, list: List<DisplayTrackerDataItem>) {
         Assert.isNotMainThread()
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NPVCDownEventState.kt b/packages/SystemUI/src/com/android/systemui/shade/NPVCDownEventState.kt
index 6143308..4644d41 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NPVCDownEventState.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/NPVCDownEventState.kt
@@ -108,7 +108,7 @@
          * @see NPVCDownEventState.asStringList
          */
         fun toList(): List<Row> {
-            return buffer.asSequence().map { it.asStringList }.toList()
+            return buffer.map { it.asStringList }
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelView.java
index af3cc86..c501d88 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelView.java
@@ -106,6 +106,11 @@
     }
 
     @Override
+    public boolean dispatchTouchEvent(MotionEvent ev) {
+        return TouchLogger.logDispatchTouch("NPV", ev, super.dispatchTouchEvent(ev));
+    }
+
+    @Override
     public void dispatchConfigurationChanged(Configuration newConfig) {
         super.dispatchConfigurationChanged(newConfig);
         mOnConfigurationChangedListener.onConfigurationChanged(newConfig);
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
index 416f147..7c4b042 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
@@ -90,6 +90,8 @@
 import android.view.animation.Interpolator;
 import android.widget.FrameLayout;
 
+import androidx.constraintlayout.widget.ConstraintLayout;
+
 import com.android.app.animation.Interpolators;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.logging.MetricsLogger;
@@ -1053,10 +1055,7 @@
         mKeyguardStatusBarViewController.init();
 
         mNotificationContainerParent = mView.findViewById(R.id.notification_container_parent);
-        updateViewControllers(
-                mView.findViewById(R.id.keyguard_status_view),
-                userAvatarContainer,
-                keyguardUserSwitcherView);
+        updateViewControllers(userAvatarContainer, keyguardUserSwitcherView);
 
         mNotificationStackScrollLayoutController.setOnHeightChangedListener(
                 new NsslHeightChangedListener());
@@ -1118,7 +1117,8 @@
         collectFlow(mView, mKeyguardTransitionInteractor.getDreamingToLockscreenTransition(),
                 mDreamingToLockscreenTransition, mMainDispatcher);
         collectFlow(mView, mDreamingToLockscreenTransitionViewModel.getLockscreenAlpha(),
-                setTransitionAlpha(mNotificationStackScrollLayoutController), mMainDispatcher);
+                setDreamLockscreenTransitionAlpha(mNotificationStackScrollLayoutController),
+                mMainDispatcher);
         collectFlow(mView, mDreamingToLockscreenTransitionViewModel.lockscreenTranslationY(
                 mDreamingToLockscreenTransitionTranslationY),
                 setTransitionY(mNotificationStackScrollLayoutController), mMainDispatcher);
@@ -1154,7 +1154,8 @@
         collectFlow(mView, mKeyguardTransitionInteractor.getLockscreenToDreamingTransition(),
                 mLockscreenToDreamingTransition, mMainDispatcher);
         collectFlow(mView, mLockscreenToDreamingTransitionViewModel.getLockscreenAlpha(),
-                setTransitionAlpha(mNotificationStackScrollLayoutController), mMainDispatcher);
+                setDreamLockscreenTransitionAlpha(mNotificationStackScrollLayoutController),
+                mMainDispatcher);
         collectFlow(mView, mLockscreenToDreamingTransitionViewModel.lockscreenTranslationY(
                 mLockscreenToDreamingTransitionTranslationY),
                 setTransitionY(mNotificationStackScrollLayoutController), mMainDispatcher);
@@ -1218,18 +1219,38 @@
         mQsController.loadDimens();
     }
 
-    private void updateViewControllers(KeyguardStatusView keyguardStatusView,
+    private void updateViewControllers(
             FrameLayout userAvatarView,
             KeyguardUserSwitcherView keyguardUserSwitcherView) {
+        // Re-associate the KeyguardStatusViewController
         if (mKeyguardStatusViewController != null) {
             mKeyguardStatusViewController.onDestroy();
         }
-        // Re-associate the KeyguardStatusViewController
-        KeyguardStatusViewComponent statusViewComponent =
+
+        if (mFeatureFlags.isEnabled(Flags.MIGRATE_KEYGUARD_STATUS_VIEW)) {
+            // Need a shared controller until mKeyguardStatusViewController can be removed from
+            // here, due to important state being set in that controller. Rebind in order to pick
+            // up config changes
+            mKeyguardViewConfigurator.bindKeyguardStatusView(mView);
+            mKeyguardStatusViewController =
+                    mKeyguardViewConfigurator.getKeyguardStatusViewController();
+        } else {
+            KeyguardStatusView keyguardStatusView = mView.getRootView().findViewById(
+                    R.id.keyguard_status_view);
+            KeyguardStatusViewComponent statusViewComponent =
                 mKeyguardStatusViewComponentFactory.build(keyguardStatusView);
-        mKeyguardStatusViewController = statusViewComponent.getKeyguardStatusViewController();
-        mKeyguardStatusViewController.init();
+            mKeyguardStatusViewController = statusViewComponent.getKeyguardStatusViewController();
+            mKeyguardStatusViewController.init();
+        }
         mKeyguardStatusViewController.setSplitShadeEnabled(mSplitShadeEnabled);
+        mKeyguardStatusViewController.getView().addOnLayoutChangeListener(
+                (v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
+                    int oldHeight = oldBottom - oldTop;
+                    if (v.getHeight() != oldHeight) {
+                        mNotificationStackScrollLayoutController.animateNextTopPaddingChange();
+                    }
+                });
+
         updateClockAppearance();
 
         if (mKeyguardUserSwitcherController != null) {
@@ -1335,15 +1356,22 @@
     void reInflateViews() {
         debugLog("reInflateViews");
         // Re-inflate the status view group.
-        KeyguardStatusView keyguardStatusView =
-                mNotificationContainerParent.findViewById(R.id.keyguard_status_view);
-        int statusIndex = mNotificationContainerParent.indexOfChild(keyguardStatusView);
-        mNotificationContainerParent.removeView(keyguardStatusView);
-        keyguardStatusView = (KeyguardStatusView) mLayoutInflater.inflate(
-                R.layout.keyguard_status_view, mNotificationContainerParent, false);
-        mNotificationContainerParent.addView(keyguardStatusView, statusIndex);
-        attachSplitShadeMediaPlayerContainer(
-                keyguardStatusView.findViewById(R.id.status_view_media_container));
+        if (!mFeatureFlags.isEnabled(Flags.MIGRATE_KEYGUARD_STATUS_VIEW)) {
+            KeyguardStatusView keyguardStatusView =
+                    mNotificationContainerParent.findViewById(R.id.keyguard_status_view);
+            int statusIndex = mNotificationContainerParent.indexOfChild(keyguardStatusView);
+            mNotificationContainerParent.removeView(keyguardStatusView);
+            keyguardStatusView = (KeyguardStatusView) mLayoutInflater.inflate(
+                    R.layout.keyguard_status_view, mNotificationContainerParent, false);
+            mNotificationContainerParent.addView(keyguardStatusView, statusIndex);
+
+            attachSplitShadeMediaPlayerContainer(
+                    keyguardStatusView.findViewById(R.id.status_view_media_container));
+        } else {
+            attachSplitShadeMediaPlayerContainer(
+                    mKeyguardViewConfigurator.getKeyguardRootView()
+                        .findViewById(R.id.status_view_media_container));
+        }
 
         // we need to update KeyguardStatusView constraints after reinflating it
         updateResources();
@@ -1369,8 +1397,7 @@
                         R.layout.keyguard_user_switcher /* layoutId */,
                         showKeyguardUserSwitcher /* enabled */);
 
-        updateViewControllers(mView.findViewById(R.id.keyguard_status_view), userAvatarView,
-                keyguardUserSwitcherView);
+        updateViewControllers(userAvatarView, keyguardUserSwitcherView);
 
         if (!mFeatureFlags.isEnabled(Flags.MIGRATE_SPLIT_KEYGUARD_BOTTOM_AREA)) {
             // Update keyguard bottom area
@@ -1666,8 +1693,14 @@
 
     private void updateKeyguardStatusViewAlignment(boolean animate) {
         boolean shouldBeCentered = shouldKeyguardStatusViewBeCentered();
+        ConstraintLayout layout;
+        if (mFeatureFlags.isEnabled(Flags.MIGRATE_KEYGUARD_STATUS_VIEW)) {
+            layout = mKeyguardViewConfigurator.getKeyguardRootView();
+        } else {
+            layout = mNotificationContainerParent;
+        }
         mKeyguardStatusViewController.updateAlignment(
-                mNotificationContainerParent, mSplitShadeEnabled, shouldBeCentered, animate);
+                layout, mSplitShadeEnabled, shouldBeCentered, animate);
         mKeyguardUnfoldTransition.ifPresent(t -> t.setStatusViewCentered(shouldBeCentered));
     }
 
@@ -2105,6 +2138,7 @@
         }
         updateExpansionAndVisibility();
         mNotificationStackScrollLayoutController.setPanelFlinging(false);
+        mShadeLog.d("onFlingEnd called"); // TODO(b/277909752): remove log when bug is fixed
         // expandImmediate should be always reset at the end of animation
         mQsController.setExpandImmediate(false);
     }
@@ -2640,6 +2674,11 @@
             setListening(true);
         }
         if (mBarState != SHADE) {
+            // TODO(b/277909752): remove below logs when bug is fixed
+            mShadeLog.d("onExpandingFinished called");
+            if (mSplitShadeEnabled && !mQsController.getExpanded()) {
+                mShadeLog.d("onExpandingFinished called before QS got expanded");
+            }
             // updating qsExpandImmediate is done in onPanelStateChanged for unlocked shade but
             // on keyguard panel state is always OPEN so we need to have that extra update
             mQsController.setExpandImmediate(false);
@@ -3166,6 +3205,11 @@
         }
     }
 
+    @Override
+    public void performHapticFeedback(int constant) {
+        mVibratorHelper.performHapticFeedback(mView, constant);
+    }
+
     private class ShadeHeadsUpTrackerImpl implements ShadeHeadsUpTracker {
         @Override
         public void addTrackingHeadsUpListener(Consumer<ExpandableNotificationRow> listener) {
@@ -3390,7 +3434,6 @@
         ipw.print("mPanelFlingOvershootAmount="); ipw.println(mPanelFlingOvershootAmount);
         ipw.print("mLastGesturedOverExpansion="); ipw.println(mLastGesturedOverExpansion);
         ipw.print("mIsSpringBackAnimation="); ipw.println(mIsSpringBackAnimation);
-        ipw.print("mSplitShadeEnabled="); ipw.println(mSplitShadeEnabled);
         ipw.print("mHintDistance="); ipw.println(mHintDistance);
         ipw.print("mInitialOffsetOnTouch="); ipw.println(mInitialOffsetOnTouch);
         ipw.print("mCollapsedAndHeadsUpOnDown="); ipw.println(mCollapsedAndHeadsUpOnDown);
@@ -3423,13 +3466,14 @@
         ipw.print("mGestureWaitForTouchSlop="); ipw.println(mGestureWaitForTouchSlop);
         ipw.print("mIgnoreXTouchSlop="); ipw.println(mIgnoreXTouchSlop);
         ipw.print("mExpandLatencyTracking="); ipw.println(mExpandLatencyTracking);
-        ipw.print("mExpandLatencyTracking="); ipw.println(mExpandLatencyTracking);
         ipw.println("gestureExclusionRect:" + calculateGestureExclusionRect());
+        Trace.beginSection("Table<DownEvents>");
         new DumpsysTableLogger(
                 TAG,
                 NPVCDownEventState.TABLE_HEADERS,
                 mLastDownEvents.toList()
         ).printTableData(ipw);
+        Trace.endSection();
     }
 
     @Override
@@ -4692,6 +4736,7 @@
     }
 
     private void onPanelStateChanged(@PanelState int state) {
+        mShadeLog.logPanelStateChanged(state);
         mQsController.updateExpansionEnabledAmbient();
 
         if (state == STATE_OPEN && mCurrentPanelState != state) {
@@ -4718,6 +4763,16 @@
         mCurrentPanelState = state;
     }
 
+    private Consumer<Float> setDreamLockscreenTransitionAlpha(
+            NotificationStackScrollLayoutController stackScroller) {
+        return (Float alpha) -> {
+            // Also animate the status bar's alpha during transitions between the lockscreen and
+            // dreams.
+            mKeyguardStatusBarViewController.setAlpha(alpha);
+            setTransitionAlpha(stackScroller).accept(alpha);
+        };
+    }
+
     private Consumer<Float> setTransitionAlpha(
             NotificationStackScrollLayoutController stackScroller) {
         return (Float alpha) -> {
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowControllerImpl.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowControllerImpl.java
index b328c55..6f726a2 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowControllerImpl.java
@@ -840,13 +840,17 @@
         pw.println("  mDeferWindowLayoutParams=" + mDeferWindowLayoutParams);
         pw.println(mCurrentState);
         if (mWindowRootView != null && mWindowRootView.getViewRootImpl() != null) {
+            Trace.beginSection("mWindowRootView.dump()");
             mWindowRootView.getViewRootImpl().dump("  ", pw);
+            Trace.endSection();
         }
+        Trace.beginSection("Table<State>");
         new DumpsysTableLogger(
                 TAG,
                 NotificationShadeWindowState.TABLE_HEADERS,
                 mStateBuffer.toList()
         ).printTableData(pw);
+        Trace.endSection();
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowState.kt b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowState.kt
index d252943..e3010ca 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowState.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowState.kt
@@ -170,7 +170,7 @@
          * @see [NotificationShadeWindowState.asStringList]
          */
         fun toList(): List<Row> {
-            return buffer.asSequence().map { it.asStringList }.toList()
+            return buffer.map { it.asStringList }
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowView.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowView.java
index a9c4aeb..f9b4e67 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowView.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowView.java
@@ -107,6 +107,8 @@
 
         result = result != null ? result : super.dispatchTouchEvent(ev);
 
+        TouchLogger.logDispatchTouch(TAG, ev, result);
+
         mInteractionEventHandler.dispatchTouchEventComplete();
 
         return result;
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowViewController.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowViewController.java
index 18e9644..832a25b 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowViewController.java
@@ -91,6 +91,7 @@
     private final NotificationStackScrollLayoutController mNotificationStackScrollLayoutController;
     private final LockscreenShadeTransitionController mLockscreenShadeTransitionController;
     private final LockIconViewController mLockIconViewController;
+    private final ShadeLogger mShadeLogger;
     private final StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
     private final StatusBarWindowStateController mStatusBarWindowStateController;
     private final KeyguardUnlockAnimationController mKeyguardUnlockAnimationController;
@@ -151,6 +152,7 @@
             KeyguardUnlockAnimationController keyguardUnlockAnimationController,
             NotificationInsetsController notificationInsetsController,
             AmbientState ambientState,
+            ShadeLogger shadeLogger,
             PulsingGestureListener pulsingGestureListener,
             LockscreenHostedDreamGestureListener lockscreenHostedDreamGestureListener,
             KeyguardBouncerViewModel keyguardBouncerViewModel,
@@ -176,6 +178,7 @@
         mStatusBarWindowStateController = statusBarWindowStateController;
         mLockIconViewController = lockIconViewController;
         mBackActionInteractor = backActionInteractor;
+        mShadeLogger = shadeLogger;
         mLockIconViewController.init();
         mService = centralSurfaces;
         mPowerInteractor = powerInteractor;
@@ -223,6 +226,13 @@
         return mView.findViewById(R.id.keyguard_message_area);
     }
 
+    private Boolean logDownDispatch(MotionEvent ev, String msg, Boolean result) {
+        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
+            mShadeLogger.logShadeWindowDispatch(ev, msg, result);
+        }
+        return result;
+    }
+
     /** Inflates the {@link R.layout#status_bar_expanded} layout and sets it up. */
     public void setupExpandedStatusBar() {
         mStackScrollLayout = mView.findViewById(R.id.notification_stack_scroller);
@@ -237,8 +247,8 @@
             @Override
             public Boolean handleDispatchTouchEvent(MotionEvent ev) {
                 if (mStatusBarViewController == null) { // Fix for b/192490822
-                    Log.w(TAG, "Ignoring touch while statusBarView not yet set.");
-                    return false;
+                    return logDownDispatch(ev,
+                            "Ignoring touch while statusBarView not yet set", false);
                 }
                 boolean isDown = ev.getActionMasked() == MotionEvent.ACTION_DOWN;
                 boolean isUp = ev.getActionMasked() == MotionEvent.ACTION_UP;
@@ -250,10 +260,9 @@
                 }
 
                 // Reset manual touch dispatch state here but make sure the UP/CANCEL event still
-                // gets
-                // delivered.
+                // gets delivered.
                 if (!isCancel && mService.shouldIgnoreTouch()) {
-                    return false;
+                    return logDownDispatch(ev, "touch ignored by CS", false);
                 }
 
                 if (isDown) {
@@ -265,8 +274,11 @@
                     mTouchActive = false;
                     mDownEvent = null;
                 }
-                if (mTouchCancelled || mExpandAnimationRunning) {
-                    return false;
+                if (mTouchCancelled) {
+                    return logDownDispatch(ev, "touch cancelled", false);
+                }
+                if (mExpandAnimationRunning) {
+                    return logDownDispatch(ev, "expand animation running", false);
                 }
 
                 if (mKeyguardUnlockAnimationController.isPlayingCannedUnlockAnimation()) {
@@ -280,17 +292,17 @@
                 }
 
                 if (mIsOcclusionTransitionRunning) {
-                    return false;
+                    return logDownDispatch(ev, "occlusion transition running", false);
                 }
 
                 mFalsingCollector.onTouchEvent(ev);
                 mPulsingWakeupGestureHandler.onTouchEvent(ev);
                 if (mDreamingWakeupGestureHandler != null
                         && mDreamingWakeupGestureHandler.onTouchEvent(ev)) {
-                    return true;
+                    return logDownDispatch(ev, "dream wakeup gesture handled", true);
                 }
                 if (mStatusBarKeyguardViewManager.dispatchTouchEvent(ev)) {
-                    return true;
+                    return logDownDispatch(ev, "dispatched to Keyguard", true);
                 }
                 if (mBrightnessMirror != null
                         && mBrightnessMirror.getVisibility() == View.VISIBLE) {
@@ -298,7 +310,7 @@
                     // 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;
+                        return logDownDispatch(ev, "disallowed new pointer", false);
                     }
                 }
                 if (isDown) {
@@ -329,7 +341,9 @@
                     expandingBelowNotch = true;
                 }
                 if (expandingBelowNotch) {
-                    return mStatusBarViewController.sendTouchToView(ev);
+                    return logDownDispatch(ev,
+                            "expand below notch. sending touch to status bar",
+                            mStatusBarViewController.sendTouchToView(ev));
                 }
 
                 if (!mIsTrackingBarGesture && isDown
@@ -339,9 +353,10 @@
                     if (mStatusBarViewController.touchIsWithinView(x, y)) {
                         if (mStatusBarWindowStateController.windowIsShowing()) {
                             mIsTrackingBarGesture = true;
-                            return mStatusBarViewController.sendTouchToView(ev);
-                        } else { // it's hidden or hiding, don't send to notification shade.
-                            return true;
+                            return logDownDispatch(ev, "sending touch to status bar",
+                                    mStatusBarViewController.sendTouchToView(ev));
+                        } else {
+                            return logDownDispatch(ev, "hidden or hiding", true);
                         }
                     }
                 } else if (mIsTrackingBarGesture) {
@@ -349,10 +364,10 @@
                     if (isUp || isCancel) {
                         mIsTrackingBarGesture = false;
                     }
-                    return sendToStatusBar;
+                    return logDownDispatch(ev, "sending bar gesture to status bar",
+                            sendToStatusBar);
                 }
-
-                return null;
+                return logDownDispatch(ev, "no custom touch dispatch of down event", null);
             }
 
             @Override
@@ -364,18 +379,26 @@
             public boolean shouldInterceptTouchEvent(MotionEvent ev) {
                 if (mStatusBarStateController.isDozing() && !mService.isPulsing()
                         && !mDockManager.isDocked()) {
-                    // Capture all touch events in always-on.
+                    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
+                        mShadeLogger.d("NSWVC: capture all touch events in always-on");
+                    }
                     return true;
                 }
 
                 if (mStatusBarKeyguardViewManager.shouldInterceptTouchEvent(ev)) {
                     // Don't allow touches to proceed to underlying views if alternate
                     // bouncer is showing
+                    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
+                        mShadeLogger.d("NSWVC: alt bouncer showing");
+                    }
                     return true;
                 }
 
                 if (mLockIconViewController.onInterceptTouchEvent(ev)) {
                     // immediately return true; don't send the touch to the drag down helper
+                    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
+                        mShadeLogger.d("NSWVC: don't send touch to drag down helper");
+                    }
                     return true;
                 }
 
@@ -383,7 +406,13 @@
                         && mDragDownHelper.isDragDownEnabled()
                         && !mService.isBouncerShowing()
                         && !mStatusBarStateController.isDozing()) {
-                    return mDragDownHelper.onInterceptTouchEvent(ev);
+                    boolean result = mDragDownHelper.onInterceptTouchEvent(ev);
+                    if (result) {
+                        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
+                            mShadeLogger.d("NSWVC: drag down helper intercepted");
+                        }
+                    }
+                    return result;
                 } else {
                     return false;
                 }
@@ -495,6 +524,7 @@
     }
 
     public void cancelCurrentTouch() {
+        mShadeLogger.d("NSWVC: cancelling current touch");
         if (mTouchActive) {
             final long now = mClock.uptimeMillis();
             final MotionEvent event;
@@ -508,6 +538,7 @@
                         MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
                 event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
             }
+            Log.w(TAG, "Canceling current touch event (should be very rare)");
             mView.dispatchTouchEvent(event);
             event.recycle();
             mTouchCancelled = true;
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationsQuickSettingsContainer.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationsQuickSettingsContainer.java
index 3b3df50..a4e439b 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationsQuickSettingsContainer.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationsQuickSettingsContainer.java
@@ -22,6 +22,7 @@
 import android.graphics.Canvas;
 import android.graphics.Rect;
 import android.util.AttributeSet;
+import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup.MarginLayoutParams;
 import android.view.WindowInsets;
@@ -183,6 +184,12 @@
     }
 
     @Override
+    public boolean dispatchTouchEvent(MotionEvent ev) {
+        return TouchLogger.logDispatchTouch("NotificationsQuickSettingsContainer", ev,
+                super.dispatchTouchEvent(ev));
+    }
+
+    @Override
     protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
         if (mIsMigratingNSSL) {
             return super.drawChild(canvas, child, drawingTime);
diff --git a/packages/SystemUI/src/com/android/systemui/shade/QuickSettingsController.java b/packages/SystemUI/src/com/android/systemui/shade/QuickSettingsController.java
index baac57c..c9c911b 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/QuickSettingsController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/QuickSettingsController.java
@@ -787,6 +787,12 @@
 
     /** update Qs height state */
     public void setExpansionHeight(float height) {
+        // TODO(b/277909752): remove below log when bug is fixed
+        if (mSplitShadeEnabled && mShadeExpandedFraction == 1.0f && height == 0) {
+            Log.wtf(TAG,
+                    "setting QS height to 0 in split shade while shade is open(ing). "
+                            + "Value of mExpandImmediate = " + mExpandImmediate);
+        }
         int maxHeight = getMaxExpansionHeight();
         height = Math.min(Math.max(
                 height, getMinExpansionHeight()), maxHeight);
@@ -933,7 +939,6 @@
         return mShadeExpandedHeight;
     }
 
-    @VisibleForTesting
     void setExpandImmediate(boolean expandImmediate) {
         if (expandImmediate != mExpandImmediate) {
             mShadeLog.logQsExpandImmediateChanged(expandImmediate);
@@ -1011,6 +1016,7 @@
                 && mPanelViewControllerLazy.get().mAnimateBack) {
             mPanelViewControllerLazy.get().adjustBackAnimationScale(adjustedExpansionFraction);
         }
+        mShadeExpansionStateManager.onQsExpansionFractionChanged(qsExpansionFraction);
         mMediaHierarchyManager.setQsExpansion(qsExpansionFraction);
         int qsPanelBottomY = calculateBottomPosition(qsExpansionFraction);
         mScrimController.setQsPosition(qsExpansionFraction, qsPanelBottomY);
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerImpl.java b/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerImpl.java
index 22c63817..d7a3392 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerImpl.java
@@ -27,6 +27,8 @@
 import com.android.systemui.assist.AssistManager;
 import com.android.systemui.dagger.SysUISingleton;
 import com.android.systemui.dagger.qualifiers.Main;
+import com.android.systemui.log.LogBuffer;
+import com.android.systemui.log.dagger.ShadeTouchLog;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.CommandQueue;
 import com.android.systemui.statusbar.NotificationPresenter;
@@ -56,6 +58,7 @@
 
     private final CommandQueue mCommandQueue;
     private final Executor mMainExecutor;
+    private final LogBuffer mTouchLog;
     private final KeyguardStateController mKeyguardStateController;
     private final NotificationShadeWindowController mNotificationShadeWindowController;
     private final StatusBarStateController mStatusBarStateController;
@@ -79,6 +82,7 @@
     public ShadeControllerImpl(
             CommandQueue commandQueue,
             @Main Executor mainExecutor,
+            @ShadeTouchLog LogBuffer touchLog,
             KeyguardStateController keyguardStateController,
             StatusBarStateController statusBarStateController,
             StatusBarKeyguardViewManager statusBarKeyguardViewManager,
@@ -92,6 +96,7 @@
     ) {
         mCommandQueue = commandQueue;
         mMainExecutor = mainExecutor;
+        mTouchLog = touchLog;
         mShadeViewControllerLazy = shadeViewControllerLazy;
         mStatusBarStateController = statusBarStateController;
         mStatusBarWindowController = statusBarWindowController;
@@ -413,6 +418,7 @@
 
     @Override
     public void start() {
+        TouchLogger.logTouchesTo(mTouchLog);
         getShadeViewController().setTrackingStartedListener(this::runPostCollapseRunnables);
         getShadeViewController().setOpenCloseListener(
                 new OpenCloseListener() {
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeExpansionStateManager.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeExpansionStateManager.kt
index 2db47ae..0554c58 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeExpansionStateManager.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeExpansionStateManager.kt
@@ -38,6 +38,8 @@
     private val expansionListeners = CopyOnWriteArrayList<ShadeExpansionListener>()
     private val fullExpansionListeners = CopyOnWriteArrayList<ShadeFullExpansionListener>()
     private val qsExpansionListeners = CopyOnWriteArrayList<ShadeQsExpansionListener>()
+    private val qsExpansionFractionListeners =
+        CopyOnWriteArrayList<ShadeQsExpansionFractionListener>()
     private val stateListeners = CopyOnWriteArrayList<ShadeStateListener>()
     private val shadeStateEventsListeners = CopyOnWriteArrayList<ShadeStateEventsListener>()
 
@@ -45,6 +47,7 @@
     @FloatRange(from = 0.0, to = 1.0) private var fraction: Float = 0f
     private var expanded: Boolean = false
     private var qsExpanded: Boolean = false
+    private var qsExpansionFraction = 0f
     private var tracking: Boolean = false
     private var dragDownPxAmount: Float = 0f
 
@@ -82,6 +85,15 @@
         qsExpansionListeners.remove(listener)
     }
 
+    fun addQsExpansionFractionListener(listener: ShadeQsExpansionFractionListener) {
+        qsExpansionFractionListeners.add(listener)
+        listener.onQsExpansionFractionChanged(qsExpansionFraction)
+    }
+
+    fun removeQsExpansionFractionListener(listener: ShadeQsExpansionFractionListener) {
+        qsExpansionFractionListeners.remove(listener)
+    }
+
     /** Adds a listener that will be notified when the panel state has changed. */
     fun addStateListener(listener: ShadeStateListener) {
         stateListeners.add(listener)
@@ -175,6 +187,15 @@
         qsExpansionListeners.forEach { it.onQsExpansionChanged(qsExpanded) }
     }
 
+    fun onQsExpansionFractionChanged(qsExpansionFraction: Float) {
+        this.qsExpansionFraction = qsExpansionFraction
+
+        debugLog("qsExpansionFraction=$qsExpansionFraction")
+        qsExpansionFractionListeners.forEach {
+            it.onQsExpansionFractionChanged(qsExpansionFraction)
+        }
+    }
+
     fun onShadeExpansionFullyChanged(isExpanded: Boolean) {
         this.expanded = isExpanded
 
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeHeaderController.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeHeaderController.kt
index c6cb9c4..6564118 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeHeaderController.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeHeaderController.kt
@@ -130,12 +130,12 @@
     private lateinit var carrierIconSlots: List<String>
     private lateinit var mShadeCarrierGroupController: ShadeCarrierGroupController
 
-    private val batteryIcon: BatteryMeterView = header.findViewById(R.id.batteryRemainingIcon)
-    private val clock: Clock = header.findViewById(R.id.clock)
-    private val date: TextView = header.findViewById(R.id.date)
-    private val iconContainer: StatusIconContainer = header.findViewById(R.id.statusIcons)
-    private val mShadeCarrierGroup: ShadeCarrierGroup = header.findViewById(R.id.carrier_group)
-    private val systemIcons: View = header.findViewById(R.id.shade_header_system_icons)
+    private val batteryIcon: BatteryMeterView = header.requireViewById(R.id.batteryRemainingIcon)
+    private val clock: Clock = header.requireViewById(R.id.clock)
+    private val date: TextView = header.requireViewById(R.id.date)
+    private val iconContainer: StatusIconContainer = header.requireViewById(R.id.statusIcons)
+    private val mShadeCarrierGroup: ShadeCarrierGroup = header.requireViewById(R.id.carrier_group)
+    private val systemIcons: View = header.requireViewById(R.id.shade_header_system_icons)
 
     private var roundedCorners = 0
     private var cutout: DisplayCutout? = null
@@ -263,9 +263,11 @@
                     resources.getDimensionPixelSize(
                         R.dimen.shade_header_system_icons_padding_start
                     ),
-                    systemIcons.paddingTop,
+                    resources.getDimensionPixelSize(R.dimen.shade_header_system_icons_padding_top),
                     resources.getDimensionPixelSize(R.dimen.shade_header_system_icons_padding_end),
-                    systemIcons.paddingBottom
+                    resources.getDimensionPixelSize(
+                        R.dimen.shade_header_system_icons_padding_bottom
+                    )
                 )
             }
 
@@ -582,7 +584,7 @@
     inner class CustomizerAnimationListener(
         private val enteringCustomizing: Boolean,
     ) : AnimatorListenerAdapter() {
-        override fun onAnimationEnd(animation: Animator?) {
+        override fun onAnimationEnd(animation: Animator) {
             super.onAnimationEnd(animation)
             header.animate().setListener(null)
             if (enteringCustomizing) {
@@ -590,7 +592,7 @@
             }
         }
 
-        override fun onAnimationStart(animation: Animator?) {
+        override fun onAnimationStart(animation: Animator) {
             super.onAnimationStart(animation)
             if (!enteringCustomizing) {
                 customizing = false
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeLogger.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeLogger.kt
index 1c30bdd..8d23f5d 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeLogger.kt
@@ -79,19 +79,39 @@
 
     fun logMotionEvent(event: MotionEvent, message: String) {
         buffer.log(
-            TAG,
-            LogLevel.VERBOSE,
-            {
-                str1 = message
-                long1 = event.eventTime
-                long2 = event.downTime
-                int1 = event.action
-                int2 = event.classification
-                double1 = event.y.toDouble()
-            },
-            {
-                "$str1: eventTime=$long1,downTime=$long2,y=$double1,action=$int1,class=$int2"
-            }
+                TAG,
+                LogLevel.VERBOSE,
+                {
+                    str1 = message
+                    long1 = event.eventTime
+                    long2 = event.downTime
+                    int1 = event.action
+                    int2 = event.classification
+                },
+                {
+                    "$str1: eventTime=$long1,downTime=$long2,action=$int1,class=$int2"
+                }
+        )
+    }
+
+    /** Logs motion event dispatch results from NotificationShadeWindowViewController. */
+    fun logShadeWindowDispatch(event: MotionEvent, message: String, result: Boolean?) {
+        buffer.log(
+                TAG,
+                LogLevel.VERBOSE,
+                {
+                    str1 = message
+                    long1 = event.eventTime
+                    long2 = event.downTime
+                },
+                {
+                    val prefix = when (result) {
+                        true -> "SHADE TOUCH REROUTED"
+                        false -> "SHADE TOUCH BLOCKED"
+                        null -> "SHADE TOUCH DISPATCHED"
+                    }
+                    "$prefix: eventTime=$long1,downTime=$long2, reason=$str1"
+                }
         )
     }
 
@@ -316,6 +336,17 @@
         )
     }
 
+    fun logPanelStateChanged(@PanelState panelState: Int) {
+        buffer.log(
+            TAG,
+            LogLevel.VERBOSE,
+            {
+                str1 = panelState.panelStateToString()
+            },
+            { "New panel State: $str1" }
+        )
+    }
+
     fun flingQs(flingType: Int, isClick: Boolean) {
         buffer.log(
             TAG,
diff --git a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl b/packages/SystemUI/src/com/android/systemui/shade/ShadeQsExpansionFractionListener.kt
similarity index 60%
copy from core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl
copy to packages/SystemUI/src/com/android/systemui/shade/ShadeQsExpansionFractionListener.kt
index f6c47dd..c787f49 100644
--- a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeQsExpansionFractionListener.kt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2022 The Android Open Source Project
+ * Copyright (c) 2022 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,15 +14,10 @@
  * limitations under the License.
  */
 
-package android.service.selectiontoolbar;
+package com.android.systemui.shade
 
-import android.os.IBinder;
-
-/**
- * The interface from the SelectionToolbarRenderService to the system.
- *
- * @hide
- */
-oneway interface ISelectionToolbarRenderServiceCallback {
-    void transferTouch(in IBinder source, in IBinder target);
+/** A listener interface to be notified of expansion events for the quick settings panel. */
+fun interface ShadeQsExpansionFractionListener {
+    /** Invoked whenever the quick settings expansion fraction changes */
+    fun onQsExpansionFractionChanged(qsExpansionFraction: Float)
 }
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeViewController.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeViewController.kt
index d5b5c87..182a676 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeViewController.kt
@@ -248,6 +248,16 @@
     /** Starts tracking a shade expansion gesture that originated from the status bar. */
     fun startTrackingExpansionFromStatusBar()
 
+    /**
+     * Performs haptic feedback from a view with a haptic feedback constant.
+     *
+     * The implementation of this method should use the [android.view.View.performHapticFeedback]
+     * method with the provided constant.
+     *
+     * @param[constant] One of [android.view.HapticFeedbackConstants]
+     */
+    fun performHapticFeedback(constant: Int)
+
     // ******* End Keyguard Section *********
 
     /** Returns the ShadeHeadsUpTracker. */
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeViewControllerEmptyImpl.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeViewControllerEmptyImpl.kt
index 287ac52..09b74b2 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeViewControllerEmptyImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeViewControllerEmptyImpl.kt
@@ -86,6 +86,8 @@
         return false
     }
     override fun startTrackingExpansionFromStatusBar() {}
+    override fun performHapticFeedback(constant: Int) {}
+
     override val shadeHeadsUpTracker = ShadeHeadsUpTrackerEmptyImpl()
     override val shadeFoldAnimator = ShadeFoldAnimatorEmptyImpl()
 }
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeViewProviderModule.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeViewProviderModule.kt
index 2955118..05b1ac6 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeViewProviderModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeViewProviderModule.kt
@@ -106,7 +106,7 @@
             featureFlags: FeatureFlags,
         ): NotificationShadeWindowView {
             if (featureFlags.isEnabled(Flags.SCENE_CONTAINER)) {
-                return root.findViewById(R.id.legacy_window_root)
+                return root.requireViewById(R.id.legacy_window_root)
             }
             return root as NotificationShadeWindowView?
                 ?: throw IllegalStateException("root view not a NotificationShadeWindowView")
@@ -118,7 +118,7 @@
         fun providesNotificationStackScrollLayout(
             notificationShadeWindowView: NotificationShadeWindowView,
         ): NotificationStackScrollLayout {
-            return notificationShadeWindowView.findViewById(R.id.notification_stack_scroller)
+            return notificationShadeWindowView.requireViewById(R.id.notification_stack_scroller)
         }
 
         @Provides
@@ -153,7 +153,7 @@
         fun providesNotificationPanelView(
             notificationShadeWindowView: NotificationShadeWindowView,
         ): NotificationPanelView {
-            return notificationShadeWindowView.findViewById(R.id.notification_panel)
+            return notificationShadeWindowView.requireViewById(R.id.notification_panel)
         }
 
         /**
@@ -175,7 +175,7 @@
         fun providesLightRevealScrim(
             notificationShadeWindowView: NotificationShadeWindowView,
         ): LightRevealScrim {
-            return notificationShadeWindowView.findViewById(R.id.light_reveal_scrim)
+            return notificationShadeWindowView.requireViewById(R.id.light_reveal_scrim)
         }
 
         @Provides
@@ -183,7 +183,7 @@
         fun providesKeyguardRootView(
             notificationShadeWindowView: NotificationShadeWindowView,
         ): KeyguardRootView {
-            return notificationShadeWindowView.findViewById(R.id.keyguard_root_view)
+            return notificationShadeWindowView.requireViewById(R.id.keyguard_root_view)
         }
 
         @Provides
@@ -191,7 +191,7 @@
         fun providesSharedNotificationContainer(
             notificationShadeWindowView: NotificationShadeWindowView,
         ): SharedNotificationContainer {
-            return notificationShadeWindowView.findViewById(R.id.shared_notification_container)
+            return notificationShadeWindowView.requireViewById(R.id.shared_notification_container)
         }
 
         // TODO(b/277762009): Only allow this view's controller to inject the view. See above.
@@ -200,7 +200,7 @@
         fun providesAuthRippleView(
             notificationShadeWindowView: NotificationShadeWindowView,
         ): AuthRippleView? {
-            return notificationShadeWindowView.findViewById(R.id.auth_ripple)
+            return notificationShadeWindowView.requireViewById(R.id.auth_ripple)
         }
 
         // TODO(b/277762009): Only allow this view's controller to inject the view. See above.
@@ -212,9 +212,9 @@
             featureFlags: FeatureFlags
         ): LockIconView {
             if (featureFlags.isEnabled(Flags.MIGRATE_LOCK_ICON)) {
-                return keyguardRootView.findViewById(R.id.lock_icon_view)
+                return keyguardRootView.requireViewById(R.id.lock_icon_view)
             } else {
-                return notificationPanelView.findViewById(R.id.lock_icon_view)
+                return notificationPanelView.requireViewById(R.id.lock_icon_view)
             }
         }
 
@@ -224,7 +224,7 @@
         fun providesTapAgainView(
             notificationPanelView: NotificationPanelView,
         ): TapAgainView {
-            return notificationPanelView.findViewById(R.id.shade_falsing_tap_again)
+            return notificationPanelView.requireViewById(R.id.shade_falsing_tap_again)
         }
 
         // TODO(b/277762009): Only allow this view's controller to inject the view. See above.
@@ -233,7 +233,7 @@
         fun providesNotificationsQuickSettingsContainer(
             notificationShadeWindowView: NotificationShadeWindowView,
         ): NotificationsQuickSettingsContainer {
-            return notificationShadeWindowView.findViewById(R.id.notification_container_parent)
+            return notificationShadeWindowView.requireViewById(R.id.notification_container_parent)
         }
 
         // TODO(b/277762009): Only allow this view's controller to inject the view. See above.
@@ -243,7 +243,7 @@
         fun providesShadeHeaderView(
             notificationShadeWindowView: NotificationShadeWindowView,
         ): MotionLayout {
-            val stub = notificationShadeWindowView.findViewById<ViewStub>(R.id.qs_header_stub)
+            val stub = notificationShadeWindowView.requireViewById<ViewStub>(R.id.qs_header_stub)
             val layoutId = R.layout.combined_qs_header
             stub.layoutResource = layoutId
             return stub.inflate() as MotionLayout
@@ -260,7 +260,7 @@
         @SysUISingleton
         @Named(SHADE_HEADER)
         fun providesBatteryMeterView(@Named(SHADE_HEADER) view: MotionLayout): BatteryMeterView {
-            return view.findViewById(R.id.batteryRemainingIcon)
+            return view.requireViewById(R.id.batteryRemainingIcon)
         }
 
         @Provides
@@ -273,6 +273,7 @@
             tunerService: TunerService,
             @Main mainHandler: Handler,
             contentResolver: ContentResolver,
+            featureFlags: FeatureFlags,
             batteryController: BatteryController,
         ): BatteryMeterViewController {
             return BatteryMeterViewController(
@@ -283,6 +284,7 @@
                 tunerService,
                 mainHandler,
                 contentResolver,
+                featureFlags,
                 batteryController,
             )
         }
@@ -293,7 +295,7 @@
         fun providesOngoingPrivacyChip(
             @Named(SHADE_HEADER) header: MotionLayout,
         ): OngoingPrivacyChip {
-            return header.findViewById(R.id.privacy_chip)
+            return header.requireViewById(R.id.privacy_chip)
         }
 
         @Provides
@@ -302,7 +304,7 @@
         fun providesStatusIconContainer(
             @Named(SHADE_HEADER) header: MotionLayout,
         ): StatusIconContainer {
-            return header.findViewById(R.id.statusIcons)
+            return header.requireViewById(R.id.statusIcons)
         }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/shade/TouchLogger.kt b/packages/SystemUI/src/com/android/systemui/shade/TouchLogger.kt
new file mode 100644
index 0000000..58704bf
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/shade/TouchLogger.kt
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.shade
+
+import android.view.MotionEvent
+import com.android.systemui.log.LogBuffer
+import com.android.systemui.log.core.LogLevel
+
+private const val TAG = "systemui.shade.touch"
+
+/**
+ * A logger for tracking touch dispatching in the shade view hierarchy. The purpose of this logger
+ * is to passively observe dispatchTouchEvent calls in order to see which subtrees of the shade are
+ * handling touches. Additionally, some touches may be passively observed for views near the top of
+ * the shade hierarchy that cannot intercept touches, i.e. scrims. The usage of static methods for
+ * logging is sub-optimal in many ways, but it was selected in this case to make usage of this
+ * non-function diagnostic code as low friction as possible.
+ */
+class TouchLogger {
+    companion object {
+        private var touchLogger: DispatchTouchLogger? = null
+
+        @JvmStatic
+        fun logTouchesTo(buffer: LogBuffer) {
+            touchLogger = DispatchTouchLogger(buffer)
+        }
+
+        @JvmStatic
+        fun logDispatchTouch(viewTag: String, ev: MotionEvent, result: Boolean): Boolean {
+            touchLogger?.logDispatchTouch(viewTag, ev, result)
+            return result
+        }
+    }
+}
+
+/** Logs touches. */
+private class DispatchTouchLogger(private val buffer: LogBuffer) {
+    fun logDispatchTouch(viewTag: String, ev: MotionEvent, result: Boolean) {
+        // NOTE: never log position of touches for security purposes
+        buffer.log(
+            TAG,
+            LogLevel.DEBUG,
+            {
+                str1 = viewTag
+                int1 = ev.action
+                long1 = ev.downTime
+                bool1 = result
+            },
+            { "Touch: view=$str1, type=${typeToString(int1)}, downtime=$long1, result=$bool1" }
+        )
+    }
+
+    private fun typeToString(type: Int): String {
+        return when (type) {
+            MotionEvent.ACTION_DOWN -> "DOWN"
+            MotionEvent.ACTION_UP -> "UP"
+            MotionEvent.ACTION_MOVE -> "MOVE"
+            MotionEvent.ACTION_CANCEL -> "CANCEL"
+            MotionEvent.ACTION_POINTER_DOWN -> "POINTER_DOWN"
+            MotionEvent.ACTION_POINTER_UP -> "POINTER_UP"
+            else -> "OTHER"
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ui/viewmodel/ShadeSceneViewModel.kt b/packages/SystemUI/src/com/android/systemui/shade/ui/viewmodel/ShadeSceneViewModel.kt
index 0b3ed56..8edc26d 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ui/viewmodel/ShadeSceneViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ui/viewmodel/ShadeSceneViewModel.kt
@@ -16,15 +16,16 @@
 
 package com.android.systemui.shade.ui.viewmodel
 
+import com.android.systemui.authentication.domain.interactor.AuthenticationInteractor
+import com.android.systemui.bouncer.domain.interactor.BouncerInteractor
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
-import com.android.systemui.keyguard.domain.interactor.LockscreenSceneInteractor
 import com.android.systemui.scene.shared.model.SceneKey
 import javax.inject.Inject
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.flow.SharingStarted
 import kotlinx.coroutines.flow.StateFlow
-import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.combine
 import kotlinx.coroutines.flow.stateIn
 
 /** Models UI state and handles user input for the shade scene. */
@@ -33,29 +34,43 @@
 @Inject
 constructor(
     @Application private val applicationScope: CoroutineScope,
-    private val lockscreenSceneInteractor: LockscreenSceneInteractor,
+    authenticationInteractor: AuthenticationInteractor,
+    private val bouncerInteractor: BouncerInteractor,
 ) {
     /** The key of the scene we should switch to when swiping up. */
     val upDestinationSceneKey: StateFlow<SceneKey> =
-        lockscreenSceneInteractor.isDeviceLocked
-            .map { isLocked -> upDestinationSceneKey(isLocked = isLocked) }
+        combine(
+                authenticationInteractor.isUnlocked,
+                authenticationInteractor.canSwipeToDismiss,
+            ) { isUnlocked, canSwipeToDismiss ->
+                upDestinationSceneKey(
+                    isUnlocked = isUnlocked,
+                    canSwipeToDismiss = canSwipeToDismiss,
+                )
+            }
             .stateIn(
                 scope = applicationScope,
                 started = SharingStarted.WhileSubscribed(),
                 initialValue =
                     upDestinationSceneKey(
-                        isLocked = lockscreenSceneInteractor.isDeviceLocked.value,
+                        isUnlocked = authenticationInteractor.isUnlocked.value,
+                        canSwipeToDismiss = authenticationInteractor.canSwipeToDismiss.value,
                     ),
             )
 
     /** Notifies that some content in the shade was clicked. */
     fun onContentClicked() {
-        lockscreenSceneInteractor.dismissLockscreen()
+        bouncerInteractor.showOrUnlockDevice()
     }
 
     private fun upDestinationSceneKey(
-        isLocked: Boolean,
+        isUnlocked: Boolean,
+        canSwipeToDismiss: Boolean,
     ): SceneKey {
-        return if (isLocked) SceneKey.Lockscreen else SceneKey.Gone
+        return when {
+            canSwipeToDismiss -> SceneKey.Lockscreen
+            isUnlocked -> SceneKey.Gone
+            else -> SceneKey.Lockscreen
+        }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/ActionClickLogger.kt b/packages/SystemUI/src/com/android/systemui/statusbar/ActionClickLogger.kt
index d3c19b7..5042f1b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/ActionClickLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/ActionClickLogger.kt
@@ -31,56 +31,68 @@
 ) {
     fun logInitialClick(
         entry: NotificationEntry?,
+        index: Integer?,
         pendingIntent: PendingIntent
     ) {
         buffer.log(TAG, LogLevel.DEBUG, {
             str1 = entry?.key
             str2 = entry?.ranking?.channel?.id
-            str3 = pendingIntent.intent.toString()
+            str3 = pendingIntent.toString()
+            int1 = index?.toInt() ?: Int.MIN_VALUE
         }, {
-            "ACTION CLICK $str1 (channel=$str2) for pending intent $str3"
+            "ACTION CLICK $str1 (channel=$str2) for pending intent $str3 at index $int1"
         })
     }
 
     fun logRemoteInputWasHandled(
-        entry: NotificationEntry?
+        entry: NotificationEntry?,
+        index: Int?
     ) {
         buffer.log(TAG, LogLevel.DEBUG, {
             str1 = entry?.key
+            int1 = index ?: Int.MIN_VALUE
         }, {
-            "  [Action click] Triggered remote input (for $str1))"
+            "  [Action click] Triggered remote input (for $str1) at index $int1"
         })
     }
 
     fun logStartingIntentWithDefaultHandler(
         entry: NotificationEntry?,
-        pendingIntent: PendingIntent
+        pendingIntent: PendingIntent,
+        index: Int?
     ) {
         buffer.log(TAG, LogLevel.DEBUG, {
             str1 = entry?.key
-            str2 = pendingIntent.intent.toString()
+            str2 = pendingIntent.toString()
+            int1 = index ?: Int.MIN_VALUE
         }, {
-            "  [Action click] Launching intent $str2 via default handler (for $str1)"
+            "  [Action click] Launching intent $str2 via default handler (for $str1 at index $int1)"
         })
     }
 
     fun logWaitingToCloseKeyguard(
-        pendingIntent: PendingIntent
+        pendingIntent: PendingIntent,
+        index: Int?
     ) {
         buffer.log(TAG, LogLevel.DEBUG, {
-            str1 = pendingIntent.intent.toString()
+            str1 = pendingIntent.toString()
+            int1 = index ?: Int.MIN_VALUE
         }, {
-            "  [Action click] Intent $str1 launches an activity, dismissing keyguard first..."
+            "  [Action click] Intent $str1 at index $int1 launches an activity, dismissing " +
+                    "keyguard first..."
         })
     }
 
     fun logKeyguardGone(
-        pendingIntent: PendingIntent
+        pendingIntent: PendingIntent,
+        index: Int?
     ) {
         buffer.log(TAG, LogLevel.DEBUG, {
-            str1 = pendingIntent.intent.toString()
+            str1 = pendingIntent.toString()
+            int1 = index ?: Int.MIN_VALUE
         }, {
-            "  [Action click] Keyguard dismissed, calling default handler for intent $str1"
+            "  [Action click] Keyguard dismissed, calling default handler for intent $str1 at " +
+                    "index $int1"
         })
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/BatteryStatusChip.kt b/packages/SystemUI/src/com/android/systemui/statusbar/BatteryStatusChip.kt
index 37140ec..5209767 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/BatteryStatusChip.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/BatteryStatusChip.kt
@@ -37,8 +37,8 @@
 
     init {
         inflate(context, R.layout.battery_status_chip, this)
-        roundedContainer = findViewById(R.id.rounded_container)
-        batteryMeterView = findViewById(R.id.battery_meter_view)
+        roundedContainer = requireViewById(R.id.rounded_container)
+        batteryMeterView = requireViewById(R.id.battery_meter_view)
         updateResources()
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/LightRevealScrim.kt b/packages/SystemUI/src/com/android/systemui/statusbar/LightRevealScrim.kt
index 823bb35..3120128 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/LightRevealScrim.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/LightRevealScrim.kt
@@ -14,9 +14,11 @@
 import android.os.Trace
 import android.util.AttributeSet
 import android.util.MathUtils.lerp
+import android.view.MotionEvent
 import android.view.View
 import android.view.animation.PathInterpolator
 import com.android.app.animation.Interpolators
+import com.android.systemui.shade.TouchLogger
 import com.android.systemui.statusbar.LightRevealEffect.Companion.getPercentPastThreshold
 import com.android.systemui.util.getColorWithAlpha
 import com.android.systemui.util.leak.RotationUtils
@@ -234,6 +236,8 @@
     }
 }
 
+private const val TAG = "LightRevealScrim"
+
 /**
  * Scrim view that partially reveals the content underneath it using a [RadialGradient] with a
  * transparent center. The center position, size, and stops of the gradient can be manipulated to
@@ -419,15 +423,14 @@
         revealGradientCenter.y = top + (revealGradientHeight / 2f)
     }
 
-    override fun onDraw(canvas: Canvas?) {
+    override fun onDraw(canvas: Canvas) {
         if (
-            canvas == null ||
-                revealGradientWidth <= 0 ||
-                revealGradientHeight <= 0 ||
-                revealAmount == 0f
+            revealGradientWidth <= 0 ||
+            revealGradientHeight <= 0 ||
+            revealAmount == 0f
         ) {
             if (revealAmount < 1f) {
-                canvas?.drawColor(revealGradientEndColor)
+                canvas.drawColor(revealGradientEndColor)
             }
             return
         }
@@ -447,6 +450,10 @@
         canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), gradientPaint)
     }
 
+    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
+        return TouchLogger.logDispatchTouch(TAG, event, super.dispatchTouchEvent(event))
+    }
+
     private fun setPaintColorFilter() {
         gradientPaint.colorFilter =
             PorterDuffColorFilter(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt
index 4710574..672796a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt
@@ -474,7 +474,7 @@
         }
         if (endlistener != null) {
             dragDownAnimator.addListener(object : AnimatorListenerAdapter() {
-                override fun onAnimationEnd(animation: Animator?) {
+                override fun onAnimationEnd(animation: Animator) {
                     endlistener.invoke()
                 }
             })
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/MediaArtworkProcessor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/MediaArtworkProcessor.kt
index 750272d..17b4e3b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/MediaArtworkProcessor.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/MediaArtworkProcessor.kt
@@ -66,7 +66,7 @@
                 inBitmap = oldIn.copy(Bitmap.Config.ARGB_8888, false /* isMutable */)
                 oldIn.recycle()
             }
-            val outBitmap = Bitmap.createBitmap(inBitmap.width, inBitmap.height,
+            val outBitmap = Bitmap.createBitmap(inBitmap?.width ?: 0, inBitmap?.height ?: 0,
                     Bitmap.Config.ARGB_8888)
 
             input = Allocation.createFromBitmap(renderScript, inBitmap,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationClickNotifier.kt b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationClickNotifier.kt
index abf81c5..692a997 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationClickNotifier.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationClickNotifier.kt
@@ -2,10 +2,12 @@
 
 import android.app.Notification
 import android.os.RemoteException
+import android.util.Log
 import com.android.internal.statusbar.IStatusBarService
 import com.android.internal.statusbar.NotificationVisibility
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.dagger.qualifiers.UiBackground
 import com.android.systemui.util.Assert
 import java.util.concurrent.Executor
 import javax.inject.Inject
@@ -21,7 +23,8 @@
 @SysUISingleton
 public class NotificationClickNotifier @Inject constructor(
     val barService: IStatusBarService,
-    @Main val mainExecutor: Executor
+    @Main val mainExecutor: Executor,
+    @UiBackground val backgroundExecutor: Executor
 ) {
     val listeners = mutableListOf<NotificationInteractionListener>()
 
@@ -48,13 +51,14 @@
         visibility: NotificationVisibility,
         generatedByAssistant: Boolean
     ) {
-        try {
-            barService.onNotificationActionClick(
-                    key, actionIndex, action, visibility, generatedByAssistant)
-        } catch (e: RemoteException) {
-            // nothing
+        backgroundExecutor.execute {
+            try {
+                barService.onNotificationActionClick(
+                        key, actionIndex, action, visibility, generatedByAssistant)
+            } catch (e: RemoteException) {
+                // nothing
+            }
         }
-
         mainExecutor.execute {
             notifyListenersAboutInteraction(key)
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationRemoteInputManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationRemoteInputManager.java
index da84afe..8089fd9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationRemoteInputManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationRemoteInputManager.java
@@ -119,11 +119,14 @@
             mPowerInteractor.wakeUpIfDozing(
                     "NOTIFICATION_CLICK", PowerManager.WAKE_REASON_GESTURE);
 
+            Integer actionIndex = (Integer)
+                    view.getTag(com.android.internal.R.id.notification_action_index_tag);
+
             final NotificationEntry entry = getNotificationForParent(view.getParent());
-            mLogger.logInitialClick(entry, pendingIntent);
+            mLogger.logInitialClick(entry, actionIndex, pendingIntent);
 
             if (handleRemoteInput(view, pendingIntent)) {
-                mLogger.logRemoteInputWasHandled(entry);
+                mLogger.logRemoteInputWasHandled(entry, actionIndex);
                 return true;
             }
 
@@ -141,9 +144,9 @@
             }
             Notification.Action action = getActionFromView(view, entry, pendingIntent);
             return mCallback.handleRemoteViewClick(view, pendingIntent,
-                    action == null ? false : action.isAuthenticationRequired(), () -> {
+                    action == null ? false : action.isAuthenticationRequired(), actionIndex, () -> {
                     Pair<Intent, ActivityOptions> options = response.getLaunchOptions(view);
-                    mLogger.logStartingIntentWithDefaultHandler(entry, pendingIntent);
+                    mLogger.logStartingIntentWithDefaultHandler(entry, pendingIntent, actionIndex);
                     boolean started = RemoteViews.startPendingIntent(view, pendingIntent, options);
                     if (started) releaseNotificationIfKeptForRemoteInputHistory(entry);
                     return started;
@@ -692,11 +695,13 @@
          * @param view
          * @param pendingIntent
          * @param appRequestedAuth
+         * @param actionIndex
          * @param defaultHandler
          * @return  true iff the click was handled
          */
         boolean handleRemoteViewClick(View view, PendingIntent pendingIntent,
-                boolean appRequestedAuth, ClickHandler defaultHandler);
+                boolean appRequestedAuth, @Nullable Integer actionIndex,
+                ClickHandler defaultHandler);
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
index b624115..59c63aa 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
@@ -272,7 +272,7 @@
                             blurUtils.blurRadiusOfRatio(animation.animatedValue as Float)
                 }
                 addListener(object : AnimatorListenerAdapter() {
-                    override fun onAnimationEnd(animation: Animator?) {
+                    override fun onAnimationEnd(animation: Animator) {
                         keyguardAnimator = null
                         wakeAndUnlockBlurRadius = 0f
                     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java
index d6a14604..6dd24ea 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java
@@ -48,8 +48,10 @@
 import com.android.internal.jank.InteractionJankMonitor;
 import com.android.internal.jank.InteractionJankMonitor.Configuration;
 import com.android.internal.logging.UiEventLogger;
+import com.android.keyguard.KeyguardClockSwitch;
 import com.android.systemui.DejankUtils;
 import com.android.systemui.Dumpable;
+import com.android.systemui.R;
 import com.android.systemui.dagger.SysUISingleton;
 import com.android.systemui.dump.DumpManager;
 import com.android.systemui.plugins.statusbar.StatusBarStateController.StateListener;
@@ -420,6 +422,25 @@
         }
     }
 
+    /** Returns the id of the currently rendering clock */
+    public String getClockId() {
+        if (mView == null) {
+            return KeyguardClockSwitch.MISSING_CLOCK_ID;
+        }
+
+        View clockSwitch = mView.findViewById(R.id.keyguard_clock_container);
+        if (clockSwitch == null) {
+            Log.e(TAG, "Clock container was missing");
+            return KeyguardClockSwitch.MISSING_CLOCK_ID;
+        }
+        if (!(clockSwitch instanceof KeyguardClockSwitch)) {
+            Log.e(TAG, "Clock container was incorrect type: " + clockSwitch);
+            return KeyguardClockSwitch.MISSING_CLOCK_ID;
+        }
+
+        return ((KeyguardClockSwitch) clockSwitch).getClockId();
+    }
+
     private void beginInteractionJankMonitor() {
         final boolean shouldPost =
                 (mIsDozing && mDozeAmount == 0) || (!mIsDozing && mDozeAmount == 1);
@@ -429,6 +450,7 @@
                         Choreographer.CALLBACK_ANIMATION, this::beginInteractionJankMonitor, null);
             } else {
                 Configuration.Builder builder = Configuration.Builder.withView(getCujType(), mView)
+                        .setTag(getClockId())
                         .setDeferMonitorForAnimationStart(false);
                 mInteractionJankMonitor.begin(builder);
             }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/events/PrivacyDotViewController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/events/PrivacyDotViewController.kt
index eddb683..d1e0a71 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/events/PrivacyDotViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/events/PrivacyDotViewController.kt
@@ -234,7 +234,7 @@
             }
 
             // Set the dot's view gravity to hug the status bar
-            (corner.findViewById<View>(R.id.privacy_dot)
+            (corner.requireViewById<View>(R.id.privacy_dot)
                     .layoutParams as FrameLayout.LayoutParams)
                         .gravity = rotatedCorner.innerGravity()
         }
@@ -255,7 +255,7 @@
         // in every rotation. The only thing we need to check is rtl
         val rtl = state.layoutRtl
         val size = Point()
-        tl.context.display.getRealSize(size)
+        tl.context.display?.getRealSize(size)
         val currentRotation = RotationUtils.getExactRotation(tl.context)
 
         val displayWidth: Int
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventChipAnimationController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventChipAnimationController.kt
index 6e8b8bd..1ad4620 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventChipAnimationController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventChipAnimationController.kt
@@ -168,10 +168,8 @@
         }
 
         val keyFrame1Height = dotSize * 2
-        val v = currentAnimatedView!!.view
-        val chipVerticalCenter = v.top + v.measuredHeight / 2
-        val height1 = ValueAnimator.ofInt(
-                currentAnimatedView!!.view.measuredHeight, keyFrame1Height).apply {
+        val chipVerticalCenter = chipBounds.top + chipBounds.height() / 2
+        val height1 = ValueAnimator.ofInt(chipBounds.height(), keyFrame1Height).apply {
             startDelay = 8.frames
             duration = 6.frames
             interpolator = STATUS_CHIP_HEIGHT_TO_DOT_KEYFRAME_1
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventCoordinator.kt
index 23edf17..2403920 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventCoordinator.kt
@@ -164,7 +164,9 @@
         }
 
         private fun isChipAnimationEnabled(): Boolean {
-            return DeviceConfig.getBoolean(NAMESPACE_PRIVACY, CHIP_ANIMATION_ENABLED, true)
+            val defaultValue =
+                context.resources.getBoolean(R.bool.config_enablePrivacyChipAnimation)
+            return DeviceConfig.getBoolean(NAMESPACE_PRIVACY, CHIP_ANIMATION_ENABLED, defaultValue)
         }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImpl.kt
index 6fc715a..f40f570 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImpl.kt
@@ -170,19 +170,19 @@
         // Set hasPersistentDot to false. If the animationState is anything before ANIMATING_OUT,
         // the disappear animation will not animate into a dot but remove the chip entirely
         hasPersistentDot = false
-        // if we are currently showing a persistent dot, hide it
-        if (animationState.value == SHOWING_PERSISTENT_DOT) notifyHidePersistentDot()
-        // if we are currently animating into a dot, wait for the animation to finish and then hide
-        // the dot
-        if (animationState.value == ANIMATING_OUT) {
-            coroutineScope.launch {
-                withTimeout(DISAPPEAR_ANIMATION_DURATION) {
-                    animationState.first {
-                        it == SHOWING_PERSISTENT_DOT || it == IDLE || it == ANIMATION_QUEUED
-                    }
-                    notifyHidePersistentDot()
-                }
+
+        if (animationState.value == SHOWING_PERSISTENT_DOT) {
+            // if we are currently showing a persistent dot, hide it and update the animationState
+            notifyHidePersistentDot()
+            if (scheduledEvent.value != null) {
+                animationState.value = ANIMATION_QUEUED
+            } else {
+                animationState.value = IDLE
             }
+        } else if (animationState.value == ANIMATING_OUT) {
+            // if we are currently animating out, hide the dot. The animationState will be updated
+            // once the animation has ended in the onAnimationEnd callback
+            notifyHidePersistentDot()
         }
     }
 
@@ -243,7 +243,7 @@
         if (!event.showAnimation && event.forceVisible) {
             // If animations are turned off, we'll transition directly to the dot
             animationState.value = SHOWING_PERSISTENT_DOT
-            notifyTransitionToPersistentDot()
+            notifyTransitionToPersistentDot(event)
             return
         }
 
@@ -335,7 +335,7 @@
         }
         animators.add(chipAnimationController.onSystemEventAnimationFinish(hasPersistentDot))
         if (hasPersistentDot) {
-            val dotAnim = notifyTransitionToPersistentDot()
+            val dotAnim = notifyTransitionToPersistentDot(currentlyDisplayedEvent)
             if (dotAnim != null) {
                 animators.add(dotAnim)
             }
@@ -344,12 +344,12 @@
         return AnimatorSet().also { it.playTogether(animators) }
     }
 
-    private fun notifyTransitionToPersistentDot(): Animator? {
+    private fun notifyTransitionToPersistentDot(event: StatusEvent?): Animator? {
         logger?.logTransitionToPersistentDotCallbackInvoked()
         val anims: List<Animator> =
             listeners.mapNotNull {
                 it.onSystemStatusAnimationTransitionToPersistentDot(
-                    currentlyDisplayedEvent?.contentDescription
+                    event?.contentDescription
                 )
             }
         if (anims.isNotEmpty()) {
@@ -366,14 +366,6 @@
         logger?.logHidePersistentDotCallbackInvoked()
         val anims: List<Animator> = listeners.mapNotNull { it.onHidePersistentDot() }
 
-        if (animationState.value == SHOWING_PERSISTENT_DOT) {
-            if (scheduledEvent.value != null) {
-                animationState.value = ANIMATION_QUEUED
-            } else {
-                animationState.value = IDLE
-            }
-        }
-
         if (anims.isNotEmpty()) {
             val aSet = AnimatorSet()
             aSet.playTogether(anims)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt
index 94251ff..6346111 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt
@@ -179,15 +179,20 @@
         }
         if (weatherTarget != null) {
             val clickIntent = weatherTarget.headerAction?.intent
-            val weatherData = WeatherData.fromBundle(weatherTarget.baseAction.extras, { v ->
-                if (!falsingManager.isFalseTap(FalsingManager.LOW_PENALTY)) {
-                    activityStarter.startActivity(
-                        clickIntent,
-                        true, /* dismissShade */
-                        null,
-                        false)
+            val weatherData = weatherTarget.baseAction?.extras?.let { extras ->
+                WeatherData.fromBundle(
+                    extras,
+                ) { _ ->
+                    if (!falsingManager.isFalseTap(FalsingManager.LOW_PENALTY)) {
+                        activityStarter.startActivity(
+                            clickIntent,
+                            true, /* dismissShade */
+                            null,
+                            false)
+                    }
                 }
-            })
+            }
+
             if (weatherData != null) {
                 keyguardUpdateMonitor.sendWeatherData(weatherData)
             }
@@ -446,6 +451,12 @@
         session?.requestSmartspaceUpdate()
     }
 
+    fun removeViewsFromParent(viewGroup: ViewGroup) {
+        smartspaceViews.toList().forEach {
+            viewGroup.removeView(it as View)
+        }
+    }
+
     /**
      * Disconnects the smartspace view from the smartspace service and cleans up any resources.
      */
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/OWNERS b/packages/SystemUI/src/com/android/systemui/statusbar/notification/OWNERS
index ed80f33..5558ab1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/OWNERS
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/OWNERS
@@ -2,13 +2,17 @@
 
 # Bug component: 78010
 
-aaliomer@google.com
+aioana@google.com
 aroederer@google.com
+iyz@google.com
 jeffdq@google.com
 juliacr@google.com
 juliatuttle@google.com
+kurucz@google.com
+liuyining@google.com
 lynhan@google.com
-steell@google.com
+matiashe@google.com
+valiiftime@google.com
 yurilin@google.com
 
 per-file MediaNotificationProcessor.java = ethibodeau@google.com, asc@google.com
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/ViewGroupFadeHelper.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/ViewGroupFadeHelper.kt
index 16f1a45..1b43922 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/ViewGroupFadeHelper.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/ViewGroupFadeHelper.kt
@@ -74,7 +74,7 @@
                     root.setTag(R.id.view_group_fade_helper_previous_value_tag, newAlpha)
                 }
                 addListener(object : AnimatorListenerAdapter() {
-                    override fun onAnimationEnd(animation: Animator?) {
+                    override fun onAnimationEnd(animation: Animator) {
                         endRunnable?.run()
                     }
                 })
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
index 5c72731..e763797 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
@@ -99,6 +99,7 @@
 import com.android.systemui.statusbar.notification.collection.notifcollection.RankingUpdatedEvent;
 import com.android.systemui.statusbar.notification.collection.provider.NotificationDismissibilityProvider;
 import com.android.systemui.util.Assert;
+import com.android.systemui.util.NamedListenerSet;
 import com.android.systemui.util.time.SystemClock;
 
 import java.io.PrintWriter;
@@ -161,7 +162,8 @@
     private final HashMap<String, FutureDismissal> mFutureDismissals = new HashMap<>();
 
     @Nullable private CollectionReadyForBuildListener mBuildListener;
-    private final List<NotifCollectionListener> mNotifCollectionListeners = new ArrayList<>();
+    private final NamedListenerSet<NotifCollectionListener>
+            mNotifCollectionListeners = new NamedListenerSet<>();
     private final List<NotifLifetimeExtender> mLifetimeExtenders = new ArrayList<>();
     private final List<NotifDismissInterceptor> mDismissInterceptors = new ArrayList<>();
 
@@ -236,7 +238,7 @@
     /** @see NotifPipeline#addCollectionListener(NotifCollectionListener) */
     void addCollectionListener(NotifCollectionListener listener) {
         Assert.isMainThread();
-        mNotifCollectionListeners.add(listener);
+        mNotifCollectionListeners.addIfAbsent(listener);
     }
 
     /** @see NotifPipeline#removeCollectionListener(NotifCollectionListener) */
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifLiveDataStoreImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifLiveDataStoreImpl.kt
index d95d593..5acc50a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifLiveDataStoreImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifLiveDataStoreImpl.kt
@@ -21,7 +21,6 @@
 import com.android.systemui.dagger.qualifiers.Main
 import com.android.systemui.util.Assert
 import com.android.systemui.util.ListenerSet
-import com.android.systemui.util.isNotEmpty
 import com.android.systemui.util.traceSection
 import java.util.Collections.unmodifiableList
 import java.util.concurrent.Executor
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipelineChoreographer.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipelineChoreographer.kt
index 4ebf337..ad22c61 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipelineChoreographer.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipelineChoreographer.kt
@@ -51,7 +51,7 @@
 object NotifPipelineChoreographerModule
 
 @Module
-private interface PrivateModule {
+interface PrivateModule {
     @Binds
     fun bindChoreographer(impl: NotifPipelineChoreographerImpl): NotifPipelineChoreographer
 }
@@ -59,7 +59,7 @@
 private const val TIMEOUT_MS: Long = 100
 
 @SysUISingleton
-private class NotifPipelineChoreographerImpl @Inject constructor(
+class NotifPipelineChoreographerImpl @Inject constructor(
     private val viewChoreographer: Choreographer,
     @Main private val executor: DelayableExecutor
 ) : NotifPipelineChoreographer {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java
index 0205523..240ae0c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java
@@ -69,6 +69,7 @@
 import com.android.systemui.statusbar.notification.collection.notifcollection.CollectionReadyForBuildListener;
 import com.android.systemui.statusbar.notification.stack.NotificationPriorityBucketKt;
 import com.android.systemui.util.Assert;
+import com.android.systemui.util.NamedListenerSet;
 import com.android.systemui.util.time.SystemClock;
 
 import java.io.PrintWriter;
@@ -121,14 +122,14 @@
     private final List<NotifSection> mNotifSections = new ArrayList<>();
     private NotifStabilityManager mNotifStabilityManager;
 
-    private final List<OnBeforeTransformGroupsListener> mOnBeforeTransformGroupsListeners =
-            new ArrayList<>();
-    private final List<OnBeforeSortListener> mOnBeforeSortListeners =
-            new ArrayList<>();
-    private final List<OnBeforeFinalizeFilterListener> mOnBeforeFinalizeFilterListeners =
-            new ArrayList<>();
-    private final List<OnBeforeRenderListListener> mOnBeforeRenderListListeners =
-            new ArrayList<>();
+    private final NamedListenerSet<OnBeforeTransformGroupsListener>
+            mOnBeforeTransformGroupsListeners = new NamedListenerSet<>();
+    private final NamedListenerSet<OnBeforeSortListener>
+            mOnBeforeSortListeners = new NamedListenerSet<>();
+    private final NamedListenerSet<OnBeforeFinalizeFilterListener>
+            mOnBeforeFinalizeFilterListeners = new NamedListenerSet<>();
+    private final NamedListenerSet<OnBeforeRenderListListener>
+            mOnBeforeRenderListListeners = new NamedListenerSet<>();
     @Nullable private OnRenderListListener mOnRenderListListener;
 
     private List<ListEntry> mReadOnlyNotifList = Collections.unmodifiableList(mNotifList);
@@ -184,28 +185,28 @@
         Assert.isMainThread();
 
         mPipelineState.requireState(STATE_IDLE);
-        mOnBeforeTransformGroupsListeners.add(listener);
+        mOnBeforeTransformGroupsListeners.addIfAbsent(listener);
     }
 
     void addOnBeforeSortListener(OnBeforeSortListener listener) {
         Assert.isMainThread();
 
         mPipelineState.requireState(STATE_IDLE);
-        mOnBeforeSortListeners.add(listener);
+        mOnBeforeSortListeners.addIfAbsent(listener);
     }
 
     void addOnBeforeFinalizeFilterListener(OnBeforeFinalizeFilterListener listener) {
         Assert.isMainThread();
 
         mPipelineState.requireState(STATE_IDLE);
-        mOnBeforeFinalizeFilterListeners.add(listener);
+        mOnBeforeFinalizeFilterListeners.addIfAbsent(listener);
     }
 
     void addOnBeforeRenderListListener(OnBeforeRenderListListener listener) {
         Assert.isMainThread();
 
         mPipelineState.requireState(STATE_IDLE);
-        mOnBeforeRenderListListeners.add(listener);
+        mOnBeforeRenderListListeners.addIfAbsent(listener);
     }
 
     void addPreRenderInvalidator(Invalidator invalidator) {
@@ -496,7 +497,9 @@
                     mTempSectionMembers.add(entry);
                 }
             }
+            Trace.beginSection(section.getLabel());
             section.getSectioner().onEntriesUpdated(mTempSectionMembers);
+            Trace.endSection();
             mTempSectionMembers.clear();
         }
         Trace.endSection();
@@ -1430,33 +1433,33 @@
 
     private void dispatchOnBeforeTransformGroups(List<ListEntry> entries) {
         Trace.beginSection("ShadeListBuilder.dispatchOnBeforeTransformGroups");
-        for (int i = 0; i < mOnBeforeTransformGroupsListeners.size(); i++) {
-            mOnBeforeTransformGroupsListeners.get(i).onBeforeTransformGroups(entries);
-        }
+        mOnBeforeTransformGroupsListeners.forEachTraced(listener -> {
+            listener.onBeforeTransformGroups(entries);
+        });
         Trace.endSection();
     }
 
     private void dispatchOnBeforeSort(List<ListEntry> entries) {
         Trace.beginSection("ShadeListBuilder.dispatchOnBeforeSort");
-        for (int i = 0; i < mOnBeforeSortListeners.size(); i++) {
-            mOnBeforeSortListeners.get(i).onBeforeSort(entries);
-        }
+        mOnBeforeSortListeners.forEachTraced(listener -> {
+            listener.onBeforeSort(entries);
+        });
         Trace.endSection();
     }
 
     private void dispatchOnBeforeFinalizeFilter(List<ListEntry> entries) {
         Trace.beginSection("ShadeListBuilder.dispatchOnBeforeFinalizeFilter");
-        for (int i = 0; i < mOnBeforeFinalizeFilterListeners.size(); i++) {
-            mOnBeforeFinalizeFilterListeners.get(i).onBeforeFinalizeFilter(entries);
-        }
+        mOnBeforeFinalizeFilterListeners.forEachTraced(listener -> {
+            listener.onBeforeFinalizeFilter(entries);
+        });
         Trace.endSection();
     }
 
     private void dispatchOnBeforeRenderList(List<ListEntry> entries) {
         Trace.beginSection("ShadeListBuilder.dispatchOnBeforeRenderList");
-        for (int i = 0; i < mOnBeforeRenderListListeners.size(); i++) {
-            mOnBeforeRenderListListeners.get(i).onBeforeRenderList(entries);
-        }
+        mOnBeforeRenderListListeners.forEachTraced(listener -> {
+            listener.onBeforeRenderList(entries);
+        });
         Trace.endSection();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/AppOpsCoordinator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/AppOpsCoordinator.java
deleted file mode 100644
index f04b24e..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/AppOpsCoordinator.java
+++ /dev/null
@@ -1,130 +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.systemui.statusbar.notification.collection.coordinator;
-
-import static android.app.NotificationManager.IMPORTANCE_MIN;
-
-import android.app.Notification;
-import android.service.notification.StatusBarNotification;
-
-import com.android.systemui.ForegroundServiceController;
-import com.android.systemui.appops.AppOpsController;
-import com.android.systemui.dagger.qualifiers.Main;
-import com.android.systemui.statusbar.notification.collection.ListEntry;
-import com.android.systemui.statusbar.notification.collection.NotifPipeline;
-import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.notification.collection.coordinator.dagger.CoordinatorScope;
-import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifFilter;
-import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifSectioner;
-import com.android.systemui.statusbar.notification.stack.NotificationPriorityBucketKt;
-import com.android.systemui.util.concurrency.DelayableExecutor;
-
-import javax.inject.Inject;
-
-/**
- * Handles ForegroundService and AppOp interactions with notifications.
- *  Tags notifications with appOps
- *  Lifetime extends notifications associated with an ongoing ForegroundService.
- *  Filters out notifications that represent foreground services that are no longer running
- *  Puts foreground service notifications into the FGS section. See {@link NotifCoordinators} for
- *      section ordering priority.
- *
- * Previously this logic lived in
- *  frameworks/base/packages/SystemUI/src/com/android/systemui/ForegroundServiceController
- *  frameworks/base/packages/SystemUI/src/com/android/systemui/ForegroundServiceNotificationListener
- *  frameworks/base/packages/SystemUI/src/com/android/systemui/ForegroundServiceLifetimeExtender
- */
-@CoordinatorScope
-public class AppOpsCoordinator implements Coordinator {
-    private static final String TAG = "AppOpsCoordinator";
-
-    private final ForegroundServiceController mForegroundServiceController;
-    private final AppOpsController mAppOpsController;
-    private final DelayableExecutor mMainExecutor;
-
-    private NotifPipeline mNotifPipeline;
-
-    @Inject
-    public AppOpsCoordinator(
-            ForegroundServiceController foregroundServiceController,
-            AppOpsController appOpsController,
-            @Main DelayableExecutor mainExecutor) {
-        mForegroundServiceController = foregroundServiceController;
-        mAppOpsController = appOpsController;
-        mMainExecutor = mainExecutor;
-    }
-
-    @Override
-    public void attach(NotifPipeline pipeline) {
-        mNotifPipeline = pipeline;
-
-        // filter out foreground service notifications that aren't necessary anymore
-        mNotifPipeline.addPreGroupFilter(mNotifFilter);
-
-    }
-
-    public NotifSectioner getSectioner() {
-        return mNotifSectioner;
-    }
-
-    /**
-     * Filters out notifications that represent foreground services that are no longer running or
-     * that already have an app notification with the appOps tagged to
-     */
-    private final NotifFilter mNotifFilter = new NotifFilter(TAG) {
-        @Override
-        public boolean shouldFilterOut(NotificationEntry entry, long now) {
-            StatusBarNotification sbn = entry.getSbn();
-
-            // Filters out system-posted disclosure notifications when unneeded
-            if (mForegroundServiceController.isDisclosureNotification(sbn)
-                    && !mForegroundServiceController.isDisclosureNeededForUser(
-                            sbn.getUser().getIdentifier())) {
-                return true;
-            }
-            return false;
-        }
-    };
-
-    /**
-     * Puts colorized foreground service and call notifications into its own section.
-     */
-    private final NotifSectioner mNotifSectioner = new NotifSectioner("ForegroundService",
-            NotificationPriorityBucketKt.BUCKET_FOREGROUND_SERVICE) {
-        @Override
-        public boolean isInSection(ListEntry entry) {
-            NotificationEntry notificationEntry = entry.getRepresentativeEntry();
-            if (notificationEntry != null) {
-                return isColorizedForegroundService(notificationEntry) || isCall(notificationEntry);
-            }
-            return false;
-        }
-
-        private boolean isColorizedForegroundService(NotificationEntry entry) {
-            Notification notification = entry.getSbn().getNotification();
-            return notification.isForegroundService()
-                    && notification.isColorized()
-                    && entry.getImportance() > IMPORTANCE_MIN;
-        }
-
-        private boolean isCall(NotificationEntry entry) {
-            Notification notification = entry.getSbn().getNotification();
-            return entry.getImportance() > IMPORTANCE_MIN
-                    && notification.isStyle(Notification.CallStyle.class);
-        }
-    };
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ColorizedFgsCoordinator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ColorizedFgsCoordinator.java
new file mode 100644
index 0000000..63997f8
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ColorizedFgsCoordinator.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.systemui.statusbar.notification.collection.coordinator;
+
+import static android.app.NotificationManager.IMPORTANCE_MIN;
+
+import android.app.Notification;
+
+import com.android.systemui.statusbar.notification.collection.ListEntry;
+import com.android.systemui.statusbar.notification.collection.NotifPipeline;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.coordinator.dagger.CoordinatorScope;
+import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifSectioner;
+import com.android.systemui.statusbar.notification.stack.NotificationPriorityBucketKt;
+
+import javax.inject.Inject;
+
+/**
+ * Handles sectioning for foreground service notifications.
+ *  Puts non-min colorized foreground service notifications into the FGS section. See
+ *  {@link NotifCoordinators} for section ordering priority.
+ */
+@CoordinatorScope
+public class ColorizedFgsCoordinator implements Coordinator {
+    private static final String TAG = "ColorizedCoordinator";
+
+    @Inject
+    public ColorizedFgsCoordinator() {
+    }
+
+    @Override
+    public void attach(NotifPipeline pipeline) {
+    }
+
+    public NotifSectioner getSectioner() {
+        return mNotifSectioner;
+    }
+
+
+    /**
+     * Puts colorized foreground service and call notifications into its own section.
+     */
+    private final NotifSectioner mNotifSectioner = new NotifSectioner("ColorizedSectioner",
+            NotificationPriorityBucketKt.BUCKET_FOREGROUND_SERVICE) {
+        @Override
+        public boolean isInSection(ListEntry entry) {
+            NotificationEntry notificationEntry = entry.getRepresentativeEntry();
+            if (notificationEntry != null) {
+                return isColorizedForegroundService(notificationEntry) || isCall(notificationEntry);
+            }
+            return false;
+        }
+
+        private boolean isColorizedForegroundService(NotificationEntry entry) {
+            Notification notification = entry.getSbn().getNotification();
+            return notification.isForegroundService()
+                    && notification.isColorized()
+                    && entry.getImportance() > IMPORTANCE_MIN;
+        }
+
+        private boolean isCall(NotificationEntry entry) {
+            Notification notification = entry.getSbn().getNotification();
+            return entry.getImportance() > IMPORTANCE_MIN
+                    && notification.isStyle(Notification.CallStyle.class);
+        }
+    };
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/NotifCoordinators.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/NotifCoordinators.kt
index 0ccab9e..226a957 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/NotifCoordinators.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/NotifCoordinators.kt
@@ -33,34 +33,34 @@
 
 @CoordinatorScope
 class NotifCoordinatorsImpl @Inject constructor(
-    sectionStyleProvider: SectionStyleProvider,
-    featureFlags: FeatureFlags,
-    dataStoreCoordinator: DataStoreCoordinator,
-    hideLocallyDismissedNotifsCoordinator: HideLocallyDismissedNotifsCoordinator,
-    hideNotifsForOtherUsersCoordinator: HideNotifsForOtherUsersCoordinator,
-    keyguardCoordinator: KeyguardCoordinator,
-    rankingCoordinator: RankingCoordinator,
-    appOpsCoordinator: AppOpsCoordinator,
-    deviceProvisionedCoordinator: DeviceProvisionedCoordinator,
-    bubbleCoordinator: BubbleCoordinator,
-    headsUpCoordinator: HeadsUpCoordinator,
-    gutsCoordinator: GutsCoordinator,
-    conversationCoordinator: ConversationCoordinator,
-    debugModeCoordinator: DebugModeCoordinator,
-    groupCountCoordinator: GroupCountCoordinator,
-    groupWhenCoordinator: GroupWhenCoordinator,
-    mediaCoordinator: MediaCoordinator,
-    preparationCoordinator: PreparationCoordinator,
-    remoteInputCoordinator: RemoteInputCoordinator,
-    rowAppearanceCoordinator: RowAppearanceCoordinator,
-    stackCoordinator: StackCoordinator,
-    shadeEventCoordinator: ShadeEventCoordinator,
-    smartspaceDedupingCoordinator: SmartspaceDedupingCoordinator,
-    viewConfigCoordinator: ViewConfigCoordinator,
-    visualStabilityCoordinator: VisualStabilityCoordinator,
-    sensitiveContentCoordinator: SensitiveContentCoordinator,
-    dismissibilityCoordinator: DismissibilityCoordinator,
-    dreamCoordinator: DreamCoordinator,
+        sectionStyleProvider: SectionStyleProvider,
+        featureFlags: FeatureFlags,
+        dataStoreCoordinator: DataStoreCoordinator,
+        hideLocallyDismissedNotifsCoordinator: HideLocallyDismissedNotifsCoordinator,
+        hideNotifsForOtherUsersCoordinator: HideNotifsForOtherUsersCoordinator,
+        keyguardCoordinator: KeyguardCoordinator,
+        rankingCoordinator: RankingCoordinator,
+        colorizedFgsCoordinator: ColorizedFgsCoordinator,
+        deviceProvisionedCoordinator: DeviceProvisionedCoordinator,
+        bubbleCoordinator: BubbleCoordinator,
+        headsUpCoordinator: HeadsUpCoordinator,
+        gutsCoordinator: GutsCoordinator,
+        conversationCoordinator: ConversationCoordinator,
+        debugModeCoordinator: DebugModeCoordinator,
+        groupCountCoordinator: GroupCountCoordinator,
+        groupWhenCoordinator: GroupWhenCoordinator,
+        mediaCoordinator: MediaCoordinator,
+        preparationCoordinator: PreparationCoordinator,
+        remoteInputCoordinator: RemoteInputCoordinator,
+        rowAppearanceCoordinator: RowAppearanceCoordinator,
+        stackCoordinator: StackCoordinator,
+        shadeEventCoordinator: ShadeEventCoordinator,
+        smartspaceDedupingCoordinator: SmartspaceDedupingCoordinator,
+        viewConfigCoordinator: ViewConfigCoordinator,
+        visualStabilityCoordinator: VisualStabilityCoordinator,
+        sensitiveContentCoordinator: SensitiveContentCoordinator,
+        dismissibilityCoordinator: DismissibilityCoordinator,
+        dreamCoordinator: DreamCoordinator,
 ) : NotifCoordinators {
 
     private val mCoreCoordinators: MutableList<CoreCoordinator> = ArrayList()
@@ -79,7 +79,7 @@
         mCoordinators.add(hideNotifsForOtherUsersCoordinator)
         mCoordinators.add(keyguardCoordinator)
         mCoordinators.add(rankingCoordinator)
-        mCoordinators.add(appOpsCoordinator)
+        mCoordinators.add(colorizedFgsCoordinator)
         mCoordinators.add(deviceProvisionedCoordinator)
         mCoordinators.add(bubbleCoordinator)
         mCoordinators.add(debugModeCoordinator)
@@ -106,7 +106,7 @@
 
         // Manually add Ordered Sections
         mOrderedSections.add(headsUpCoordinator.sectioner) // HeadsUp
-        mOrderedSections.add(appOpsCoordinator.sectioner) // ForegroundService
+        mOrderedSections.add(colorizedFgsCoordinator.sectioner) // ForegroundService
         mOrderedSections.add(conversationCoordinator.peopleAlertingSectioner) // People Alerting
         mOrderedSections.add(conversationCoordinator.peopleSilentSectioner) // People Silent
         mOrderedSections.add(rankingCoordinator.alertingSectioner) // Alerting
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/PreparationCoordinator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/PreparationCoordinator.java
index 6500ff7..73decfc 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/PreparationCoordinator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/PreparationCoordinator.java
@@ -23,6 +23,7 @@
 
 import android.annotation.IntDef;
 import android.os.RemoteException;
+import android.os.Trace;
 import android.service.notification.StatusBarNotification;
 import android.util.ArrayMap;
 import android.util.ArraySet;
@@ -342,11 +343,13 @@
     private void inflateEntry(NotificationEntry entry,
             NotifUiAdjustment newAdjustment,
             String reason) {
+        Trace.beginSection("PrepCoord.inflateEntry");
         abortInflation(entry, reason);
         mInflationAdjustments.put(entry, newAdjustment);
         mInflatingNotifs.add(entry);
         NotifInflater.Params params = getInflaterParams(newAdjustment, reason);
         mNotifInflater.inflateViews(entry, params, this::onInflationFinished);
+        Trace.endSection();
     }
 
     private void rebind(NotificationEntry entry,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt
index aeeeb4f..9ba1f7a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt
@@ -38,7 +38,7 @@
 interface SensitiveContentCoordinatorModule
 
 @Module
-private interface PrivateSensitiveContentCoordinatorModule {
+interface PrivateSensitiveContentCoordinatorModule {
     @Binds
     fun bindCoordinator(impl: SensitiveContentCoordinatorImpl): SensitiveContentCoordinator
 }
@@ -47,7 +47,7 @@
 interface SensitiveContentCoordinator : Coordinator
 
 @CoordinatorScope
-private class SensitiveContentCoordinatorImpl @Inject constructor(
+class SensitiveContentCoordinatorImpl @Inject constructor(
     private val dynamicPrivacyController: DynamicPrivacyController,
     private val lockscreenUserManager: NotificationLockscreenUserManager,
     private val keyguardUpdateMonitor: KeyguardUpdateMonitor,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt
index 5c2f9a8..62a0d13 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt
@@ -39,10 +39,7 @@
 
     override fun attach(pipeline: NotifPipeline) {
         pipeline.addOnAfterRenderListListener(::onAfterRenderList)
-        // TODO(b/282865576): This has an issue where it makes changes to some groups without
-        // notifying listeners. To be fixed in QPR, but for now let's comment it out to avoid the
-        // group expansion bug.
-        // groupExpansionManagerImpl.attach(pipeline)
+        groupExpansionManagerImpl.attach(pipeline)
     }
 
     fun onAfterRenderList(entries: List<ListEntry>, controller: NotifStackController) =
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt
index 357c5b2..c00bb93 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt
@@ -50,7 +50,7 @@
 @Module(includes = [
     SensitiveContentCoordinatorModule::class,
 ])
-private abstract class InternalCoordinatorsModule {
+abstract class InternalCoordinatorsModule {
     @Binds
     @Internal
     abstract fun bindNotifCoordinators(impl: NotifCoordinatorsImpl): NotifCoordinators
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifEvent.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifEvent.kt
index e20f0e5..e06e2d0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifEvent.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifEvent.kt
@@ -22,6 +22,8 @@
 import android.service.notification.StatusBarNotification
 import com.android.systemui.statusbar.notification.collection.NotifCollection
 import com.android.systemui.statusbar.notification.collection.NotificationEntry
+import com.android.systemui.util.NamedListenerSet
+import com.android.systemui.util.traceSection
 
 /**
  * Set of classes that represent the various events that [NotifCollection] can dispatch to
@@ -30,10 +32,10 @@
  * These events build up in a queue and are periodically emitted in chunks by the collection.
  */
 
-sealed class NotifEvent {
-    fun dispatchTo(listeners: List<NotifCollectionListener>) {
-        for (i in listeners.indices) {
-            dispatchToListener(listeners[i])
+sealed class NotifEvent(private val traceName: String) {
+    fun dispatchTo(listeners: NamedListenerSet<NotifCollectionListener>) {
+        traceSection(traceName) {
+            listeners.forEachTraced(::dispatchToListener)
         }
     }
 
@@ -43,7 +45,7 @@
 data class BindEntryEvent(
     val entry: NotificationEntry,
     val sbn: StatusBarNotification
-) : NotifEvent() {
+) : NotifEvent("onEntryBind") {
     override fun dispatchToListener(listener: NotifCollectionListener) {
         listener.onEntryBind(entry, sbn)
     }
@@ -51,7 +53,7 @@
 
 data class InitEntryEvent(
     val entry: NotificationEntry
-) : NotifEvent() {
+) : NotifEvent("onEntryInit") {
     override fun dispatchToListener(listener: NotifCollectionListener) {
         listener.onEntryInit(entry)
     }
@@ -59,7 +61,7 @@
 
 data class EntryAddedEvent(
     val entry: NotificationEntry
-) : NotifEvent() {
+) : NotifEvent("onEntryAdded") {
     override fun dispatchToListener(listener: NotifCollectionListener) {
         listener.onEntryAdded(entry)
     }
@@ -68,7 +70,7 @@
 data class EntryUpdatedEvent(
     val entry: NotificationEntry,
     val fromSystem: Boolean
-) : NotifEvent() {
+) : NotifEvent(if (fromSystem) "onEntryUpdated" else "onEntryUpdated fromSystem=true") {
     override fun dispatchToListener(listener: NotifCollectionListener) {
         listener.onEntryUpdated(entry, fromSystem)
     }
@@ -77,7 +79,7 @@
 data class EntryRemovedEvent(
     val entry: NotificationEntry,
     val reason: Int
-) : NotifEvent() {
+) : NotifEvent("onEntryRemoved ${cancellationReasonDebugString(reason)}") {
     override fun dispatchToListener(listener: NotifCollectionListener) {
         listener.onEntryRemoved(entry, reason)
     }
@@ -85,7 +87,7 @@
 
 data class CleanUpEntryEvent(
     val entry: NotificationEntry
-) : NotifEvent() {
+) : NotifEvent("onEntryCleanUp") {
     override fun dispatchToListener(listener: NotifCollectionListener) {
         listener.onEntryCleanUp(entry)
     }
@@ -93,13 +95,13 @@
 
 data class RankingUpdatedEvent(
     val rankingMap: RankingMap
-) : NotifEvent() {
+) : NotifEvent("onRankingUpdate") {
     override fun dispatchToListener(listener: NotifCollectionListener) {
         listener.onRankingUpdate(rankingMap)
     }
 }
 
-class RankingAppliedEvent() : NotifEvent() {
+class RankingAppliedEvent : NotifEvent("onRankingApplied") {
     override fun dispatchToListener(listener: NotifCollectionListener) {
         listener.onRankingApplied()
     }
@@ -110,7 +112,7 @@
     val user: UserHandle,
     val channel: NotificationChannel,
     val modificationType: Int
-) : NotifEvent() {
+) : NotifEvent("onNotificationChannelModified") {
     override fun dispatchToListener(listener: NotifCollectionListener) {
         listener.onNotificationChannelModified(pkgName, user, channel, modificationType)
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/DebugModeFilterProvider.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/DebugModeFilterProvider.kt
index fd5bae1..c873e6a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/DebugModeFilterProvider.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/DebugModeFilterProvider.kt
@@ -26,7 +26,6 @@
 import com.android.systemui.statusbar.notification.collection.NotificationEntry
 import com.android.systemui.util.Assert
 import com.android.systemui.util.ListenerSet
-import com.android.systemui.util.isNotEmpty
 import java.io.PrintWriter
 import javax.inject.Inject
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerImpl.java
index 46af03a..5d33804 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerImpl.java
@@ -67,18 +67,29 @@
      * Cleanup entries from mExpandedGroups that no longer exist in the pipeline.
      */
     private final OnBeforeRenderListListener mNotifTracker = (entries) -> {
+        if (mExpandedGroups.isEmpty()) {
+            return; // nothing to do
+        }
+
         final Set<NotificationEntry> renderingSummaries = new HashSet<>();
         for (ListEntry entry : entries) {
             if (entry instanceof GroupEntry) {
                 renderingSummaries.add(entry.getRepresentativeEntry());
             }
         }
-        mExpandedGroups.removeIf(expandedGroup -> !renderingSummaries.contains(expandedGroup));
+
+        // Create a copy of mExpandedGroups so we can modify it in a thread-safe way.
+        final var currentExpandedGroups = new HashSet<>(mExpandedGroups);
+        for (NotificationEntry entry : currentExpandedGroups) {
+            setExpanded(entry, renderingSummaries.contains(entry));
+        }
     };
 
     public void attach(NotifPipeline pipeline) {
-        mDumpManager.registerDumpable(this);
-        pipeline.addOnBeforeRenderListListener(mNotifTracker);
+        if (mFeatureFlags.isEnabled(Flags.NOTIFICATION_GROUP_EXPANSION_CHANGE)) {
+            mDumpManager.registerDumpable(this);
+            pipeline.addOnBeforeRenderListListener(mNotifTracker);
+        }
     }
 
     @Override
@@ -94,11 +105,24 @@
     @Override
     public void setGroupExpanded(NotificationEntry entry, boolean expanded) {
         final NotificationEntry groupSummary = mGroupMembershipManager.getGroupSummary(entry);
+        setExpanded(groupSummary, expanded);
+    }
+
+    /**
+     * Add or remove {@code entry} to/from {@code mExpandedGroups} and notify listeners if
+     * something changed. This assumes that {@code entry} is a group summary.
+     * <p>
+     * TODO(b/293434635): Currently, in spite of its docs,
+     * {@code mGroupMembershipManager.getGroupSummary(entry)} returns null if {@code entry} is
+     * already a summary. Instead of needing this helper method to bypass that, we probably want to
+     * move this code back to {@code setGroupExpanded} and use that everywhere.
+     */
+    private void setExpanded(NotificationEntry entry, boolean expanded) {
         boolean changed;
         if (expanded) {
-            changed = mExpandedGroups.add(groupSummary);
+            changed = mExpandedGroups.add(entry);
         } else {
-            changed = mExpandedGroups.remove(groupSummary);
+            changed = mExpandedGroups.remove(entry);
         }
 
         // Only notify listeners if something changed.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/SectionHeaderController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/SectionHeaderController.kt
index 7b59266..49990d9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/SectionHeaderController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/SectionHeaderController.kt
@@ -38,7 +38,7 @@
 }
 
 @SectionHeaderScope
-internal class SectionHeaderNodeControllerImpl @Inject constructor(
+class SectionHeaderNodeControllerImpl @Inject constructor(
     @NodeLabel override val nodeLabel: String,
     private val layoutInflater: LayoutInflater,
     @HeaderText @StringRes private val headerTextResId: Int,
@@ -103,4 +103,4 @@
     override fun offerToKeepInParentForAnimation(): Boolean = false
     override fun removeFromParentIfKeptForAnimation(): Boolean = false
     override fun resetKeepInParentForAnimation() {}
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt
index 2a9cfd0..75801a8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt
@@ -145,7 +145,7 @@
 }
 
 @Module
-private abstract class SectionHeaderBindingModule {
+abstract class SectionHeaderBindingModule {
     @Binds abstract fun bindsNodeController(impl: SectionHeaderNodeControllerImpl): NodeController
     @Binds abstract fun bindsSectionHeaderController(
         impl: SectionHeaderNodeControllerImpl
@@ -182,4 +182,4 @@
 
 @Scope
 @Retention(AnnotationRetention.BINARY)
-annotation class SectionHeaderScope
\ No newline at end of file
+annotation class SectionHeaderScope
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt
index d896541..9d95342 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt
@@ -33,6 +33,7 @@
 import com.android.systemui.statusbar.notification.collection.NotificationEntry
 import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection
 import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionListener
+import com.android.systemui.util.traceSection
 import javax.inject.Inject
 
 /**
@@ -95,7 +96,7 @@
      * @throws InflationException Exception if required icons are not valid or specified
      */
     @Throws(InflationException::class)
-    fun createIcons(entry: NotificationEntry) {
+    fun createIcons(entry: NotificationEntry) = traceSection("IconManager.createIcons") {
         // Construct the status bar icon view.
         val sbIcon = iconBuilder.createIconView(entry)
         sbIcon.scaleType = ImageView.ScaleType.CENTER_INSIDE
@@ -143,9 +144,9 @@
      * @throws InflationException Exception if required icons are not valid or specified
      */
     @Throws(InflationException::class)
-    fun updateIcons(entry: NotificationEntry) {
+    fun updateIcons(entry: NotificationEntry) = traceSection("IconManager.updateIcons") {
         if (!entry.icons.areIconsAvailable) {
-            return
+            return@traceSection
         }
         entry.icons.smallIconDescriptor = null
         entry.icons.peopleAvatarDescriptor = null
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconAreaControllerViewBinderWrapperImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconAreaControllerViewBinderWrapperImpl.kt
new file mode 100644
index 0000000..26dfe3e
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconAreaControllerViewBinderWrapperImpl.kt
@@ -0,0 +1,684 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.icon.ui.viewbinder
+
+import android.content.Context
+import android.graphics.Color
+import android.graphics.Rect
+import android.os.Bundle
+import android.os.Trace
+import android.view.LayoutInflater
+import android.view.View
+import android.widget.FrameLayout
+import androidx.annotation.ColorInt
+import androidx.annotation.VisibleForTesting
+import androidx.collection.ArrayMap
+import com.android.app.animation.Interpolators
+import com.android.internal.statusbar.StatusBarIcon
+import com.android.internal.util.ContrastColorUtil
+import com.android.settingslib.Utils
+import com.android.systemui.R
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.demomode.DemoMode
+import com.android.systemui.demomode.DemoModeController
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
+import com.android.systemui.flags.ViewRefactorFlag
+import com.android.systemui.plugins.DarkIconDispatcher
+import com.android.systemui.plugins.statusbar.StatusBarStateController
+import com.android.systemui.statusbar.CrossFadeHelper
+import com.android.systemui.statusbar.NotificationListener
+import com.android.systemui.statusbar.NotificationMediaManager
+import com.android.systemui.statusbar.NotificationShelfController
+import com.android.systemui.statusbar.StatusBarIconView
+import com.android.systemui.statusbar.StatusBarState
+import com.android.systemui.statusbar.notification.NotificationUtils
+import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator
+import com.android.systemui.statusbar.notification.collection.ListEntry
+import com.android.systemui.statusbar.notification.collection.NotificationEntry
+import com.android.systemui.statusbar.notification.collection.provider.SectionStyleProvider
+import com.android.systemui.statusbar.notification.icon.ui.viewmodel.NotificationIconContainerAlwaysOnDisplayViewModel
+import com.android.systemui.statusbar.notification.icon.ui.viewmodel.NotificationIconContainerShelfViewModel
+import com.android.systemui.statusbar.notification.icon.ui.viewmodel.NotificationIconContainerStatusBarViewModel
+import com.android.systemui.statusbar.notification.shelf.ui.viewbinder.NotificationShelfViewBinderWrapperControllerImpl
+import com.android.systemui.statusbar.phone.DozeParameters
+import com.android.systemui.statusbar.phone.KeyguardBypassController
+import com.android.systemui.statusbar.phone.NotificationIconAreaController
+import com.android.systemui.statusbar.phone.NotificationIconContainer
+import com.android.systemui.statusbar.phone.ScreenOffAnimationController
+import com.android.systemui.statusbar.window.StatusBarWindowController
+import com.android.wm.shell.bubbles.Bubbles
+import java.util.Optional
+import java.util.function.Function
+import javax.inject.Inject
+import kotlinx.coroutines.DisposableHandle
+
+/**
+ * Controller class for [NotificationIconContainer]. This implementation serves as a temporary
+ * wrapper around [NotificationIconContainerViewBinder], so that external code can continue to
+ * depend on the [NotificationIconAreaController] interface. Once
+ * [LegacyNotificationIconAreaControllerImpl] is removed, this class can go away and the ViewBinder
+ * can be used directly.
+ */
+@SysUISingleton
+class NotificationIconAreaControllerViewBinderWrapperImpl
+@Inject
+constructor(
+    private val context: Context,
+    private val statusBarStateController: StatusBarStateController,
+    private val wakeUpCoordinator: NotificationWakeUpCoordinator,
+    private val bypassController: KeyguardBypassController,
+    private val mediaManager: NotificationMediaManager,
+    notificationListener: NotificationListener,
+    private val dozeParameters: DozeParameters,
+    private val sectionStyleProvider: SectionStyleProvider,
+    private val bubblesOptional: Optional<Bubbles>,
+    demoModeController: DemoModeController,
+    darkIconDispatcher: DarkIconDispatcher,
+    featureFlags: FeatureFlags,
+    private val statusBarWindowController: StatusBarWindowController,
+    private val screenOffAnimationController: ScreenOffAnimationController,
+    private val shelfIconsViewModel: NotificationIconContainerShelfViewModel,
+    private val statusBarIconsViewModel: NotificationIconContainerStatusBarViewModel,
+    private val aodIconsViewModel: NotificationIconContainerAlwaysOnDisplayViewModel,
+) :
+    NotificationIconAreaController,
+    DarkIconDispatcher.DarkReceiver,
+    StatusBarStateController.StateListener,
+    NotificationWakeUpCoordinator.WakeUpListener,
+    DemoMode {
+
+    private val contrastColorUtil: ContrastColorUtil = ContrastColorUtil.getInstance(context)
+    private val updateStatusBarIcons = Runnable { updateStatusBarIcons() }
+    private val shelfRefactor = ViewRefactorFlag(featureFlags, Flags.NOTIFICATION_SHELF_REFACTOR)
+    private val tintAreas = ArrayList<Rect>()
+
+    private var iconSize = 0
+    private var iconHPadding = 0
+    private var iconTint = Color.WHITE
+    private var notificationEntries = listOf<ListEntry>()
+    private var notificationIconArea: View? = null
+    private var notificationIcons: NotificationIconContainer? = null
+    private var shelfIcons: NotificationIconContainer? = null
+    private var aodIcons: NotificationIconContainer? = null
+    private var aodBindJob: DisposableHandle? = null
+    private var aodIconAppearTranslation = 0
+    private var animationsEnabled = false
+    private var aodIconTint = 0
+    private var aodIconsVisible = false
+    private var showLowPriority = true
+
+    @VisibleForTesting
+    val settingsListener: NotificationListener.NotificationSettingsListener =
+        object : NotificationListener.NotificationSettingsListener {
+            override fun onStatusBarIconsBehaviorChanged(hideSilentStatusIcons: Boolean) {
+                showLowPriority = !hideSilentStatusIcons
+                updateStatusBarIcons()
+            }
+        }
+
+    init {
+        statusBarStateController.addCallback(this)
+        wakeUpCoordinator.addListener(this)
+        demoModeController.addCallback(this)
+        notificationListener.addNotificationSettingsListener(settingsListener)
+        initializeNotificationAreaViews(context)
+        reloadAodColor()
+        darkIconDispatcher.addDarkReceiver(this)
+    }
+
+    @VisibleForTesting
+    fun shouldShowLowPriorityIcons(): Boolean {
+        return showLowPriority
+    }
+
+    /** Called by the Keyguard*ViewController whose view contains the aod icons. */
+    override fun setupAodIcons(aodIcons: NotificationIconContainer) {
+        val changed = this.aodIcons != null && aodIcons !== this.aodIcons
+        if (changed) {
+            this.aodIcons!!.setAnimationsEnabled(false)
+            this.aodIcons!!.removeAllViews()
+            aodBindJob?.dispose()
+        }
+        this.aodIcons = aodIcons
+        this.aodIcons!!.setOnLockScreen(true)
+        aodBindJob = NotificationIconContainerViewBinder.bind(aodIcons, aodIconsViewModel)
+        updateAodIconsVisibility(animate = false, forceUpdate = changed)
+        updateAnimations()
+        if (changed) {
+            updateAodNotificationIcons()
+        }
+        updateIconLayoutParams(context)
+    }
+
+    override fun setupShelf(notificationShelfController: NotificationShelfController) =
+        NotificationShelfViewBinderWrapperControllerImpl.unsupported
+
+    override fun setShelfIcons(icons: NotificationIconContainer) {
+        if (shelfRefactor.expectEnabled()) {
+            NotificationIconContainerViewBinder.bind(icons, shelfIconsViewModel)
+            shelfIcons = icons
+        }
+    }
+
+    override fun onDensityOrFontScaleChanged(context: Context) {
+        updateIconLayoutParams(context)
+    }
+
+    /** Returns the view that represents the notification area. */
+    override fun getNotificationInnerAreaView(): View? {
+        return notificationIconArea
+    }
+
+    /**
+     * See [com.android.systemui.statusbar.policy.DarkIconDispatcher.setIconsDarkArea]. Sets the
+     * color that should be used to tint any icons in the notification area.
+     *
+     * @param tintAreas the areas in which to tint the icons, specified in screen coordinates
+     * @param darkIntensity
+     */
+    override fun onDarkChanged(tintAreas: ArrayList<Rect>, darkIntensity: Float, iconTint: Int) {
+        this.tintAreas.clear()
+        this.tintAreas.addAll(tintAreas)
+        if (DarkIconDispatcher.isInAreas(tintAreas, notificationIconArea)) {
+            this.iconTint = iconTint
+        }
+        applyNotificationIconsTint()
+    }
+
+    /** Updates the notifications with the given list of notifications to display. */
+    override fun updateNotificationIcons(entries: List<ListEntry>) {
+        notificationEntries = entries
+        updateNotificationIcons()
+    }
+
+    private fun updateStatusBarIcons() {
+        updateIconsForLayout(
+            { entry: NotificationEntry -> entry.icons.statusBarIcon },
+            notificationIcons,
+            showAmbient = false /* showAmbient */,
+            showLowPriority = showLowPriority,
+            hideDismissed = true /* hideDismissed */,
+            hideRepliedMessages = true /* hideRepliedMessages */,
+            hideCurrentMedia = false /* hideCurrentMedia */,
+            hidePulsing = false /* hidePulsing */
+        )
+    }
+
+    override fun updateAodNotificationIcons() {
+        if (aodIcons == null) {
+            return
+        }
+        updateIconsForLayout(
+            { entry: NotificationEntry -> entry.icons.aodIcon },
+            aodIcons,
+            showAmbient = false /* showAmbient */,
+            showLowPriority = true /* showLowPriority */,
+            hideDismissed = true /* hideDismissed */,
+            hideRepliedMessages = true /* hideRepliedMessages */,
+            hideCurrentMedia = true /* hideCurrentMedia */,
+            hidePulsing = bypassController.bypassEnabled /* hidePulsing */
+        )
+    }
+
+    override fun showIconIsolated(icon: StatusBarIconView?, animated: Boolean) {
+        notificationIcons!!.showIconIsolated(icon, animated)
+    }
+
+    override fun setIsolatedIconLocation(iconDrawingRect: Rect, requireStateUpdate: Boolean) {
+        notificationIcons!!.setIsolatedIconLocation(iconDrawingRect, requireStateUpdate)
+    }
+
+    override fun onDozingChanged(isDozing: Boolean) {
+        if (aodIcons == null) {
+            return
+        }
+        val animate = (dozeParameters.alwaysOn && !dozeParameters.displayNeedsBlanking)
+        aodIcons!!.setDozing(isDozing, animate, 0)
+    }
+
+    override fun setAnimationsEnabled(enabled: Boolean) {
+        animationsEnabled = enabled
+        updateAnimations()
+    }
+
+    override fun onStateChanged(newState: Int) {
+        updateAodIconsVisibility(animate = false, forceUpdate = false)
+        updateAnimations()
+    }
+
+    override fun onThemeChanged() {
+        reloadAodColor()
+        updateAodIconColors()
+    }
+
+    override fun getHeight(): Int {
+        return if (aodIcons == null) 0 else aodIcons!!.height
+    }
+
+    @VisibleForTesting
+    fun appearAodIcons() {
+        if (aodIcons == null) {
+            return
+        }
+        if (screenOffAnimationController.shouldAnimateAodIcons()) {
+            aodIcons!!.translationY = -aodIconAppearTranslation.toFloat()
+            aodIcons!!.alpha = 0f
+            animateInAodIconTranslation()
+            aodIcons!!
+                .animate()
+                .alpha(1f)
+                .setInterpolator(Interpolators.LINEAR)
+                .setDuration(AOD_ICONS_APPEAR_DURATION)
+                .start()
+        } else {
+            aodIcons!!.alpha = 1.0f
+            aodIcons!!.translationY = 0f
+        }
+    }
+
+    override fun onFullyHiddenChanged(isFullyHidden: Boolean) {
+        var animate = true
+        if (!bypassController.bypassEnabled) {
+            animate = dozeParameters.alwaysOn && !dozeParameters.displayNeedsBlanking
+            // We only want the appear animations to happen when the notifications get fully hidden,
+            // since otherwise the unhide animation overlaps
+            animate = animate and isFullyHidden
+        }
+        updateAodIconsVisibility(animate, false /* force */)
+        updateAodNotificationIcons()
+        updateAodIconColors()
+    }
+
+    override fun onPulseExpansionChanged(expandingChanged: Boolean) {
+        if (expandingChanged) {
+            updateAodIconsVisibility(animate = true, forceUpdate = false)
+        }
+    }
+
+    override fun demoCommands(): List<String> {
+        val commands = ArrayList<String>()
+        commands.add(DemoMode.COMMAND_NOTIFICATIONS)
+        return commands
+    }
+
+    override fun dispatchDemoCommand(command: String, args: Bundle) {
+        if (notificationIconArea != null) {
+            val visible = args.getString("visible")
+            val vis = if ("false" == visible) View.INVISIBLE else View.VISIBLE
+            notificationIconArea?.visibility = vis
+        }
+    }
+
+    override fun onDemoModeFinished() {
+        if (notificationIconArea != null) {
+            notificationIconArea?.visibility = View.VISIBLE
+        }
+    }
+
+    private fun inflateIconArea(inflater: LayoutInflater): View {
+        return inflater.inflate(R.layout.notification_icon_area, null)
+    }
+
+    /** Initializes the views that will represent the notification area. */
+    private fun initializeNotificationAreaViews(context: Context) {
+        reloadDimens(context)
+        val layoutInflater = LayoutInflater.from(context)
+        notificationIconArea = inflateIconArea(layoutInflater)
+        notificationIcons = notificationIconArea?.findViewById(R.id.notificationIcons)
+        NotificationIconContainerViewBinder.bind(notificationIcons!!, statusBarIconsViewModel)
+    }
+
+    private fun updateIconLayoutParams(context: Context) {
+        reloadDimens(context)
+        val params = generateIconLayoutParams()
+        for (i in 0 until notificationIcons!!.childCount) {
+            val child = notificationIcons!!.getChildAt(i)
+            child.layoutParams = params
+        }
+        if (shelfIcons != null) {
+            for (i in 0 until shelfIcons!!.childCount) {
+                val child = shelfIcons!!.getChildAt(i)
+                child.layoutParams = params
+            }
+        }
+        if (aodIcons != null) {
+            for (i in 0 until aodIcons!!.childCount) {
+                val child = aodIcons!!.getChildAt(i)
+                child.layoutParams = params
+            }
+        }
+    }
+
+    private fun generateIconLayoutParams(): FrameLayout.LayoutParams {
+        return FrameLayout.LayoutParams(
+            iconSize + 2 * iconHPadding,
+            statusBarWindowController.statusBarHeight
+        )
+    }
+
+    private fun reloadDimens(context: Context) {
+        val res = context.resources
+        iconSize = res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_icon_size_sp)
+        iconHPadding = res.getDimensionPixelSize(R.dimen.status_bar_icon_horizontal_margin)
+        aodIconAppearTranslation = res.getDimensionPixelSize(R.dimen.shelf_appear_translation)
+    }
+
+    private fun shouldShowNotificationIcon(
+        entry: NotificationEntry,
+        showAmbient: Boolean,
+        showLowPriority: Boolean,
+        hideDismissed: Boolean,
+        hideRepliedMessages: Boolean,
+        hideCurrentMedia: Boolean,
+        hidePulsing: Boolean
+    ): Boolean {
+        if (!showAmbient && sectionStyleProvider.isMinimized(entry)) {
+            return false
+        }
+        if (hideCurrentMedia && entry.key == mediaManager.mediaNotificationKey) {
+            return false
+        }
+        if (!showLowPriority && sectionStyleProvider.isSilent(entry)) {
+            return false
+        }
+        if (entry.isRowDismissed && hideDismissed) {
+            return false
+        }
+        if (hideRepliedMessages && entry.isLastMessageFromReply) {
+            return false
+        }
+        // showAmbient == show in shade but not shelf
+        if (!showAmbient && entry.shouldSuppressStatusBar()) {
+            return false
+        }
+        if (
+            hidePulsing &&
+                entry.showingPulsing() &&
+                (!wakeUpCoordinator.notificationsFullyHidden || !entry.isPulseSuppressed)
+        ) {
+            return false
+        }
+        return if (bubblesOptional.isPresent && bubblesOptional.get().isBubbleExpanded(entry.key)) {
+            false
+        } else true
+    }
+
+    private fun updateNotificationIcons() {
+        Trace.beginSection("NotificationIconAreaController.updateNotificationIcons")
+        updateStatusBarIcons()
+        updateShelfIcons()
+        updateAodNotificationIcons()
+        applyNotificationIconsTint()
+        Trace.endSection()
+    }
+
+    private fun updateShelfIcons() {
+        if (shelfIcons == null) {
+            return
+        }
+        updateIconsForLayout(
+            { entry: NotificationEntry -> entry.icons.shelfIcon },
+            shelfIcons,
+            showAmbient = true,
+            showLowPriority = true,
+            hideDismissed = false,
+            hideRepliedMessages = false,
+            hideCurrentMedia = false,
+            hidePulsing = false
+        )
+    }
+
+    /**
+     * Updates the notification icons for a host layout. This will ensure that the notification host
+     * layout will have the same icons like the ones in here.
+     *
+     * @param function A function to look up an icon view based on an entry
+     * @param hostLayout which layout should be updated
+     * @param showAmbient should ambient notification icons be shown
+     * @param showLowPriority should icons from silent notifications be shown
+     * @param hideDismissed should dismissed icons be hidden
+     * @param hideRepliedMessages should messages that have been replied to be hidden
+     * @param hidePulsing should pulsing notifications be hidden
+     */
+    private fun updateIconsForLayout(
+        function: Function<NotificationEntry, StatusBarIconView?>,
+        hostLayout: NotificationIconContainer?,
+        showAmbient: Boolean,
+        showLowPriority: Boolean,
+        hideDismissed: Boolean,
+        hideRepliedMessages: Boolean,
+        hideCurrentMedia: Boolean,
+        hidePulsing: Boolean,
+    ) {
+        val toShow = ArrayList<StatusBarIconView>(notificationEntries.size)
+        // Filter out ambient notifications and notification children.
+        for (i in notificationEntries.indices) {
+            val entry = notificationEntries[i].representativeEntry
+            if (entry != null && entry.row != null) {
+                if (
+                    shouldShowNotificationIcon(
+                        entry,
+                        showAmbient,
+                        showLowPriority,
+                        hideDismissed,
+                        hideRepliedMessages,
+                        hideCurrentMedia,
+                        hidePulsing
+                    )
+                ) {
+                    val iconView = function.apply(entry)
+                    if (iconView != null) {
+                        toShow.add(iconView)
+                    }
+                }
+            }
+        }
+
+        // In case we are changing the suppression of a group, the replacement shouldn't flicker
+        // and it should just be replaced instead. We therefore look for notifications that were
+        // just replaced by the child or vice-versa to suppress this.
+        val replacingIcons = ArrayMap<String, ArrayList<StatusBarIcon>>()
+        val toRemove = ArrayList<View>()
+        for (i in 0 until hostLayout!!.childCount) {
+            val child = hostLayout.getChildAt(i) as? StatusBarIconView ?: continue
+            if (!toShow.contains(child)) {
+                var iconWasReplaced = false
+                val removedGroupKey = child.notification.groupKey
+                for (j in toShow.indices) {
+                    val candidate = toShow[j]
+                    if (
+                        candidate.sourceIcon.sameAs(child.sourceIcon) &&
+                            candidate.notification.groupKey == removedGroupKey
+                    ) {
+                        if (!iconWasReplaced) {
+                            iconWasReplaced = true
+                        } else {
+                            iconWasReplaced = false
+                            break
+                        }
+                    }
+                }
+                if (iconWasReplaced) {
+                    var statusBarIcons = replacingIcons[removedGroupKey]
+                    if (statusBarIcons == null) {
+                        statusBarIcons = ArrayList()
+                        replacingIcons[removedGroupKey] = statusBarIcons
+                    }
+                    statusBarIcons.add(child.statusBarIcon)
+                }
+                toRemove.add(child)
+            }
+        }
+        // removing all duplicates
+        val duplicates = ArrayList<String?>()
+        for (key in replacingIcons.keys) {
+            val statusBarIcons = replacingIcons[key]!!
+            if (statusBarIcons.size != 1) {
+                duplicates.add(key)
+            }
+        }
+        replacingIcons.removeAll(duplicates)
+        hostLayout.setReplacingIcons(replacingIcons)
+        val toRemoveCount = toRemove.size
+        for (i in 0 until toRemoveCount) {
+            hostLayout.removeView(toRemove[i])
+        }
+        val params = generateIconLayoutParams()
+        for (i in toShow.indices) {
+            val v = toShow[i]
+            // The view might still be transiently added if it was just removed and added again
+            hostLayout.removeTransientView(v)
+            if (v.parent == null) {
+                if (hideDismissed) {
+                    v.setOnDismissListener(updateStatusBarIcons)
+                }
+                hostLayout.addView(v, i, params)
+            }
+        }
+        hostLayout.setChangingViewPositions(true)
+        // Re-sort notification icons
+        val childCount = hostLayout.childCount
+        for (i in 0 until childCount) {
+            val actual = hostLayout.getChildAt(i)
+            val expected = toShow[i]
+            if (actual === expected) {
+                continue
+            }
+            hostLayout.removeView(expected)
+            hostLayout.addView(expected, i)
+        }
+        hostLayout.setChangingViewPositions(false)
+        hostLayout.setReplacingIcons(null)
+    }
+
+    /** Applies [.mIconTint] to the notification icons. */
+    private fun applyNotificationIconsTint() {
+        for (i in 0 until notificationIcons!!.childCount) {
+            val iv = notificationIcons!!.getChildAt(i) as StatusBarIconView
+            if (iv.width != 0) {
+                updateTintForIcon(iv, iconTint)
+            } else {
+                iv.executeOnLayout { updateTintForIcon(iv, iconTint) }
+            }
+        }
+        updateAodIconColors()
+    }
+
+    private fun updateTintForIcon(v: StatusBarIconView, tint: Int) {
+        val isPreL = java.lang.Boolean.TRUE == v.getTag(R.id.icon_is_pre_L)
+        var color = StatusBarIconView.NO_COLOR
+        val colorize = !isPreL || NotificationUtils.isGrayscale(v, contrastColorUtil)
+        if (colorize) {
+            color = DarkIconDispatcher.getTint(tintAreas, v, tint)
+        }
+        v.staticDrawableColor = color
+        v.setDecorColor(tint)
+    }
+
+    private fun updateAnimations() {
+        val inShade = statusBarStateController.state == StatusBarState.SHADE
+        if (aodIcons != null) {
+            aodIcons!!.setAnimationsEnabled(animationsEnabled && !inShade)
+        }
+        notificationIcons!!.setAnimationsEnabled(animationsEnabled && inShade)
+    }
+
+    private fun animateInAodIconTranslation() {
+        aodIcons!!
+            .animate()
+            .setInterpolator(Interpolators.DECELERATE_QUINT)
+            .translationY(0f)
+            .setDuration(AOD_ICONS_APPEAR_DURATION)
+            .start()
+    }
+
+    private fun reloadAodColor() {
+        aodIconTint =
+            Utils.getColorAttrDefaultColor(
+                context,
+                R.attr.wallpaperTextColor,
+                DEFAULT_AOD_ICON_COLOR
+            )
+    }
+
+    private fun updateAodIconColors() {
+        if (aodIcons != null) {
+            for (i in 0 until aodIcons!!.childCount) {
+                val iv = aodIcons!!.getChildAt(i) as StatusBarIconView
+                if (iv.width != 0) {
+                    updateTintForIcon(iv, aodIconTint)
+                } else {
+                    iv.executeOnLayout { updateTintForIcon(iv, aodIconTint) }
+                }
+            }
+        }
+    }
+
+    private fun updateAodIconsVisibility(animate: Boolean, forceUpdate: Boolean) {
+        if (aodIcons == null) {
+            return
+        }
+        var visible = (bypassController.bypassEnabled || wakeUpCoordinator.notificationsFullyHidden)
+
+        // Hide the AOD icons if we're not in the KEYGUARD state unless the screen off animation is
+        // playing, in which case we want them to be visible since we're animating in the AOD UI and
+        // will be switching to KEYGUARD shortly.
+        if (
+            statusBarStateController.state != StatusBarState.KEYGUARD &&
+                !screenOffAnimationController.shouldShowAodIconsWhenShade()
+        ) {
+            visible = false
+        }
+        if (visible && wakeUpCoordinator.isPulseExpanding() && !bypassController.bypassEnabled) {
+            visible = false
+        }
+        if (aodIconsVisible != visible || forceUpdate) {
+            aodIconsVisible = visible
+            aodIcons!!.animate().cancel()
+            if (animate) {
+                val wasFullyInvisible = aodIcons!!.visibility != View.VISIBLE
+                if (aodIconsVisible) {
+                    if (wasFullyInvisible) {
+                        // No fading here, let's just appear the icons instead!
+                        aodIcons!!.visibility = View.VISIBLE
+                        aodIcons!!.alpha = 1.0f
+                        appearAodIcons()
+                    } else {
+                        // Let's make sure the icon are translated to 0, since we cancelled it above
+                        animateInAodIconTranslation()
+                        // We were fading out, let's fade in instead
+                        CrossFadeHelper.fadeIn(aodIcons)
+                    }
+                } else {
+                    // Let's make sure the icon are translated to 0, since we cancelled it above
+                    animateInAodIconTranslation()
+                    CrossFadeHelper.fadeOut(aodIcons)
+                }
+            } else {
+                aodIcons!!.alpha = 1.0f
+                aodIcons!!.translationY = 0f
+                aodIcons!!.visibility = if (visible) View.VISIBLE else View.INVISIBLE
+            }
+        }
+    }
+
+    companion object {
+        private const val AOD_ICONS_APPEAR_DURATION: Long = 200
+
+        @ColorInt private val DEFAULT_AOD_ICON_COLOR = -0x1
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconContainerViewBinder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconContainerViewBinder.kt
new file mode 100644
index 0000000..8293bb3
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconContainerViewBinder.kt
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.icon.ui.viewbinder
+
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.repeatOnLifecycle
+import com.android.systemui.lifecycle.repeatWhenAttached
+import com.android.systemui.statusbar.notification.icon.ui.viewmodel.NotificationIconContainerViewModel
+import com.android.systemui.statusbar.phone.NotificationIconContainer
+import kotlinx.coroutines.DisposableHandle
+
+/** Binds a [NotificationIconContainer] to its [view model][NotificationIconContainerViewModel]. */
+object NotificationIconContainerViewBinder {
+    fun bind(
+        view: NotificationIconContainer,
+        viewModel: NotificationIconContainerViewModel,
+    ): DisposableHandle {
+        return view.repeatWhenAttached { repeatOnLifecycle(Lifecycle.State.CREATED) {} }
+    }
+}
diff --git a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerAlwaysOnDisplayViewModel.kt
similarity index 60%
copy from core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl
copy to packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerAlwaysOnDisplayViewModel.kt
index f6c47dd..f68b0ef 100644
--- a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerAlwaysOnDisplayViewModel.kt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2022 The Android Open Source Project
+ * Copyright (C) 2023 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -13,16 +13,10 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+package com.android.systemui.statusbar.notification.icon.ui.viewmodel
 
-package android.service.selectiontoolbar;
+import javax.inject.Inject
 
-import android.os.IBinder;
-
-/**
- * The interface from the SelectionToolbarRenderService to the system.
- *
- * @hide
- */
-oneway interface ISelectionToolbarRenderServiceCallback {
-    void transferTouch(in IBinder source, in IBinder target);
-}
+/** View-model for the row of notification icons displayed on the always-on display. */
+class NotificationIconContainerAlwaysOnDisplayViewModel @Inject constructor() :
+    NotificationIconContainerViewModel
diff --git a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerShelfViewModel.kt
similarity index 60%
copy from core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl
copy to packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerShelfViewModel.kt
index f6c47dd..933c76f 100644
--- a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerShelfViewModel.kt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2022 The Android Open Source Project
+ * Copyright (C) 2023 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -13,16 +13,10 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+package com.android.systemui.statusbar.notification.icon.ui.viewmodel
 
-package android.service.selectiontoolbar;
+import javax.inject.Inject
 
-import android.os.IBinder;
-
-/**
- * The interface from the SelectionToolbarRenderService to the system.
- *
- * @hide
- */
-oneway interface ISelectionToolbarRenderServiceCallback {
-    void transferTouch(in IBinder source, in IBinder target);
-}
+/** View-model for the overflow row of notification icons displayed in the notification shade. */
+class NotificationIconContainerShelfViewModel @Inject constructor() :
+    NotificationIconContainerViewModel
diff --git a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerStatusBarViewModel.kt
similarity index 61%
copy from core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl
copy to packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerStatusBarViewModel.kt
index f6c47dd..2217646 100644
--- a/core/java/android/service/selectiontoolbar/ISelectionToolbarRenderServiceCallback.aidl
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerStatusBarViewModel.kt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2022 The Android Open Source Project
+ * Copyright (C) 2023 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -13,16 +13,10 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+package com.android.systemui.statusbar.notification.icon.ui.viewmodel
 
-package android.service.selectiontoolbar;
+import javax.inject.Inject
 
-import android.os.IBinder;
-
-/**
- * The interface from the SelectionToolbarRenderService to the system.
- *
- * @hide
- */
-oneway interface ISelectionToolbarRenderServiceCallback {
-    void transferTouch(in IBinder source, in IBinder target);
-}
+/** View-model for the row of notification icons displayed in the status bar, */
+class NotificationIconContainerStatusBarViewModel @Inject constructor() :
+    NotificationIconContainerViewModel
diff --git a/core/java/android/view/selectiontoolbar/WidgetInfo.aidl b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerViewModel.kt
similarity index 66%
copy from core/java/android/view/selectiontoolbar/WidgetInfo.aidl
copy to packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerViewModel.kt
index 1057c51..892b2be 100644
--- a/core/java/android/view/selectiontoolbar/WidgetInfo.aidl
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/ui/viewmodel/NotificationIconContainerViewModel.kt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2021 The Android Open Source Project
+ * Copyright (C) 2023 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -13,10 +13,10 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
-package android.view.selectiontoolbar;
+package com.android.systemui.statusbar.notification.icon.ui.viewmodel
 
 /**
- * @hide
+ * View-model for the row of notification icons displayed in the NotificationShelf, StatusBar, and
+ * AOD.
  */
-parcelable WidgetInfo;
+interface NotificationIconContainerViewModel
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/init/NotificationsControllerImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/init/NotificationsControllerImpl.kt
index 106d11f..7d1cca8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/init/NotificationsControllerImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/init/NotificationsControllerImpl.kt
@@ -17,7 +17,6 @@
 package com.android.systemui.statusbar.notification.init
 
 import android.service.notification.StatusBarNotification
-import com.android.systemui.ForegroundServiceNotificationListener
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.flags.FeatureFlags
 import com.android.systemui.people.widget.PeopleSpaceWidgetManager
@@ -70,7 +69,6 @@
     private val animatedImageNotificationManager: AnimatedImageNotificationManager,
     private val peopleSpaceWidgetManager: PeopleSpaceWidgetManager,
     private val bubblesOptional: Optional<Bubbles>,
-    private val fgsNotifListener: ForegroundServiceNotificationListener,
     private val featureFlags: FeatureFlags
 ) : NotificationsController {
 
@@ -105,7 +103,6 @@
         notificationsMediaManager.setUpWithPresenter(presenter)
         notificationLogger.setUpWithContainer(listContainer)
         peopleSpaceWidgetManager.attach(notificationListener)
-        fgsNotifListener.init()
     }
 
     // TODO: Convert all functions below this line into listeners instead of public methods
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/KeyguardNotificationVisibilityProvider.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/KeyguardNotificationVisibilityProvider.kt
index 78225df..b2c32cd 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/KeyguardNotificationVisibilityProvider.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/KeyguardNotificationVisibilityProvider.kt
@@ -57,7 +57,7 @@
 object KeyguardNotificationVisibilityProviderModule
 
 @Module
-private interface KeyguardNotificationVisibilityProviderImplModule {
+interface KeyguardNotificationVisibilityProviderImplModule {
     @Binds
     fun bindImpl(impl: KeyguardNotificationVisibilityProviderImpl):
             KeyguardNotificationVisibilityProvider
@@ -69,7 +69,7 @@
 }
 
 @SysUISingleton
-private class KeyguardNotificationVisibilityProviderImpl @Inject constructor(
+class KeyguardNotificationVisibilityProviderImpl @Inject constructor(
     @Main private val handler: Handler,
     private val keyguardStateController: KeyguardStateController,
     private val lockscreenUserManager: NotificationLockscreenUserManager,
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 5e7e4be..1b790fd 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
@@ -321,7 +321,8 @@
     protected void setBackgroundTintColor(int color) {
         if (color != mCurrentBackgroundTint) {
             mCurrentBackgroundTint = color;
-            if (color == mNormalColor) {
+            // TODO(282173943): re-enable this tinting optimization when Resources are thread-safe
+            if (false && color == mNormalColor) {
                 // We don't need to tint a normal notification
                 color = 0;
             }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ChannelEditorListView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ChannelEditorListView.kt
index 38a1579..9c4aa07 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ChannelEditorListView.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ChannelEditorListView.kt
@@ -60,7 +60,7 @@
     override fun onFinishInflate() {
         super.onFinishInflate()
 
-        appControlRow = findViewById(R.id.app_control)
+        appControlRow = requireViewById(R.id.app_control)
     }
 
     /**
@@ -143,9 +143,9 @@
     lateinit var switch: Switch
 
     override fun onFinishInflate() {
-        iconView = findViewById(R.id.icon)
-        channelName = findViewById(R.id.app_name)
-        switch = findViewById(R.id.toggle)
+        iconView = requireViewById(R.id.icon)
+        channelName = requireViewById(R.id.app_name)
+        switch = requireViewById(R.id.toggle)
 
         setOnClickListener { switch.toggle() }
     }
@@ -174,9 +174,9 @@
 
     override fun onFinishInflate() {
         super.onFinishInflate()
-        channelName = findViewById(R.id.channel_name)
-        channelDescription = findViewById(R.id.channel_description)
-        switch = findViewById(R.id.toggle)
+        channelName = requireViewById(R.id.channel_name)
+        channelDescription = requireViewById(R.id.channel_description)
+        switch = requireViewById(R.id.toggle)
         switch.setOnCheckedChangeListener { _, b ->
             channel?.let {
                 controller.proposeEditForChannel(it, if (b) it.importance else IMPORTANCE_NONE)
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 ed489a6c..d92d11b 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
@@ -1894,6 +1894,9 @@
             return traceTag;
         }
 
+        if (isSummaryWithChildren()) {
+            return traceTag + "(summary)";
+        }
         Class<? extends Notification.Style> style =
                 getEntry().getSbn().getNotification().getNotificationStyle();
         if (style == null) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowController.java
index a4e8c2e..80f5d19 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowController.java
@@ -21,12 +21,16 @@
 import static com.android.systemui.statusbar.StatusBarState.KEYGUARD;
 import static com.android.systemui.statusbar.notification.NotificationUtils.logKey;
 
+import android.net.Uri;
+import android.os.UserHandle;
+import android.provider.Settings;
 import android.util.Log;
 import android.view.View;
 import android.view.ViewGroup;
 
 import androidx.annotation.NonNull;
 import androidx.annotation.Nullable;
+import androidx.annotation.VisibleForTesting;
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.statusbar.IStatusBarService;
@@ -71,6 +75,10 @@
 @NotificationRowScope
 public class ExpandableNotificationRowController implements NotifViewController {
     private static final String TAG = "NotifRowController";
+
+    static final Uri BUBBLES_SETTING_URI =
+            Settings.Secure.getUriFor(Settings.Secure.NOTIFICATION_BUBBLES);
+    private static final String BUBBLES_SETTING_ENABLED_VALUE = "1";
     private final ExpandableNotificationRow mView;
     private final NotificationListContainer mListContainer;
     private final RemoteInputViewSubcomponent.Factory mRemoteInputViewSubcomponentFactory;
@@ -104,6 +112,23 @@
     private final ExpandableNotificationRowDragController mDragController;
     private final NotificationDismissibilityProvider mDismissibilityProvider;
     private final IStatusBarService mStatusBarService;
+
+    private final NotificationSettingsController mSettingsController;
+
+    @VisibleForTesting
+    final NotificationSettingsController.Listener mSettingsListener =
+            new NotificationSettingsController.Listener() {
+                @Override
+                public void onSettingChanged(Uri setting, int userId, String value) {
+                    if (BUBBLES_SETTING_URI.equals(setting)) {
+                        final int viewUserId = mView.getEntry().getSbn().getUserId();
+                        if (viewUserId == UserHandle.USER_ALL || viewUserId == userId) {
+                            mView.getPrivateLayout().setBubblesEnabledForUser(
+                                    BUBBLES_SETTING_ENABLED_VALUE.equals(value));
+                        }
+                    }
+                }
+            };
     private final ExpandableNotificationRow.ExpandableNotificationRowLogger mLoggerCallback =
             new ExpandableNotificationRow.ExpandableNotificationRowLogger() {
                 @Override
@@ -201,6 +226,7 @@
             FeatureFlags featureFlags,
             PeopleNotificationIdentifier peopleNotificationIdentifier,
             Optional<BubblesManager> bubblesManagerOptional,
+            NotificationSettingsController settingsController,
             ExpandableNotificationRowDragController dragController,
             NotificationDismissibilityProvider dismissibilityProvider,
             IStatusBarService statusBarService) {
@@ -229,6 +255,7 @@
         mFeatureFlags = featureFlags;
         mPeopleNotificationIdentifier = peopleNotificationIdentifier;
         mBubblesManagerOptional = bubblesManagerOptional;
+        mSettingsController = settingsController;
         mDragController = dragController;
         mMetricsLogger = metricsLogger;
         mChildrenContainerLogger = childrenContainerLogger;
@@ -298,12 +325,14 @@
                         NotificationMenuRowPlugin.class, false /* Allow multiple */);
                 mView.setOnKeyguard(mStatusBarStateController.getState() == KEYGUARD);
                 mStatusBarStateController.addCallback(mStatusBarStateListener);
+                mSettingsController.addCallback(BUBBLES_SETTING_URI, mSettingsListener);
             }
 
             @Override
             public void onViewDetachedFromWindow(View v) {
                 mPluginManager.removePluginListener(mView);
                 mStatusBarStateController.removeCallback(mStatusBarStateListener);
+                mSettingsController.removeCallback(BUBBLES_SETTING_URI, mSettingsListener);
             }
         });
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/FooterView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/FooterView.java
index 6bbeebf..0989df6 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/FooterView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/FooterView.java
@@ -16,11 +16,15 @@
 
 package com.android.systemui.statusbar.notification.row;
 
+import static android.graphics.PorterDuff.Mode.SRC_ATOP;
+
 import android.annotation.ColorInt;
 import android.content.Context;
 import android.content.res.ColorStateList;
 import android.content.res.Configuration;
 import android.content.res.Resources;
+import android.graphics.ColorFilter;
+import android.graphics.PorterDuffColorFilter;
 import android.graphics.drawable.Drawable;
 import android.util.AttributeSet;
 import android.util.IndentingPrintWriter;
@@ -157,10 +161,20 @@
      */
     public void updateColors() {
         Resources.Theme theme = mContext.getTheme();
-        int textColor = getResources().getColor(R.color.notif_pill_text, theme);
-        mClearAllButton.setBackground(theme.getDrawable(R.drawable.notif_footer_btn_background));
+        final @ColorInt int textColor = getResources().getColor(R.color.notif_pill_text, theme);
+        final Drawable clearAllBg = theme.getDrawable(R.drawable.notif_footer_btn_background);
+        final Drawable manageBg = theme.getDrawable(R.drawable.notif_footer_btn_background);
+        // TODO(b/282173943): Remove redundant tinting once Resources are thread-safe
+        final @ColorInt int buttonBgColor =
+                Utils.getColorAttrDefaultColor(mContext, com.android.internal.R.attr.colorSurface);
+        final ColorFilter bgColorFilter = new PorterDuffColorFilter(buttonBgColor, SRC_ATOP);
+        if (buttonBgColor != 0) {
+            clearAllBg.setColorFilter(bgColorFilter);
+            manageBg.setColorFilter(bgColorFilter);
+        }
+        mClearAllButton.setBackground(clearAllBg);
         mClearAllButton.setTextColor(textColor);
-        mManageButton.setBackground(theme.getDrawable(R.drawable.notif_footer_btn_background));
+        mManageButton.setBackground(manageBg);
         mManageButton.setTextColor(textColor);
         final @ColorInt int labelTextColor =
                 Utils.getColorAttrDefaultColor(mContext, android.R.attr.textColorPrimary);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
index 0322573..065828b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
@@ -41,6 +41,8 @@
 import android.widget.ImageView;
 import android.widget.LinearLayout;
 
+import androidx.annotation.MainThread;
+
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.statusbar.IStatusBarService;
 import com.android.systemui.R;
@@ -65,7 +67,6 @@
 import com.android.systemui.statusbar.policy.SmartReplyView;
 import com.android.systemui.statusbar.policy.dagger.RemoteInputViewSubcomponent;
 import com.android.systemui.util.Compile;
-import com.android.systemui.wmshell.BubblesManager;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -134,6 +135,7 @@
     private PeopleNotificationIdentifier mPeopleIdentifier;
     private RemoteInputViewSubcomponent.Factory mRemoteInputSubcomponentFactory;
     private IStatusBarService mStatusBarService;
+    private boolean mBubblesEnabledForUser;
 
     /**
      * List of listeners for when content views become inactive (i.e. not the showing view).
@@ -1440,12 +1442,20 @@
         }
     }
 
+    @MainThread
+    public void setBubblesEnabledForUser(boolean enabled) {
+        mBubblesEnabledForUser = enabled;
+
+        applyBubbleAction(mExpandedChild, mNotificationEntry);
+        applyBubbleAction(mHeadsUpChild, mNotificationEntry);
+    }
+
     @VisibleForTesting
     boolean shouldShowBubbleButton(NotificationEntry entry) {
         boolean isPersonWithShortcut =
                 mPeopleIdentifier.getPeopleNotificationType(entry)
                         >= PeopleNotificationIdentifier.TYPE_FULL_PERSON;
-        return BubblesManager.areBubblesEnabled(mContext, entry.getSbn().getUser())
+        return mBubblesEnabledForUser
                 && isPersonWithShortcut
                 && entry.getBubbleMetadata() != null;
     }
@@ -2079,6 +2089,7 @@
             pw.print("null");
         }
         pw.println();
+        pw.println("mBubblesEnabledForUser: " + mBubblesEnabledForUser);
 
         pw.print("RemoteInputViews { ");
         pw.print(" visibleType: " + mVisibleType);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfo.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfo.java
index 9bc0333..7134f15 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfo.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfo.java
@@ -48,6 +48,7 @@
 import android.os.Handler;
 import android.os.RemoteException;
 import android.os.UserHandle;
+import android.os.UserManager;
 import android.service.notification.StatusBarNotification;
 import android.text.TextUtils;
 import android.transition.ChangeBounds;
@@ -118,6 +119,8 @@
     private NotificationGuts mGutsContainer;
     private OnConversationSettingsClickListener mOnConversationSettingsClickListener;
 
+    private UserManager mUm;
+
     @VisibleForTesting
     boolean mSkipPost = false;
     private int mActualHeight;
@@ -155,7 +158,9 @@
         // People Tile add request.
         if (mSelectedAction == ACTION_FAVORITE && getPriority() != mSelectedAction) {
             mShadeController.animateCollapseShade();
-            mPeopleSpaceWidgetManager.requestPinAppWidget(mShortcutInfo, new Bundle());
+            if (mUm.isSameProfileGroup(UserHandle.USER_SYSTEM, mSbn.getNormalizedUserId())) {
+                mPeopleSpaceWidgetManager.requestPinAppWidget(mShortcutInfo, new Bundle());
+            }
         }
         mGutsContainer.closeControls(v, /* save= */ true);
     };
@@ -188,6 +193,7 @@
     public void bindNotification(
             ShortcutManager shortcutManager,
             PackageManager pm,
+            UserManager um,
             PeopleSpaceWidgetManager peopleSpaceWidgetManager,
             INotificationManager iNotificationManager,
             OnUserInteractionCallback onUserInteractionCallback,
@@ -211,6 +217,7 @@
         mEntry = entry;
         mSbn = entry.getSbn();
         mPm = pm;
+        mUm = um;
         mAppName = mPackageName;
         mOnSettingsClickListener = onSettingsClick;
         mNotificationChannel = notificationChannel;
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 7dbca42..6f79ea8 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
@@ -30,6 +30,7 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.UserHandle;
+import android.os.UserManager;
 import android.provider.Settings;
 import android.service.notification.StatusBarNotification;
 import android.util.ArraySet;
@@ -112,6 +113,9 @@
     private Runnable mOpenRunnable;
     private final INotificationManager mNotificationManager;
     private final PeopleSpaceWidgetManager mPeopleSpaceWidgetManager;
+
+    private final UserManager mUserManager;
+
     private final LauncherApps mLauncherApps;
     private final ShortcutManager mShortcutManager;
     private final UserContextProvider mContextTracker;
@@ -128,6 +132,7 @@
             AccessibilityManager accessibilityManager,
             HighPriorityProvider highPriorityProvider,
             INotificationManager notificationManager,
+            UserManager userManager,
             PeopleSpaceWidgetManager peopleSpaceWidgetManager,
             LauncherApps launcherApps,
             ShortcutManager shortcutManager,
@@ -150,6 +155,7 @@
         mAccessibilityManager = accessibilityManager;
         mHighPriorityProvider = highPriorityProvider;
         mNotificationManager = notificationManager;
+        mUserManager = userManager;
         mPeopleSpaceWidgetManager = peopleSpaceWidgetManager;
         mLauncherApps = launcherApps;
         mShortcutManager = shortcutManager;
@@ -471,6 +477,7 @@
         notificationInfoView.bindNotification(
                 mShortcutManager,
                 pmUser,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mNotificationManager,
                 mOnUserInteractionCallback,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationSettingsController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationSettingsController.java
new file mode 100644
index 0000000..51e4537
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationSettingsController.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.row;
+
+import android.content.Context;
+import android.database.ContentObserver;
+import android.net.Uri;
+import android.os.Handler;
+import android.os.HandlerExecutor;
+
+import androidx.annotation.MainThread;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import com.android.systemui.Dumpable;
+import com.android.systemui.dagger.SysUISingleton;
+import com.android.systemui.dagger.qualifiers.Background;
+import com.android.systemui.dagger.qualifiers.Main;
+import com.android.systemui.dump.DumpManager;
+import com.android.systemui.settings.UserTracker;
+import com.android.systemui.util.settings.SecureSettings;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import javax.inject.Inject;
+
+/**
+ * Centralized controller for listening to Secure Settings changes and informing in-process
+ * listeners, on a background thread.
+ */
+@SysUISingleton
+public class NotificationSettingsController implements Dumpable {
+
+    private final static String TAG = "NotificationSettingsController";
+    private final UserTracker mUserTracker;
+    private final UserTracker.Callback mCurrentUserTrackerCallback;
+    private final Handler mMainHandler;
+    private final Handler mBackgroundHandler;
+    private final ContentObserver mContentObserver;
+    private final SecureSettings mSecureSettings;
+    private final HashMap<Uri, ArrayList<Listener>> mListeners = new HashMap<>();
+
+    @Inject
+    public NotificationSettingsController(UserTracker userTracker,
+            @Main Handler mainHandler,
+            @Background Handler backgroundHandler,
+            SecureSettings secureSettings,
+            DumpManager dumpManager) {
+        mUserTracker = userTracker;
+        mMainHandler = mainHandler;
+        mBackgroundHandler = backgroundHandler;
+        mSecureSettings = secureSettings;
+        mContentObserver = new ContentObserver(mBackgroundHandler) {
+            @Override
+            public void onChange(boolean selfChange, Uri uri) {
+                super.onChange(selfChange, uri);
+                synchronized (mListeners) {
+                    if (mListeners.containsKey(uri)) {
+                        int userId = mUserTracker.getUserId();
+                        String value = getCurrentSettingValue(uri, userId);
+                        for (Listener listener : mListeners.get(uri)) {
+                            mMainHandler.post(() -> listener.onSettingChanged(uri, userId, value));
+                        }
+                    }
+                }
+            }
+        };
+
+        mCurrentUserTrackerCallback = new UserTracker.Callback() {
+            @Override
+            public void onUserChanged(int newUser, Context userContext) {
+                synchronized (mListeners) {
+                    if (mListeners.size() > 0) {
+                        mSecureSettings.unregisterContentObserver(mContentObserver);
+                        for (Uri uri : mListeners.keySet()) {
+                            mSecureSettings.registerContentObserverForUser(
+                                    uri, false, mContentObserver, newUser);
+                        }
+                    }
+                }
+            }
+        };
+        mUserTracker.addCallback(
+                mCurrentUserTrackerCallback, new HandlerExecutor(mBackgroundHandler));
+
+        dumpManager.registerNormalDumpable(TAG, this);
+    }
+
+    /**
+     * Register a callback whenever the given secure settings changes.
+     *
+     * On registration, will trigger the listener on the main thread with the current value of
+     * the setting.
+     */
+    @Main
+    public void addCallback(@NonNull Uri uri, @NonNull Listener listener) {
+        if (uri == null || listener == null) {
+            return;
+        }
+        synchronized (mListeners) {
+            ArrayList<Listener> currentListeners = mListeners.get(uri);
+            if (currentListeners == null) {
+                currentListeners = new ArrayList<>();
+            }
+            if (!currentListeners.contains(listener)) {
+                currentListeners.add(listener);
+            }
+            mListeners.put(uri, currentListeners);
+            if (currentListeners.size() == 1) {
+                mSecureSettings.registerContentObserverForUser(
+                        uri, false, mContentObserver, mUserTracker.getUserId());
+            }
+        }
+        mBackgroundHandler.post(() -> {
+            int userId = mUserTracker.getUserId();
+            String value = getCurrentSettingValue(uri, userId);
+            mMainHandler.post(() -> listener.onSettingChanged(uri, userId, value));
+        });
+
+    }
+
+    public void removeCallback(Uri uri, Listener listener) {
+        synchronized (mListeners) {
+            ArrayList<Listener> currentListeners = mListeners.get(uri);
+
+            if (currentListeners != null) {
+                currentListeners.remove(listener);
+            }
+            if (currentListeners == null || currentListeners.size() == 0) {
+                mListeners.remove(uri);
+            }
+
+            if (mListeners.size() == 0) {
+                mSecureSettings.unregisterContentObserver(mContentObserver);
+            }
+        }
+    }
+
+    @Override
+    public void dump(@NonNull PrintWriter pw, @NonNull String[] args) {
+        synchronized (mListeners) {
+            pw.println("Settings Uri Listener List:");
+            for (Uri uri : mListeners.keySet()) {
+                pw.println("   Uri=" + uri);
+                for (Listener listener : mListeners.get(uri)) {
+                    pw.println("      Listener=" + listener.getClass().getName());
+                }
+            }
+        }
+    }
+
+    private String getCurrentSettingValue(Uri uri, int userId) {
+        final String setting = uri == null ? null : uri.getLastPathSegment();
+        return mSecureSettings.getStringForUser(setting, userId);
+    }
+
+    /**
+     * Listener invoked whenever settings are changed.
+     */
+    public interface Listener {
+        @MainThread
+        void onSettingChanged(@NonNull Uri setting, int userId, @Nullable String value);
+    }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/shelf/ui/viewbinder/NotificationShelfViewBinder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/shelf/ui/viewbinder/NotificationShelfViewBinder.kt
index 22a87a7..b92c51f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/shelf/ui/viewbinder/NotificationShelfViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/shelf/ui/viewbinder/NotificationShelfViewBinder.kt
@@ -64,8 +64,10 @@
 
     override fun setOnClickListener(listener: View.OnClickListener) = unsupported
 
-    private val unsupported: Nothing
-        get() = error("Code path not supported when NOTIFICATION_SHELF_REFACTOR is disabled")
+    companion object {
+        val unsupported: Nothing
+            get() = error("Code path not supported when NOTIFICATION_SHELF_REFACTOR is disabled")
+    }
 }
 
 /** Binds a [NotificationShelf] to its [view model][NotificationShelfViewModel]. */
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 d71bc2f..5e3a67e 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
@@ -93,6 +93,7 @@
 import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.plugins.statusbar.NotificationSwipeActionHelper;
 import com.android.systemui.shade.ShadeController;
+import com.android.systemui.shade.TouchLogger;
 import com.android.systemui.statusbar.CommandQueue;
 import com.android.systemui.statusbar.EmptyShadeView;
 import com.android.systemui.statusbar.NotificationShelf;
@@ -3480,6 +3481,11 @@
         return super.onTouchEvent(ev);
     }
 
+    @Override
+    public boolean dispatchTouchEvent(MotionEvent ev) {
+        return TouchLogger.logDispatchTouch(TAG, ev, super.dispatchTouchEvent(ev));
+    }
+
     void dispatchDownEventToScroller(MotionEvent ev) {
         MotionEvent downEvent = MotionEvent.obtain(ev);
         downEvent.setAction(MotionEvent.ACTION_DOWN);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
index 4668aa4..6db8df9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
@@ -28,7 +28,6 @@
 import static com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout.ROWS_GENTLE;
 import static com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout.ROWS_HIGH_PRIORITY;
 import static com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout.SelectedRows;
-import static com.android.systemui.statusbar.phone.NotificationIconAreaController.HIGH_PRIORITY;
 import static com.android.systemui.util.kotlin.JavaAdapterKt.collectFlow;
 
 import android.content.res.Configuration;
@@ -150,6 +149,7 @@
 public class NotificationStackScrollLayoutController {
     private static final String TAG = "StackScrollerController";
     private static final boolean DEBUG = Compile.IS_DEBUG && Log.isLoggable(TAG, Log.DEBUG);
+    private static final String HIGH_PRIORITY = "high_priority";
 
     private final boolean mAllowLongPress;
     private final NotificationGutsManager mNotificationGutsManager;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ActivityStarterImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ActivityStarterImpl.kt
index dcd18dd..baeae79 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ActivityStarterImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ActivityStarterImpl.kt
@@ -401,7 +401,7 @@
         isActivityIntent: Boolean,
         showOverLockscreen: Boolean,
     ): Boolean {
-        // TODO(b/184121838): Support launch animations when occluded.
+        // TODO(b/294418322): Support launch animations when occluded.
         if (keyguardStateController.isOccluded) {
             return false
         }
@@ -914,8 +914,8 @@
             val packages: Array<String> =
                 context.resources.getStringArray(R.array.system_ui_packages)
             for (pkg in packages) {
-                if (intent.component == null) break
-                if (pkg == intent.component.packageName) {
+                val componentName = intent.component ?: break
+                if (pkg == componentName.packageName) {
                     return UserHandle(UserHandle.myUserId())
                 }
             }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacks.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacks.java
index 6431ef9..2bc7b99 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacks.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacks.java
@@ -16,6 +16,7 @@
 
 package com.android.systemui.statusbar.phone;
 
+import static com.android.systemui.flags.Flags.ONE_WAY_HAPTICS_API_MIGRATION;
 import static com.android.systemui.keyguard.WakefulnessLifecycle.WAKEFULNESS_AWAKE;
 import static com.android.systemui.keyguard.WakefulnessLifecycle.WAKEFULNESS_WAKING;
 
@@ -33,12 +34,15 @@
 import android.os.Vibrator;
 import android.util.Log;
 import android.util.Slog;
+import android.view.HapticFeedbackConstants;
 import android.view.KeyEvent;
 import android.view.WindowInsets;
 import android.view.WindowInsets.Type.InsetsType;
 import android.view.WindowInsetsController.Appearance;
 import android.view.WindowInsetsController.Behavior;
 
+import androidx.annotation.VisibleForTesting;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.internal.statusbar.LetterboxDetails;
@@ -49,6 +53,7 @@
 import com.android.systemui.camera.CameraIntents;
 import com.android.systemui.dagger.qualifiers.DisplayId;
 import com.android.systemui.dagger.qualifiers.Main;
+import com.android.systemui.flags.FeatureFlags;
 import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.qs.QSHost;
@@ -107,6 +112,7 @@
     private final Lazy<CameraLauncher> mCameraLauncherLazy;
     private final QuickSettingsController mQsController;
     private final QSHost mQSHost;
+    private final FeatureFlags mFeatureFlags;
 
     private static final VibrationAttributes HARDWARE_FEEDBACK_VIBRATION_ATTRIBUTES =
             VibrationAttributes.createForUsage(VibrationAttributes.USAGE_HARDWARE_FEEDBACK);
@@ -144,7 +150,8 @@
             Lazy<CameraLauncher> cameraLauncherLazy,
             UserTracker userTracker,
             QSHost qsHost,
-            ActivityStarter activityStarter) {
+            ActivityStarter activityStarter,
+            FeatureFlags featureFlags) {
         mCentralSurfaces = centralSurfaces;
         mQsController = quickSettingsController;
         mContext = context;
@@ -171,6 +178,7 @@
         mCameraLauncherLazy = cameraLauncherLazy;
         mUserTracker = userTracker;
         mQSHost = qsHost;
+        mFeatureFlags = featureFlags;
 
         mVibrateOnOpening = resources.getBoolean(R.bool.config_vibrateOnIconAnimation);
         mCameraLaunchGestureVibrationEffect = getCameraGestureVibrationEffect(
@@ -314,7 +322,7 @@
             mMetricsLogger.action(MetricsEvent.ACTION_SYSTEM_NAVIGATION_KEY_DOWN);
             if (mShadeViewController.isFullyCollapsed()) {
                 if (mVibrateOnOpening) {
-                    mVibratorHelper.vibrate(VibrationEffect.EFFECT_TICK);
+                    vibrateOnNavigationKeyDown();
                 }
                 mShadeViewController.expand(true /* animate */);
                 mNotificationStackScrollLayoutController.setWillExpand(true);
@@ -587,4 +595,15 @@
         }
         return VibrationEffect.createWaveform(timings, /* repeat= */ -1);
     }
+
+    @VisibleForTesting
+    void vibrateOnNavigationKeyDown() {
+        if (mFeatureFlags.isEnabled(ONE_WAY_HAPTICS_API_MIGRATION)) {
+            mShadeViewController.performHapticFeedback(
+                    HapticFeedbackConstants.GESTURE_START
+            );
+        } else {
+            mVibratorHelper.vibrate(VibrationEffect.EFFECT_TICK);
+        }
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
index 632f241..8ffd43a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
@@ -634,7 +634,7 @@
 
     private final ActivityIntentHelper mActivityIntentHelper;
 
-    private final NotificationStackScrollLayoutController mStackScrollerController;
+    public final NotificationStackScrollLayoutController mStackScrollerController;
 
     private final ColorExtractor.OnColorsChangedListener mOnColorsChangedListener =
             (extractor, which) -> updateTheme();
@@ -1612,8 +1612,6 @@
         mBackActionInteractor.setup(mQsController, mShadeSurface);
         mNotificationActivityStarter = mCentralSurfacesComponent.getNotificationActivityStarter();
 
-        mHeadsUpManager.addListener(mCentralSurfacesComponent.getStatusBarHeadsUpChangeListener());
-
         // Listen for demo mode changes
         mDemoModeController.addCallback(mDemoModeCallback);
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ConfigurationControllerImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ConfigurationControllerImpl.kt
index 7dcdc0b..97cb45a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ConfigurationControllerImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ConfigurationControllerImpl.kt
@@ -22,8 +22,6 @@
 import android.view.View.LAYOUT_DIRECTION_RTL
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.statusbar.policy.ConfigurationController
-
-import java.util.ArrayList
 import javax.inject.Inject
 
 @SysUISingleton
@@ -40,6 +38,7 @@
     private var localeList: LocaleList? = null
     private val context: Context
     private var layoutDirection: Int
+    private var orientation = Configuration.ORIENTATION_UNDEFINED
 
     init {
         val currentConfig = context.resources.configuration
@@ -134,8 +133,18 @@
                 it.onThemeChanged()
             }
         }
+
+        val newOrientation = newConfig.orientation
+        if (orientation != newOrientation) {
+            orientation = newOrientation
+            listeners.filterForEach({ this.listeners.contains(it) }) {
+                it.onOrientationChanged(orientation)
+            }
+        }
     }
 
+
+
     override fun addCallback(listener: ConfigurationController.ConfigurationListener) {
         listeners.add(listener)
         listener.onDensityOrFontScaleChanged()
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 f15dcc3..a1f12b8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
@@ -81,6 +81,7 @@
     private final BiConsumer<Float, Float> mSetExpandedHeight = this::setAppearFraction;
     private final KeyguardBypassController mBypassController;
     private final StatusBarStateController mStatusBarStateController;
+    private final PhoneStatusBarTransitions mPhoneStatusBarTransitions;
     private final CommandQueue mCommandQueue;
     private final NotificationWakeUpCoordinator mWakeUpCoordinator;
 
@@ -109,6 +110,7 @@
             NotificationIconAreaController notificationIconAreaController,
             HeadsUpManagerPhone headsUpManager,
             StatusBarStateController stateController,
+            PhoneStatusBarTransitions phoneStatusBarTransitions,
             KeyguardBypassController bypassController,
             NotificationWakeUpCoordinator wakeUpCoordinator,
             DarkIconDispatcher darkIconDispatcher,
@@ -156,6 +158,7 @@
         });
         mBypassController = bypassController;
         mStatusBarStateController = stateController;
+        mPhoneStatusBarTransitions = phoneStatusBarTransitions;
         mWakeUpCoordinator = wakeUpCoordinator;
         mCommandQueue = commandQueue;
         mKeyguardStateController = keyguardStateController;
@@ -203,6 +206,7 @@
     @Override
     public void onHeadsUpStateChanged(@NonNull NotificationEntry entry, boolean isHeadsUp) {
         updateHeadsUpAndPulsingRoundness(entry);
+        mPhoneStatusBarTransitions.onHeadsUpStateChanged(isHeadsUp);
     }
 
     private void updateTopEntry() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.kt
index 34bbd13..cdd410e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.kt
@@ -32,6 +32,7 @@
 import com.android.systemui.plugins.ActivityStarter
 import com.android.systemui.plugins.FalsingManager
 import com.android.systemui.statusbar.VibratorHelper
+import com.android.systemui.util.animation.requiresRemeasuring
 
 /**
  * Renders the bottom area of the lock-screen. Concerned primarily with the quick affordance UI
@@ -98,7 +99,7 @@
         ambientIndicationArea?.let { nonNullAmbientIndicationArea ->
             // remove old ambient indication from its parent
             val originalAmbientIndicationView =
-                oldBottomArea.findViewById<View>(R.id.ambient_indication_container)
+                oldBottomArea.requireViewById<View>(R.id.ambient_indication_container)
             (originalAmbientIndicationView.parent as ViewGroup).removeView(
                 originalAmbientIndicationView
             )
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
index 117a1a4..914e0c0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
@@ -87,6 +87,7 @@
     private int mStatusBarPaddingEnd;
     private int mMinDotWidth;
     private View mSystemIconsContainer;
+    private View mSystemIcons;
     private final MutableStateFlow<DarkChange> mDarkChange = StateFlowKt.MutableStateFlow(
             DarkChange.EMPTY);
 
@@ -119,6 +120,7 @@
     protected void onFinishInflate() {
         super.onFinishInflate();
         mSystemIconsContainer = findViewById(R.id.system_icons_container);
+        mSystemIcons = findViewById(R.id.system_icons);
         mMultiUserAvatar = findViewById(R.id.multi_user_avatar);
         mCarrierLabel = findViewById(R.id.keyguard_carrier_text);
         mBatteryView = mSystemIconsContainer.findViewById(R.id.battery);
@@ -167,6 +169,13 @@
                 mStatusIconContainer.getPaddingBottom()
         );
 
+        mSystemIcons.setPaddingRelative(
+                getResources().getDimensionPixelSize(R.dimen.status_bar_icons_padding_start),
+                getResources().getDimensionPixelSize(R.dimen.status_bar_icons_padding_top),
+                getResources().getDimensionPixelSize(R.dimen.status_bar_icons_padding_end),
+                getResources().getDimensionPixelSize(R.dimen.status_bar_icons_padding_bottom)
+        );
+
         // Respect font size setting.
         mCarrierLabel.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                 getResources().getDimensionPixelSize(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImpl.java
similarity index 96%
rename from packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.java
rename to packages/SystemUI/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImpl.java
index 0bf0f4b..d22ed38 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImpl.java
@@ -1,3 +1,18 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.Context;
@@ -43,6 +58,8 @@
 import com.android.systemui.statusbar.window.StatusBarWindowController;
 import com.android.wm.shell.bubbles.Bubbles;
 
+import org.jetbrains.annotations.NotNull;
+
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Optional;
@@ -55,13 +72,13 @@
  * normally reserved for notifications.
  */
 @SysUISingleton
-public class NotificationIconAreaController implements
+public class LegacyNotificationIconAreaControllerImpl implements
+        NotificationIconAreaController,
         DarkReceiver,
         StatusBarStateController.StateListener,
         NotificationWakeUpCoordinator.WakeUpListener,
         DemoMode {
 
-    public static final String HIGH_PRIORITY = "high_priority";
     private static final long AOD_ICONS_APPEAR_DURATION = 200;
     @ColorInt
     private static final int DEFAULT_AOD_ICON_COLOR = 0xffffffff;
@@ -110,7 +127,7 @@
             };
 
     @Inject
-    public NotificationIconAreaController(
+    public LegacyNotificationIconAreaControllerImpl(
             Context context,
             StatusBarStateController statusBarStateController,
             NotificationWakeUpCoordinator wakeUpCoordinator,
@@ -192,7 +209,7 @@
         }
     }
 
-    public void onDensityOrFontScaleChanged(Context context) {
+    public void onDensityOrFontScaleChanged(@NotNull Context context) {
         updateIconLayoutParams(context);
     }
 
@@ -493,7 +510,7 @@
         mNotificationIcons.showIconIsolated(icon, animated);
     }
 
-    public void setIsolatedIconLocation(Rect iconDrawingRect, boolean requireStateUpdate) {
+    public void setIsolatedIconLocation(@NotNull Rect iconDrawingRect, boolean requireStateUpdate) {
         mNotificationIcons.setIsolatedIconLocation(iconDrawingRect, requireStateUpdate);
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.kt
new file mode 100644
index 0000000..0079f7c
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.kt
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.Context
+import android.graphics.Rect
+import android.view.View
+import com.android.systemui.statusbar.NotificationShelfController
+import com.android.systemui.statusbar.StatusBarIconView
+import com.android.systemui.statusbar.notification.collection.ListEntry
+
+/**
+ * A controller for the space in the status bar to the left of the system icons. This area is
+ * normally reserved for notifications.
+ */
+interface NotificationIconAreaController {
+    /** Called by the Keyguard*ViewController whose view contains the aod icons. */
+    fun setupAodIcons(aodIcons: NotificationIconContainer)
+    fun setupShelf(notificationShelfController: NotificationShelfController)
+    fun setShelfIcons(icons: NotificationIconContainer)
+    fun onDensityOrFontScaleChanged(context: Context)
+
+    /** Returns the view that represents the notification area. */
+    fun getNotificationInnerAreaView(): View?
+
+    /** Updates the notifications with the given list of notifications to display. */
+    fun updateNotificationIcons(entries: List<@JvmSuppressWildcards ListEntry>)
+    fun updateAodNotificationIcons()
+    fun showIconIsolated(icon: StatusBarIconView?, animated: Boolean)
+    fun setIsolatedIconLocation(iconDrawingRect: Rect, requireStateUpdate: Boolean)
+    fun setAnimationsEnabled(enabled: Boolean)
+    fun onThemeChanged()
+    fun getHeight(): Int
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerModule.kt
new file mode 100644
index 0000000..d1ddd51
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerModule.kt
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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 com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
+import com.android.systemui.statusbar.notification.icon.ui.viewbinder.NotificationIconAreaControllerViewBinderWrapperImpl
+import dagger.Module
+import dagger.Provides
+import javax.inject.Provider
+
+@Module
+object NotificationIconAreaControllerModule {
+    @Provides
+    fun provideNotificationIconAreaControllerImpl(
+        featureFlags: FeatureFlags,
+        legacyProvider: Provider<LegacyNotificationIconAreaControllerImpl>,
+        newProvider: Provider<NotificationIconAreaControllerViewBinderWrapperImpl>,
+    ): NotificationIconAreaController =
+        if (featureFlags.isEnabled(Flags.NOTIFICATION_ICON_CONTAINER_REFACTOR)) {
+            newProvider.get()
+        } else {
+            legacyProvider.get()
+        }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarTransitions.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarTransitions.java
index 15c6dcf..cc38405 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarTransitions.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarTransitions.java
@@ -31,6 +31,8 @@
 
     private final float mIconAlphaWhenOpaque;
 
+    private boolean mIsHeadsUp;
+
     private View mStartSide, mStatusIcons, mBattery;
     private Animator mCurrentAnimation;
 
@@ -52,15 +54,32 @@
         return ObjectAnimator.ofFloat(v, "alpha", v.getAlpha(), toAlpha);
     }
 
-    private float getNonBatteryClockAlphaFor(int mode) {
-        return isLightsOut(mode) ? ICON_ALPHA_WHEN_LIGHTS_OUT_NON_BATTERY_CLOCK
-                : !isOpaque(mode) ? ICON_ALPHA_WHEN_NOT_OPAQUE
-                : mIconAlphaWhenOpaque;
+    private float getStatusIconsAlphaFor(int mode) {
+        return getDefaultAlphaFor(mode);
+    }
+
+    private float getStartSideAlphaFor(int mode) {
+        // When there's a heads up notification, we need the start side icons to show regardless of
+        // lights out mode.
+        if (mIsHeadsUp) {
+            return getIconAlphaBasedOnOpacity(mode);
+        }
+        return getDefaultAlphaFor(mode);
     }
 
     private float getBatteryClockAlpha(int mode) {
         return isLightsOut(mode) ? ICON_ALPHA_WHEN_LIGHTS_OUT_BATTERY_CLOCK
-                : getNonBatteryClockAlphaFor(mode);
+                : getIconAlphaBasedOnOpacity(mode);
+    }
+
+    private float getDefaultAlphaFor(int mode) {
+        return isLightsOut(mode) ? ICON_ALPHA_WHEN_LIGHTS_OUT_NON_BATTERY_CLOCK
+                : getIconAlphaBasedOnOpacity(mode);
+    }
+
+    private float getIconAlphaBasedOnOpacity(int mode) {
+        return !isOpaque(mode) ? ICON_ALPHA_WHEN_NOT_OPAQUE
+                : mIconAlphaWhenOpaque;
     }
 
     private boolean isOpaque(int mode) {
@@ -74,19 +93,28 @@
         applyMode(newMode, animate);
     }
 
+    /** Informs this controller that the heads up notification state has changed. */
+    public void onHeadsUpStateChanged(boolean isHeadsUp) {
+        mIsHeadsUp = isHeadsUp;
+        // We want the icon to be fully visible when the HUN appears, so just immediately change the
+        // icon visibility and don't animate.
+        applyMode(getMode(), /* animate= */ false);
+    }
+
     private void applyMode(int mode, boolean animate) {
         if (mStartSide == null) return; // pre-init
-        float newAlpha = getNonBatteryClockAlphaFor(mode);
-        float newAlphaBC = getBatteryClockAlpha(mode);
+        float newStartSideAlpha = getStartSideAlphaFor(mode);
+        float newStatusIconsAlpha = getStatusIconsAlphaFor(mode);
+        float newBatteryAlpha = getBatteryClockAlpha(mode);
         if (mCurrentAnimation != null) {
             mCurrentAnimation.cancel();
         }
         if (animate) {
             AnimatorSet anims = new AnimatorSet();
             anims.playTogether(
-                    animateTransitionTo(mStartSide, newAlpha),
-                    animateTransitionTo(mStatusIcons, newAlpha),
-                    animateTransitionTo(mBattery, newAlphaBC)
+                    animateTransitionTo(mStartSide, newStartSideAlpha),
+                    animateTransitionTo(mStatusIcons, newStatusIconsAlpha),
+                    animateTransitionTo(mBattery, newBatteryAlpha)
                     );
             if (isLightsOut(mode)) {
                 anims.setDuration(LIGHTS_OUT_DURATION);
@@ -94,9 +122,9 @@
             anims.start();
             mCurrentAnimation = anims;
         } else {
-            mStartSide.setAlpha(newAlpha);
-            mStatusIcons.setAlpha(newAlpha);
-            mBattery.setAlpha(newAlphaBC);
+            mStartSide.setAlpha(newStartSideAlpha);
+            mStatusIcons.setAlpha(newStatusIconsAlpha);
+            mBattery.setAlpha(newBatteryAlpha);
         }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
index d546a84..83a040c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
@@ -208,25 +208,29 @@
         ViewGroup.LayoutParams layoutParams = getLayoutParams();
         mStatusBarHeight = SystemBarUtils.getStatusBarHeight(mContext);
         layoutParams.height = mStatusBarHeight - waterfallTopInset;
+        updatePaddings();
+        setLayoutParams(layoutParams);
+    }
 
-        int statusBarPaddingTop = getResources().getDimensionPixelSize(
-                R.dimen.status_bar_padding_top);
+    private void updatePaddings() {
         int statusBarPaddingStart = getResources().getDimensionPixelSize(
                 R.dimen.status_bar_padding_start);
-        int statusBarPaddingEnd = getResources().getDimensionPixelSize(
-                R.dimen.status_bar_padding_end);
 
-        View sbContents = findViewById(R.id.status_bar_contents);
-        sbContents.setPaddingRelative(
+        findViewById(R.id.status_bar_contents).setPaddingRelative(
                 statusBarPaddingStart,
-                statusBarPaddingTop,
-                statusBarPaddingEnd,
+                getResources().getDimensionPixelSize(R.dimen.status_bar_padding_top),
+                getResources().getDimensionPixelSize(R.dimen.status_bar_padding_end),
                 0);
 
         findViewById(R.id.notification_lights_out)
                 .setPaddingRelative(0, statusBarPaddingStart, 0, 0);
 
-        setLayoutParams(layoutParams);
+        findViewById(R.id.system_icons).setPaddingRelative(
+                getResources().getDimensionPixelSize(R.dimen.status_bar_icons_padding_start),
+                getResources().getDimensionPixelSize(R.dimen.status_bar_icons_padding_top),
+                getResources().getDimensionPixelSize(R.dimen.status_bar_icons_padding_end),
+                getResources().getDimensionPixelSize(R.dimen.status_bar_icons_padding_bottom)
+        );
     }
 
     private void updateLayoutForCutout() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewController.kt
index 2affb817..4de669c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewController.kt
@@ -28,8 +28,7 @@
 import com.android.systemui.R
 import com.android.systemui.flags.FeatureFlags
 import com.android.systemui.flags.Flags
-import com.android.systemui.scene.domain.interactor.SceneInteractor
-import com.android.systemui.scene.shared.model.RemoteUserInput
+import com.android.systemui.scene.ui.view.WindowRootView
 import com.android.systemui.shade.ShadeController
 import com.android.systemui.shade.ShadeLogger
 import com.android.systemui.shade.ShadeViewController
@@ -56,7 +55,7 @@
     private val centralSurfaces: CentralSurfaces,
     private val shadeController: ShadeController,
     private val shadeViewController: ShadeViewController,
-    private val sceneInteractor: Provider<SceneInteractor>,
+    private val windowRootView: Provider<WindowRootView>,
     private val shadeLogger: ShadeLogger,
     private val moveFromCenterAnimationController: StatusBarMoveFromCenterAnimationController?,
     private val userChipViewModel: StatusBarUserChipViewModel,
@@ -75,13 +74,14 @@
     }
 
     override fun onViewAttached() {
-        statusContainer = mView.findViewById(R.id.system_icons)
+        statusContainer = mView.requireViewById(R.id.system_icons)
         statusContainer.setOnHoverListener(
             statusOverlayHoverListenerFactory.createDarkAwareListener(statusContainer))
         if (moveFromCenterAnimationController == null) return
 
-        val statusBarLeftSide: View = mView.findViewById(R.id.status_bar_start_side_except_heads_up)
-        val systemIconArea: ViewGroup = mView.findViewById(R.id.status_bar_end_side_content)
+        val statusBarLeftSide: View =
+                mView.requireViewById(R.id.status_bar_start_side_except_heads_up)
+        val systemIconArea: ViewGroup = mView.requireViewById(R.id.status_bar_end_side_content)
 
         val viewsToAnimate = arrayOf(
             statusBarLeftSide,
@@ -179,11 +179,8 @@
             // If scene framework is enabled, route the touch to it and
             // ignore the rest of the gesture.
             if (featureFlags.isEnabled(Flags.SCENE_CONTAINER)) {
-                sceneInteractor.get()
-                    .onRemoteUserInput(RemoteUserInput.translateMotionEvent(event))
-                // TODO(b/291965119): remove once view is expanded to cover the status bar
-                sceneInteractor.get().setVisible(true, "swipe down from status bar")
-                return false
+                windowRootView.get().dispatchTouchEvent(event)
+                return true
             }
 
             if (event.action == MotionEvent.ACTION_DOWN) {
@@ -247,7 +244,7 @@
         private val centralSurfaces: CentralSurfaces,
         private val shadeController: ShadeController,
         private val shadeViewController: ShadeViewController,
-        private val sceneInteractor: Provider<SceneInteractor>,
+        private val windowRootView: Provider<WindowRootView>,
         private val shadeLogger: ShadeLogger,
         private val viewUtil: ViewUtil,
         private val configurationController: ConfigurationController,
@@ -269,7 +266,7 @@
                 centralSurfaces,
                 shadeController,
                 shadeViewController,
-                sceneInteractor,
+                windowRootView,
                 shadeLogger,
                 statusBarMoveFromCenterAnimationController,
                 userChipViewModel,
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 e82ac59..fc66138 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
@@ -370,6 +370,9 @@
         mScrimBehind = behindScrim;
         mScrimInFront = scrimInFront;
         updateThemeColors();
+        mNotificationsScrim.setScrimName(getScrimName(mNotificationsScrim));
+        mScrimBehind.setScrimName(getScrimName(mScrimBehind));
+        mScrimInFront.setScrimName(getScrimName(mScrimInFront));
 
         behindScrim.enableBottomEdgeConcave(mClipsQsScrim);
         mNotificationsScrim.enableRoundedCorners(true);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarContentInsetsProvider.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarContentInsetsProvider.kt
index c850d4f..ad18170 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarContentInsetsProvider.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarContentInsetsProvider.kt
@@ -117,11 +117,11 @@
      * status bar area is contiguous.
      */
     fun currentRotationHasCornerCutout(): Boolean {
-        val cutout = context.display.cutout ?: return false
+        val cutout = checkNotNull(context.display).cutout ?: return false
         val topBounds = cutout.boundingRectTop
 
         val point = Point()
-        context.display.getRealSize(point)
+        checkNotNull(context.display).getRealSize(point)
 
         return topBounds.left <= 0 || topBounds.right >= point.x
     }
@@ -161,7 +161,7 @@
      */
     fun getStatusBarContentInsetsForRotation(@Rotation rotation: Int): Pair<Int, Int> =
         traceSection(tag = "StatusBarContentInsetsProvider.getStatusBarContentInsetsForRotation") {
-            val displayCutout = context.display.cutout
+            val displayCutout = checkNotNull(context.display).cutout
             val key = getCacheKey(rotation, displayCutout)
 
             val screenBounds = context.resources.configuration.windowConfiguration.maxBounds
@@ -198,7 +198,7 @@
     fun getStatusBarContentAreaForRotation(
         @Rotation rotation: Int
     ): Rect {
-        val displayCutout = context.display.cutout
+        val displayCutout = checkNotNull(context.display).cutout
         val key = getCacheKey(rotation, displayCutout)
         return insetsCache[key] ?: getAndSetCalculatedAreaForRotation(
                 rotation, displayCutout, getResourcesForRotation(rotation, context), key)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeadsUpChangeListener.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeadsUpChangeListener.java
index 9a295e6..4b39854 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeadsUpChangeListener.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeadsUpChangeListener.java
@@ -16,23 +16,24 @@
 
 package com.android.systemui.statusbar.phone;
 
+import com.android.systemui.CoreStartable;
+import com.android.systemui.dagger.SysUISingleton;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.shade.ShadeViewController;
 import com.android.systemui.statusbar.NotificationRemoteInputManager;
 import com.android.systemui.statusbar.NotificationShadeWindowController;
 import com.android.systemui.statusbar.StatusBarState;
 import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayoutController;
-import com.android.systemui.statusbar.phone.dagger.CentralSurfacesComponent;
 import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener;
 import com.android.systemui.statusbar.window.StatusBarWindowController;
 
 import javax.inject.Inject;
 
 /**
- * Ties the {@link CentralSurfaces} to {@link com.android.systemui.statusbar.policy.HeadsUpManager}.
+ * Ties the status bar to {@link com.android.systemui.statusbar.policy.HeadsUpManager}.
  */
-@CentralSurfacesComponent.CentralSurfacesScope
-public class StatusBarHeadsUpChangeListener implements OnHeadsUpChangedListener {
+@SysUISingleton
+public class StatusBarHeadsUpChangeListener implements OnHeadsUpChangedListener, CoreStartable {
     private final NotificationShadeWindowController mNotificationShadeWindowController;
     private final StatusBarWindowController mStatusBarWindowController;
     private final ShadeViewController mShadeViewController;
@@ -63,6 +64,11 @@
     }
 
     @Override
+    public void start() {
+        mHeadsUpManager.addListener(this);
+    }
+
+    @Override
     public void onHeadsUpPinnedModeChanged(boolean inPinnedMode) {
         if (inPinnedMode) {
             mNotificationShadeWindowController.setHeadsUpShowing(true);
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 5c1dfbe..ea57eb4 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
@@ -22,6 +22,8 @@
 import static com.android.systemui.plugins.ActivityStarter.OnDismissAction;
 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.util.kotlin.JavaAdapterKt.collectFlow;
+import static com.android.systemui.util.kotlin.JavaAdapterKt.combineFlows;
 
 import android.content.Context;
 import android.content.res.ColorStateList;
@@ -60,10 +62,14 @@
 import com.android.systemui.bouncer.domain.interactor.PrimaryBouncerInteractor;
 import com.android.systemui.bouncer.ui.BouncerView;
 import com.android.systemui.dagger.SysUISingleton;
+import com.android.systemui.dagger.qualifiers.Main;
 import com.android.systemui.dock.DockManager;
 import com.android.systemui.dreams.DreamOverlayStateController;
 import com.android.systemui.flags.FeatureFlags;
 import com.android.systemui.flags.Flags;
+import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor;
+import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor;
+import com.android.systemui.keyguard.domain.interactor.WindowManagerLockscreenVisibilityInteractor;
 import com.android.systemui.navigationbar.NavigationBarView;
 import com.android.systemui.navigationbar.NavigationModeController;
 import com.android.systemui.navigationbar.TaskbarDelegate;
@@ -86,8 +92,6 @@
 import com.android.systemui.unfold.FoldAodAnimationController;
 import com.android.systemui.unfold.SysUIUnfoldComponent;
 
-import dagger.Lazy;
-
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.HashSet;
@@ -97,6 +101,9 @@
 
 import javax.inject.Inject;
 
+import dagger.Lazy;
+import kotlinx.coroutines.CoroutineDispatcher;
+
 /**
  * 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,
@@ -281,6 +288,9 @@
     private int mLastBiometricMode;
     private boolean mLastScreenOffAnimationPlaying;
     private float mQsExpansion;
+
+    private FeatureFlags mFlags;
+
     final Set<KeyguardViewManagerCallback> mCallbacks = new HashSet<>();
     private boolean mIsBackAnimationEnabled;
     private final boolean mUdfpsNewTouchDetectionEnabled;
@@ -326,6 +336,7 @@
             }
         }
     };
+    private Lazy<WindowManagerLockscreenVisibilityInteractor> mWmLockscreenVisibilityInteractor;
 
     @Inject
     public StatusBarKeyguardViewManager(
@@ -352,7 +363,10 @@
             BouncerView primaryBouncerView,
             AlternateBouncerInteractor alternateBouncerInteractor,
             UdfpsOverlayInteractor udfpsOverlayInteractor,
-            ActivityStarter activityStarter
+            ActivityStarter activityStarter,
+            KeyguardTransitionInteractor keyguardTransitionInteractor,
+            @Main CoroutineDispatcher mainDispatcher,
+            Lazy<WindowManagerLockscreenVisibilityInteractor> wmLockscreenVisibilityInteractor
     ) {
         mContext = context;
         mViewMediatorCallback = callback;
@@ -370,6 +384,7 @@
         mShadeController = shadeController;
         mLatencyTracker = latencyTracker;
         mKeyguardSecurityModel = keyguardSecurityModel;
+        mFlags = featureFlags;
         mPrimaryBouncerCallbackInteractor = primaryBouncerCallbackInteractor;
         mPrimaryBouncerInteractor = primaryBouncerInteractor;
         mPrimaryBouncerView = primaryBouncerView;
@@ -381,8 +396,14 @@
         mUdfpsNewTouchDetectionEnabled = featureFlags.isEnabled(Flags.UDFPS_NEW_TOUCH_DETECTION);
         mUdfpsOverlayInteractor = udfpsOverlayInteractor;
         mActivityStarter = activityStarter;
+        mKeyguardTransitionInteractor = keyguardTransitionInteractor;
+        mMainDispatcher = mainDispatcher;
+        mWmLockscreenVisibilityInteractor = wmLockscreenVisibilityInteractor;
     }
 
+    KeyguardTransitionInteractor mKeyguardTransitionInteractor;
+    CoroutineDispatcher mMainDispatcher;
+
     @Override
     public void registerCentralSurfaces(CentralSurfaces centralSurfaces,
             ShadeViewController shadeViewController,
@@ -429,6 +450,14 @@
         }
     }
 
+    private KeyguardStateController.Callback mKeyguardStateControllerCallback =
+            new KeyguardStateController.Callback() {
+                @Override
+                public void onUnlockedChanged() {
+                    updateAlternateBouncerShowing(mAlternateBouncerInteractor.maybeHide());
+                }
+            };
+
     private void registerListeners() {
         mKeyguardUpdateManager.registerCallback(mUpdateMonitorCallback);
         mStatusBarStateController.addCallback(this);
@@ -442,6 +471,32 @@
             mDockManager.addListener(mDockEventListener);
             mIsDocked = mDockManager.isDocked();
         }
+        mKeyguardStateController.addCallback(mKeyguardStateControllerCallback);
+
+        if (mFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+            mShadeViewController.postToView(() ->
+                    collectFlow(
+                        getViewRootImpl().getView(),
+                        combineFlows(
+                                mKeyguardTransitionInteractor.getFinishedKeyguardState(),
+                                mWmLockscreenVisibilityInteractor.get()
+                                        .getUsingKeyguardGoingAwayAnimation(),
+                                (finishedState, animating) ->
+                                        KeyguardInteractor.Companion.isKeyguardVisibleInState(
+                                                finishedState)
+                                                || animating),
+                        this::consumeShowStatusBarKeyguardView));
+        }
+    }
+
+    private void consumeShowStatusBarKeyguardView(boolean show) {
+        if (show != mLastShowing) {
+            if (show) {
+                show(null);
+            } else {
+                hide(0, 0);
+            }
+        }
     }
 
     /** Register a callback, to be invoked by the Predictive Back system. */
@@ -1313,6 +1368,10 @@
             hideAlternateBouncer(false);
             executeAfterKeyguardGoneAction();
         }
+
+        if (mFlags.isEnabled(Flags.KEYGUARD_WM_STATE_REFACTOR)) {
+            mKeyguardTransitionInteractor.startDismissKeyguardTransition();
+        }
     }
 
     /** Display security message to relevant KeyguardMessageArea. */
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 7fe01825..a6284e3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java
@@ -32,6 +32,8 @@
 import android.view.View;
 import android.view.ViewParent;
 
+import androidx.annotation.Nullable;
+
 import com.android.systemui.ActivityIntentHelper;
 import com.android.systemui.dagger.SysUISingleton;
 import com.android.systemui.dagger.qualifiers.Main;
@@ -254,16 +256,16 @@
 
     @Override
     public boolean handleRemoteViewClick(View view, PendingIntent pendingIntent,
-            boolean appRequestedAuth,
+            boolean appRequestedAuth, @Nullable Integer actionIndex,
             NotificationRemoteInputManager.ClickHandler defaultHandler) {
         final boolean isActivity = pendingIntent.isActivity();
         if (isActivity || appRequestedAuth) {
-            mActionClickLogger.logWaitingToCloseKeyguard(pendingIntent);
+            mActionClickLogger.logWaitingToCloseKeyguard(pendingIntent, actionIndex);
             final boolean afterKeyguardGone = mActivityIntentHelper
                     .wouldPendingLaunchResolverActivity(pendingIntent,
                             mLockscreenUserManager.getCurrentUserId());
             mActivityStarter.dismissKeyguardThenExecute(() -> {
-                mActionClickLogger.logKeyguardGone(pendingIntent);
+                mActionClickLogger.logKeyguardGone(pendingIntent, actionIndex);
 
                 try {
                     ActivityManager.getService().resumeAppSwitches();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockedScreenOffAnimationController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockedScreenOffAnimationController.kt
index e8da951..cd1afc7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockedScreenOffAnimationController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockedScreenOffAnimationController.kt
@@ -105,18 +105,18 @@
             }
         }
         addListener(object : AnimatorListenerAdapter() {
-            override fun onAnimationCancel(animation: Animator?) {
+            override fun onAnimationCancel(animation: Animator) {
                 if (lightRevealScrim.revealEffect !is CircleReveal) {
                     lightRevealScrim.revealAmount = 1f
                 }
             }
 
-            override fun onAnimationEnd(animation: Animator?) {
+            override fun onAnimationEnd(animation: Animator) {
                 lightRevealAnimationPlaying = false
                 interactionJankMonitor.end(CUJ_SCREEN_OFF)
             }
 
-            override fun onAnimationStart(animation: Animator?) {
+            override fun onAnimationStart(animation: Animator) {
                 interactionJankMonitor.begin(
                         notifShadeWindowControllerLazy.get().windowRootView, CUJ_SCREEN_OFF)
             }
@@ -223,10 +223,14 @@
                 }
                 .setCustomInterpolator(View.ALPHA, Interpolators.FAST_OUT_SLOW_IN),
             true /* animate */)
-        interactionJankMonitor.begin(
-                notifShadeWindowControllerLazy.get().windowRootView,
-            CUJ_SCREEN_OFF_SHOW_AOD
-        )
+        val builder = InteractionJankMonitor.Configuration.Builder
+            .withView(
+                    InteractionJankMonitor.CUJ_SCREEN_OFF_SHOW_AOD,
+                    notifShadeWindowControllerLazy.get().windowRootView
+            )
+            .setTag(statusBarStateControllerImpl.getClockId())
+
+        interactionJankMonitor.begin(builder)
     }
 
     override fun onStartedWakingUp() {
@@ -345,7 +349,7 @@
         // portrait. If we're in another orientation, disable the screen off animation so we don't
         // animate in the keyguard AOD UI sideways or upside down.
         if (!keyguardStateController.isKeyguardScreenRotationAllowed &&
-            context.display.rotation != Surface.ROTATION_0) {
+            context.display?.rotation != Surface.ROTATION_0) {
             return false
         }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/CentralSurfacesComponent.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/CentralSurfacesComponent.java
index 3a3663d..bbbe16f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/CentralSurfacesComponent.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/CentralSurfacesComponent.java
@@ -25,7 +25,6 @@
 import com.android.systemui.statusbar.notification.NotificationActivityStarter;
 import com.android.systemui.statusbar.phone.CentralSurfacesCommandQueueCallbacks;
 import com.android.systemui.statusbar.phone.CentralSurfacesImpl;
-import com.android.systemui.statusbar.phone.StatusBarHeadsUpChangeListener;
 import com.android.systemui.statusbar.phone.StatusBarNotificationActivityStarterModule;
 import com.android.systemui.statusbar.phone.fragment.CollapsedStatusBarFragment;
 
@@ -72,11 +71,6 @@
     WindowRootView getWindowRootView();
 
     /**
-     * Creates a StatusBarHeadsUpChangeListener.
-     */
-    StatusBarHeadsUpChangeListener getStatusBarHeadsUpChangeListener();
-
-    /**
      * Creates a CentralSurfacesCommandQueueCallbacks.
      */
     CentralSurfacesCommandQueueCallbacks getCentralSurfacesCommandQueueCallbacks();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/userswitcher/StatusBarUserSwitcherContainer.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/userswitcher/StatusBarUserSwitcherContainer.kt
index 270c592..1259477 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/userswitcher/StatusBarUserSwitcherContainer.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/userswitcher/StatusBarUserSwitcherContainer.kt
@@ -34,7 +34,7 @@
 
     override fun onFinishInflate() {
         super.onFinishInflate()
-        text = findViewById(R.id.current_user_name)
-        avatar = findViewById(R.id.current_user_avatar)
+        text = requireViewById(R.id.current_user_name)
+        avatar = requireViewById(R.id.current_user_avatar)
     }
 }
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
index 3a11635..c1af6df 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
@@ -118,6 +118,11 @@
     /** The service provider name for this network connection, or the default name */
     val networkName: StateFlow<NetworkNameModel>
 
+    /**
+     * True if this type of connection is allowed while airplane mode is on, and false otherwise.
+     */
+    val isAllowedDuringAirplaneMode: StateFlow<Boolean>
+
     companion object {
         /** The default number of levels to use for [numberOfLevels]. */
         const val DEFAULT_NUM_LEVELS = 4
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
index 6b86432..17d20c2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
@@ -186,6 +186,8 @@
 
     override val networkName = MutableStateFlow(NetworkNameModel.IntentDerived("demo network"))
 
+    override val isAllowedDuringAirplaneMode = MutableStateFlow(false)
+
     /**
      * Process a new demo mobile event. Note that [resolvedNetworkType] must be passed in separately
      * from the event, due to the requirement to reverse the mobile mappings lookup in the top-level
@@ -217,6 +219,8 @@
             (event.activity ?: TelephonyManager.DATA_ACTIVITY_NONE).toMobileDataActivityModel()
         _carrierNetworkChangeActive.value = event.carrierNetworkChange
         _resolvedNetworkType.value = resolvedNetworkType
+
+        isAllowedDuringAirplaneMode.value = false
     }
 
     fun processCarrierMergedEvent(event: FakeWifiEventModel.CarrierMerged) {
@@ -240,6 +244,7 @@
         _isInService.value = true
         _isGsm.value = false
         _carrierNetworkChangeActive.value = false
+        isAllowedDuringAirplaneMode.value = true
     }
 
     companion object {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt
index a609917..65f4866 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt
@@ -165,6 +165,13 @@
     override val isGsm = MutableStateFlow(false).asStateFlow()
     override val carrierNetworkChangeActive = MutableStateFlow(false).asStateFlow()
 
+    /**
+     * Carrier merged connections happen over wifi but are displayed as a mobile triangle. Because
+     * they occur over wifi, it's possible to have a valid carrier merged connection even during
+     * airplane mode. See b/291993542.
+     */
+    override val isAllowedDuringAirplaneMode = MutableStateFlow(true).asStateFlow()
+
     override val dataEnabled: StateFlow<Boolean> = wifiRepository.isWifiEnabled
 
     companion object {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt
index 8869dfe..8ba7d21 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt
@@ -287,6 +287,15 @@
             )
             .stateIn(scope, SharingStarted.WhileSubscribed(), activeRepo.value.networkName.value)
 
+    override val isAllowedDuringAirplaneMode =
+        activeRepo
+            .flatMapLatest { it.isAllowedDuringAirplaneMode }
+            .stateIn(
+                scope,
+                SharingStarted.WhileSubscribed(),
+                activeRepo.value.isAllowedDuringAirplaneMode.value,
+            )
+
     class Factory
     @Inject
     constructor(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt
index b475183..aadc975 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt
@@ -59,8 +59,10 @@
 import kotlinx.coroutines.asExecutor
 import kotlinx.coroutines.channels.awaitClose
 import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.SharingStarted
 import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
 import kotlinx.coroutines.flow.callbackFlow
 import kotlinx.coroutines.flow.filter
 import kotlinx.coroutines.flow.map
@@ -331,6 +333,9 @@
             .stateIn(scope, SharingStarted.WhileSubscribed(), initial)
     }
 
+    /** Typical mobile connections aren't available during airplane mode. */
+    override val isAllowedDuringAirplaneMode = MutableStateFlow(false).asStateFlow()
+
     class Factory
     @Inject
     constructor(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
index d42e30c..1a13827 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
@@ -111,6 +111,9 @@
     /** See [MobileIconsInteractor.isForceHidden]. */
     val isForceHidden: Flow<Boolean>
 
+    /** See [MobileConnectionRepository.isAllowedDuringAirplaneMode]. */
+    val isAllowedDuringAirplaneMode: StateFlow<Boolean>
+
     /** True when in carrier network change mode */
     val carrierNetworkChangeActive: StateFlow<Boolean>
 }
@@ -267,4 +270,6 @@
             .stateIn(scope, SharingStarted.WhileSubscribed(), false)
 
     override val isInService = connectionRepository.isInService
+
+    override val isAllowedDuringAirplaneMode = connectionRepository.isAllowedDuringAirplaneMode
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModel.kt
index 35f4f9a..275cfc5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModel.kt
@@ -102,9 +102,16 @@
             } else {
                 combine(
                     airplaneModeInteractor.isAirplaneMode,
+                    iconInteractor.isAllowedDuringAirplaneMode,
                     iconInteractor.isForceHidden,
-                ) { isAirplaneMode, isForceHidden ->
-                    !isAirplaneMode && !isForceHidden
+                ) { isAirplaneMode, isAllowedDuringAirplaneMode, isForceHidden ->
+                    if (isForceHidden) {
+                        false
+                    } else if (isAirplaneMode) {
+                        isAllowedDuringAirplaneMode
+                    } else {
+                        true
+                    }
                 }
             }
             .distinctUntilChanged()
@@ -214,36 +221,15 @@
     override val activityInVisible: Flow<Boolean> =
         activity
             .map { it?.hasActivityIn ?: false }
-            .distinctUntilChanged()
-            .logDiffsForTable(
-                iconInteractor.tableLogBuffer,
-                columnPrefix = "",
-                columnName = "activityInVisible",
-                initialValue = false,
-            )
             .stateIn(scope, SharingStarted.WhileSubscribed(), false)
 
     override val activityOutVisible: Flow<Boolean> =
         activity
             .map { it?.hasActivityOut ?: false }
-            .distinctUntilChanged()
-            .logDiffsForTable(
-                iconInteractor.tableLogBuffer,
-                columnPrefix = "",
-                columnName = "activityOutVisible",
-                initialValue = false,
-            )
             .stateIn(scope, SharingStarted.WhileSubscribed(), false)
 
     override val activityContainerVisible: Flow<Boolean> =
         activity
             .map { it != null && (it.hasActivityIn || it.hasActivityOut) }
-            .distinctUntilChanged()
-            .logDiffsForTable(
-                iconInteractor.tableLogBuffer,
-                columnPrefix = "",
-                columnName = "activityContainerVisible",
-                initialValue = false,
-            )
             .stateIn(scope, SharingStarted.WhileSubscribed(), false)
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepository.kt
index b11b472..b5b99a7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepository.kt
@@ -29,9 +29,18 @@
     /** Observable for the current wifi default status. */
     val isWifiDefault: StateFlow<Boolean>
 
-    /** Observable for the current wifi network. */
+    /** Observable for the current primary wifi network. */
     val wifiNetwork: StateFlow<WifiNetworkModel>
 
+    /**
+     * Observable for secondary wifi networks (if any). Should specifically exclude the primary
+     * network emitted by [wifiNetwork].
+     *
+     * This isn't used by phones/tablets, which only display the primary network, but may be used by
+     * other variants like Car.
+     */
+    val secondaryNetworks: StateFlow<List<WifiNetworkModel>>
+
     /** Observable for the current wifi network activity. */
     val wifiActivity: StateFlow<DataActivityModel>
 
@@ -49,6 +58,9 @@
         const val COL_NAME_IS_ENABLED = "isEnabled"
         /** Column name to use for [isWifiDefault] for table logging. */
         const val COL_NAME_IS_DEFAULT = "isDefault"
+
+        const val CARRIER_MERGED_INVALID_SUB_ID_REASON =
+            "Wifi network was carrier merged but had invalid sub ID"
     }
 }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositorySwitcher.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositorySwitcher.kt
index e96288a..80091ac 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositorySwitcher.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositorySwitcher.kt
@@ -115,6 +115,11 @@
             .flatMapLatest { it.wifiNetwork }
             .stateIn(scope, SharingStarted.WhileSubscribed(), realImpl.wifiNetwork.value)
 
+    override val secondaryNetworks: StateFlow<List<WifiNetworkModel>> =
+        activeRepo
+            .flatMapLatest { it.secondaryNetworks }
+            .stateIn(scope, SharingStarted.WhileSubscribed(), realImpl.secondaryNetworks.value)
+
     override val wifiActivity: StateFlow<DataActivityModel> =
         activeRepo
             .flatMapLatest { it.wifiActivity }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/DemoModeWifiDataSource.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/DemoModeWifiDataSource.kt
index 7d2501ca..ab9b516 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/DemoModeWifiDataSource.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/DemoModeWifiDataSource.kt
@@ -24,6 +24,7 @@
 import com.android.systemui.demomode.DemoModeController
 import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionRepository.Companion.DEFAULT_NUM_LEVELS
 import com.android.systemui.statusbar.pipeline.wifi.data.repository.demo.model.FakeWifiEventModel
+import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiNetworkModel
 import javax.inject.Inject
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.flow.SharingStarted
@@ -56,12 +57,14 @@
         val activity = getString("activity").toActivity()
         val ssid = getString("ssid")
         val validated = getString("fully").toBoolean()
+        val hotspotDeviceType = getString("hotspot").toHotspotDeviceType()
 
         return FakeWifiEventModel.Wifi(
             level = level,
             activity = activity,
             ssid = ssid,
             validated = validated,
+            hotspotDeviceType,
         )
     }
 
@@ -82,6 +85,20 @@
             else -> WifiManager.TrafficStateCallback.DATA_ACTIVITY_NONE
         }
 
+    private fun String?.toHotspotDeviceType(): WifiNetworkModel.HotspotDeviceType {
+        return when (this) {
+            null,
+            "none" -> WifiNetworkModel.HotspotDeviceType.NONE
+            "unknown" -> WifiNetworkModel.HotspotDeviceType.UNKNOWN
+            "phone" -> WifiNetworkModel.HotspotDeviceType.PHONE
+            "tablet" -> WifiNetworkModel.HotspotDeviceType.TABLET
+            "laptop" -> WifiNetworkModel.HotspotDeviceType.LAPTOP
+            "watch" -> WifiNetworkModel.HotspotDeviceType.WATCH
+            "auto" -> WifiNetworkModel.HotspotDeviceType.AUTO
+            else -> WifiNetworkModel.HotspotDeviceType.INVALID
+        }
+    }
+
     companion object {
         const val DEFAULT_CARRIER_MERGED_SUB_ID = 10
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/DemoWifiRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/DemoWifiRepository.kt
index a57be66..4b19c3a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/DemoWifiRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/DemoWifiRepository.kt
@@ -48,6 +48,9 @@
     private val _wifiNetwork = MutableStateFlow<WifiNetworkModel>(WifiNetworkModel.Inactive)
     override val wifiNetwork: StateFlow<WifiNetworkModel> = _wifiNetwork
 
+    private val _secondaryNetworks = MutableStateFlow<List<WifiNetworkModel>>(emptyList())
+    override val secondaryNetworks: StateFlow<List<WifiNetworkModel>> = _secondaryNetworks
+
     private val _wifiActivity =
         MutableStateFlow(DataActivityModel(hasActivityIn = false, hasActivityOut = false))
     override val wifiActivity: StateFlow<DataActivityModel> = _wifiActivity
@@ -97,6 +100,7 @@
             isValidated = validated ?: true,
             level = level ?: 0,
             ssid = ssid ?: DEMO_NET_SSID,
+            hotspotDeviceType = hotspotDeviceType,
 
             // These fields below aren't supported in demo mode, since they aren't needed to satisfy
             // the interface.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/model/FakeWifiEventModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/model/FakeWifiEventModel.kt
index f5035cbc..b2e843e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/model/FakeWifiEventModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/demo/model/FakeWifiEventModel.kt
@@ -17,6 +17,7 @@
 package com.android.systemui.statusbar.pipeline.wifi.data.repository.demo.model
 
 import android.telephony.Annotation
+import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiNetworkModel
 
 /**
  * Model for demo wifi commands, ported from [NetworkControllerImpl]
@@ -29,6 +30,8 @@
         @Annotation.DataActivityType val activity: Int,
         val ssid: String?,
         val validated: Boolean?,
+        val hotspotDeviceType: WifiNetworkModel.HotspotDeviceType =
+            WifiNetworkModel.HotspotDeviceType.NONE,
     ) : FakeWifiEventModel
 
     data class CarrierMerged(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/DisabledWifiRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/DisabledWifiRepository.kt
index 9ed7c6a..36c46a9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/DisabledWifiRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/DisabledWifiRepository.kt
@@ -43,6 +43,9 @@
 
     override val wifiNetwork: StateFlow<WifiNetworkModel> = MutableStateFlow(NETWORK).asStateFlow()
 
+    override val secondaryNetworks: StateFlow<List<WifiNetworkModel>> =
+        MutableStateFlow(emptyList<WifiNetworkModel>()).asStateFlow()
+
     override val wifiActivity: StateFlow<DataActivityModel> =
         MutableStateFlow(ACTIVITY).asStateFlow()
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryHelper.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryHelper.kt
new file mode 100644
index 0000000..f1b98b3
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryHelper.kt
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.pipeline.wifi.data.repository.prod
+
+import android.net.wifi.WifiManager
+import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow
+import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.log.table.TableLogBuffer
+import com.android.systemui.log.table.logDiffsForTable
+import com.android.systemui.statusbar.pipeline.shared.data.model.DataActivityModel
+import com.android.systemui.statusbar.pipeline.shared.data.model.toWifiDataActivityModel
+import java.util.concurrent.Executor
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.channels.awaitClose
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.stateIn
+
+/**
+ * Object to provide shared helper functions between [WifiRepositoryImpl] and
+ * [WifiRepositoryViaTrackerLib].
+ */
+object WifiRepositoryHelper {
+    /** Creates a flow that fetches the [DataActivityModel] from [WifiManager]. */
+    fun createActivityFlow(
+        wifiManager: WifiManager,
+        @Main mainExecutor: Executor,
+        scope: CoroutineScope,
+        tableLogBuffer: TableLogBuffer,
+        inputLogger: (String) -> Unit,
+    ): StateFlow<DataActivityModel> {
+        return conflatedCallbackFlow {
+                val callback =
+                    WifiManager.TrafficStateCallback { state ->
+                        inputLogger.invoke(prettyPrintActivity(state))
+                        trySend(state.toWifiDataActivityModel())
+                    }
+                wifiManager.registerTrafficStateCallback(mainExecutor, callback)
+                awaitClose { wifiManager.unregisterTrafficStateCallback(callback) }
+            }
+            .logDiffsForTable(
+                tableLogBuffer,
+                columnPrefix = ACTIVITY_PREFIX,
+                initialValue = ACTIVITY_DEFAULT,
+            )
+            .stateIn(
+                scope,
+                started = SharingStarted.WhileSubscribed(),
+                initialValue = ACTIVITY_DEFAULT,
+            )
+    }
+
+    // TODO(b/292534484): This print should only be done in [MessagePrinter] part of the log buffer.
+    private fun prettyPrintActivity(activity: Int): String {
+        return when (activity) {
+            WifiManager.TrafficStateCallback.DATA_ACTIVITY_NONE -> "NONE"
+            WifiManager.TrafficStateCallback.DATA_ACTIVITY_IN -> "IN"
+            WifiManager.TrafficStateCallback.DATA_ACTIVITY_OUT -> "OUT"
+            WifiManager.TrafficStateCallback.DATA_ACTIVITY_INOUT -> "INOUT"
+            else -> "INVALID"
+        }
+    }
+
+    private const val ACTIVITY_PREFIX = "wifiActivity"
+    val ACTIVITY_DEFAULT = DataActivityModel(hasActivityIn = false, hasActivityOut = false)
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt
index 995de6d..7c7b58d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt
@@ -28,7 +28,6 @@
 import android.net.NetworkRequest
 import android.net.wifi.WifiInfo
 import android.net.wifi.WifiManager
-import android.net.wifi.WifiManager.TrafficStateCallback
 import android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID
 import com.android.systemui.broadcast.BroadcastDispatcher
 import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow
@@ -40,10 +39,10 @@
 import com.android.systemui.log.table.logDiffsForTable
 import com.android.systemui.statusbar.pipeline.dagger.WifiTableLog
 import com.android.systemui.statusbar.pipeline.shared.data.model.DataActivityModel
-import com.android.systemui.statusbar.pipeline.shared.data.model.toWifiDataActivityModel
 import com.android.systemui.statusbar.pipeline.shared.data.repository.ConnectivityRepository
 import com.android.systemui.statusbar.pipeline.shared.data.repository.ConnectivityRepositoryImpl.Companion.getMainOrUnderlyingWifiInfo
 import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepository
+import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepository.Companion.CARRIER_MERGED_INVALID_SUB_ID_REASON
 import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepository.Companion.COL_NAME_IS_DEFAULT
 import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepository.Companion.COL_NAME_IS_ENABLED
 import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepositoryDagger
@@ -57,8 +56,10 @@
 import kotlinx.coroutines.channels.awaitClose
 import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.SharingStarted
 import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
 import kotlinx.coroutines.flow.distinctUntilChanged
 import kotlinx.coroutines.flow.map
 import kotlinx.coroutines.flow.mapLatest
@@ -217,30 +218,20 @@
                 initialValue = WIFI_NETWORK_DEFAULT,
             )
 
+    // Secondary networks can only be supported by [WifiRepositoryViaTrackerLib].
+    override val secondaryNetworks: StateFlow<List<WifiNetworkModel>> =
+        MutableStateFlow(emptyList<WifiNetworkModel>()).asStateFlow()
+
     override val wifiActivity: StateFlow<DataActivityModel> =
-        conflatedCallbackFlow {
-                val callback = TrafficStateCallback { state ->
-                    logger.logActivity(prettyPrintActivity(state))
-                    trySend(state.toWifiDataActivityModel())
-                }
-                wifiManager.registerTrafficStateCallback(mainExecutor, callback)
-                awaitClose { wifiManager.unregisterTrafficStateCallback(callback) }
-            }
-            .logDiffsForTable(
-                wifiTableLogBuffer,
-                columnPrefix = ACTIVITY_PREFIX,
-                initialValue = ACTIVITY_DEFAULT,
-            )
-            .stateIn(
-                scope,
-                started = SharingStarted.WhileSubscribed(),
-                initialValue = ACTIVITY_DEFAULT,
-            )
+        WifiRepositoryHelper.createActivityFlow(
+            wifiManager,
+            mainExecutor,
+            scope,
+            wifiTableLogBuffer,
+            logger::logActivity,
+        )
 
     companion object {
-        private const val ACTIVITY_PREFIX = "wifiActivity"
-
-        val ACTIVITY_DEFAULT = DataActivityModel(hasActivityIn = false, hasActivityOut = false)
         // Start out with no known wifi network.
         // Note: [WifiStatusTracker] (the old implementation of connectivity logic) does do an
         // initial fetch to get a starting wifi network. But, it uses a deprecated API
@@ -277,6 +268,8 @@
                     isValidated = networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED),
                     level = wifiManager.calculateSignalLevel(wifiInfo.rssi),
                     wifiInfo.ssid,
+                    // This repository doesn't support any hotspot information.
+                    WifiNetworkModel.HotspotDeviceType.NONE,
                     wifiInfo.isPasspointAp,
                     wifiInfo.isOsuAp,
                     wifiInfo.passpointProviderFriendlyName
@@ -284,16 +277,6 @@
             }
         }
 
-        private fun prettyPrintActivity(activity: Int): String {
-            return when (activity) {
-                TrafficStateCallback.DATA_ACTIVITY_NONE -> "NONE"
-                TrafficStateCallback.DATA_ACTIVITY_IN -> "IN"
-                TrafficStateCallback.DATA_ACTIVITY_OUT -> "OUT"
-                TrafficStateCallback.DATA_ACTIVITY_INOUT -> "INOUT"
-                else -> "INVALID"
-            }
-        }
-
         private val WIFI_NETWORK_CALLBACK_REQUEST: NetworkRequest =
             NetworkRequest.Builder()
                 .clearCapabilities()
@@ -301,9 +284,6 @@
                 .addTransportType(TRANSPORT_WIFI)
                 .addTransportType(TRANSPORT_CELLULAR)
                 .build()
-
-        private const val CARRIER_MERGED_INVALID_SUB_ID_REASON =
-            "Wifi network was carrier merged but had invalid sub ID"
     }
 
     @SysUISingleton
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryViaTrackerLib.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryViaTrackerLib.kt
index 1271367..d4f40dd 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryViaTrackerLib.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryViaTrackerLib.kt
@@ -17,12 +17,15 @@
 package com.android.systemui.statusbar.pipeline.wifi.data.repository.prod
 
 import android.net.wifi.WifiManager
+import android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID
 import androidx.lifecycle.Lifecycle
 import androidx.lifecycle.LifecycleOwner
 import androidx.lifecycle.LifecycleRegistry
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
 import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
 import com.android.systemui.log.LogBuffer
 import com.android.systemui.log.core.LogLevel
 import com.android.systemui.log.table.TableLogBuffer
@@ -31,20 +34,25 @@
 import com.android.systemui.statusbar.pipeline.dagger.WifiTrackerLibInputLog
 import com.android.systemui.statusbar.pipeline.dagger.WifiTrackerLibTableLog
 import com.android.systemui.statusbar.pipeline.shared.data.model.DataActivityModel
+import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepository.Companion.CARRIER_MERGED_INVALID_SUB_ID_REASON
 import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepository.Companion.COL_NAME_IS_DEFAULT
 import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepository.Companion.COL_NAME_IS_ENABLED
 import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepositoryViaTrackerLibDagger
 import com.android.systemui.statusbar.pipeline.wifi.data.repository.prod.WifiRepositoryImpl.Companion.WIFI_NETWORK_DEFAULT
 import com.android.systemui.statusbar.pipeline.wifi.data.repository.prod.WifiRepositoryImpl.Companion.WIFI_STATE_DEFAULT
 import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiNetworkModel
+import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiNetworkModel.Inactive.toHotspotDeviceType
+import com.android.wifitrackerlib.HotspotNetworkEntry
 import com.android.wifitrackerlib.MergedCarrierEntry
 import com.android.wifitrackerlib.WifiEntry
+import com.android.wifitrackerlib.WifiEntry.WIFI_LEVEL_MAX
+import com.android.wifitrackerlib.WifiEntry.WIFI_LEVEL_MIN
+import com.android.wifitrackerlib.WifiEntry.WIFI_LEVEL_UNREACHABLE
 import com.android.wifitrackerlib.WifiPickerTracker
 import java.util.concurrent.Executor
 import javax.inject.Inject
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.channels.awaitClose
-import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.SharingStarted
 import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.flow.callbackFlow
@@ -62,6 +70,7 @@
 class WifiRepositoryViaTrackerLib
 @Inject
 constructor(
+    featureFlags: FeatureFlags,
     @Application private val scope: CoroutineScope,
     @Main private val mainExecutor: Executor,
     private val wifiPickerTrackerFactory: WifiPickerTrackerFactory,
@@ -75,6 +84,8 @@
             mainExecutor.execute { it.currentState = Lifecycle.State.CREATED }
         }
 
+    private val isInstantTetherEnabled = featureFlags.isEnabled(Flags.INSTANT_TETHER)
+
     private var wifiPickerTracker: WifiPickerTracker? = null
 
     private val wifiPickerTrackerInfo: StateFlow<WifiPickerTrackerInfo> = run {
@@ -82,7 +93,8 @@
             WifiPickerTrackerInfo(
                 state = WIFI_STATE_DEFAULT,
                 isDefault = false,
-                network = WIFI_NETWORK_DEFAULT,
+                primaryNetwork = WIFI_NETWORK_DEFAULT,
+                secondaryNetworks = emptyList(),
             )
         callbackFlow {
                 val callback =
@@ -91,6 +103,17 @@
                             val connectedEntry = wifiPickerTracker?.connectedWifiEntry
                             logOnWifiEntriesChanged(connectedEntry)
 
+                            val secondaryNetworks =
+                                if (featureFlags.isEnabled(Flags.WIFI_SECONDARY_NETWORKS)) {
+                                    val activeNetworks =
+                                        wifiPickerTracker?.activeWifiEntries ?: emptyList()
+                                    activeNetworks
+                                        .filter { it != connectedEntry && !it.isPrimaryNetwork }
+                                        .map { it.toWifiNetworkModel() }
+                                } else {
+                                    emptyList()
+                                }
+
                             // [WifiPickerTracker.connectedWifiEntry] will return the same instance
                             // but with updated internals. For example, when its validation status
                             // changes from false to true, the same instance is re-used but with the
@@ -101,8 +124,9 @@
                             // into our internal model immediately. [toWifiNetworkModel] always
                             // returns a new instance, so the flow is guaranteed to emit.
                             send(
-                                newNetwork = connectedEntry?.toWifiNetworkModel()
+                                newPrimaryNetwork = connectedEntry?.toPrimaryWifiNetworkModel()
                                         ?: WIFI_NETWORK_DEFAULT,
+                                newSecondaryNetworks = secondaryNetworks,
                                 newIsDefault = connectedEntry?.isDefaultNetwork ?: false,
                             )
                         }
@@ -120,27 +144,37 @@
                         private fun send(
                             newState: Int = current.state,
                             newIsDefault: Boolean = current.isDefault,
-                            newNetwork: WifiNetworkModel = current.network,
+                            newPrimaryNetwork: WifiNetworkModel = current.primaryNetwork,
+                            newSecondaryNetworks: List<WifiNetworkModel> =
+                                current.secondaryNetworks,
                         ) {
-                            val new = WifiPickerTrackerInfo(newState, newIsDefault, newNetwork)
+                            val new =
+                                WifiPickerTrackerInfo(
+                                    newState,
+                                    newIsDefault,
+                                    newPrimaryNetwork,
+                                    newSecondaryNetworks,
+                                )
                             current = new
                             trySend(new)
                         }
                     }
 
-                // TODO(b/292591403): [WifiPickerTrackerFactory] currently scans to see all
-                // available wifi networks every 10s. Because SysUI only needs to display the
-                // **connected** network, we don't need scans to be running. We should disable these
-                // scans (ideal) or at least run them very infrequently.
-                wifiPickerTracker = wifiPickerTrackerFactory.create(lifecycle, callback)
+                wifiPickerTracker =
+                    wifiPickerTrackerFactory.create(lifecycle, callback).apply {
+                        // By default, [WifiPickerTracker] will scan to see all available wifi
+                        // networks in the area. Because SysUI only needs to display the
+                        // **connected** network, we don't need scans to be running (and in fact,
+                        // running scans is costly and should be avoided whenever possible).
+                        this?.disableScanning()
+                    }
                 // The lifecycle must be STARTED in order for the callback to receive events.
                 mainExecutor.execute { lifecycle.currentState = Lifecycle.State.STARTED }
                 awaitClose {
                     mainExecutor.execute { lifecycle.currentState = Lifecycle.State.CREATED }
                 }
             }
-            // TODO(b/292534484): Update to Eagerly once scans are disabled. (Here and other flows)
-            .stateIn(scope, SharingStarted.WhileSubscribed(), current)
+            .stateIn(scope, SharingStarted.Eagerly, current)
     }
 
     override val isWifiEnabled: StateFlow<Boolean> =
@@ -153,49 +187,98 @@
                 columnName = COL_NAME_IS_ENABLED,
                 initialValue = false,
             )
-            .stateIn(scope, SharingStarted.WhileSubscribed(), false)
+            .stateIn(scope, SharingStarted.Eagerly, false)
 
     override val wifiNetwork: StateFlow<WifiNetworkModel> =
         wifiPickerTrackerInfo
-            .map { it.network }
+            .map { it.primaryNetwork }
             .distinctUntilChanged()
             .logDiffsForTable(
                 wifiTrackerLibTableLogBuffer,
                 columnPrefix = "",
                 initialValue = WIFI_NETWORK_DEFAULT,
             )
-            .stateIn(scope, SharingStarted.WhileSubscribed(), WIFI_NETWORK_DEFAULT)
+            .stateIn(scope, SharingStarted.Eagerly, WIFI_NETWORK_DEFAULT)
+
+    override val secondaryNetworks: StateFlow<List<WifiNetworkModel>> =
+        wifiPickerTrackerInfo
+            .map { it.secondaryNetworks }
+            .distinctUntilChanged()
+            .logDiffsForTable(
+                wifiTrackerLibTableLogBuffer,
+                columnPrefix = "",
+                columnName = "secondaryNetworks",
+                initialValue = emptyList(),
+            )
+            .stateIn(scope, SharingStarted.Eagerly, emptyList())
+
+    /**
+     * Converts WifiTrackerLib's [WifiEntry] into our internal model only if the entry is the
+     * primary network. Returns an inactive network if it's not primary.
+     */
+    private fun WifiEntry.toPrimaryWifiNetworkModel(): WifiNetworkModel {
+        return if (!this.isPrimaryNetwork) {
+            WIFI_NETWORK_DEFAULT
+        } else {
+            this.toWifiNetworkModel()
+        }
+    }
 
     /** Converts WifiTrackerLib's [WifiEntry] into our internal model. */
     private fun WifiEntry.toWifiNetworkModel(): WifiNetworkModel {
-        if (!this.isPrimaryNetwork) {
-            return WIFI_NETWORK_DEFAULT
-        }
         return if (this is MergedCarrierEntry) {
+            this.convertCarrierMergedToModel()
+        } else {
+            this.convertNormalToModel()
+        }
+    }
+
+    private fun MergedCarrierEntry.convertCarrierMergedToModel(): WifiNetworkModel {
+        return if (this.subscriptionId == INVALID_SUBSCRIPTION_ID) {
+            WifiNetworkModel.Invalid(CARRIER_MERGED_INVALID_SUB_ID_REASON)
+        } else {
             WifiNetworkModel.CarrierMerged(
                 networkId = NETWORK_ID,
-                // TODO(b/292534484): Fetch the real subscription ID from [MergedCarrierEntry].
-                subscriptionId = TEMP_SUB_ID,
+                subscriptionId = this.subscriptionId,
                 level = this.level,
                 // WifiManager APIs to calculate the signal level start from 0, so
                 // maxSignalLevel + 1 represents the total level buckets count.
                 numberOfLevels = wifiManager.maxSignalLevel + 1,
             )
-        } else {
-            WifiNetworkModel.Active(
-                networkId = NETWORK_ID,
-                isValidated = this.hasInternetAccess(),
-                level = this.level,
-                ssid = this.ssid,
-                // TODO(b/292534484): Fetch the real values from [WifiEntry] (#getTitle might be
-                // appropriate).
-                isPasspointAccessPoint = false,
-                isOnlineSignUpForPasspointAccessPoint = false,
-                passpointProviderFriendlyName = null,
-            )
         }
     }
 
+    private fun WifiEntry.convertNormalToModel(): WifiNetworkModel {
+        if (this.level == WIFI_LEVEL_UNREACHABLE || this.level !in WIFI_LEVEL_MIN..WIFI_LEVEL_MAX) {
+            // If our level means the network is unreachable or the level is otherwise invalid, we
+            // don't have an active network.
+            return WifiNetworkModel.Inactive
+        }
+
+        val hotspotDeviceType =
+            if (isInstantTetherEnabled && this is HotspotNetworkEntry) {
+                this.deviceType.toHotspotDeviceType()
+            } else {
+                WifiNetworkModel.HotspotDeviceType.NONE
+            }
+
+        return WifiNetworkModel.Active(
+            networkId = NETWORK_ID,
+            isValidated = this.hasInternetAccess(),
+            level = this.level,
+            ssid = this.title,
+            hotspotDeviceType = hotspotDeviceType,
+            // With WifiTrackerLib, [WifiEntry.title] will appropriately fetch the  SSID for
+            // typical wifi networks *and* passpoint/OSU APs. So, the AP-specific values can
+            // always be false/null in this repository.
+            // TODO(b/292534484): Remove these fields from the wifi network model once this
+            //  repository is fully enabled.
+            isPasspointAccessPoint = false,
+            isOnlineSignUpForPasspointAccessPoint = false,
+            passpointProviderFriendlyName = null,
+        )
+    }
+
     override val isWifiDefault: StateFlow<Boolean> =
         wifiPickerTrackerInfo
             .map { it.isDefault }
@@ -206,12 +289,16 @@
                 columnName = COL_NAME_IS_DEFAULT,
                 initialValue = false,
             )
-            .stateIn(scope, SharingStarted.WhileSubscribed(), false)
+            .stateIn(scope, SharingStarted.Eagerly, false)
 
-    // TODO(b/292534484): Re-use WifiRepositoryImpl code to implement wifi activity since
-    // WifiTrackerLib doesn't expose activity details.
     override val wifiActivity: StateFlow<DataActivityModel> =
-        MutableStateFlow(DataActivityModel(false, false))
+        WifiRepositoryHelper.createActivityFlow(
+            wifiManager,
+            mainExecutor,
+            scope,
+            wifiTrackerLibTableLogBuffer,
+            this::logActivity,
+        )
 
     private fun logOnWifiEntriesChanged(connectedEntry: WifiEntry?) {
         inputLogger.log(
@@ -231,6 +318,10 @@
         )
     }
 
+    private fun logActivity(activity: String) {
+        inputLogger.log(TAG, LogLevel.DEBUG, { str1 = activity }, { "onActivityChanged: $str1" })
+    }
+
     /**
      * Data class storing all the information fetched from [WifiPickerTracker].
      *
@@ -242,13 +333,16 @@
         /** True if wifi is currently the default connection and false otherwise. */
         val isDefault: Boolean,
         /** The currently primary wifi network. */
-        val network: WifiNetworkModel,
+        val primaryNetwork: WifiNetworkModel,
+        /** The current secondary network(s), if any. Specifically excludes the primary network. */
+        val secondaryNetworks: List<WifiNetworkModel>
     )
 
     @SysUISingleton
     class Factory
     @Inject
     constructor(
+        private val featureFlags: FeatureFlags,
         @Application private val scope: CoroutineScope,
         @Main private val mainExecutor: Executor,
         private val wifiPickerTrackerFactory: WifiPickerTrackerFactory,
@@ -257,6 +351,7 @@
     ) {
         fun create(wifiManager: WifiManager): WifiRepositoryViaTrackerLib {
             return WifiRepositoryViaTrackerLib(
+                featureFlags,
                 scope,
                 mainExecutor,
                 wifiPickerTrackerFactory,
@@ -283,13 +378,5 @@
          * to [WifiRepositoryViaTrackerLib].
          */
         private const val NETWORK_ID = -1
-
-        /**
-         * A temporary subscription ID until WifiTrackerLib exposes a method to fetch the
-         * subscription ID.
-         *
-         * Use -2 because [SubscriptionManager.INVALID_SUBSCRIPTION_ID] is -1.
-         */
-        private const val TEMP_SUB_ID = -2
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/shared/model/WifiNetworkModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/shared/model/WifiNetworkModel.kt
index 4b33c88..7078a2e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/shared/model/WifiNetworkModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/shared/model/WifiNetworkModel.kt
@@ -17,11 +17,13 @@
 package com.android.systemui.statusbar.pipeline.wifi.shared.model
 
 import android.net.wifi.WifiManager.UNKNOWN_SSID
+import android.net.wifi.sharedconnectivity.app.NetworkProviderInfo
 import android.telephony.SubscriptionManager
 import androidx.annotation.VisibleForTesting
 import com.android.systemui.log.table.Diffable
 import com.android.systemui.log.table.TableRowLogger
 import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionRepository
+import com.android.wifitrackerlib.HotspotNetworkEntry.DeviceType
 
 /** Provides information about the current wifi network. */
 sealed class WifiNetworkModel : Diffable<WifiNetworkModel> {
@@ -52,6 +54,7 @@
             row.logChange(COL_LEVEL, LEVEL_DEFAULT)
             row.logChange(COL_NUM_LEVELS, NUM_LEVELS_DEFAULT)
             row.logChange(COL_SSID, null)
+            row.logChange(COL_HOTSPOT, null)
             row.logChange(COL_PASSPOINT_ACCESS_POINT, false)
             row.logChange(COL_ONLINE_SIGN_UP, false)
             row.logChange(COL_PASSPOINT_NAME, null)
@@ -83,6 +86,7 @@
             row.logChange(COL_LEVEL, LEVEL_DEFAULT)
             row.logChange(COL_NUM_LEVELS, NUM_LEVELS_DEFAULT)
             row.logChange(COL_SSID, null)
+            row.logChange(COL_HOTSPOT, null)
             row.logChange(COL_PASSPOINT_ACCESS_POINT, false)
             row.logChange(COL_ONLINE_SIGN_UP, false)
             row.logChange(COL_PASSPOINT_NAME, null)
@@ -110,6 +114,7 @@
             row.logChange(COL_LEVEL, LEVEL_DEFAULT)
             row.logChange(COL_NUM_LEVELS, NUM_LEVELS_DEFAULT)
             row.logChange(COL_SSID, null)
+            row.logChange(COL_HOTSPOT, null)
             row.logChange(COL_PASSPOINT_ACCESS_POINT, false)
             row.logChange(COL_ONLINE_SIGN_UP, false)
             row.logChange(COL_PASSPOINT_NAME, null)
@@ -184,6 +189,7 @@
             row.logChange(COL_LEVEL, level)
             row.logChange(COL_NUM_LEVELS, numberOfLevels)
             row.logChange(COL_SSID, null)
+            row.logChange(COL_HOTSPOT, null)
             row.logChange(COL_PASSPOINT_ACCESS_POINT, false)
             row.logChange(COL_ONLINE_SIGN_UP, false)
             row.logChange(COL_PASSPOINT_NAME, null)
@@ -209,6 +215,12 @@
         /** See [android.net.wifi.WifiInfo.ssid]. */
         val ssid: String? = null,
 
+        /**
+         * The type of device providing a hotspot connection, or [HotspotDeviceType.NONE] if this
+         * isn't a hotspot connection.
+         */
+        val hotspotDeviceType: HotspotDeviceType = WifiNetworkModel.HotspotDeviceType.NONE,
+
         /** See [android.net.wifi.WifiInfo.isPasspointAp]. */
         val isPasspointAccessPoint: Boolean = false,
 
@@ -247,6 +259,9 @@
             if (prevVal.ssid != ssid) {
                 row.logChange(COL_SSID, ssid)
             }
+            if (prevVal.hotspotDeviceType != hotspotDeviceType) {
+                row.logChange(COL_HOTSPOT, hotspotDeviceType.name)
+            }
 
             // TODO(b/238425913): The passpoint-related values are frequently never used, so it
             //   would be great to not log them when they're not used.
@@ -272,6 +287,7 @@
             row.logChange(COL_LEVEL, level)
             row.logChange(COL_NUM_LEVELS, null)
             row.logChange(COL_SSID, ssid)
+            row.logChange(COL_HOTSPOT, hotspotDeviceType.name)
             row.logChange(COL_PASSPOINT_ACCESS_POINT, isPasspointAccessPoint)
             row.logChange(COL_ONLINE_SIGN_UP, isOnlineSignUpForPasspointAccessPoint)
             row.logChange(COL_PASSPOINT_NAME, passpointProviderFriendlyName)
@@ -298,13 +314,51 @@
         }
 
         companion object {
+            // TODO(b/292534484): Use [com.android.wifitrackerlib.WifiEntry.WIFI_LEVEL_MAX] instead
+            // once the migration to WifiTrackerLib is complete.
             @VisibleForTesting internal const val MAX_VALID_LEVEL = 4
         }
     }
 
     companion object {
+        // TODO(b/292534484): Use [com.android.wifitrackerlib.WifiEntry.WIFI_LEVEL_MIN] instead
+        // once the migration to WifiTrackerLib is complete.
         @VisibleForTesting internal const val MIN_VALID_LEVEL = 0
     }
+
+    /**
+     * Enum for the type of device providing the hotspot connection, or [NONE] if this connection
+     * isn't a hotspot.
+     */
+    enum class HotspotDeviceType {
+        /* This wifi connection isn't a hotspot. */
+        NONE,
+        /** The device type for this hotspot is unknown. */
+        UNKNOWN,
+        PHONE,
+        TABLET,
+        LAPTOP,
+        WATCH,
+        AUTO,
+        /** The device type sent for this hotspot is invalid to SysUI. */
+        INVALID,
+    }
+
+    /**
+     * Converts a device type from [com.android.wifitrackerlib.HotspotNetworkEntry.deviceType] to
+     * our internal representation.
+     */
+    fun @receiver:DeviceType Int.toHotspotDeviceType(): HotspotDeviceType {
+        return when (this) {
+            NetworkProviderInfo.DEVICE_TYPE_UNKNOWN -> HotspotDeviceType.UNKNOWN
+            NetworkProviderInfo.DEVICE_TYPE_PHONE -> HotspotDeviceType.PHONE
+            NetworkProviderInfo.DEVICE_TYPE_TABLET -> HotspotDeviceType.TABLET
+            NetworkProviderInfo.DEVICE_TYPE_LAPTOP -> HotspotDeviceType.LAPTOP
+            NetworkProviderInfo.DEVICE_TYPE_WATCH -> HotspotDeviceType.WATCH
+            NetworkProviderInfo.DEVICE_TYPE_AUTO -> HotspotDeviceType.AUTO
+            else -> HotspotDeviceType.INVALID
+        }
+    }
 }
 
 const val TYPE_CARRIER_MERGED = "CarrierMerged"
@@ -319,6 +373,7 @@
 const val COL_LEVEL = "level"
 const val COL_NUM_LEVELS = "maxLevel"
 const val COL_SSID = "ssid"
+const val COL_HOTSPOT = "hotspot"
 const val COL_PASSPOINT_ACCESS_POINT = "isPasspointAccessPoint"
 const val COL_ONLINE_SIGN_UP = "isOnlineSignUpForPasspointAccessPoint"
 const val COL_PASSPOINT_NAME = "passpointProviderFriendlyName"
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 7df083afc..37eda64 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryController.java
@@ -162,6 +162,9 @@
         default void onIsBatteryDefenderChanged(boolean isBatteryDefender) {
         }
 
+        default void onIsIncompatibleChargingChanged(boolean isIncompatibleCharging) {
+        }
+
         @Override
         default void dump(@NonNull PrintWriter pw, @NonNull String[] args) {
             pw.println(this);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java
index d5d8f4d..4b51511 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java
@@ -29,6 +29,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.hardware.usb.UsbManager;
 import android.os.BatteryManager;
 import android.os.Bundle;
 import android.os.Handler;
@@ -42,6 +43,7 @@
 import androidx.annotation.Nullable;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.settingslib.Utils;
 import com.android.settingslib.fuelgauge.BatterySaverUtils;
 import com.android.settingslib.fuelgauge.Estimate;
 import com.android.settingslib.utils.PowerUtil;
@@ -97,6 +99,7 @@
     private boolean mAodPowerSave;
     private boolean mWirelessCharging;
     private boolean mIsBatteryDefender = false;
+    private boolean mIsIncompatibleCharging = false;
     private boolean mTestMode = false;
     @VisibleForTesting
     boolean mHasReceivedBattery = false;
@@ -136,6 +139,7 @@
         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
         filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
         filter.addAction(ACTION_LEVEL_TEST);
+        filter.addAction(UsbManager.ACTION_USB_PORT_COMPLIANCE_CHANGED);
         mBroadcastDispatcher.registerReceiver(this, filter);
     }
 
@@ -169,6 +173,7 @@
         ipw.print("mCharging="); ipw.println(mCharging);
         ipw.print("mCharged="); ipw.println(mCharged);
         ipw.print("mIsBatteryDefender="); ipw.println(mIsBatteryDefender);
+        ipw.print("mIsIncompatibleCharging="); ipw.println(mIsIncompatibleCharging);
         ipw.print("mPowerSave="); ipw.println(mPowerSave);
         ipw.print("mStateUnknown="); ipw.println(mStateUnknown);
         ipw.println("Callbacks:------------------");
@@ -214,6 +219,7 @@
         cb.onBatteryUnknownStateChanged(mStateUnknown);
         cb.onWirelessChargingChanged(mWirelessCharging);
         cb.onIsBatteryDefenderChanged(mIsBatteryDefender);
+        cb.onIsIncompatibleChargingChanged(mIsIncompatibleCharging);
     }
 
     @Override
@@ -229,7 +235,7 @@
         if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
             if (mTestMode && !intent.getBooleanExtra("testmode", false)) return;
             mHasReceivedBattery = true;
-            mLevel = (int)(100f
+            mLevel = (int) (100f
                     * intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
                     / intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100));
             mPluggedChargingSource = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
@@ -262,6 +268,12 @@
             fireBatteryLevelChanged();
         } else if (action.equals(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)) {
             updatePowerSave();
+        } else if (action.equals(UsbManager.ACTION_USB_PORT_COMPLIANCE_CHANGED)) {
+            boolean isIncompatibleCharging = Utils.containsIncompatibleChargers(mContext, TAG);
+            if (isIncompatibleCharging != mIsIncompatibleCharging) {
+                mIsIncompatibleCharging = isIncompatibleCharging;
+                fireIsIncompatibleChargingChanged();
+            }
         } else if (action.equals(ACTION_LEVEL_TEST)) {
             mTestMode = true;
             mMainHandler.post(new Runnable() {
@@ -270,6 +282,7 @@
                 int mSavedLevel = mLevel;
                 boolean mSavedPluggedIn = mPluggedIn;
                 Intent mTestIntent = new Intent(Intent.ACTION_BATTERY_CHANGED);
+
                 @Override
                 public void run() {
                     if (mCurrentLevel < 0) {
@@ -333,6 +346,13 @@
         return mIsBatteryDefender;
     }
 
+    /**
+     * Returns whether the charging adapter is incompatible.
+     */
+    public boolean isIncompatibleCharging() {
+        return mIsIncompatibleCharging;
+    }
+
     @Override
     public void getEstimatedTimeRemainingString(EstimateFetchCompletion completion) {
         // Need to fetch or refresh the estimate, but it may involve binder calls so offload the
@@ -453,6 +473,15 @@
         }
     }
 
+    private void fireIsIncompatibleChargingChanged() {
+        synchronized (mChangeCallbacks) {
+            final int n = mChangeCallbacks.size();
+            for (int i = 0; i < n; i++) {
+                mChangeCallbacks.get(i).onIsIncompatibleChargingChanged(mIsIncompatibleCharging);
+            }
+        }
+    }
+
     @Override
     public void dispatchDemoCommand(String command, Bundle args) {
         if (!mDemoModeController.isInDemoMode()) {
@@ -464,6 +493,7 @@
         String powerSave = args.getString("powersave");
         String present = args.getString("present");
         String defender = args.getString("defender");
+        String incompatible = args.getString("incompatible");
         if (level != null) {
             mLevel = Math.min(Math.max(Integer.parseInt(level), 0), 100);
         }
@@ -482,6 +512,10 @@
             mIsBatteryDefender = defender.equals("true");
             fireIsBatteryDefenderChanged();
         }
+        if (incompatible != null) {
+            mIsIncompatibleCharging = incompatible.equals("true");
+            fireIsIncompatibleChargingChanged();
+        }
         fireBatteryLevelChanged();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/ConfigurationController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/ConfigurationController.java
index 6b80a9d..b2ef818 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/ConfigurationController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/ConfigurationController.java
@@ -42,5 +42,6 @@
         default void onThemeChanged() {}
         default void onLocaleListChanged() {}
         default void onLayoutDirectionChanged(boolean isLayoutRtl) {}
+        default void onOrientationChanged(int orientation) {}
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceControlsControllerImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceControlsControllerImpl.kt
index 4950482..ffb743f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceControlsControllerImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceControlsControllerImpl.kt
@@ -128,7 +128,8 @@
 
         val prefs = userContextProvider.userContext.getSharedPreferences(
             PREFS_CONTROLS_FILE, Context.MODE_PRIVATE)
-        val seededPackages = prefs.getStringSet(PREFS_CONTROLS_SEEDING_COMPLETED, emptySet())
+        val seededPackages =
+            prefs.getStringSet(PREFS_CONTROLS_SEEDING_COMPLETED, emptySet()) ?: emptySet()
 
         val controlsController = controlsComponent.getControlsController().get()
         val componentsToSeed = mutableListOf<ComponentName>()
@@ -174,7 +175,8 @@
     }
 
     private fun addPackageToSeededSet(prefs: SharedPreferences, pkg: String) {
-        val seededPackages = prefs.getStringSet(PREFS_CONTROLS_SEEDING_COMPLETED, emptySet())
+        val seededPackages =
+            prefs.getStringSet(PREFS_CONTROLS_SEEDING_COMPLETED, emptySet()) ?: emptySet()
         val updatedPkgs = seededPackages.toMutableSet()
         updatedPkgs.add(pkg)
         prefs.edit().putStringSet(PREFS_CONTROLS_SEEDING_COMPLETED, updatedPkgs).apply()
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateControllerImpl.java
index 710588c..63dcad9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateControllerImpl.java
@@ -18,6 +18,8 @@
 
 import static android.hardware.biometrics.BiometricSourceType.FACE;
 
+import static com.android.systemui.flags.Flags.LOCKSCREEN_ENABLE_LANDSCAPE;
+
 import android.annotation.NonNull;
 import android.content.BroadcastReceiver;
 import android.content.Context;
@@ -38,6 +40,7 @@
 import com.android.systemui.R;
 import com.android.systemui.dagger.SysUISingleton;
 import com.android.systemui.dump.DumpManager;
+import com.android.systemui.flags.FeatureFlags;
 import com.android.systemui.keyguard.KeyguardUnlockAnimationController;
 
 import dagger.Lazy;
@@ -49,6 +52,7 @@
 import javax.inject.Inject;
 
 /**
+ *
  */
 @SysUISingleton
 public class KeyguardStateControllerImpl implements KeyguardStateController, Dumpable {
@@ -103,7 +107,10 @@
      */
     private boolean mSnappingKeyguardBackAfterSwipe = false;
 
+    private FeatureFlags mFeatureFlags;
+
     /**
+     *
      */
     @Inject
     public KeyguardStateControllerImpl(
@@ -112,13 +119,15 @@
             LockPatternUtils lockPatternUtils,
             Lazy<KeyguardUnlockAnimationController> keyguardUnlockAnimationController,
             KeyguardUpdateMonitorLogger logger,
-            DumpManager dumpManager) {
+            DumpManager dumpManager,
+            FeatureFlags featureFlags) {
         mContext = context;
         mLogger = logger;
         mKeyguardUpdateMonitor = keyguardUpdateMonitor;
         mLockPatternUtils = lockPatternUtils;
         mKeyguardUpdateMonitor.registerCallback(mKeyguardUpdateMonitorCallback);
         mUnlockAnimationControllerLazy = keyguardUnlockAnimationController;
+        mFeatureFlags = featureFlags;
 
         dumpManager.registerDumpable(getClass().getSimpleName(), this);
 
@@ -272,7 +281,8 @@
     @Override
     public boolean isKeyguardScreenRotationAllowed() {
         return SystemProperties.getBoolean("lockscreen.rot_override", false)
-                || mContext.getResources().getBoolean(R.bool.config_enableLockScreenRotation);
+                || mContext.getResources().getBoolean(R.bool.config_enableLockScreenRotation)
+                || mFeatureFlags.isEnabled(LOCKSCREEN_ENABLE_LANDSCAPE);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/LocationControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/LocationControllerImpl.java
index f8c36dc..518a9b3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/LocationControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/LocationControllerImpl.java
@@ -55,7 +55,6 @@
 import com.android.systemui.dagger.qualifiers.Main;
 import com.android.systemui.settings.UserTracker;
 import com.android.systemui.util.DeviceConfigProxy;
-import com.android.systemui.util.Utils;
 import com.android.systemui.util.settings.SecureSettings;
 
 import java.util.ArrayList;
@@ -362,7 +361,8 @@
         private static final int MSG_ADD_CALLBACK = 3;
         private static final int MSG_REMOVE_CALLBACK = 4;
 
-        private ArrayList<LocationChangeCallback> mSettingsChangeCallbacks = new ArrayList<>();
+        private final ArrayList<LocationChangeCallback> mSettingsChangeCallbacks =
+                new ArrayList<>();
 
         H(Looper looper) {
             super(looper);
@@ -388,14 +388,23 @@
         }
 
         private void locationActiveChanged() {
-            Utils.safeForeach(mSettingsChangeCallbacks,
-                    cb -> cb.onLocationActiveChanged(mAreActiveLocationRequests));
+            synchronized (mSettingsChangeCallbacks) {
+                final int n = mSettingsChangeCallbacks.size();
+                for (int i = 0; i < n; i++) {
+                    mSettingsChangeCallbacks.get(i)
+                            .onLocationActiveChanged(mAreActiveLocationRequests);
+                }
+            }
         }
 
         private void locationSettingsChanged() {
             boolean isEnabled = isLocationEnabled();
-            Utils.safeForeach(mSettingsChangeCallbacks,
-                    cb -> cb.onLocationSettingsChanged(isEnabled));
+            synchronized (mSettingsChangeCallbacks) {
+                final int n = mSettingsChangeCallbacks.size();
+                for (int i = 0; i < n; i++) {
+                    mSettingsChangeCallbacks.get(i).onLocationSettingsChanged(isEnabled);
+                }
+            }
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/VariableDateView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/policy/VariableDateView.kt
index ae9d9ee..cd1dcd5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/VariableDateView.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/VariableDateView.kt
@@ -64,7 +64,7 @@
     override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
         val availableWidth = MeasureSpec.getSize(widthMeasureSpec) - paddingStart - paddingEnd
         if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED && !freezeSwitching) {
-            onMeasureListener?.onMeasureAction(availableWidth)
+            onMeasureListener?.onMeasureAction(availableWidth, widthMeasureSpec)
         }
         super.onMeasure(widthMeasureSpec, heightMeasureSpec)
     }
@@ -74,6 +74,6 @@
     }
 
     interface OnMeasureListener {
-        fun onMeasureAction(availableWidth: Int)
+        fun onMeasureAction(availableWidth: Int, widthMeasureSpec: Int)
     }
 }
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/VariableDateViewController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/policy/VariableDateViewController.kt
index f040d0a..eaae0f0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/VariableDateViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/VariableDateViewController.kt
@@ -28,9 +28,12 @@
 import android.os.UserHandle
 import android.text.TextUtils
 import android.util.Log
+import android.view.View.MeasureSpec
 import androidx.annotation.VisibleForTesting
 import com.android.systemui.Dependency
 import com.android.systemui.broadcast.BroadcastDispatcher
+import com.android.systemui.shade.ShadeExpansionStateManager
+import com.android.systemui.shade.ShadeLogger
 import com.android.systemui.util.ViewController
 import com.android.systemui.util.time.SystemClock
 import java.text.FieldPosition
@@ -80,6 +83,8 @@
 class VariableDateViewController(
     private val systemClock: SystemClock,
     private val broadcastDispatcher: BroadcastDispatcher,
+    private val shadeExpansionStateManager: ShadeExpansionStateManager,
+    private val shadeLogger: ShadeLogger,
     private val timeTickHandler: Handler,
     view: VariableDateView
 ) : ViewController<VariableDateView>(view) {
@@ -94,6 +99,7 @@
                 post(::updateClock)
             }
         }
+    private var isQsExpanded = false
     private var lastWidth = Integer.MAX_VALUE
     private var lastText = ""
     private var currentTime = Date()
@@ -107,31 +113,40 @@
 
     private val intentReceiver: BroadcastReceiver = object : BroadcastReceiver() {
         override fun onReceive(context: Context, intent: Intent) {
+            val action = intent.action
+            if (
+                    Intent.ACTION_LOCALE_CHANGED == action ||
+                    Intent.ACTION_TIMEZONE_CHANGED == action
+            ) {
+                // need to get a fresh date format
+                dateFormat = null
+                shadeLogger.d("VariableDateViewController received intent to refresh date format")
+            }
+
+            val handler = mView.handler
+
             // If the handler is null, it means we received a broadcast while the view has not
             // finished being attached or in the process of being detached.
             // In that case, do not post anything.
-            val handler = mView.handler ?: return
-            val action = intent.action
-            if (
+            if (handler == null) {
+                shadeLogger.d("VariableDateViewController received intent but handler was null")
+            } else if (
                     Intent.ACTION_TIME_TICK == action ||
                     Intent.ACTION_TIME_CHANGED == action ||
                     Intent.ACTION_TIMEZONE_CHANGED == action ||
                     Intent.ACTION_LOCALE_CHANGED == action
             ) {
-                if (
-                        Intent.ACTION_LOCALE_CHANGED == action ||
-                        Intent.ACTION_TIMEZONE_CHANGED == action
-                ) {
-                    // need to get a fresh date format
-                    handler.post { dateFormat = null }
-                }
                 handler.post(::updateClock)
             }
         }
     }
 
     private val onMeasureListener = object : VariableDateView.OnMeasureListener {
-        override fun onMeasureAction(availableWidth: Int) {
+        override fun onMeasureAction(availableWidth: Int, widthMeasureSpec: Int) {
+            if (!isQsExpanded && MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) {
+                // ignore measured width from AT_MOST passes when in QQS (b/289489856)
+                return
+            }
             if (availableWidth != lastWidth) {
                 // maybeChangeFormat will post if the pattern needs to change.
                 maybeChangeFormat(availableWidth)
@@ -140,6 +155,15 @@
         }
     }
 
+    private fun onQsExpansionFractionChanged(qsExpansionFraction: Float) {
+        val newIsQsExpanded = qsExpansionFraction > 0.5
+        if (newIsQsExpanded != isQsExpanded) {
+            isQsExpanded = newIsQsExpanded
+            // manually trigger a measure pass midway through the transition from QS to QQS
+            post { mView.measure(0, 0) }
+        }
+    }
+
     override fun onViewAttached() {
         val filter = IntentFilter().apply {
             addAction(Intent.ACTION_TIME_TICK)
@@ -151,6 +175,7 @@
         broadcastDispatcher.registerReceiver(intentReceiver, filter,
                 HandlerExecutor(timeTickHandler), UserHandle.SYSTEM)
 
+        shadeExpansionStateManager.addQsExpansionFractionListener(::onQsExpansionFractionChanged)
         post(::updateClock)
         mView.onAttach(onMeasureListener)
     }
@@ -158,6 +183,7 @@
     override fun onViewDetached() {
         dateFormat = null
         mView.onAttach(null)
+        shadeExpansionStateManager.removeQsExpansionFractionListener(::onQsExpansionFractionChanged)
         broadcastDispatcher.unregisterReceiver(intentReceiver)
     }
 
@@ -211,12 +237,16 @@
     class Factory @Inject constructor(
         private val systemClock: SystemClock,
         private val broadcastDispatcher: BroadcastDispatcher,
+        private val shadeExpansionStateManager: ShadeExpansionStateManager,
+        private val shadeLogger: ShadeLogger,
         @Named(Dependency.TIME_TICK_HANDLER_NAME) private val handler: Handler
     ) {
         fun create(view: VariableDateView): VariableDateViewController {
             return VariableDateViewController(
                     systemClock,
                     broadcastDispatcher,
+                    shadeExpansionStateManager,
+                    shadeLogger,
                     handler,
                     view
             )
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/RemoteInput.kt b/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/RemoteInput.kt
index d4abc40..d31c001 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/RemoteInput.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/RemoteInput.kt
@@ -41,7 +41,7 @@
 }
 
 @Module
-private interface InternalRemoteInputViewModule {
+interface InternalRemoteInputViewModule {
     @Binds
     fun bindController(impl: RemoteInputViewControllerImpl): RemoteInputViewController
 }
diff --git a/packages/SystemUI/src/com/android/systemui/stylus/StylusManager.kt b/packages/SystemUI/src/com/android/systemui/stylus/StylusManager.kt
index 27aaa68..eb7d339 100644
--- a/packages/SystemUI/src/com/android/systemui/stylus/StylusManager.kt
+++ b/packages/SystemUI/src/com/android/systemui/stylus/StylusManager.kt
@@ -353,8 +353,8 @@
                     // before CoreStartables run, and will not be removed.
                     // In many cases, it reports the battery level of the stylus.
                     registerBatteryListener(deviceId)
-                } else if (device.bluetoothAddress != null) {
-                    onStylusBluetoothConnected(deviceId, device.bluetoothAddress)
+                } else {
+                    device.bluetoothAddress?.let { onStylusBluetoothConnected(deviceId, it) }
                 }
             }
         }
diff --git a/packages/SystemUI/src/com/android/systemui/user/UserSwitcherFullscreenDialog.kt b/packages/SystemUI/src/com/android/systemui/user/UserSwitcherFullscreenDialog.kt
index 72786ef..5ad96303 100644
--- a/packages/SystemUI/src/com/android/systemui/user/UserSwitcherFullscreenDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/user/UserSwitcherFullscreenDialog.kt
@@ -60,7 +60,7 @@
 
     override fun getWidth(): Int {
         val displayMetrics = context.resources.displayMetrics.apply {
-            context.display.getRealMetrics(this)
+            checkNotNull(context.display).getRealMetrics(this)
         }
         return displayMetrics.widthPixels
     }
diff --git a/packages/SystemUI/src/com/android/systemui/user/UserSwitcherPopupMenu.kt b/packages/SystemUI/src/com/android/systemui/user/UserSwitcherPopupMenu.kt
index 088cd93..ee84580 100644
--- a/packages/SystemUI/src/com/android/systemui/user/UserSwitcherPopupMenu.kt
+++ b/packages/SystemUI/src/com/android/systemui/user/UserSwitcherPopupMenu.kt
@@ -52,22 +52,22 @@
     override fun show() {
         // need to call show() first in order to construct the listView
         super.show()
-        val listView = getListView()
+        listView?.apply {
+            isVerticalScrollBarEnabled = false
+            isHorizontalScrollBarEnabled = false
 
-        listView.setVerticalScrollBarEnabled(false)
-        listView.setHorizontalScrollBarEnabled(false)
+            // Creates a transparent spacer between items
+            val shape = ShapeDrawable()
+            shape.alpha = 0
+            divider = shape
+            dividerHeight = res.getDimensionPixelSize(
+                R.dimen.bouncer_user_switcher_popup_divider_height)
 
-        // Creates a transparent spacer between items
-        val shape = ShapeDrawable()
-        shape.setAlpha(0)
-        listView.setDivider(shape)
-        listView.setDividerHeight(res.getDimensionPixelSize(
-            R.dimen.bouncer_user_switcher_popup_divider_height))
-
-        val height = res.getDimensionPixelSize(R.dimen.bouncer_user_switcher_popup_header_height)
-        listView.addHeaderView(createSpacer(height), null, false)
-        listView.addFooterView(createSpacer(height), null, false)
-        setWidth(findMaxWidth(listView))
+            val height = res.getDimensionPixelSize(R.dimen.bouncer_user_switcher_popup_header_height)
+            addHeaderView(createSpacer(height), null, false)
+            addFooterView(createSpacer(height), null, false)
+            setWidth(findMaxWidth(this))
+        }
 
         super.show()
     }
diff --git a/packages/SystemUI/src/com/android/systemui/user/domain/interactor/GuestUserInteractor.kt b/packages/SystemUI/src/com/android/systemui/user/domain/interactor/GuestUserInteractor.kt
index f026f0f..bfed0c4 100644
--- a/packages/SystemUI/src/com/android/systemui/user/domain/interactor/GuestUserInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/user/domain/interactor/GuestUserInteractor.kt
@@ -227,7 +227,8 @@
                     )
                 }
                 try {
-                    WindowManagerGlobal.getWindowManagerService().lockNow(/* options= */ null)
+                    checkNotNull(WindowManagerGlobal.getWindowManagerService())
+                        .lockNow(/* options= */ null)
                 } catch (e: RemoteException) {
                     Log.e(
                         TAG,
diff --git a/packages/SystemUI/src/com/android/systemui/user/legacyhelper/ui/LegacyUserUiHelper.kt b/packages/SystemUI/src/com/android/systemui/user/legacyhelper/ui/LegacyUserUiHelper.kt
index 00ca92d..1ac86ce 100644
--- a/packages/SystemUI/src/com/android/systemui/user/legacyhelper/ui/LegacyUserUiHelper.kt
+++ b/packages/SystemUI/src/com/android/systemui/user/legacyhelper/ui/LegacyUserUiHelper.kt
@@ -67,7 +67,7 @@
         val resourceId: Int? = getGuestUserRecordNameResourceId(record)
         return when {
             resourceId != null -> context.getString(resourceId)
-            record.info != null -> record.info.name
+            record.info != null -> checkNotNull(record.info.name)
             else ->
                 context.getString(
                     getUserSwitcherActionTextResourceId(
diff --git a/packages/SystemUI/src/com/android/systemui/util/IListenerSet.kt b/packages/SystemUI/src/com/android/systemui/util/IListenerSet.kt
new file mode 100644
index 0000000..b0230b8
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/util/IListenerSet.kt
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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
+
+/**
+ * A collection of listeners, observers, callbacks, etc.
+ *
+ * This container is optimized for infrequent mutation and frequent iteration, with thread safety
+ * and reentrant-safety guarantees as well. Specifically, to ensure that
+ * [ConcurrentModificationException] is never thrown, this iterator will not reflect changes made to
+ * the set after the iterator is constructed.
+ */
+interface IListenerSet<E : Any> : Set<E> {
+    /**
+     * A thread-safe, reentrant-safe method to add a listener. Does nothing if the listener is
+     * already in the set.
+     */
+    fun addIfAbsent(element: E): Boolean
+
+    /** A thread-safe, reentrant-safe method to remove a listener. */
+    fun remove(element: E): Boolean
+}
diff --git a/packages/SystemUI/src/com/android/systemui/util/ListenerSet.kt b/packages/SystemUI/src/com/android/systemui/util/ListenerSet.kt
index a47e614..f8e0b3d 100644
--- a/packages/SystemUI/src/com/android/systemui/util/ListenerSet.kt
+++ b/packages/SystemUI/src/com/android/systemui/util/ListenerSet.kt
@@ -29,20 +29,12 @@
 class ListenerSet<E : Any>
 /** Private constructor takes the internal list so that we can use auto-delegation */
 private constructor(private val listeners: CopyOnWriteArrayList<E>) :
-    Collection<E> by listeners, Set<E> {
+    Collection<E> by listeners, IListenerSet<E> {
 
     /** Create a new instance */
     constructor() : this(CopyOnWriteArrayList())
 
-    /**
-     * A thread-safe, reentrant-safe method to add a listener. Does nothing if the listener is
-     * already in the set.
-     */
-    fun addIfAbsent(element: E): Boolean = listeners.addIfAbsent(element)
+    override fun addIfAbsent(element: E): Boolean = listeners.addIfAbsent(element)
 
-    /** A thread-safe, reentrant-safe method to remove a listener. */
-    fun remove(element: E): Boolean = listeners.remove(element)
+    override fun remove(element: E): Boolean = listeners.remove(element)
 }
-
-/** Extension to match Collection which is implemented to only be (easily) accessible in kotlin */
-fun <T : Any> ListenerSet<T>.isNotEmpty(): Boolean = !isEmpty()
diff --git a/packages/SystemUI/src/com/android/systemui/util/NamedListenerSet.kt b/packages/SystemUI/src/com/android/systemui/util/NamedListenerSet.kt
new file mode 100644
index 0000000..c90b57e
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/util/NamedListenerSet.kt
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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
+
+import java.util.concurrent.CopyOnWriteArrayList
+import java.util.function.Consumer
+
+/**
+ * A collection of listeners, observers, callbacks, etc.
+ *
+ * This container is optimized for infrequent mutation and frequent iteration, with thread safety
+ * and reentrant-safety guarantees as well. Specifically, to ensure that
+ * [ConcurrentModificationException] is never thrown, this iterator will not reflect changes made to
+ * the set after the iterator is constructed.
+ *
+ * This class provides all the abilities of [ListenerSet], except that each listener has a name
+ * calculated at runtime which can be used for time-efficient tracing of listener invocations.
+ */
+class NamedListenerSet<E : Any>(
+    private val getName: (E) -> String = { it.javaClass.name },
+) : IListenerSet<E> {
+    private val listeners = CopyOnWriteArrayList<NamedListener>()
+
+    override val size: Int
+        get() = listeners.size
+
+    override fun isEmpty() = listeners.isEmpty()
+
+    override fun iterator(): Iterator<E> = iterator {
+        listeners.iterator().forEach { yield(it.listener) }
+    }
+
+    override fun containsAll(elements: Collection<E>) =
+        listeners.count { it.listener in elements } == elements.size
+
+    override fun contains(element: E) = listeners.firstOrNull { it.listener == element } != null
+
+    override fun addIfAbsent(element: E): Boolean = listeners.addIfAbsent(NamedListener(element))
+
+    override fun remove(element: E): Boolean = listeners.removeIf { it.listener == element }
+
+    /** A wrapper for the listener with an associated name. */
+    inner class NamedListener(val listener: E) {
+        val name: String = getName(listener)
+
+        override fun hashCode(): Int {
+            return listener.hashCode()
+        }
+
+        override fun equals(other: Any?): Boolean =
+            when {
+                other === null -> false
+                other === this -> true
+                other !is NamedListenerSet<*>.NamedListener -> false
+                listener == other.listener -> true
+                else -> false
+            }
+    }
+
+    /** Iterate the listeners in the set, providing the name for each one as well. */
+    inline fun forEachNamed(block: (String, E) -> Unit) =
+        namedIterator().forEach { element -> block(element.name, element.listener) }
+
+    /**
+     * Iterate the listeners in the set, wrapping each call to the block with [traceSection] using
+     * the listener name.
+     */
+    inline fun forEachTraced(block: (E) -> Unit) = forEachNamed { name, listener ->
+        traceSection(name) { block(listener) }
+    }
+
+    /**
+     * Iterate the listeners in the set, wrapping each call to the block with [traceSection] using
+     * the listener name.
+     */
+    fun forEachTraced(consumer: Consumer<E>) = forEachNamed { name, listener ->
+        traceSection(name) { consumer.accept(listener) }
+    }
+
+    /** Iterate over the [NamedListener]s currently in the set. */
+    fun namedIterator(): Iterator<NamedListener> = listeners.iterator()
+}
diff --git a/packages/SystemUI/src/com/android/systemui/util/Utils.java b/packages/SystemUI/src/com/android/systemui/util/Utils.java
index c2727fc..e0daa070 100644
--- a/packages/SystemUI/src/com/android/systemui/util/Utils.java
+++ b/packages/SystemUI/src/com/android/systemui/util/Utils.java
@@ -37,6 +37,10 @@
     /**
      * Allows lambda iteration over a list. It is done in reverse order so it is safe
      * to add or remove items during the iteration.  Skips over null items.
+     *
+     * @deprecated According to b/286841705, this is *not* safe: If an item is removed from the
+     *   list, then list.get(i) could throw an IndexOutOfBoundsException. This method should not be
+     *   used; try using `synchronized` or making a copy of the list instead.
      */
     public static <T> void safeForeach(List<T> list, Consumer<T> c) {
         for (int i = list.size() - 1; i >= 0; i--) {
diff --git a/packages/SystemUI/src/com/android/systemui/util/animation/TransitionLayout.kt b/packages/SystemUI/src/com/android/systemui/util/animation/TransitionLayout.kt
index 56c5d3b..7866d76 100644
--- a/packages/SystemUI/src/com/android/systemui/util/animation/TransitionLayout.kt
+++ b/packages/SystemUI/src/com/android/systemui/util/animation/TransitionLayout.kt
@@ -223,11 +223,11 @@
         }
     }
 
-    override fun dispatchDraw(canvas: Canvas?) {
-        canvas?.save()
-        canvas?.clipRect(boundsRect)
+    override fun dispatchDraw(canvas: Canvas) {
+        canvas.save()
+        canvas.clipRect(boundsRect)
         super.dispatchDraw(canvas)
-        canvas?.restore()
+        canvas.restore()
     }
 
     private fun updateBounds() {
diff --git a/packages/SystemUI/src/com/android/systemui/util/kotlin/JavaAdapter.kt b/packages/SystemUI/src/com/android/systemui/util/kotlin/JavaAdapter.kt
index 12d7b4d..0d0a646 100644
--- a/packages/SystemUI/src/com/android/systemui/util/kotlin/JavaAdapter.kt
+++ b/packages/SystemUI/src/com/android/systemui/util/kotlin/JavaAdapter.kt
@@ -29,7 +29,7 @@
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.Job
 import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.flow.combine
 import kotlinx.coroutines.launch
 
 /** A class allowing Java classes to collect on Kotlin flows. */
@@ -75,3 +75,7 @@
         repeatOnLifecycle(state) { flow.collect { consumer.accept(it) } }
     }
 }
+
+fun <A, B, R> combineFlows(flow1: Flow<A>, flow2: Flow<B>, bifunction: (A, B) -> R): Flow<R> {
+    return combine(flow1, flow2, bifunction)
+}
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogControllerImpl.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogControllerImpl.java
index 53f4837..9cc3cdb 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogControllerImpl.java
@@ -67,7 +67,6 @@
 import com.android.systemui.R;
 import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.dagger.SysUISingleton;
-import com.android.systemui.dagger.qualifiers.Main;
 import com.android.systemui.dump.DumpManager;
 import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.plugins.VolumeDialogController;
@@ -84,6 +83,7 @@
 import java.util.Map;
 import java.util.Objects;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
 
 import javax.inject.Inject;
 
@@ -134,7 +134,7 @@
     private final Receiver mReceiver = new Receiver();
     private final RingerModeObservers mRingerModeObservers;
     private final MediaSessions mMediaSessions;
-    private CaptioningManager mCaptioningManager;
+    private final AtomicReference<CaptioningManager> mCaptioningManager = new AtomicReference<>();
     private final KeyguardManager mKeyguardManager;
     private final ActivityManager mActivityManager;
     private final UserTracker mUserTracker;
@@ -158,16 +158,16 @@
 
     private final WakefulnessLifecycle.Observer mWakefullnessLifecycleObserver =
             new WakefulnessLifecycle.Observer() {
-        @Override
-        public void onStartedWakingUp() {
-            mDeviceInteractive = true;
-        }
+                @Override
+                public void onStartedWakingUp() {
+                    mDeviceInteractive = true;
+                }
 
-        @Override
-        public void onFinishedGoingToSleep() {
-            mDeviceInteractive = false;
-        }
-    };
+                @Override
+                public void onFinishedGoingToSleep() {
+                    mDeviceInteractive = false;
+                }
+            };
 
     @Inject
     public VolumeDialogControllerImpl(
@@ -185,8 +185,7 @@
             KeyguardManager keyguardManager,
             ActivityManager activityManager,
             UserTracker userTracker,
-            DumpManager dumpManager,
-            @Main Handler mainHandler
+            DumpManager dumpManager
     ) {
         mContext = context.getApplicationContext();
         mPackageManager = packageManager;
@@ -215,7 +214,7 @@
         mKeyguardManager = keyguardManager;
         mActivityManager = activityManager;
         mUserTracker = userTracker;
-        mUserTracker.addCallback(mUserChangedCallback, new HandlerExecutor(mainHandler));
+        mUserTracker.addCallback(mUserChangedCallback, new HandlerExecutor(mWorker));
         createCaptioningManagerServiceByUserContext(mUserTracker.getUserContext());
 
         dumpManager.registerDumpable("VolumeDialogControllerImpl", this);
@@ -223,8 +222,8 @@
         boolean accessibilityVolumeStreamActive = accessibilityManager
                 .isAccessibilityVolumeStreamActive();
         mVolumeController.setA11yMode(accessibilityVolumeStreamActive ?
-                    VolumePolicy.A11Y_MODE_INDEPENDENT_A11Y_VOLUME :
-                        VolumePolicy.A11Y_MODE_MEDIA_A11Y_VOLUME);
+                VolumePolicy.A11Y_MODE_INDEPENDENT_A11Y_VOLUME :
+                VolumePolicy.A11Y_MODE_MEDIA_A11Y_VOLUME);
 
         mWakefulnessLifecycle.addObserver(mWakefullnessLifecycleObserver);
     }
@@ -337,15 +336,15 @@
             };
 
     private void createCaptioningManagerServiceByUserContext(@NonNull Context userContext) {
-        mCaptioningManager = userContext.getSystemService(CaptioningManager.class);
+        mCaptioningManager.set(userContext.getSystemService(CaptioningManager.class));
     }
 
-    public boolean areCaptionsEnabled() {
-        return mCaptioningManager.isSystemAudioCaptioningEnabled();
+    public void getCaptionsEnabledState(boolean checkForSwitchState) {
+        mWorker.obtainMessage(W.GET_CAPTIONS_ENABLED_STATE, checkForSwitchState).sendToTarget();
     }
 
-    public void setCaptionsEnabled(boolean isEnabled) {
-        mCaptioningManager.setSystemAudioCaptioningEnabled(isEnabled);
+    public void setCaptionsEnabledState(boolean enabled) {
+        mWorker.obtainMessage(W.SET_CAPTIONS_ENABLED_STATE, enabled).sendToTarget();
     }
 
     public void getCaptionsComponentState(boolean fromTooltip) {
@@ -386,8 +385,8 @@
     }
 
     public void setEnableDialogs(boolean volumeUi, boolean safetyWarning) {
-      mShowVolumeDialog = volumeUi;
-      mShowSafetyWarning = safetyWarning;
+        mShowVolumeDialog = volumeUi;
+        mShowSafetyWarning = safetyWarning;
     }
 
     @Override
@@ -438,12 +437,38 @@
     }
 
     private void onShowCsdWarningW(@AudioManager.CsdWarning int csdWarning, int durationMs) {
-            mCallbacks.onShowCsdWarning(csdWarning, durationMs);
+        mCallbacks.onShowCsdWarning(csdWarning, durationMs);
     }
 
     private void onGetCaptionsComponentStateW(boolean fromTooltip) {
-        mCallbacks.onCaptionComponentStateChanged(
-                mCaptioningManager.isSystemAudioCaptioningUiEnabled(), fromTooltip);
+        CaptioningManager captioningManager = mCaptioningManager.get();
+        if (null != captioningManager) {
+            mCallbacks.onCaptionComponentStateChanged(
+                    captioningManager.isSystemAudioCaptioningUiEnabled(), fromTooltip);
+        } else {
+            Log.e(TAG, "onGetCaptionsComponentStateW(), null captioningManager");
+        }
+    }
+
+    private void onGetCaptionsEnabledStateW(boolean checkForSwitchState) {
+        CaptioningManager captioningManager = mCaptioningManager.get();
+        if (null != captioningManager) {
+            mCallbacks.onCaptionEnabledStateChanged(
+                    captioningManager.isSystemAudioCaptioningEnabled(), checkForSwitchState);
+        } else {
+            Log.e(TAG, "onGetCaptionsEnabledStateW(), null captioningManager");
+        }
+    }
+
+    private void onSetCaptionsEnabledStateW(boolean enabled) {
+        CaptioningManager captioningManager = mCaptioningManager.get();
+        if (null != captioningManager) {
+            captioningManager.setSystemAudioCaptioningEnabled(enabled);
+            mCallbacks.onCaptionEnabledStateChanged(
+                    captioningManager.isSystemAudioCaptioningEnabled(), false);
+        } else {
+            Log.e(TAG, "onGetCaptionsEnabledStateW(), null captioningManager");
+        }
     }
 
     private void onAccessibilityModeChanged(Boolean showA11yStream) {
@@ -822,6 +847,8 @@
         private static final int ACCESSIBILITY_MODE_CHANGED = 15;
         private static final int GET_CAPTIONS_COMPONENT_STATE = 16;
         private static final int SHOW_CSD_WARNING = 17;
+        private static final int GET_CAPTIONS_ENABLED_STATE = 18;
+        private static final int SET_CAPTIONS_ENABLED_STATE = 19;
 
         W(Looper looper) {
             super(looper);
@@ -849,6 +876,10 @@
                 case ACCESSIBILITY_MODE_CHANGED: onAccessibilityModeChanged((Boolean) msg.obj);
                     break;
                 case SHOW_CSD_WARNING: onShowCsdWarningW(msg.arg1, msg.arg2); break;
+                case GET_CAPTIONS_ENABLED_STATE:
+                    onGetCaptionsEnabledStateW((Boolean) msg.obj); break;
+                case SET_CAPTIONS_ENABLED_STATE:
+                    onSetCaptionsEnabledStateW((Boolean) msg.obj); break;
             }
         }
     }
@@ -1017,6 +1048,17 @@
                                 componentEnabled, fromTooltip));
             }
         }
+
+        @Override
+        public void onCaptionEnabledStateChanged(Boolean isEnabled, Boolean checkBeforeSwitch) {
+            boolean captionsEnabled = isEnabled != null && isEnabled;
+            for (final Map.Entry<Callbacks, Handler> entry : mCallbackMap.entrySet()) {
+                entry.getValue().post(
+                        () -> entry.getKey().onCaptionEnabledStateChanged(
+                                captionsEnabled, checkBeforeSwitch));
+            }
+        }
+
     }
 
     private final class RingerModeObservers {
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
index 0e97e21..dcc0525 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
@@ -1333,21 +1333,30 @@
 
         if (!isServiceComponentEnabled) return;
 
-        updateCaptionsIcon();
+        checkEnabledStateForCaptionsIconUpdate();
         if (fromTooltip) showCaptionsTooltip();
     }
 
-    private void updateCaptionsIcon() {
-        boolean captionsEnabled = mController.areCaptionsEnabled();
-        if (mODICaptionsIcon.getCaptionsEnabled() != captionsEnabled) {
-            mHandler.post(mODICaptionsIcon.setCaptionsEnabled(captionsEnabled));
+    private void updateCaptionsEnabledH(boolean isCaptionsEnabled, boolean checkForSwitchState) {
+        if (checkForSwitchState) {
+            mController.setCaptionsEnabledState(!isCaptionsEnabled);
+        } else {
+            updateCaptionsIcon(isCaptionsEnabled);
+        }
+    }
+
+    private void checkEnabledStateForCaptionsIconUpdate() {
+        mController.getCaptionsEnabledState(false);
+    }
+
+    private void updateCaptionsIcon(boolean isCaptionsEnabled) {
+        if (mODICaptionsIcon.getCaptionsEnabled() != isCaptionsEnabled) {
+            mHandler.post(mODICaptionsIcon.setCaptionsEnabled(isCaptionsEnabled));
         }
     }
 
     private void onCaptionIconClicked() {
-        boolean isEnabled = mController.areCaptionsEnabled();
-        mController.setCaptionsEnabled(!isEnabled);
-        updateCaptionsIcon();
+        mController.getCaptionsEnabledState(true);
     }
 
     private void incrementManualToggleCount() {
@@ -2365,7 +2374,6 @@
             } else {
                 updateRowsH(activeRow);
             }
-
         }
 
         @Override
@@ -2373,6 +2381,11 @@
                 Boolean isComponentEnabled, Boolean fromTooltip) {
             updateODICaptionsH(isComponentEnabled, fromTooltip);
         }
+
+        @Override
+        public void onCaptionEnabledStateChanged(Boolean isEnabled, Boolean checkForSwitchState) {
+            updateCaptionsEnabledH(isEnabled, checkForSwitchState);
+        }
     };
 
     @VisibleForTesting void onPostureChanged(int posture) {
diff --git a/packages/SystemUI/src/com/android/systemui/wallpapers/ImageWallpaper.java b/packages/SystemUI/src/com/android/systemui/wallpapers/ImageWallpaper.java
index 316b54e..aea3030 100644
--- a/packages/SystemUI/src/com/android/systemui/wallpapers/ImageWallpaper.java
+++ b/packages/SystemUI/src/com/android/systemui/wallpapers/ImageWallpaper.java
@@ -109,6 +109,7 @@
         private WallpaperManager mWallpaperManager;
         private final WallpaperLocalColorExtractor mWallpaperLocalColorExtractor;
         private SurfaceHolder mSurfaceHolder;
+        private boolean mDrawn = false;
         @VisibleForTesting
         static final int MIN_SURFACE_WIDTH = 128;
         @VisibleForTesting
@@ -133,6 +134,7 @@
             setShowForAllUsers(true);
             mWallpaperLocalColorExtractor = new WallpaperLocalColorExtractor(
                     mLongExecutor,
+                    mLock,
                     new WallpaperLocalColorExtractor.WallpaperLocalColorExtractorCallback() {
                         @Override
                         public void onColorsProcessed(List<RectF> regions,
@@ -238,6 +240,7 @@
 
         private void drawFrameSynchronized() {
             synchronized (mLock) {
+                if (mDrawn) return;
                 drawFrameInternal();
             }
         }
@@ -275,6 +278,7 @@
                 Rect dest = mSurfaceHolder.getSurfaceFrame();
                 try {
                     canvas.drawBitmap(bitmap, null, dest, null);
+                    mDrawn = true;
                 } finally {
                     surface.unlockCanvasAndPost(canvas);
                 }
diff --git a/packages/SystemUI/src/com/android/systemui/wallpapers/WallpaperLocalColorExtractor.java b/packages/SystemUI/src/com/android/systemui/wallpapers/WallpaperLocalColorExtractor.java
index 1e8446f..e2ec8dc 100644
--- a/packages/SystemUI/src/com/android/systemui/wallpapers/WallpaperLocalColorExtractor.java
+++ b/packages/SystemUI/src/com/android/systemui/wallpapers/WallpaperLocalColorExtractor.java
@@ -61,7 +61,7 @@
     private int mBitmapWidth = -1;
     private int mBitmapHeight = -1;
 
-    private final Object mLock = new Object();
+    private final Object mLock;
 
     private final List<RectF> mPendingRegions = new ArrayList<>();
     private final Set<RectF> mProcessedRegions = new ArraySet<>();
@@ -102,12 +102,15 @@
     /**
      * Creates a new color extractor.
      * @param longExecutor the executor on which the color extraction will be performed
+     * @param lock the lock object to use for computing colors or processing the bitmap
      * @param wallpaperLocalColorExtractorCallback an interface to handle the callbacks from
      *                                        the color extractor.
      */
     public WallpaperLocalColorExtractor(@LongRunning Executor longExecutor,
+            Object lock,
             WallpaperLocalColorExtractorCallback wallpaperLocalColorExtractorCallback) {
         mLongExecutor = longExecutor;
+        mLock = lock;
         mWallpaperLocalColorExtractorCallback = wallpaperLocalColorExtractorCallback;
     }
 
@@ -149,6 +152,12 @@
 
     private void onBitmapChangedSynchronized(@NonNull Bitmap bitmap) {
         synchronized (mLock) {
+            if (bitmap.isRecycled()) {
+                // ImageWallpaper loaded a new bitmap before the extraction of the previous one
+                // In that case, ImageWallpaper also scheduled the extraction of the next bitmap
+                Log.i(TAG, "Wallpaper has changed; deferring color extraction");
+                return;
+            }
             if (bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {
                 Log.e(TAG, "Attempt to extract colors from an invalid bitmap");
                 return;
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextManagerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextManagerTest.java
index e7d420b..9016220 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextManagerTest.java
@@ -419,7 +419,15 @@
 
         assertFalse(mWifiRepository.isWifiConnectedWithValidSsid());
         mWifiRepository.setWifiNetwork(
-                new WifiNetworkModel.Active(0, false, 0, "", false, false, null));
+                new WifiNetworkModel.Active(
+                        /* networkId= */ 0,
+                        /* isValidated= */ false,
+                        /* level= */ 0,
+                        /* ssid= */ "",
+                        /* hotspotDeviceType= */ WifiNetworkModel.HotspotDeviceType.NONE,
+                        /* isPasspointAccessPoint= */ false,
+                        /* isOnlineSignUpForPasspointAccessPoint= */ false,
+                        /* passpointProviderFriendlyName= */ null));
         assertTrue(mWifiRepository.isWifiConnectedWithValidSsid());
 
         mKeyguardUpdateMonitor.mServiceStates = new HashMap<>();
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardAbsKeyInputViewControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardAbsKeyInputViewControllerTest.java
index 677d3ff..c894d91 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardAbsKeyInputViewControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardAbsKeyInputViewControllerTest.java
@@ -180,8 +180,9 @@
     }
 
     @Test
-    public void testResume() {
-        mKeyguardAbsKeyInputViewController.onResume(KeyguardSecurityView.VIEW_REVEALED);
+    public void testOnViewAttached() {
+        reset(mLockPatternUtils);
+        mKeyguardAbsKeyInputViewController.onViewAttached();
         verify(mLockPatternUtils).getLockoutAttemptDeadline(anyInt());
     }
 
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerBaseTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerBaseTest.java
index ac04bc4..98d4d22 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerBaseTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerBaseTest.java
@@ -23,6 +23,7 @@
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -157,6 +158,12 @@
         when(mSmartspaceController.buildAndConnectDateView(any())).thenReturn(mFakeDateView);
         when(mSmartspaceController.buildAndConnectWeatherView(any())).thenReturn(mFakeWeatherView);
         when(mSmartspaceController.buildAndConnectView(any())).thenReturn(mFakeSmartspaceView);
+        doAnswer(invocation -> {
+            removeView(mFakeDateView);
+            removeView(mFakeWeatherView);
+            removeView(mFakeSmartspaceView);
+            return null;
+        }).when(mSmartspaceController).removeViewsFromParent(any());
         mExecutor = new FakeExecutor(new FakeSystemClock());
         mFakeFeatureFlags = new FakeFeatureFlags();
         mFakeFeatureFlags.set(FACE_AUTH_REFACTOR, false);
@@ -201,6 +208,13 @@
         when(mView.findViewById(R.id.keyguard_status_area)).thenReturn(mStatusArea);
     }
 
+    private void removeView(View v) {
+        ViewGroup group = ((ViewGroup) v.getParent());
+        if (group != null) {
+            group.removeView(v);
+        }
+    }
+
     protected void init() {
         mController.init();
 
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardDisplayManagerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardDisplayManagerTest.java
index b349696..438f0f4 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardDisplayManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardDisplayManagerTest.java
@@ -18,6 +18,8 @@
 
 import static android.view.DisplayAdjustments.DEFAULT_DISPLAY_ADJUSTMENTS;
 
+import static com.android.systemui.flags.Flags.ENABLE_CLOCK_KEYGUARD_PRESENTATION;
+
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.doReturn;
@@ -37,6 +39,7 @@
 
 import com.android.keyguard.dagger.KeyguardStatusViewComponent;
 import com.android.systemui.SysuiTestCase;
+import com.android.systemui.flags.FakeFeatureFlags;
 import com.android.systemui.navigationbar.NavigationBarController;
 import com.android.systemui.settings.FakeDisplayTracker;
 import com.android.systemui.statusbar.policy.KeyguardStateController;
@@ -59,8 +62,13 @@
     @Mock
     private KeyguardStatusViewComponent.Factory mKeyguardStatusViewComponentFactory;
     @Mock
+    private ConnectedDisplayKeyguardPresentation.Factory
+            mConnectedDisplayKeyguardPresentationFactory;
+    @Mock
     private KeyguardDisplayManager.KeyguardPresentation mKeyguardPresentation;
     @Mock
+    private ConnectedDisplayKeyguardPresentation mConnectedDisplayKeyguardPresentation;
+    @Mock
     private KeyguardDisplayManager.DeviceStateHelper mDeviceStateHelper;
     @Mock
     private KeyguardStateController mKeyguardStateController;
@@ -69,7 +77,7 @@
     private Executor mBackgroundExecutor = Runnable::run;
     private KeyguardDisplayManager mManager;
     private FakeDisplayTracker mDisplayTracker = new FakeDisplayTracker(mContext);
-
+    private FakeFeatureFlags mFakeFeatureFlags = new FakeFeatureFlags();
     // The default and secondary displays are both in the default group
     private Display mDefaultDisplay;
     private Display mSecondaryDisplay;
@@ -80,10 +88,14 @@
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
+        mFakeFeatureFlags.set(ENABLE_CLOCK_KEYGUARD_PRESENTATION, false);
         mManager = spy(new KeyguardDisplayManager(mContext, () -> mNavigationBarController,
                 mKeyguardStatusViewComponentFactory, mDisplayTracker, mMainExecutor,
-                mBackgroundExecutor, mDeviceStateHelper, mKeyguardStateController));
+                mBackgroundExecutor, mDeviceStateHelper, mKeyguardStateController,
+                mConnectedDisplayKeyguardPresentationFactory, mFakeFeatureFlags));
         doReturn(mKeyguardPresentation).when(mManager).createPresentation(any());
+        doReturn(mConnectedDisplayKeyguardPresentation).when(
+                mConnectedDisplayKeyguardPresentationFactory).create(any());
 
         mDefaultDisplay = new Display(DisplayManagerGlobal.getInstance(), Display.DEFAULT_DISPLAY,
                 new DisplayInfo(), DEFAULT_DISPLAY_ADJUSTMENTS);
@@ -138,4 +150,15 @@
         when(mKeyguardStateController.isOccluded()).thenReturn(true);
         verify(mManager, never()).createPresentation(eq(mSecondaryDisplay));
     }
+
+    @Test
+    public void testShow_withClockPresentationFlagEnabled_presentationCreated() {
+        when(mManager.createPresentation(any())).thenCallRealMethod();
+        mFakeFeatureFlags.set(ENABLE_CLOCK_KEYGUARD_PRESENTATION, true);
+        mDisplayTracker.setAllDisplays(new Display[]{mDefaultDisplay, mSecondaryDisplay});
+
+        mManager.show();
+
+        verify(mConnectedDisplayKeyguardPresentationFactory).create(eq(mSecondaryDisplay));
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPasswordViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPasswordViewControllerTest.kt
index 1a9260c..3a94730 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPasswordViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPasswordViewControllerTest.kt
@@ -20,6 +20,7 @@
 import android.testing.TestableLooper
 import android.view.inputmethod.InputMethodManager
 import android.widget.EditText
+import android.widget.ImageView
 import androidx.test.filters.SmallTest
 import com.android.internal.util.LatencyTracker
 import com.android.internal.widget.LockPatternUtils
@@ -29,6 +30,7 @@
 import com.android.systemui.flags.FakeFeatureFlags
 import com.android.systemui.flags.Flags
 import com.android.systemui.util.concurrency.DelayableExecutor
+import com.android.systemui.util.mockito.whenever
 import org.junit.Before
 import org.junit.Test
 import org.junit.runner.RunWith
@@ -36,6 +38,7 @@
 import org.mockito.ArgumentMatchers.anyString
 import org.mockito.Mock
 import org.mockito.Mockito
+import org.mockito.Mockito.mock
 import org.mockito.Mockito.never
 import org.mockito.Mockito.verify
 import org.mockito.Mockito.`when`
@@ -45,104 +48,109 @@
 @RunWith(AndroidTestingRunner::class)
 @TestableLooper.RunWithLooper
 class KeyguardPasswordViewControllerTest : SysuiTestCase() {
-  @Mock private lateinit var keyguardPasswordView: KeyguardPasswordView
-  @Mock private lateinit var passwordEntry: EditText
-  @Mock lateinit var keyguardUpdateMonitor: KeyguardUpdateMonitor
-  @Mock lateinit var securityMode: KeyguardSecurityModel.SecurityMode
-  @Mock lateinit var lockPatternUtils: LockPatternUtils
-  @Mock lateinit var keyguardSecurityCallback: KeyguardSecurityCallback
-  @Mock lateinit var messageAreaControllerFactory: KeyguardMessageAreaController.Factory
-  @Mock lateinit var latencyTracker: LatencyTracker
-  @Mock lateinit var inputMethodManager: InputMethodManager
-  @Mock lateinit var emergencyButtonController: EmergencyButtonController
-  @Mock lateinit var mainExecutor: DelayableExecutor
-  @Mock lateinit var falsingCollector: FalsingCollector
-  @Mock lateinit var keyguardViewController: KeyguardViewController
-  @Mock private lateinit var mKeyguardMessageArea: BouncerKeyguardMessageArea
-  @Mock
-  private lateinit var mKeyguardMessageAreaController:
-      KeyguardMessageAreaController<BouncerKeyguardMessageArea>
+    @Mock private lateinit var keyguardPasswordView: KeyguardPasswordView
+    @Mock private lateinit var passwordEntry: EditText
+    @Mock lateinit var keyguardUpdateMonitor: KeyguardUpdateMonitor
+    @Mock lateinit var securityMode: KeyguardSecurityModel.SecurityMode
+    @Mock lateinit var lockPatternUtils: LockPatternUtils
+    @Mock lateinit var keyguardSecurityCallback: KeyguardSecurityCallback
+    @Mock lateinit var messageAreaControllerFactory: KeyguardMessageAreaController.Factory
+    @Mock lateinit var latencyTracker: LatencyTracker
+    @Mock lateinit var inputMethodManager: InputMethodManager
+    @Mock lateinit var emergencyButtonController: EmergencyButtonController
+    @Mock lateinit var mainExecutor: DelayableExecutor
+    @Mock lateinit var falsingCollector: FalsingCollector
+    @Mock lateinit var keyguardViewController: KeyguardViewController
+    @Mock private lateinit var mKeyguardMessageArea: BouncerKeyguardMessageArea
+    @Mock
+    private lateinit var mKeyguardMessageAreaController:
+        KeyguardMessageAreaController<BouncerKeyguardMessageArea>
 
-  private lateinit var keyguardPasswordViewController: KeyguardPasswordViewController
+    private lateinit var keyguardPasswordViewController: KeyguardPasswordViewController
 
-  @Before
-  fun setup() {
-    MockitoAnnotations.initMocks(this)
-    Mockito.`when`(
-            keyguardPasswordView.requireViewById<BouncerKeyguardMessageArea>(
-                R.id.bouncer_message_area))
-        .thenReturn(mKeyguardMessageArea)
-    Mockito.`when`(messageAreaControllerFactory.create(mKeyguardMessageArea))
-        .thenReturn(mKeyguardMessageAreaController)
-    Mockito.`when`(keyguardPasswordView.passwordTextViewId).thenReturn(R.id.passwordEntry)
-    Mockito.`when`(keyguardPasswordView.findViewById<EditText>(R.id.passwordEntry))
-        .thenReturn(passwordEntry)
-    `when`(keyguardPasswordView.resources).thenReturn(context.resources)
-    val fakeFeatureFlags = FakeFeatureFlags()
-    fakeFeatureFlags.set(Flags.REVAMPED_BOUNCER_MESSAGES, true)
-    keyguardPasswordViewController =
-        KeyguardPasswordViewController(
-            keyguardPasswordView,
-            keyguardUpdateMonitor,
-            securityMode,
-            lockPatternUtils,
-            keyguardSecurityCallback,
-            messageAreaControllerFactory,
-            latencyTracker,
-            inputMethodManager,
-            emergencyButtonController,
-            mainExecutor,
-            mContext.resources,
-            falsingCollector,
-            keyguardViewController,
-            fakeFeatureFlags)
-  }
-
-  @Test
-  fun testFocusWhenBouncerIsShown() {
-    Mockito.`when`(keyguardViewController.isBouncerShowing).thenReturn(true)
-    Mockito.`when`(keyguardPasswordView.isShown).thenReturn(true)
-    keyguardPasswordViewController.onResume(KeyguardSecurityView.VIEW_REVEALED)
-    keyguardPasswordView.post {
-      verify(keyguardPasswordView).requestFocus()
-      verify(keyguardPasswordView).showKeyboard()
+    @Before
+    fun setup() {
+        MockitoAnnotations.initMocks(this)
+        Mockito.`when`(
+                keyguardPasswordView.requireViewById<BouncerKeyguardMessageArea>(
+                    R.id.bouncer_message_area
+                )
+            )
+            .thenReturn(mKeyguardMessageArea)
+        Mockito.`when`(messageAreaControllerFactory.create(mKeyguardMessageArea))
+            .thenReturn(mKeyguardMessageAreaController)
+        Mockito.`when`(keyguardPasswordView.passwordTextViewId).thenReturn(R.id.passwordEntry)
+        Mockito.`when`(keyguardPasswordView.findViewById<EditText>(R.id.passwordEntry))
+            .thenReturn(passwordEntry)
+        whenever(keyguardPasswordView.findViewById<ImageView>(R.id.switch_ime_button))
+            .thenReturn(mock(ImageView::class.java))
+        `when`(keyguardPasswordView.resources).thenReturn(context.resources)
+        val fakeFeatureFlags = FakeFeatureFlags()
+        fakeFeatureFlags.set(Flags.REVAMPED_BOUNCER_MESSAGES, true)
+        keyguardPasswordViewController =
+            KeyguardPasswordViewController(
+                keyguardPasswordView,
+                keyguardUpdateMonitor,
+                securityMode,
+                lockPatternUtils,
+                keyguardSecurityCallback,
+                messageAreaControllerFactory,
+                latencyTracker,
+                inputMethodManager,
+                emergencyButtonController,
+                mainExecutor,
+                mContext.resources,
+                falsingCollector,
+                keyguardViewController,
+                fakeFeatureFlags
+            )
     }
-  }
 
-  @Test
-  fun testDoNotFocusWhenBouncerIsHidden() {
-    Mockito.`when`(keyguardViewController.isBouncerShowing).thenReturn(false)
-    Mockito.`when`(keyguardPasswordView.isShown).thenReturn(true)
-    keyguardPasswordViewController.onResume(KeyguardSecurityView.VIEW_REVEALED)
-    verify(keyguardPasswordView, never()).requestFocus()
-  }
-
-  @Test
-  fun testHideKeyboardWhenOnPause() {
-    keyguardPasswordViewController.onPause()
-    keyguardPasswordView.post {
-      verify(keyguardPasswordView).clearFocus()
-      verify(keyguardPasswordView).hideKeyboard()
+    @Test
+    fun testFocusWhenBouncerIsShown() {
+        Mockito.`when`(keyguardViewController.isBouncerShowing).thenReturn(true)
+        Mockito.`when`(keyguardPasswordView.isShown).thenReturn(true)
+        keyguardPasswordViewController.onResume(KeyguardSecurityView.VIEW_REVEALED)
+        keyguardPasswordView.post {
+            verify(keyguardPasswordView).requestFocus()
+            verify(keyguardPasswordView).showKeyboard()
+        }
     }
-  }
 
-  @Test
-  fun startAppearAnimation() {
-    keyguardPasswordViewController.startAppearAnimation()
-    verify(mKeyguardMessageAreaController)
-        .setMessage(context.resources.getString(R.string.keyguard_enter_your_password), false)
-  }
+    @Test
+    fun testDoNotFocusWhenBouncerIsHidden() {
+        Mockito.`when`(keyguardViewController.isBouncerShowing).thenReturn(false)
+        Mockito.`when`(keyguardPasswordView.isShown).thenReturn(true)
+        keyguardPasswordViewController.onResume(KeyguardSecurityView.VIEW_REVEALED)
+        verify(keyguardPasswordView, never()).requestFocus()
+    }
 
-  @Test
-  fun startAppearAnimation_withExistingMessage() {
-    `when`(mKeyguardMessageAreaController.message).thenReturn("Unlock to continue.")
-    keyguardPasswordViewController.startAppearAnimation()
-    verify(mKeyguardMessageAreaController, never()).setMessage(anyString(), anyBoolean())
-  }
+    @Test
+    fun testHideKeyboardWhenOnPause() {
+        keyguardPasswordViewController.onPause()
+        keyguardPasswordView.post {
+            verify(keyguardPasswordView).clearFocus()
+            verify(keyguardPasswordView).hideKeyboard()
+        }
+    }
 
-  @Test
-  fun testMessageIsSetWhenReset() {
-    keyguardPasswordViewController.resetState()
-    verify(mKeyguardMessageAreaController).setMessage(R.string.keyguard_enter_your_password)
-  }
+    @Test
+    fun testOnViewAttached() {
+        keyguardPasswordViewController.onViewAttached()
+        verify(mKeyguardMessageAreaController)
+            .setMessage(context.resources.getString(R.string.keyguard_enter_your_password), false)
+    }
+
+    @Test
+    fun testOnViewAttached_withExistingMessage() {
+        `when`(mKeyguardMessageAreaController.message).thenReturn("Unlock to continue.")
+        keyguardPasswordViewController.onViewAttached()
+        verify(mKeyguardMessageAreaController, never()).setMessage(anyString(), anyBoolean())
+    }
+
+    @Test
+    fun testMessageIsSetWhenReset() {
+        keyguardPasswordViewController.resetState()
+        verify(mKeyguardMessageAreaController).setMessage(R.string.keyguard_enter_your_password)
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewControllerTest.kt
index cb18229..1acd676 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewControllerTest.kt
@@ -46,6 +46,7 @@
 import org.mockito.Captor
 import org.mockito.Mock
 import org.mockito.Mockito.never
+import org.mockito.Mockito.reset
 import org.mockito.Mockito.verify
 import org.mockito.Mockito.`when`
 import org.mockito.MockitoAnnotations
@@ -54,35 +55,35 @@
 @RunWith(AndroidTestingRunner::class)
 @TestableLooper.RunWithLooper
 class KeyguardPatternViewControllerTest : SysuiTestCase() {
-   private lateinit var mKeyguardPatternView: KeyguardPatternView
+    private lateinit var mKeyguardPatternView: KeyguardPatternView
 
-  @Mock private lateinit var mKeyguardUpdateMonitor: KeyguardUpdateMonitor
+    @Mock private lateinit var mKeyguardUpdateMonitor: KeyguardUpdateMonitor
 
-  @Mock private lateinit var mSecurityMode: KeyguardSecurityModel.SecurityMode
+    @Mock private lateinit var mSecurityMode: KeyguardSecurityModel.SecurityMode
 
-  @Mock private lateinit var mLockPatternUtils: LockPatternUtils
+    @Mock private lateinit var mLockPatternUtils: LockPatternUtils
 
-  @Mock private lateinit var mKeyguardSecurityCallback: KeyguardSecurityCallback
+    @Mock private lateinit var mKeyguardSecurityCallback: KeyguardSecurityCallback
 
-  @Mock private lateinit var mLatencyTracker: LatencyTracker
-  private var mFalsingCollector: FalsingCollector = FalsingCollectorFake()
+    @Mock private lateinit var mLatencyTracker: LatencyTracker
+    private var mFalsingCollector: FalsingCollector = FalsingCollectorFake()
 
-  @Mock private lateinit var mEmergencyButtonController: EmergencyButtonController
+    @Mock private lateinit var mEmergencyButtonController: EmergencyButtonController
 
-  @Mock
-  private lateinit var mKeyguardMessageAreaControllerFactory: KeyguardMessageAreaController.Factory
+    @Mock
+    private lateinit var mKeyguardMessageAreaControllerFactory:
+        KeyguardMessageAreaController.Factory
 
-  @Mock
-  private lateinit var mKeyguardMessageAreaController:
-      KeyguardMessageAreaController<BouncerKeyguardMessageArea>
+    @Mock
+    private lateinit var mKeyguardMessageAreaController:
+        KeyguardMessageAreaController<BouncerKeyguardMessageArea>
 
-  @Mock private lateinit var mPostureController: DevicePostureController
+    @Mock private lateinit var mPostureController: DevicePostureController
 
-  private lateinit var mKeyguardPatternViewController: KeyguardPatternViewController
-  private lateinit var fakeFeatureFlags: FakeFeatureFlags
+    private lateinit var mKeyguardPatternViewController: KeyguardPatternViewController
+    private lateinit var fakeFeatureFlags: FakeFeatureFlags
 
-  @Captor
-  lateinit var postureCallbackCaptor: ArgumentCaptor<DevicePostureController.Callback>
+    @Captor lateinit var postureCallbackCaptor: ArgumentCaptor<DevicePostureController.Callback>
 
     @Before
     fun setup() {
@@ -91,9 +92,8 @@
             .thenReturn(mKeyguardMessageAreaController)
         fakeFeatureFlags = FakeFeatureFlags()
         fakeFeatureFlags.set(Flags.REVAMPED_BOUNCER_MESSAGES, false)
-        mKeyguardPatternView = View.inflate(mContext, R.layout.keyguard_pattern_view, null)
-                as KeyguardPatternView
-
+        mKeyguardPatternView =
+            View.inflate(mContext, R.layout.keyguard_pattern_view, null) as KeyguardPatternView
 
         mKeyguardPatternViewController =
             KeyguardPatternViewController(
@@ -125,8 +125,7 @@
     @Test
     fun onDevicePostureChanged_deviceOpened_propagatedToPatternView() {
         overrideResource(R.dimen.half_opened_bouncer_height_ratio, 0.5f)
-        whenever(mPostureController.devicePosture)
-                .thenReturn(DEVICE_POSTURE_HALF_OPENED)
+        whenever(mPostureController.devicePosture).thenReturn(DEVICE_POSTURE_HALF_OPENED)
 
         mKeyguardPatternViewController.onViewAttached()
 
@@ -150,7 +149,7 @@
     private fun getPatternTopGuideline(): Float {
         val cs = ConstraintSet()
         val container =
-            mKeyguardPatternView.findViewById(R.id.pattern_container) as ConstraintLayout
+            mKeyguardPatternView.requireViewById(R.id.pattern_container) as ConstraintLayout
         cs.clone(container)
         return cs.getConstraint(R.id.pattern_top_guideline).layout.guidePercent
     }
@@ -159,39 +158,37 @@
         return mContext.resources.getFloat(R.dimen.half_opened_bouncer_height_ratio)
     }
 
-  @Test
-  fun withFeatureFlagOn_oldMessage_isHidden() {
-    fakeFeatureFlags.set(Flags.REVAMPED_BOUNCER_MESSAGES, true)
+    @Test
+    fun withFeatureFlagOn_oldMessage_isHidden() {
+        fakeFeatureFlags.set(Flags.REVAMPED_BOUNCER_MESSAGES, true)
 
-    mKeyguardPatternViewController.onViewAttached()
+        mKeyguardPatternViewController.onViewAttached()
 
-    verify<KeyguardMessageAreaController<*>>(mKeyguardMessageAreaController).disable()
-  }
+        verify<KeyguardMessageAreaController<*>>(mKeyguardMessageAreaController).disable()
+    }
 
-  @Test
-  fun onPause_resetsText() {
-    mKeyguardPatternViewController.init()
-    mKeyguardPatternViewController.onPause()
-    verify(mKeyguardMessageAreaController).setMessage(R.string.keyguard_enter_your_pattern)
-  }
+    @Test
+    fun onPause_resetsText() {
+        mKeyguardPatternViewController.init()
+        mKeyguardPatternViewController.onPause()
+        verify(mKeyguardMessageAreaController).setMessage(R.string.keyguard_enter_your_pattern)
+    }
 
-  @Test
-  fun startAppearAnimation() {
-    mKeyguardPatternViewController.startAppearAnimation()
-    verify(mKeyguardMessageAreaController)
-        .setMessage(context.resources.getString(R.string.keyguard_enter_your_pattern), false)
-  }
+    @Test
+    fun testOnViewAttached() {
+        reset(mKeyguardMessageAreaController)
+        reset(mLockPatternUtils)
+        mKeyguardPatternViewController.onViewAttached()
+        verify(mKeyguardMessageAreaController)
+            .setMessage(context.resources.getString(R.string.keyguard_enter_your_pattern), false)
+        verify(mLockPatternUtils).getLockoutAttemptDeadline(anyInt())
+    }
 
-  @Test
-  fun startAppearAnimation_withExistingMessage() {
-    `when`(mKeyguardMessageAreaController.message).thenReturn("Unlock to continue.")
-    mKeyguardPatternViewController.startAppearAnimation()
-    verify(mKeyguardMessageAreaController, never()).setMessage(anyString(), anyBoolean())
-  }
-
-  @Test
-  fun resume() {
-    mKeyguardPatternViewController.onResume(KeyguardSecurityView.VIEW_REVEALED)
-    verify(mLockPatternUtils).getLockoutAttemptDeadline(anyInt())
-  }
+    @Test
+    fun testOnViewAttached_withExistingMessage() {
+        reset(mKeyguardMessageAreaController)
+        `when`(mKeyguardMessageAreaController.message).thenReturn("Unlock to continue.")
+        mKeyguardPatternViewController.onViewAttached()
+        verify(mKeyguardMessageAreaController, never()).setMessage(anyString(), anyBoolean())
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinBasedInputViewControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinBasedInputViewControllerTest.java
index cf86c21..efe1955 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinBasedInputViewControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinBasedInputViewControllerTest.java
@@ -100,6 +100,8 @@
                 .thenReturn(mDeleteButton);
         when(mPinBasedInputView.findViewById(R.id.key_enter))
                 .thenReturn(mOkButton);
+
+        when(mPinBasedInputView.getResources()).thenReturn(getContext().getResources());
         FakeFeatureFlags featureFlags = new FakeFeatureFlags();
         featureFlags.set(Flags.REVAMPED_BOUNCER_MESSAGES, true);
 
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinViewControllerTest.kt
index 4dc7652..80fd721 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinViewControllerTest.kt
@@ -114,7 +114,7 @@
 
         objectKeyguardPINView =
             View.inflate(mContext, R.layout.keyguard_pin_view, null)
-                .findViewById(R.id.keyguard_pin_view) as KeyguardPINView
+                .requireViewById(R.id.keyguard_pin_view) as KeyguardPINView
     }
 
     private fun constructPinViewController(
@@ -175,7 +175,7 @@
 
     private fun getPinTopGuideline(): Float {
         val cs = ConstraintSet()
-        val container = objectKeyguardPINView.findViewById(R.id.pin_container) as ConstraintLayout
+        val container = objectKeyguardPINView.requireViewById(R.id.pin_container) as ConstraintLayout
         cs.clone(container)
         return cs.getConstraint(R.id.pin_pad_top_guideline).layout.guidePercent
     }
@@ -185,27 +185,27 @@
     }
 
     @Test
-    fun startAppearAnimation() {
+    fun testOnViewAttached() {
         val pinViewController = constructPinViewController(mockKeyguardPinView)
 
-        pinViewController.startAppearAnimation()
+        pinViewController.onViewAttached()
 
         verify(keyguardMessageAreaController)
             .setMessage(context.resources.getString(R.string.keyguard_enter_your_pin), false)
     }
 
     @Test
-    fun startAppearAnimation_withExistingMessage() {
+    fun testOnViewAttached_withExistingMessage() {
         val pinViewController = constructPinViewController(mockKeyguardPinView)
         Mockito.`when`(keyguardMessageAreaController.message).thenReturn("Unlock to continue.")
 
-        pinViewController.startAppearAnimation()
+        pinViewController.onViewAttached()
 
         verify(keyguardMessageAreaController, Mockito.never()).setMessage(anyString(), anyBoolean())
     }
 
     @Test
-    fun startAppearAnimation_withAutoPinConfirmationFailedPasswordAttemptsLessThan5() {
+    fun testOnViewAttached_withAutoPinConfirmationFailedPasswordAttemptsLessThan5() {
         val pinViewController = constructPinViewController(mockKeyguardPinView)
         `when`(featureFlags.isEnabled(Flags.AUTO_PIN_CONFIRMATION)).thenReturn(true)
         `when`(lockPatternUtils.getPinLength(anyInt())).thenReturn(6)
@@ -213,7 +213,7 @@
         `when`(lockPatternUtils.getCurrentFailedPasswordAttempts(anyInt())).thenReturn(3)
         `when`(passwordTextView.text).thenReturn("")
 
-        pinViewController.startAppearAnimation()
+        pinViewController.onViewAttached()
 
         verify(deleteButton).visibility = View.INVISIBLE
         verify(enterButton).visibility = View.INVISIBLE
@@ -222,7 +222,7 @@
     }
 
     @Test
-    fun startAppearAnimation_withAutoPinConfirmationFailedPasswordAttemptsMoreThan5() {
+    fun testOnViewAttached_withAutoPinConfirmationFailedPasswordAttemptsMoreThan5() {
         val pinViewController = constructPinViewController(mockKeyguardPinView)
         `when`(featureFlags.isEnabled(Flags.AUTO_PIN_CONFIRMATION)).thenReturn(true)
         `when`(lockPatternUtils.getPinLength(anyInt())).thenReturn(6)
@@ -230,7 +230,7 @@
         `when`(lockPatternUtils.getCurrentFailedPasswordAttempts(anyInt())).thenReturn(6)
         `when`(passwordTextView.text).thenReturn("")
 
-        pinViewController.startAppearAnimation()
+        pinViewController.onViewAttached()
 
         verify(deleteButton).visibility = View.VISIBLE
         verify(enterButton).visibility = View.VISIBLE
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.kt
index efb981e..ad4bd58 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.kt
@@ -27,6 +27,7 @@
 import android.view.Gravity
 import android.view.LayoutInflater
 import android.view.MotionEvent
+import android.view.View
 import android.view.WindowInsetsController
 import android.widget.FrameLayout
 import androidx.test.filters.SmallTest
@@ -37,6 +38,7 @@
 import com.android.keyguard.KeyguardSecurityModel.SecurityMode
 import com.android.systemui.R
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.domain.interactor.AuthenticationInteractor
 import com.android.systemui.biometrics.FaceAuthAccessibilityDelegate
 import com.android.systemui.biometrics.SideFpsController
 import com.android.systemui.biometrics.SideFpsUiRequestSource
@@ -45,20 +47,26 @@
 import com.android.systemui.classifier.FalsingCollector
 import com.android.systemui.flags.FakeFeatureFlags
 import com.android.systemui.flags.Flags
+import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
+import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractorFactory
 import com.android.systemui.log.SessionTracker
 import com.android.systemui.plugins.ActivityStarter.OnDismissAction
 import com.android.systemui.plugins.FalsingManager
 import com.android.systemui.scene.SceneTestUtils
 import com.android.systemui.scene.domain.interactor.SceneInteractor
+import com.android.systemui.scene.shared.model.ObservableTransitionState
 import com.android.systemui.scene.shared.model.SceneKey
 import com.android.systemui.scene.shared.model.SceneModel
 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.UserSwitcherController
 import com.android.systemui.user.domain.interactor.UserInteractor
 import com.android.systemui.util.kotlin.JavaAdapter
 import com.android.systemui.util.mockito.any
 import com.android.systemui.util.mockito.argThat
+import com.android.systemui.util.mockito.argumentCaptor
+import com.android.systemui.util.mockito.capture
 import com.android.systemui.util.mockito.mock
 import com.android.systemui.util.mockito.whenever
 import com.android.systemui.util.settings.GlobalSettings
@@ -66,6 +74,8 @@
 import java.util.Optional
 import junit.framework.Assert
 import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.flowOf
 import kotlinx.coroutines.test.runCurrent
 import kotlinx.coroutines.test.runTest
 import org.junit.Before
@@ -80,6 +90,7 @@
 import org.mockito.Mock
 import org.mockito.Mockito.atLeastOnce
 import org.mockito.Mockito.clearInvocations
+import org.mockito.Mockito.mock
 import org.mockito.Mockito.never
 import org.mockito.Mockito.spy
 import org.mockito.Mockito.verify
@@ -125,6 +136,7 @@
     @Mock private lateinit var audioManager: AudioManager
     @Mock private lateinit var userInteractor: UserInteractor
     @Mock private lateinit var faceAuthAccessibilityDelegate: FaceAuthAccessibilityDelegate
+    @Mock private lateinit var deviceProvisionedController: DeviceProvisionedController
 
     @Captor
     private lateinit var swipeListenerArgumentCaptor:
@@ -139,6 +151,9 @@
     private lateinit var testableResources: TestableResources
     private lateinit var sceneTestUtils: SceneTestUtils
     private lateinit var sceneInteractor: SceneInteractor
+    private lateinit var keyguardTransitionInteractor: KeyguardTransitionInteractor
+    private lateinit var authenticationInteractor: AuthenticationInteractor
+    private lateinit var sceneTransitionStateFlow: MutableStateFlow<ObservableTransitionState>
 
     private lateinit var underTest: KeyguardSecurityContainerController
 
@@ -171,11 +186,13 @@
         whenever(keyguardPasswordView.windowInsetsController).thenReturn(windowInsetsController)
         whenever(keyguardSecurityModel.getSecurityMode(anyInt())).thenReturn(SecurityMode.PIN)
         whenever(keyguardStateController.canDismissLockScreen()).thenReturn(true)
+        whenever(deviceProvisionedController.isUserSetup(anyInt())).thenReturn(true)
 
         featureFlags = FakeFeatureFlags()
         featureFlags.set(Flags.REVAMPED_BOUNCER_MESSAGES, true)
         featureFlags.set(Flags.SCENE_CONTAINER, false)
         featureFlags.set(Flags.BOUNCER_USER_SWITCHER, false)
+        featureFlags.set(Flags.KEYGUARD_WM_STATE_REFACTOR, false)
 
         keyguardPasswordViewController =
             KeyguardPasswordViewController(
@@ -198,6 +215,17 @@
         whenever(userInteractor.getSelectedUserId()).thenReturn(TARGET_USER_ID)
         sceneTestUtils = SceneTestUtils(this)
         sceneInteractor = sceneTestUtils.sceneInteractor()
+        keyguardTransitionInteractor =
+            KeyguardTransitionInteractorFactory.create(sceneTestUtils.testScope.backgroundScope)
+                .keyguardTransitionInteractor
+        sceneTransitionStateFlow =
+            MutableStateFlow(ObservableTransitionState.Idle(SceneKey.Lockscreen))
+        sceneInteractor.setTransitionState(sceneTransitionStateFlow)
+        authenticationInteractor =
+            sceneTestUtils.authenticationInteractor(
+                repository = sceneTestUtils.authenticationRepository(),
+                sceneInteractor = sceneInteractor
+            )
 
         underTest =
             KeyguardSecurityContainerController(
@@ -226,9 +254,11 @@
                 mock(),
                 { JavaAdapter(sceneTestUtils.testScope.backgroundScope) },
                 userInteractor,
+                deviceProvisionedController,
                 faceAuthAccessibilityDelegate,
+                keyguardTransitionInteractor
             ) {
-                sceneInteractor
+                authenticationInteractor
             }
     }
 
@@ -482,6 +512,30 @@
         // THEN the next security method of None will dismiss keyguard.
         verify(viewMediatorCallback, never()).keyguardDone(anyBoolean(), anyInt())
     }
+    @Test
+    fun showNextSecurityScreenOrFinish_SimPin_Swipe_userNotSetup() {
+        // GIVEN the current security method is SimPin
+        whenever(keyguardUpdateMonitor.getUserHasTrust(anyInt())).thenReturn(false)
+        whenever(keyguardUpdateMonitor.getUserUnlockedWithBiometric(TARGET_USER_ID))
+            .thenReturn(false)
+        underTest.showSecurityScreen(SecurityMode.SimPin)
+
+        // WHEN a request is made from the SimPin screens to show the next security method
+        whenever(keyguardSecurityModel.getSecurityMode(TARGET_USER_ID))
+            .thenReturn(SecurityMode.None)
+        // WHEN security method is SWIPE
+        whenever(lockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false)
+        whenever(deviceProvisionedController.isUserSetup(anyInt())).thenReturn(false)
+        underTest.showNextSecurityScreenOrFinish(
+            /* authenticated= */ true,
+            TARGET_USER_ID,
+            /* bypassSecondaryLockScreen= */ true,
+            SecurityMode.SimPin
+        )
+
+        // THEN the next security method of None will dismiss keyguard.
+        verify(viewMediatorCallback).keyguardDone(anyBoolean(), anyInt())
+    }
 
     @Test
     fun onSwipeUp_whenFaceDetectionIsNotRunning_initiatesFaceAuth() {
@@ -554,18 +608,7 @@
             ArgumentCaptor.forClass(ConfigurationController.ConfigurationListener::class.java)
         underTest.onViewAttached()
         verify(configurationController).addCallback(configurationListenerArgumentCaptor.capture())
-        clearInvocations(viewFlipperController)
         configurationListenerArgumentCaptor.value.onThemeChanged()
-        verify(viewFlipperController).clearViews()
-        verify(viewFlipperController)
-            .asynchronouslyInflateView(
-                eq(SecurityMode.PIN),
-                any(),
-                onViewInflatedCallbackArgumentCaptor.capture()
-            )
-        onViewInflatedCallbackArgumentCaptor.value.onViewInflated(inputViewController)
-        verify(view).reset()
-        verify(viewFlipperController).reset()
         verify(view).reloadColors()
     }
 
@@ -575,16 +618,7 @@
             ArgumentCaptor.forClass(ConfigurationController.ConfigurationListener::class.java)
         underTest.onViewAttached()
         verify(configurationController).addCallback(configurationListenerArgumentCaptor.capture())
-        clearInvocations(viewFlipperController)
         configurationListenerArgumentCaptor.value.onUiModeChanged()
-        verify(viewFlipperController).clearViews()
-        verify(viewFlipperController)
-            .asynchronouslyInflateView(
-                eq(SecurityMode.PIN),
-                any(),
-                onViewInflatedCallbackArgumentCaptor.capture()
-            )
-        onViewInflatedCallbackArgumentCaptor.value.onViewInflated(inputViewController)
         verify(view).reloadColors()
     }
 
@@ -720,7 +754,7 @@
     }
 
     @Test
-    fun dismissesKeyguard_whenSceneChangesFromBouncerToGone() =
+    fun dismissesKeyguard_whenSceneChangesToGone() =
         sceneTestUtils.testScope.runTest {
             featureFlags.set(Flags.SCENE_CONTAINER, true)
 
@@ -733,20 +767,39 @@
             // is
             // not enough to trigger a dismissal of the keyguard.
             underTest.onViewAttached()
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer, null), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer, null), "reason")
+            sceneTransitionStateFlow.value =
+                ObservableTransitionState.Transition(
+                    SceneKey.Lockscreen,
+                    SceneKey.Bouncer,
+                    flowOf(.5f)
+                )
+            runCurrent()
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer, null), "reason")
+            sceneTransitionStateFlow.value = ObservableTransitionState.Idle(SceneKey.Bouncer)
             runCurrent()
             verify(viewMediatorCallback, never()).keyguardDone(anyBoolean(), anyInt())
 
             // While listening, going from the bouncer scene to the gone scene, does dismiss the
             // keyguard.
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Gone, null), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Gone, null), "reason")
+            sceneTransitionStateFlow.value =
+                ObservableTransitionState.Transition(SceneKey.Bouncer, SceneKey.Gone, flowOf(.5f))
+            runCurrent()
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Gone, null), "reason")
+            sceneTransitionStateFlow.value = ObservableTransitionState.Idle(SceneKey.Gone)
             runCurrent()
             verify(viewMediatorCallback).keyguardDone(anyBoolean(), anyInt())
 
             // While listening, moving back to the bouncer scene does not dismiss the keyguard
             // again.
             clearInvocations(viewMediatorCallback)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer, null), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer, null), "reason")
+            sceneTransitionStateFlow.value =
+                ObservableTransitionState.Transition(SceneKey.Gone, SceneKey.Bouncer, flowOf(.5f))
+            runCurrent()
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer, null), "reason")
+            sceneTransitionStateFlow.value = ObservableTransitionState.Idle(SceneKey.Bouncer)
             runCurrent()
             verify(viewMediatorCallback, never()).keyguardDone(anyBoolean(), anyInt())
 
@@ -754,24 +807,67 @@
             // scene
             // does not dismiss the keyguard while we're not listening.
             underTest.onViewDetached()
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Gone, null), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Gone, null), "reason")
+            sceneTransitionStateFlow.value =
+                ObservableTransitionState.Transition(SceneKey.Bouncer, SceneKey.Gone, flowOf(.5f))
+            runCurrent()
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Gone, null), "reason")
+            sceneTransitionStateFlow.value = ObservableTransitionState.Idle(SceneKey.Gone)
             runCurrent()
             verify(viewMediatorCallback, never()).keyguardDone(anyBoolean(), anyInt())
 
-            // While not listening, moving back to the bouncer does not dismiss the keyguard.
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer, null), "reason")
+            // While not listening, moving to the lockscreen does not dismiss the keyguard.
+            sceneInteractor.changeScene(SceneModel(SceneKey.Lockscreen, null), "reason")
+            sceneTransitionStateFlow.value =
+                ObservableTransitionState.Transition(
+                    SceneKey.Gone,
+                    SceneKey.Lockscreen,
+                    flowOf(.5f)
+                )
+            runCurrent()
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Lockscreen, null), "reason")
+            sceneTransitionStateFlow.value = ObservableTransitionState.Idle(SceneKey.Lockscreen)
             runCurrent()
             verify(viewMediatorCallback, never()).keyguardDone(anyBoolean(), anyInt())
 
             // Reattaching the view starts listening again so moving from the bouncer scene to the
-            // gone
-            // scene now does dismiss the keyguard again.
+            // gone scene now does dismiss the keyguard again, this time from lockscreen.
             underTest.onViewAttached()
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Gone, null), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Gone, null), "reason")
+            sceneTransitionStateFlow.value =
+                ObservableTransitionState.Transition(
+                    SceneKey.Lockscreen,
+                    SceneKey.Gone,
+                    flowOf(.5f)
+                )
+            runCurrent()
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Gone, null), "reason")
+            sceneTransitionStateFlow.value = ObservableTransitionState.Idle(SceneKey.Gone)
             runCurrent()
             verify(viewMediatorCallback).keyguardDone(anyBoolean(), anyInt())
         }
 
+    @Test
+    fun testResetUserSwitcher() {
+        val userSwitcher = mock(View::class.java)
+        whenever(view.findViewById<View>(R.id.keyguard_bouncer_user_switcher))
+            .thenReturn(userSwitcher)
+
+        underTest.prepareToShow()
+        verify(userSwitcher).setAlpha(0f)
+    }
+
+    @Test
+    fun testOnUserSwitched() {
+        val userSwitchCallbackArgumentCaptor =
+            argumentCaptor<UserSwitcherController.UserSwitchCallback>()
+        underTest.onViewAttached()
+        verify(userSwitcherController)
+            .addUserSwitchCallback(capture(userSwitchCallbackArgumentCaptor))
+        userSwitchCallbackArgumentCaptor.value.onUserSwitched()
+        verify(viewFlipperController).asynchronouslyInflateView(any(), any(), any())
+    }
+
     private val registeredSwipeListener: KeyguardSecurityContainer.SwipeListener
         get() {
             underTest.onViewAttached()
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSimPinViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSimPinViewControllerTest.kt
index a3acc78..291dda25 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSimPinViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSimPinViewControllerTest.kt
@@ -97,6 +97,8 @@
     @Test
     fun onViewAttached() {
         underTest.onViewAttached()
+        verify(keyguardMessageAreaController)
+            .setMessage(context.resources.getString(R.string.keyguard_enter_your_pin), false)
     }
 
     @Test
@@ -120,8 +122,6 @@
     @Test
     fun startAppearAnimation() {
         underTest.startAppearAnimation()
-        verify(keyguardMessageAreaController)
-            .setMessage(context.resources.getString(R.string.keyguard_enter_your_pin), false)
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSimPukViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSimPukViewControllerTest.kt
index efcf4dd..626faa6 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSimPukViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSimPukViewControllerTest.kt
@@ -98,6 +98,8 @@
         underTest.onViewAttached()
         Mockito.verify(keyguardUpdateMonitor)
             .registerCallback(any(KeyguardUpdateMonitorCallback::class.java))
+        Mockito.verify(keyguardMessageAreaController)
+            .setMessage(context.resources.getString(R.string.keyguard_enter_your_pin), false)
     }
 
     @Test
@@ -120,8 +122,6 @@
     @Test
     fun startAppearAnimation() {
         underTest.startAppearAnimation()
-        Mockito.verify(keyguardMessageAreaController)
-            .setMessage(context.resources.getString(R.string.keyguard_enter_your_pin), false)
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewControllerTest.java
index 20d9ef1..b8b0198 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewControllerTest.java
@@ -16,6 +16,7 @@
 
 package com.android.keyguard;
 
+import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
@@ -76,7 +77,7 @@
     public void updatePosition_primaryClockAnimation() {
         ClockController mockClock = mock(ClockController.class);
         when(mKeyguardClockSwitchController.getClock()).thenReturn(mockClock);
-        when(mockClock.getConfig()).thenReturn(new ClockConfig(false, true));
+        when(mockClock.getConfig()).thenReturn(new ClockConfig("MOCK", false, true));
 
         mController.updatePosition(10, 15, 20f, true);
 
@@ -91,7 +92,7 @@
     public void updatePosition_alternateClockAnimation() {
         ClockController mockClock = mock(ClockController.class);
         when(mKeyguardClockSwitchController.getClock()).thenReturn(mockClock);
-        when(mockClock.getConfig()).thenReturn(new ClockConfig(true, true));
+        when(mockClock.getConfig()).thenReturn(new ClockConfig("MOCK", true, true));
 
         mController.updatePosition(10, 15, 20f, true);
 
@@ -119,8 +120,8 @@
     @Test
     public void correctlyDump() {
         mController.onInit();
-        verify(mDumpManager).registerDumpable(mController);
+        verify(mDumpManager).registerDumpable(eq(mController.getInstanceName()), eq(mController));
         mController.onDestroy();
-        verify(mDumpManager, times(1)).unregisterDumpable(KeyguardStatusViewController.TAG);
+        verify(mDumpManager, times(1)).unregisterDumpable(eq(mController.getInstanceName()));
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewTest.kt
index f8262d4..210f3cb 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewTest.kt
@@ -21,9 +21,9 @@
 
     private lateinit var keyguardStatusView: KeyguardStatusView
     private val mediaView: View
-        get() = keyguardStatusView.findViewById(R.id.status_view_media_container)
+        get() = keyguardStatusView.requireViewById(R.id.status_view_media_container)
     private val statusViewContainer: ViewGroup
-        get() = keyguardStatusView.findViewById(R.id.status_view_container)
+        get() = keyguardStatusView.requireViewById(R.id.status_view_container)
     private val childrenExcludingMedia
         get() = statusViewContainer.children.filter { it != mediaView }
 
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
index 5abab62..0cd82f0 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
@@ -40,6 +40,7 @@
 import static com.android.keyguard.KeyguardUpdateMonitor.HAL_POWER_PRESS_TIMEOUT;
 import static com.android.keyguard.KeyguardUpdateMonitor.getCurrentUser;
 import static com.android.systemui.flags.Flags.FP_LISTEN_OCCLUDING_APPS;
+import static com.android.systemui.flags.Flags.STOP_FACE_AUTH_ON_DISPLAY_OFF;
 import static com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_CLOSED;
 import static com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_OPENED;
 import static com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_UNKNOWN;
@@ -89,6 +90,7 @@
 import android.hardware.biometrics.BiometricSourceType;
 import android.hardware.biometrics.ComponentInfoInternal;
 import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
+import android.hardware.display.DisplayManagerGlobal;
 import android.hardware.face.FaceAuthenticateOptions;
 import android.hardware.face.FaceManager;
 import android.hardware.face.FaceSensorProperties;
@@ -121,6 +123,9 @@
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.text.TextUtils;
+import android.view.Display;
+import android.view.DisplayAdjustments;
+import android.view.DisplayInfo;
 
 import androidx.annotation.NonNull;
 
@@ -143,6 +148,7 @@
 import com.android.systemui.flags.FakeFeatureFlags;
 import com.android.systemui.log.SessionTracker;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
+import com.android.systemui.settings.FakeDisplayTracker;
 import com.android.systemui.settings.UserTracker;
 import com.android.systemui.shared.system.TaskStackChangeListener;
 import com.android.systemui.shared.system.TaskStackChangeListeners;
@@ -304,10 +310,12 @@
             mFingerprintAuthenticatorsRegisteredCallback;
     private IFaceAuthenticatorsRegisteredCallback mFaceAuthenticatorsRegisteredCallback;
     private final InstanceId mKeyguardInstanceId = InstanceId.fakeInstanceId(999);
+    private FakeDisplayTracker mDisplayTracker;
 
     @Before
     public void setup() throws RemoteException {
         MockitoAnnotations.initMocks(this);
+        mDisplayTracker = new FakeDisplayTracker(mContext);
         when(mSessionTracker.getSessionId(SESSION_KEYGUARD)).thenReturn(mKeyguardInstanceId);
 
         when(mUserManager.isUserUnlocked(anyInt())).thenReturn(true);
@@ -348,6 +356,7 @@
         allowTestableLooperAsMainThread();
         mFeatureFlags = new FakeFeatureFlags();
         mFeatureFlags.set(FP_LISTEN_OCCLUDING_APPS, false);
+        mFeatureFlags.set(STOP_FACE_AUTH_ON_DISPLAY_OFF, false);
 
         when(mSecureSettings.getUriFor(anyString())).thenReturn(mURI);
 
@@ -358,6 +367,11 @@
                         anyInt());
 
         mKeyguardUpdateMonitor = new TestableKeyguardUpdateMonitor(mContext);
+        setupBiometrics(mKeyguardUpdateMonitor);
+    }
+
+    private void setupBiometrics(KeyguardUpdateMonitor keyguardUpdateMonitor)
+            throws RemoteException {
         captureAuthenticatorsRegisteredCallbacks();
         setupFaceAuth(/* isClass3 */ false);
         setupFingerprintAuth(/* isClass3 */ true);
@@ -367,9 +381,9 @@
         mBiometricEnabledOnKeyguardCallback = mBiometricEnabledCallbackArgCaptor.getValue();
         biometricsEnabledForCurrentUser();
 
-        mHandler = spy(mKeyguardUpdateMonitor.getHandler());
+        mHandler = spy(keyguardUpdateMonitor.getHandler());
         try {
-            FieldSetter.setField(mKeyguardUpdateMonitor,
+            FieldSetter.setField(keyguardUpdateMonitor,
                     KeyguardUpdateMonitor.class.getDeclaredField("mHandler"), mHandler);
         } catch (NoSuchFieldException e) {
 
@@ -1680,71 +1694,6 @@
     }
 
     @Test
-    public void startsListeningForSfps_whenKeyguardIsVisible_ifRequireInteractiveToAuthEnabled()
-            throws RemoteException {
-        // SFPS supported and enrolled
-        when(mAuthController.isSfpsSupported()).thenReturn(true);
-        when(mAuthController.isSfpsEnrolled(anyInt())).thenReturn(true);
-
-        // WHEN require interactive to auth is disabled, and keyguard is not awake
-        when(mInteractiveToAuthProvider.isEnabled(anyInt())).thenReturn(false);
-
-        // Preconditions for sfps auth to run
-        keyguardNotGoingAway();
-        currentUserIsSystem();
-        currentUserDoesNotHaveTrust();
-        biometricsNotDisabledThroughDevicePolicyManager();
-        biometricsEnabledForCurrentUser();
-        userNotCurrentlySwitching();
-
-        statusBarShadeIsLocked();
-        mTestableLooper.processAllMessages();
-
-        // THEN we should listen for sfps when screen off, because require screen on is disabled
-        assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isTrue();
-
-        // WHEN require interactive to auth is enabled, and keyguard is not awake
-        when(mInteractiveToAuthProvider.isEnabled(anyInt())).thenReturn(true);
-
-        // THEN we shouldn't listen for sfps when screen off, because require screen on is enabled
-        assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isFalse();
-
-        // Device now awake & keyguard is now interactive
-        deviceNotGoingToSleep();
-        deviceIsInteractive();
-        keyguardIsVisible();
-
-        // THEN we should listen for sfps when screen on, and require screen on is enabled
-        assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isTrue();
-    }
-
-    @Test
-    public void notListeningForSfps_whenGoingToSleep_ifRequireInteractiveToAuthEnabled()
-            throws RemoteException {
-        // GIVEN SFPS supported and enrolled
-        when(mAuthController.isSfpsSupported()).thenReturn(true);
-        when(mAuthController.isSfpsEnrolled(anyInt())).thenReturn(true);
-
-        // GIVEN Preconditions for sfps auth to run
-        keyguardNotGoingAway();
-        currentUserIsSystem();
-        currentUserDoesNotHaveTrust();
-        biometricsNotDisabledThroughDevicePolicyManager();
-        biometricsEnabledForCurrentUser();
-        userNotCurrentlySwitching();
-        statusBarShadeIsLocked();
-
-        // WHEN require interactive to auth is enabled & keyguard is going to sleep
-        when(mInteractiveToAuthProvider.isEnabled(anyInt())).thenReturn(true);
-        deviceGoingToSleep();
-
-        mTestableLooper.processAllMessages();
-
-        // THEN we should NOT listen for sfps because device is going to sleep
-        assertThat(mKeyguardUpdateMonitor.shouldListenForFingerprint(false)).isFalse();
-    }
-
-    @Test
     public void listeningForSfps_whenGoingToSleep_ifRequireInteractiveToAuthDisabled()
             throws RemoteException {
         // GIVEN SFPS supported and enrolled
@@ -3029,6 +2978,79 @@
         verify(callback).onBiometricEnrollmentStateChanged(BiometricSourceType.FACE);
     }
 
+    @Test
+    public void stopFaceAuthOnDisplayOffFlagNotEnabled_doNotRegisterForDisplayCallback() {
+        assertThat(mDisplayTracker.getDisplayCallbacks().size()).isEqualTo(0);
+    }
+
+    @Test
+    public void onDisplayOn_nothingHappens() throws RemoteException {
+        // GIVEN
+        keyguardIsVisible();
+        enableStopFaceAuthOnDisplayOff();
+
+        // WHEN the default display state changes to ON
+        triggerDefaultDisplayStateChangeToOn();
+
+        // THEN face auth is NOT started since we rely on STARTED_WAKING_UP to start face auth,
+        // NOT the display on event
+        verifyFaceAuthenticateNeverCalled();
+        verifyFaceDetectNeverCalled();
+    }
+
+    @Test
+    public void onDisplayOff_stopFaceAuth() throws RemoteException {
+        enableStopFaceAuthOnDisplayOff();
+
+        // GIVEN device is listening for face
+        mKeyguardUpdateMonitor.setKeyguardShowing(true, false);
+        mKeyguardUpdateMonitor.dispatchStartedWakingUp(PowerManager.WAKE_REASON_POWER_BUTTON);
+        mTestableLooper.processAllMessages();
+        verifyFaceAuthenticateCall();
+
+        final CancellationSignal faceCancel = spy(mKeyguardUpdateMonitor.mFaceCancelSignal);
+        mKeyguardUpdateMonitor.mFaceCancelSignal = faceCancel;
+        KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
+        mKeyguardUpdateMonitor.registerCallback(callback);
+
+        // WHEN the default display state changes to OFF
+        triggerDefaultDisplayStateChangeToOff();
+
+        // THEN face listening is stopped.
+        verify(faceCancel).cancel();
+        verify(callback).onBiometricRunningStateChanged(
+                eq(false), eq(BiometricSourceType.FACE)); // beverlyt
+
+    }
+
+    private void triggerDefaultDisplayStateChangeToOn() {
+        triggerDefaultDisplayStateChangeTo(true);
+    }
+
+    private void triggerDefaultDisplayStateChangeToOff() {
+        triggerDefaultDisplayStateChangeTo(false);
+    }
+
+    /**
+     * @param on true for Display.STATE_ON, else Display.STATE_OFF
+     */
+    private void triggerDefaultDisplayStateChangeTo(boolean on) {
+        DisplayManagerGlobal displayManagerGlobal = mock(DisplayManagerGlobal.class);
+        DisplayInfo displayInfoWithDisplayState = new DisplayInfo();
+        displayInfoWithDisplayState.state = on ? Display.STATE_ON : Display.STATE_OFF;
+        when(displayManagerGlobal.getDisplayInfo(mDisplayTracker.getDefaultDisplayId()))
+                .thenReturn(displayInfoWithDisplayState);
+        mDisplayTracker.setAllDisplays(new Display[]{
+                new Display(
+                        displayManagerGlobal,
+                        mDisplayTracker.getDefaultDisplayId(),
+                        displayInfoWithDisplayState,
+                        DisplayAdjustments.DEFAULT_DISPLAY_ADJUSTMENTS
+                )
+        });
+        mDisplayTracker.triggerOnDisplayChanged(mDisplayTracker.getDefaultDisplayId());
+    }
+
     private void verifyFingerprintAuthenticateNeverCalled() {
         verify(mFingerprintManager, never()).authenticate(any(), any(), any(), any(), any());
         verify(mFingerprintManager, never()).authenticate(any(), any(), any(), any(), anyInt(),
@@ -3297,6 +3319,18 @@
         mTestableLooper.processAllMessages();
     }
 
+    private void enableStopFaceAuthOnDisplayOff() throws RemoteException {
+        cleanupKeyguardUpdateMonitor();
+        clearInvocations(mFaceManager);
+        clearInvocations(mFingerprintManager);
+        clearInvocations(mBiometricManager);
+        clearInvocations(mStatusBarStateController);
+        mFeatureFlags.set(STOP_FACE_AUTH_ON_DISPLAY_OFF, true);
+        mKeyguardUpdateMonitor = new TestableKeyguardUpdateMonitor(mContext);
+        setupBiometrics(mKeyguardUpdateMonitor);
+        assertThat(mDisplayTracker.getDisplayCallbacks().size()).isEqualTo(1);
+    }
+
     private Intent putPhoneInfo(Intent intent, Bundle data, Boolean simInited) {
         int subscription = simInited
                 ? 1/* mock subid=1 */ : SubscriptionManager.PLACEHOLDER_SUBSCRIPTION_ID_BASE;
@@ -3374,7 +3408,7 @@
                     mPackageManager, mFaceManager, mFingerprintManager, mBiometricManager,
                     mFaceWakeUpTriggersConfig, mDevicePostureController,
                     Optional.of(mInteractiveToAuthProvider), mFeatureFlags,
-                    mTaskStackChangeListeners, mActivityTaskManager);
+                    mTaskStackChangeListeners, mActivityTaskManager, mDisplayTracker);
             setStrongAuthTracker(KeyguardUpdateMonitorTest.this.mStrongAuthTracker);
         }
 
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/LockIconViewControllerBaseTest.java b/packages/SystemUI/tests/src/com/android/keyguard/LockIconViewControllerBaseTest.java
index 956e0b81..b18137c 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/LockIconViewControllerBaseTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/LockIconViewControllerBaseTest.java
@@ -49,7 +49,7 @@
 import com.android.systemui.flags.FakeFeatureFlags;
 import com.android.systemui.keyguard.data.repository.KeyguardTransitionRepository;
 import com.android.systemui.keyguard.domain.interactor.KeyguardInteractorFactory;
-import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor;
+import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractorFactory;
 import com.android.systemui.plugins.FalsingManager;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.StatusBarState;
@@ -164,8 +164,9 @@
                 mVibrator,
                 mAuthRippleController,
                 mResources,
-                new KeyguardTransitionInteractor(mTransitionRepository,
-                        TestScopeProvider.getTestScope().getBackgroundScope()),
+                KeyguardTransitionInteractorFactory.create(
+                        TestScopeProvider.getTestScope().getBackgroundScope(),
+                                mTransitionRepository).getKeyguardTransitionInteractor(),
                 KeyguardInteractorFactory.create(mFeatureFlags).getKeyguardInteractor(),
                 mFeatureFlags,
                 mPrimaryBouncerInteractor
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/LockIconViewControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/LockIconViewControllerTest.java
index ed6a891..45021ba 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/LockIconViewControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/LockIconViewControllerTest.java
@@ -20,7 +20,9 @@
 
 import static com.android.keyguard.LockIconView.ICON_LOCK;
 import static com.android.keyguard.LockIconView.ICON_UNLOCK;
+import static com.android.systemui.flags.Flags.ONE_WAY_HAPTICS_API_MIGRATION;
 
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.anyBoolean;
 import static org.mockito.Mockito.anyInt;
 import static org.mockito.Mockito.eq;
@@ -33,11 +35,13 @@
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.util.Pair;
+import android.view.HapticFeedbackConstants;
 import android.view.View;
 
 import androidx.test.filters.SmallTest;
 
 import com.android.settingslib.udfps.UdfpsOverlayParams;
+import com.android.systemui.biometrics.UdfpsController;
 import com.android.systemui.doze.util.BurnInHelperKt;
 
 import org.junit.Test;
@@ -339,4 +343,59 @@
         // THEN the lock icon is shown
         verify(mLockIconView).setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
     }
+
+    @Test
+    public void playHaptic_onTouchExploration_NoOneWayHaptics_usesVibrate() {
+        mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, false);
+
+        // WHEN request to vibrate on touch exploration
+        mUnderTest.vibrateOnTouchExploration();
+
+        // THEN vibrates
+        verify(mVibrator).vibrate(
+                anyInt(),
+                any(),
+                eq(UdfpsController.EFFECT_CLICK),
+                eq("lock-icon-down"),
+                any());
+    }
+
+    @Test
+    public void playHaptic_onTouchExploration_withOneWayHaptics_performHapticFeedback() {
+        mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, true);
+
+        // WHEN request to vibrate on touch exploration
+        mUnderTest.vibrateOnTouchExploration();
+
+        // THEN performHapticFeedback is used
+        verify(mVibrator).performHapticFeedback(any(), eq(HapticFeedbackConstants.CONTEXT_CLICK));
+    }
+
+    @Test
+    public void playHaptic_onLongPress_NoOneWayHaptics_usesVibrate() {
+        mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, false);
+
+        // WHEN request to vibrate on long press
+        mUnderTest.vibrateOnLongPress();
+
+        // THEN uses vibrate
+        verify(mVibrator).vibrate(
+                anyInt(),
+                any(),
+                eq(UdfpsController.EFFECT_CLICK),
+                eq("lock-screen-lock-icon-longpress"),
+                any());
+    }
+
+    @Test
+    public void playHaptic_onLongPress_withOneWayHaptics_performHapticFeedback() {
+        mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, true);
+
+        // WHEN request to vibrate on long press
+        mUnderTest.vibrateOnLongPress();
+
+        // THEN uses perform haptic feedback
+        verify(mVibrator).performHapticFeedback(any(), eq(UdfpsController.LONG_PRESS));
+
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/NumPadAnimatorTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/NumPadAnimatorTest.kt
index 9fcb9c8..7c2550f 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/NumPadAnimatorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/NumPadAnimatorTest.kt
@@ -47,10 +47,10 @@
 
     @Test
     fun testOnLayout() {
-        underTest.onLayout(100)
+        underTest.onLayout(100, 100)
         verify(background).cornerRadius = 50f
         reset(background)
-        underTest.onLayout(100)
+        underTest.onLayout(100, 100)
         verify(background, never()).cornerRadius = anyFloat()
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/SplitShadeTransitionAdapterTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/SplitShadeTransitionAdapterTest.kt
index 6fe8892..9f9b9a4 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/SplitShadeTransitionAdapterTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/SplitShadeTransitionAdapterTest.kt
@@ -19,9 +19,11 @@
 import android.testing.AndroidTestingRunner
 import android.transition.TransitionValues
 import android.view.View
+import android.view.ViewGroup
 import androidx.test.filters.SmallTest
 import com.android.keyguard.KeyguardStatusViewController.SplitShadeTransitionAdapter
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.util.mockito.mock
 import com.google.common.truth.Truth.assertThat
 import org.junit.Before
 import org.junit.Test
@@ -84,5 +86,5 @@
     startValues: TransitionValues?,
     endValues: TransitionValues?
 ): Animator? {
-    return createAnimator(/* sceneRoot= */ null, startValues, endValues)
+    return createAnimator(/* sceneRoot= */ mock(), startValues, endValues)
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/FaceScanningProviderFactoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/FaceScanningProviderFactoryTest.kt
index 01d3a39..ea7cc3d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/FaceScanningProviderFactoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/FaceScanningProviderFactoryTest.kt
@@ -27,6 +27,8 @@
 import com.android.systemui.biometrics.AuthController
 import com.android.systemui.decor.FaceScanningProviderFactory
 import com.android.systemui.dump.logcatLogBuffer
+import com.android.systemui.flags.FakeFeatureFlags
+import com.android.systemui.flags.Flags
 import com.android.systemui.log.ScreenDecorationsLogger
 import com.android.systemui.plugins.statusbar.StatusBarStateController
 import com.android.systemui.util.mockito.whenever
@@ -80,6 +82,8 @@
             R.bool.config_fillMainBuiltInDisplayCutout,
             true
         )
+        val featureFlags = FakeFeatureFlags()
+        featureFlags.set(Flags.STOP_PULSING_FACE_SCANNING_ANIMATION, true)
         underTest =
             FaceScanningProviderFactory(
                 authController,
@@ -87,7 +91,8 @@
                 statusBarStateController,
                 keyguardUpdateMonitor,
                 mock(Executor::class.java),
-                ScreenDecorationsLogger(logcatLogBuffer("FaceScanningProviderFactoryTest"))
+                ScreenDecorationsLogger(logcatLogBuffer("FaceScanningProviderFactoryTest")),
+                featureFlags,
             )
 
         whenever(authController.faceSensorLocation).thenReturn(Point(10, 10))
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java
deleted file mode 100644
index b47b08c..0000000
--- a/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java
+++ /dev/null
@@ -1,487 +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 static android.service.notification.NotificationListenerService.REASON_APP_CANCEL;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNull;
-import static junit.framework.TestCase.fail;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.annotation.UserIdInt;
-import android.app.AppOpsManager;
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.UserHandle;
-import android.service.notification.StatusBarNotification;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-import android.widget.RemoteViews;
-
-import androidx.test.filters.SmallTest;
-
-import com.android.internal.messages.nano.SystemMessageProto;
-import com.android.systemui.appops.AppOpsController;
-import com.android.systemui.statusbar.notification.collection.NotifPipeline;
-import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
-import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionListener;
-
-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;
-
-@SmallTest
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
-public class ForegroundServiceControllerTest extends SysuiTestCase {
-    private ForegroundServiceController mFsc;
-    private ForegroundServiceNotificationListener mListener;
-    private NotifCollectionListener mCollectionListener;
-    @Mock private AppOpsController mAppOpsController;
-    @Mock private Handler mMainHandler;
-    @Mock private NotifPipeline mNotifPipeline;
-
-    @Before
-    public void setUp() throws Exception {
-        // allow the TestLooper to be asserted as the main thread these tests
-        allowTestableLooperAsMainThread();
-
-        MockitoAnnotations.initMocks(this);
-        mFsc = new ForegroundServiceController(mAppOpsController, mMainHandler);
-        mListener = new ForegroundServiceNotificationListener(
-                mContext, mFsc, mNotifPipeline);
-        mListener.init();
-        ArgumentCaptor<NotifCollectionListener> entryListenerCaptor =
-                ArgumentCaptor.forClass(NotifCollectionListener.class);
-        verify(mNotifPipeline).addCollectionListener(
-                entryListenerCaptor.capture());
-        mCollectionListener = entryListenerCaptor.getValue();
-    }
-
-    @Test
-    public void testAppOpsChangedCalledFromBgThread() {
-        try {
-            // WHEN onAppOpChanged is called from a different thread than the MainLooper
-            disallowTestableLooperAsMainThread();
-            NotificationEntry entry = createFgEntry();
-            mFsc.onAppOpChanged(
-                    AppOpsManager.OP_CAMERA,
-                    entry.getSbn().getUid(),
-                    entry.getSbn().getPackageName(),
-                    true);
-
-            // This test is run on the TestableLooper, which is not the MainLooper, so
-            // we expect an exception to be thrown
-            fail("onAppOpChanged shouldn't be allowed to be called from a bg thread.");
-        } catch (IllegalStateException e) {
-            // THEN expect an exception
-        }
-    }
-
-    @Test
-    public void testAppOpsCRUD() {
-        // no crash on remove that doesn't exist
-        mFsc.onAppOpChanged(9, 1000, "pkg1", false);
-        assertNull(mFsc.getAppOps(0, "pkg1"));
-
-        // multiuser & multipackage
-        mFsc.onAppOpChanged(8, 50, "pkg1", true);
-        mFsc.onAppOpChanged(1, 60, "pkg3", true);
-        mFsc.onAppOpChanged(7, 500000, "pkg2", true);
-
-        assertEquals(1, mFsc.getAppOps(0, "pkg1").size());
-        assertTrue(mFsc.getAppOps(0, "pkg1").contains(8));
-
-        assertEquals(1, mFsc.getAppOps(UserHandle.getUserId(500000), "pkg2").size());
-        assertTrue(mFsc.getAppOps(UserHandle.getUserId(500000), "pkg2").contains(7));
-
-        assertEquals(1, mFsc.getAppOps(0, "pkg3").size());
-        assertTrue(mFsc.getAppOps(0, "pkg3").contains(1));
-
-        // multiple ops for the same package
-        mFsc.onAppOpChanged(9, 50, "pkg1", true);
-        mFsc.onAppOpChanged(5, 50, "pkg1", true);
-
-        assertEquals(3, mFsc.getAppOps(0, "pkg1").size());
-        assertTrue(mFsc.getAppOps(0, "pkg1").contains(8));
-        assertTrue(mFsc.getAppOps(0, "pkg1").contains(9));
-        assertTrue(mFsc.getAppOps(0, "pkg1").contains(5));
-
-        assertEquals(1, mFsc.getAppOps(UserHandle.getUserId(500000), "pkg2").size());
-        assertTrue(mFsc.getAppOps(UserHandle.getUserId(500000), "pkg2").contains(7));
-
-        // remove one of the multiples
-        mFsc.onAppOpChanged(9, 50, "pkg1", false);
-        assertEquals(2, mFsc.getAppOps(0, "pkg1").size());
-        assertTrue(mFsc.getAppOps(0, "pkg1").contains(8));
-        assertTrue(mFsc.getAppOps(0, "pkg1").contains(5));
-
-        // remove last op
-        mFsc.onAppOpChanged(1, 60, "pkg3", false);
-        assertNull(mFsc.getAppOps(0, "pkg3"));
-    }
-
-    @Test
-    public void testDisclosurePredicate() {
-        StatusBarNotification sbn_user1_app1 = makeMockSBN(USERID_ONE, "com.example.app1",
-                5000, "monkeys", Notification.FLAG_AUTO_CANCEL);
-        StatusBarNotification sbn_user1_disclosure = makeMockSBN(USERID_ONE, "android",
-                SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
-                null, Notification.FLAG_NO_CLEAR);
-
-        assertTrue(mFsc.isDisclosureNotification(sbn_user1_disclosure));
-        assertFalse(mFsc.isDisclosureNotification(sbn_user1_app1));
-    }
-
-    @Test
-    public void testNeedsDisclosureAfterRemovingUnrelatedNotification() {
-        final String PKG1 = "com.example.app100";
-
-        StatusBarNotification sbn_user1_app1 = makeMockSBN(USERID_ONE, PKG1,
-                5000, "monkeys", Notification.FLAG_AUTO_CANCEL);
-        StatusBarNotification sbn_user1_app1_fg = makeMockFgSBN(USERID_ONE, PKG1);
-
-        // first add a normal notification
-        entryAdded(sbn_user1_app1, NotificationManager.IMPORTANCE_DEFAULT);
-        // nothing required yet
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_ONE));
-        // now the app starts a fg service
-        entryAdded(makeMockDisclosure(USERID_ONE, new String[]{PKG1}),
-                NotificationManager.IMPORTANCE_DEFAULT);
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE)); // should be required!
-        // add the fg notification
-        entryAdded(sbn_user1_app1_fg, NotificationManager.IMPORTANCE_DEFAULT);
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_ONE)); // app1 has got it covered
-        // remove the boring notification
-        entryRemoved(sbn_user1_app1);
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_ONE)); // app1 has STILL got it covered
-        entryRemoved(sbn_user1_app1_fg);
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE)); // should be required!
-    }
-
-    @Test
-    public void testSimpleAddRemove() {
-        final String PKG1 = "com.example.app1";
-        final String PKG2 = "com.example.app2";
-
-        StatusBarNotification sbn_user1_app1 = makeMockSBN(USERID_ONE, PKG1,
-                5000, "monkeys", Notification.FLAG_AUTO_CANCEL);
-        entryAdded(sbn_user1_app1, NotificationManager.IMPORTANCE_DEFAULT);
-
-        // no services are "running"
-        entryAdded(makeMockDisclosure(USERID_ONE, null),
-                NotificationManager.IMPORTANCE_DEFAULT);
-
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_ONE));
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-
-        entryUpdated(makeMockDisclosure(USERID_ONE, new String[]{PKG1}),
-                NotificationManager.IMPORTANCE_DEFAULT);
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE)); // should be required!
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-
-        // switch to different package
-        entryUpdated(makeMockDisclosure(USERID_ONE, new String[]{PKG2}),
-                NotificationManager.IMPORTANCE_DEFAULT);
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE));
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-
-        entryUpdated(makeMockDisclosure(USERID_TWO, new String[]{PKG1}),
-                NotificationManager.IMPORTANCE_DEFAULT);
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE));
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_TWO)); // finally user2 needs one too
-
-        entryUpdated(makeMockDisclosure(USERID_ONE, new String[]{PKG2, PKG1}),
-                NotificationManager.IMPORTANCE_DEFAULT);
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE));
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_TWO));
-
-        entryRemoved(makeMockDisclosure(USERID_ONE, null /*unused*/));
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_ONE));
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_TWO));
-
-        entryRemoved(makeMockDisclosure(USERID_TWO, null /*unused*/));
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_ONE));
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-    }
-
-    @Test
-    public void testDisclosureBasic() {
-        final String PKG1 = "com.example.app0";
-
-        StatusBarNotification sbn_user1_app1 = makeMockSBN(USERID_ONE, PKG1,
-                5000, "monkeys", Notification.FLAG_AUTO_CANCEL);
-        StatusBarNotification sbn_user1_app1_fg = makeMockFgSBN(USERID_ONE, PKG1);
-
-        entryAdded(sbn_user1_app1, NotificationManager.IMPORTANCE_DEFAULT); // not fg
-        entryAdded(makeMockDisclosure(USERID_ONE, new String[]{PKG1}),
-                NotificationManager.IMPORTANCE_DEFAULT);
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE)); // should be required!
-        entryAdded(sbn_user1_app1_fg, NotificationManager.IMPORTANCE_DEFAULT);
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_ONE)); // app1 has got it covered
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-
-        // let's take out the other notification and see what happens.
-
-        entryRemoved(sbn_user1_app1);
-        assertFalse(
-                mFsc.isDisclosureNeededForUser(USERID_ONE)); // still covered by sbn_user1_app1_fg
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-
-        // let's attempt to downgrade the notification from FLAG_FOREGROUND and see what we get
-        StatusBarNotification sbn_user1_app1_fg_sneaky = makeMockFgSBN(USERID_ONE, PKG1);
-        sbn_user1_app1_fg_sneaky.getNotification().flags = 0;
-        entryUpdated(sbn_user1_app1_fg_sneaky,
-                NotificationManager.IMPORTANCE_DEFAULT);
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE)); // should be required!
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-
-        // ok, ok, we'll put it back
-        sbn_user1_app1_fg_sneaky.getNotification().flags = Notification.FLAG_FOREGROUND_SERVICE;
-        entryUpdated(sbn_user1_app1_fg, NotificationManager.IMPORTANCE_DEFAULT);
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_ONE));
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-
-        entryRemoved(sbn_user1_app1_fg_sneaky);
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE)); // should be required!
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-
-        // now let's test an upgrade
-        entryAdded(sbn_user1_app1, NotificationManager.IMPORTANCE_DEFAULT);
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE));
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-        sbn_user1_app1.getNotification().flags |= Notification.FLAG_FOREGROUND_SERVICE;
-        entryUpdated(sbn_user1_app1,
-                NotificationManager.IMPORTANCE_DEFAULT); // this is now a fg notification
-
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_ONE));
-
-        // remove it, make sure we're out of compliance again
-        entryRemoved(sbn_user1_app1); // was fg, should return true
-        entryRemoved(sbn_user1_app1);
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE));
-
-        // importance upgrade
-        entryAdded(sbn_user1_app1_fg, NotificationManager.IMPORTANCE_MIN);
-        assertTrue(mFsc.isDisclosureNeededForUser(USERID_ONE));
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-        sbn_user1_app1.getNotification().flags |= Notification.FLAG_FOREGROUND_SERVICE;
-        entryUpdated(sbn_user1_app1_fg,
-                NotificationManager.IMPORTANCE_DEFAULT); // this is now a fg notification
-
-        // finally, let's turn off the service
-        entryAdded(makeMockDisclosure(USERID_ONE, null),
-                NotificationManager.IMPORTANCE_DEFAULT);
-
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_ONE));
-        assertFalse(mFsc.isDisclosureNeededForUser(USERID_TWO));
-    }
-
-    @Test
-    public void testNoNotifsNorAppOps_noSystemAlertWarningRequired() {
-        // no notifications nor app op signals that this package/userId requires system alert
-        // warning
-        assertFalse(mFsc.isSystemAlertWarningNeeded(USERID_ONE, "any"));
-    }
-
-    @Test
-    public void testCustomLayouts_systemAlertWarningRequired() {
-        // GIVEN a notification with a custom layout
-        final String pkg = "com.example.app0";
-        StatusBarNotification customLayoutNotif = makeMockSBN(USERID_ONE, pkg, 0,
-                false);
-
-        // WHEN the custom layout entry is added
-        entryAdded(customLayoutNotif, NotificationManager.IMPORTANCE_MIN);
-
-        // THEN a system alert warning is required since there aren't any notifications that can
-        // display the app ops
-        assertTrue(mFsc.isSystemAlertWarningNeeded(USERID_ONE, pkg));
-    }
-
-    @Test
-    public void testStandardLayoutExists_noSystemAlertWarningRequired() {
-        // GIVEN two notifications (one with a custom layout, the other with a standard layout)
-        final String pkg = "com.example.app0";
-        StatusBarNotification customLayoutNotif = makeMockSBN(USERID_ONE, pkg, 0,
-                false);
-        StatusBarNotification standardLayoutNotif = makeMockSBN(USERID_ONE, pkg, 1, true);
-
-        // WHEN the entries are added
-        entryAdded(customLayoutNotif, NotificationManager.IMPORTANCE_MIN);
-        entryAdded(standardLayoutNotif, NotificationManager.IMPORTANCE_MIN);
-
-        // THEN no system alert warning is required, since there is at least one notification
-        // with a standard layout that can display the app ops on the notification
-        assertFalse(mFsc.isSystemAlertWarningNeeded(USERID_ONE, pkg));
-    }
-
-    @Test
-    public void testStandardLayoutRemoved_systemAlertWarningRequired() {
-        // GIVEN two notifications (one with a custom layout, the other with a standard layout)
-        final String pkg = "com.example.app0";
-        StatusBarNotification customLayoutNotif = makeMockSBN(USERID_ONE, pkg, 0,
-                false);
-        StatusBarNotification standardLayoutNotif = makeMockSBN(USERID_ONE, pkg, 1, true);
-
-        // WHEN the entries are added and then the standard layout notification is removed
-        entryAdded(customLayoutNotif, NotificationManager.IMPORTANCE_MIN);
-        entryAdded(standardLayoutNotif, NotificationManager.IMPORTANCE_MIN);
-        entryRemoved(standardLayoutNotif);
-
-        // THEN a system alert warning is required since there aren't any notifications that can
-        // display the app ops
-        assertTrue(mFsc.isSystemAlertWarningNeeded(USERID_ONE, pkg));
-    }
-
-    @Test
-    public void testStandardLayoutUpdatedToCustomLayout_systemAlertWarningRequired() {
-        // GIVEN a standard layout notification and then an updated version with a customLayout
-        final String pkg = "com.example.app0";
-        StatusBarNotification standardLayoutNotif = makeMockSBN(USERID_ONE, pkg, 1, true);
-        StatusBarNotification updatedToCustomLayoutNotif = makeMockSBN(USERID_ONE, pkg, 1, false);
-
-        // WHEN the entries is added and then updated to a custom layout
-        entryAdded(standardLayoutNotif, NotificationManager.IMPORTANCE_MIN);
-        entryUpdated(updatedToCustomLayoutNotif, NotificationManager.IMPORTANCE_MIN);
-
-        // THEN a system alert warning is required since there aren't any notifications that can
-        // display the app ops
-        assertTrue(mFsc.isSystemAlertWarningNeeded(USERID_ONE, pkg));
-    }
-
-    private StatusBarNotification makeMockSBN(int userId, String pkg, int id, String tag,
-            int flags) {
-        final Notification n = mock(Notification.class);
-        n.extras = new Bundle();
-        n.flags = flags;
-        return makeMockSBN(userId, pkg, id, tag, n);
-    }
-
-    private StatusBarNotification makeMockSBN(int userid, String pkg, int id, String tag,
-            Notification n) {
-        final StatusBarNotification sbn = mock(StatusBarNotification.class);
-        when(sbn.getNotification()).thenReturn(n);
-        when(sbn.getId()).thenReturn(id);
-        when(sbn.getPackageName()).thenReturn(pkg);
-        when(sbn.getTag()).thenReturn(tag);
-        when(sbn.getUserId()).thenReturn(userid);
-        when(sbn.getUser()).thenReturn(new UserHandle(userid));
-        when(sbn.getKey()).thenReturn("MOCK:"+userid+"|"+pkg+"|"+id+"|"+tag);
-        return sbn;
-    }
-
-    private StatusBarNotification makeMockSBN(int uid, String pkg, int id,
-            boolean usesStdLayout) {
-        StatusBarNotification sbn = makeMockSBN(uid, pkg, id, "foo", 0);
-        if (usesStdLayout) {
-            sbn.getNotification().contentView = null;
-            sbn.getNotification().headsUpContentView = null;
-            sbn.getNotification().bigContentView = null;
-        } else {
-            sbn.getNotification().contentView = mock(RemoteViews.class);
-        }
-        return sbn;
-    }
-
-    private StatusBarNotification makeMockFgSBN(int uid, String pkg, int id,
-            boolean usesStdLayout) {
-        StatusBarNotification sbn =
-                makeMockSBN(uid, pkg, id, "foo", Notification.FLAG_FOREGROUND_SERVICE);
-        if (usesStdLayout) {
-            sbn.getNotification().contentView = null;
-            sbn.getNotification().headsUpContentView = null;
-            sbn.getNotification().bigContentView = null;
-        } else {
-            sbn.getNotification().contentView = mock(RemoteViews.class);
-        }
-        return sbn;
-    }
-
-    private StatusBarNotification makeMockFgSBN(int uid, String pkg) {
-        return makeMockSBN(uid, pkg, 1000, "foo", Notification.FLAG_FOREGROUND_SERVICE);
-    }
-
-    private StatusBarNotification makeMockDisclosure(int userid, String[] pkgs) {
-        final Notification n = mock(Notification.class);
-        n.flags = Notification.FLAG_ONGOING_EVENT;
-        final Bundle extras = new Bundle();
-        if (pkgs != null) extras.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
-        n.extras = extras;
-        n.when = System.currentTimeMillis() - 10000; // ten seconds ago
-        final StatusBarNotification sbn = makeMockSBN(userid, "android",
-                SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
-                null, n);
-        sbn.getNotification().extras = extras;
-        return sbn;
-    }
-
-    private NotificationEntry addFgEntry() {
-        NotificationEntry entry = createFgEntry();
-        mCollectionListener.onEntryAdded(entry);
-        return entry;
-    }
-
-    private NotificationEntry createFgEntry() {
-        return new NotificationEntryBuilder()
-                .setSbn(makeMockFgSBN(0, TEST_PACKAGE_NAME, 1000, true))
-                .setImportance(NotificationManager.IMPORTANCE_DEFAULT)
-                .build();
-    }
-
-    private void entryRemoved(StatusBarNotification notification) {
-        mCollectionListener.onEntryRemoved(
-                new NotificationEntryBuilder()
-                        .setSbn(notification)
-                        .build(),
-                REASON_APP_CANCEL);
-    }
-
-    private void entryAdded(StatusBarNotification notification, int importance) {
-        NotificationEntry entry = new NotificationEntryBuilder()
-                .setSbn(notification)
-                .setImportance(importance)
-                .build();
-        mCollectionListener.onEntryAdded(entry);
-    }
-
-    private void entryUpdated(StatusBarNotification notification, int importance) {
-        NotificationEntry entry = new NotificationEntryBuilder()
-                .setSbn(notification)
-                .setImportance(importance)
-                .build();
-        mCollectionListener.onEntryUpdated(entry);
-    }
-
-    @UserIdInt private static final int USERID_ONE = 10; // UserManagerService.MIN_USER_ID;
-    @UserIdInt private static final int USERID_TWO = USERID_ONE + 1;
-    private static final String TEST_PACKAGE_NAME = "test";
-}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
index 796e665..f81ef10 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
@@ -92,6 +92,8 @@
 import com.android.systemui.decor.PrivacyDotCornerDecorProviderImpl;
 import com.android.systemui.decor.PrivacyDotDecorProviderFactory;
 import com.android.systemui.decor.RoundedCornerResDelegate;
+import com.android.systemui.flags.FakeFeatureFlags;
+import com.android.systemui.flags.Flags;
 import com.android.systemui.log.ScreenDecorationsLogger;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.settings.FakeDisplayTracker;
@@ -226,13 +228,16 @@
         doAnswer(it -> !(mMockCutoutList.isEmpty())).when(mCutoutFactory).getHasProviders();
         doReturn(mMockCutoutList).when(mCutoutFactory).getProviders();
 
+        FakeFeatureFlags featureFlags = new FakeFeatureFlags();
+        featureFlags.set(Flags.STOP_PULSING_FACE_SCANNING_ANIMATION, true);
         mFaceScanningDecorProvider = spy(new FaceScanningOverlayProviderImpl(
                 BOUNDS_POSITION_TOP,
                 mAuthController,
                 mStatusBarStateController,
                 mKeyguardUpdateMonitor,
                 mExecutor,
-                new ScreenDecorationsLogger(logcatLogBuffer("TestLogBuffer"))));
+                new ScreenDecorationsLogger(logcatLogBuffer("TestLogBuffer")),
+                featureFlags));
 
         mScreenDecorations = spy(new ScreenDecorations(mContext, mSecureSettings,
                 mCommandRegistry, mUserTracker, mDisplayTracker, mDotViewController,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerTest.java
index a48fa5d..0fb0b03 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerTest.java
@@ -721,6 +721,36 @@
     }
 
     @Test
+    public void windowMagnifierEditMode_performA11yClickAction_exitEditMode() {
+        mInstrumentation.runOnMainSync(() -> {
+            mWindowMagnificationController.enableWindowMagnificationInternal(Float.NaN, Float.NaN,
+                    Float.NaN);
+            mWindowMagnificationController.setEditMagnifierSizeMode(true);
+        });
+
+        View closeButton = getInternalView(R.id.close_button);
+        View bottomRightCorner = getInternalView(R.id.bottom_right_corner);
+        View bottomLeftCorner = getInternalView(R.id.bottom_left_corner);
+        View topRightCorner = getInternalView(R.id.top_right_corner);
+        View topLeftCorner = getInternalView(R.id.top_left_corner);
+
+        assertEquals(View.VISIBLE, closeButton.getVisibility());
+        assertEquals(View.VISIBLE, bottomRightCorner.getVisibility());
+        assertEquals(View.VISIBLE, bottomLeftCorner.getVisibility());
+        assertEquals(View.VISIBLE, topRightCorner.getVisibility());
+        assertEquals(View.VISIBLE, topLeftCorner.getVisibility());
+
+        final View mirrorView = mWindowManager.getAttachedView();
+        mirrorView.performAccessibilityAction(AccessibilityAction.ACTION_CLICK.getId(), null);
+
+        assertEquals(View.GONE, closeButton.getVisibility());
+        assertEquals(View.GONE, bottomRightCorner.getVisibility());
+        assertEquals(View.GONE, bottomLeftCorner.getVisibility());
+        assertEquals(View.GONE, topRightCorner.getVisibility());
+        assertEquals(View.GONE, topLeftCorner.getVisibility());
+    }
+
+    @Test
     public void enableWindowMagnification_hasA11yWindowTitle() {
         mInstrumentation.runOnMainSync(() -> {
             mWindowMagnificationController.enableWindowMagnificationInternal(Float.NaN, Float.NaN,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/animation/DialogLaunchAnimatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/animation/DialogLaunchAnimatorTest.kt
index 316de59..2233e322 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/animation/DialogLaunchAnimatorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/animation/DialogLaunchAnimatorTest.kt
@@ -70,7 +70,7 @@
         assertTrue(dialog.isShowing)
 
         // The dialog is now fullscreen.
-        val window = dialog.window
+        val window = checkNotNull(dialog.window)
         val decorView = window.decorView as DecorView
         assertEquals(MATCH_PARENT, window.attributes.width)
         assertEquals(MATCH_PARENT, window.attributes.height)
@@ -172,14 +172,15 @@
         // Important: the power menu animation relies on this behavior to know when to animate (see
         // http://ag/16774605).
         val dialog = runOnMainThreadAndWaitForIdleSync { TestDialog(context) }
-        dialog.window.setWindowAnimations(0)
-        assertEquals(0, dialog.window.attributes.windowAnimations)
+        val window = checkNotNull(dialog.window)
+        window.setWindowAnimations(0)
+        assertEquals(0, window.attributes.windowAnimations)
 
         val touchSurface = createTouchSurface()
         runOnMainThreadAndWaitForIdleSync {
             dialogLaunchAnimator.showFromView(dialog, touchSurface)
         }
-        assertNotEquals(0, dialog.window.attributes.windowAnimations)
+        assertNotEquals(0, window.attributes.windowAnimations)
     }
 
     @Test
@@ -351,13 +352,14 @@
 
         init {
             // We need to set the window type for dialogs shown by SysUI, otherwise WM will throw.
-            window.setType(WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL)
+            checkNotNull(window).setType(WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL)
         }
 
         override fun onCreate(savedInstanceState: Bundle?) {
             super.onCreate(savedInstanceState)
             setContentView(contentView)
 
+            val window = checkNotNull(window)
             window.setLayout(DIALOG_WIDTH, DIALOG_HEIGHT)
             window.setBackgroundDrawable(windowBackground)
         }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/appops/AppOpsControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/appops/AppOpsControllerTest.java
index 61a6512..b100336 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/appops/AppOpsControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/appops/AppOpsControllerTest.java
@@ -19,6 +19,10 @@
 import static android.hardware.SensorPrivacyManager.Sensors.CAMERA;
 import static android.hardware.SensorPrivacyManager.Sensors.MICROPHONE;
 
+import static com.android.systemui.appops.AppOpsControllerImpl.OPS_MIC;
+
+import static com.google.common.truth.Truth.assertThat;
+
 import static junit.framework.TestCase.assertFalse;
 
 import static org.junit.Assert.assertEquals;
@@ -64,6 +68,7 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 
@@ -171,6 +176,28 @@
                 TEST_UID, TEST_PACKAGE_NAME, true);
     }
 
+
+    // Only the app ops in the {@link com.android.systemui.appops.AppOpsControllerImpl.OPS} will be
+    // supported by the {@link AppOpsControllerImpl} to add callbacks. The state changes of active
+    // app ops will be notified by the callback.
+    @Test
+    public void addCallback_partialIncludedCode() {
+        mController.addCallback(new int[]{AppOpsManager.OP_RECEIVE_SANDBOX_TRIGGER_AUDIO,
+                AppOpsManager.OP_FINE_LOCATION}, mCallback);
+        mController.onOpActiveChanged(
+                AppOpsManager.OPSTR_RECORD_AUDIO, TEST_UID, TEST_PACKAGE_NAME, true);
+        mController.onOpActiveChanged(
+                AppOpsManager.OPSTR_RECEIVE_SANDBOX_TRIGGER_AUDIO, TEST_UID, TEST_PACKAGE_NAME,
+                true);
+        assertEquals(2, mController.getActiveAppOps().size());
+
+        mTestableLooper.processAllMessages();
+        verify(mCallback).onActiveStateChanged(AppOpsManager.OP_RECEIVE_SANDBOX_TRIGGER_AUDIO,
+                TEST_UID, TEST_PACKAGE_NAME, true);
+        verify(mCallback, never()).onActiveStateChanged(AppOpsManager.OP_RECORD_AUDIO,
+                TEST_UID, TEST_PACKAGE_NAME, true);
+    }
+
     @Test
     public void addCallback_notIncludedCode() {
         mController.addCallback(new int[]{AppOpsManager.OP_FINE_LOCATION}, mCallback);
@@ -504,108 +531,129 @@
     }
 
     @Test
-    public void testUnpausedRecordingSentActive() {
-        mController.addCallback(new int[]{AppOpsManager.OP_RECORD_AUDIO}, mCallback);
-        mTestableLooper.processAllMessages();
-        mController.onOpActiveChanged(
-                AppOpsManager.OPSTR_RECORD_AUDIO, TEST_UID, TEST_PACKAGE_NAME, true);
-
-        mTestableLooper.processAllMessages();
-        mRecordingCallback.onRecordingConfigChanged(Collections.emptyList());
-
-        mTestableLooper.processAllMessages();
-
-        verify(mCallback).onActiveStateChanged(
-                AppOpsManager.OP_RECORD_AUDIO, TEST_UID, TEST_PACKAGE_NAME, true);
+    public void testUnPausedRecordingSentActive() {
+        for (int i = 0; i < OPS_MIC.length; i++) {
+            verifyUnPausedSentActive(OPS_MIC[i]);
+        }
     }
 
     @Test
     public void testAudioPausedSentInactive() {
-        mController.addCallback(new int[]{AppOpsManager.OP_RECORD_AUDIO}, mCallback);
-        mTestableLooper.processAllMessages();
-        mController.onOpActiveChanged(
-                AppOpsManager.OPSTR_RECORD_AUDIO, TEST_UID_OTHER, TEST_PACKAGE_NAME, true);
-        mTestableLooper.processAllMessages();
-
-        AudioRecordingConfiguration mockARC = mock(AudioRecordingConfiguration.class);
-        when(mockARC.getClientUid()).thenReturn(TEST_UID_OTHER);
-        when(mockARC.isClientSilenced()).thenReturn(true);
-
-        mRecordingCallback.onRecordingConfigChanged(List.of(mockARC));
-        mTestableLooper.processAllMessages();
-
-        InOrder inOrder = inOrder(mCallback);
-        inOrder.verify(mCallback).onActiveStateChanged(
-                AppOpsManager.OP_RECORD_AUDIO, TEST_UID_OTHER, TEST_PACKAGE_NAME, true);
-        inOrder.verify(mCallback).onActiveStateChanged(
-                AppOpsManager.OP_RECORD_AUDIO, TEST_UID_OTHER, TEST_PACKAGE_NAME, false);
+        for (int i = 0; i < OPS_MIC.length; i++) {
+            verifyAudioPausedSentInactive(OPS_MIC[i]);
+        }
     }
 
     @Test
     public void testAudioFilteredWhenMicDisabled() {
-        mController.addCallback(new int[]{AppOpsManager.OP_RECORD_AUDIO, AppOpsManager.OP_CAMERA},
-                mCallback);
+        int micOp = AppOpsManager.OP_RECORD_AUDIO;
+        int nonMicOp = AppOpsManager.OP_CAMERA;
+
+        // Add callbacks for the micOp and nonMicOp, called for the micOp active state change,
+        // verify the micOp is the only active op returned.
+        mController.addCallback(new int[]{micOp, nonMicOp}, mCallback);
         mTestableLooper.processAllMessages();
         mController.onOpActiveChanged(
-                AppOpsManager.OPSTR_RECORD_AUDIO, TEST_UID_OTHER, TEST_PACKAGE_NAME, true);
+                AppOpsManager.opToPublicName(micOp), TEST_UID_OTHER, TEST_PACKAGE_NAME, true);
         mTestableLooper.processAllMessages();
-        List<AppOpItem> list = mController.getActiveAppOps();
-        assertEquals(1, list.size());
-        assertEquals(AppOpsManager.OP_RECORD_AUDIO, list.get(0).getCode());
-        assertFalse(list.get(0).isDisabled());
+        verifySingleActiveOps(micOp);
 
-        // Add a camera op, and disable the microphone. The camera op should be the only op returned
+        // Add a non-mic op, and disable the microphone. The camera op should be the only active op
+        // returned.
         mController.onSensorBlockedChanged(MICROPHONE, true);
-        mController.onOpActiveChanged(
-                AppOpsManager.OPSTR_CAMERA, TEST_UID_OTHER, TEST_PACKAGE_NAME, true);
+        mController.onOpActiveChanged(AppOpsManager.opToPublicName(nonMicOp), TEST_UID_OTHER,
+                TEST_PACKAGE_NAME, true);
         mTestableLooper.processAllMessages();
-        list = mController.getActiveAppOps();
-        assertEquals(1, list.size());
-        assertEquals(AppOpsManager.OP_CAMERA, list.get(0).getCode());
+        verifySingleActiveOps(nonMicOp);
 
-
-        // Re enable the microphone, and verify the op returns
+        // Re-enable the microphone, and verify the active op returns.
         mController.onSensorBlockedChanged(MICROPHONE, false);
         mTestableLooper.processAllMessages();
-
-        list = mController.getActiveAppOps();
-        assertEquals(2, list.size());
-        int micIdx = list.get(0).getCode() == AppOpsManager.OP_CAMERA ? 1 : 0;
-        assertEquals(AppOpsManager.OP_RECORD_AUDIO, list.get(micIdx).getCode());
+        verifyActiveOps(micOp, nonMicOp);
     }
 
     @Test
     public void testPhoneCallMicrophoneFilteredWhenMicDisabled() {
-        mController.addCallback(
-                new int[]{AppOpsManager.OP_PHONE_CALL_MICROPHONE, AppOpsManager.OP_CAMERA},
-                mCallback);
+        int micOp = AppOpsManager.OP_PHONE_CALL_MICROPHONE;
+        int nonMicOp = AppOpsManager.OP_CAMERA;
+
+        // Add callbacks for the micOp and nonMicOp, called for the micOp active state change,
+        // verify the micOp is the only active op returned.
+        mController.addCallback(new int[]{micOp, nonMicOp}, mCallback);
         mTestableLooper.processAllMessages();
         mController.onOpActiveChanged(
-                AppOpsManager.OPSTR_PHONE_CALL_MICROPHONE, TEST_UID_OTHER, TEST_PACKAGE_NAME, true);
+                AppOpsManager.opToPublicName(micOp), TEST_UID_OTHER, TEST_PACKAGE_NAME, true);
         mTestableLooper.processAllMessages();
-        List<AppOpItem> list = mController.getActiveAppOps();
-        assertEquals(1, list.size());
-        assertEquals(AppOpsManager.OP_PHONE_CALL_MICROPHONE, list.get(0).getCode());
-        assertFalse(list.get(0).isDisabled());
+        verifySingleActiveOps(micOp);
 
-        // Add a camera op, and disable the microphone. The camera op should be the only op returned
+        // Add a non-mic op, and disable the microphone. The camera op should be the only active op
+        // returned.
         mController.onSensorBlockedChanged(MICROPHONE, true);
-        mController.onOpActiveChanged(
-                AppOpsManager.OPSTR_CAMERA, TEST_UID_OTHER, TEST_PACKAGE_NAME, true);
+        mController.onOpActiveChanged(AppOpsManager.opToPublicName(nonMicOp), TEST_UID_OTHER,
+                TEST_PACKAGE_NAME, true);
         mTestableLooper.processAllMessages();
-        list = mController.getActiveAppOps();
-        assertEquals(1, list.size());
-        assertEquals(AppOpsManager.OP_CAMERA, list.get(0).getCode());
+        verifySingleActiveOps(nonMicOp);
 
-
-        // Re enable the microphone, and verify the op returns
+        // Re-enable the microphone, and verify the active op returns.
         mController.onSensorBlockedChanged(MICROPHONE, false);
         mTestableLooper.processAllMessages();
+        verifyActiveOps(micOp, nonMicOp);
+    }
 
-        list = mController.getActiveAppOps();
-        assertEquals(2, list.size());
-        int micIdx = list.get(0).getCode() == AppOpsManager.OP_CAMERA ? 1 : 0;
-        assertEquals(AppOpsManager.OP_PHONE_CALL_MICROPHONE, list.get(micIdx).getCode());
+    @Test
+    public void testAmbientTriggerMicrophoneFilteredWhenMicDisabled() {
+        int micOp = AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO;
+        int nonMicOp = AppOpsManager.OP_CAMERA;
+
+        // Add callbacks for the micOp and nonMicOp, called for the micOp active state change,
+        // verify the micOp is the only active op returned.
+        mController.addCallback(new int[]{micOp, nonMicOp}, mCallback);
+        mTestableLooper.processAllMessages();
+        mController.onOpActiveChanged(
+                AppOpsManager.opToPublicName(micOp), TEST_UID_OTHER, TEST_PACKAGE_NAME, true);
+        mTestableLooper.processAllMessages();
+        verifySingleActiveOps(micOp);
+
+        // Add a non-mic op, and disable the microphone. The camera op should be the only active op
+        // returned.
+        mController.onSensorBlockedChanged(MICROPHONE, true);
+        mController.onOpActiveChanged(AppOpsManager.opToPublicName(nonMicOp), TEST_UID_OTHER,
+                TEST_PACKAGE_NAME, true);
+        mTestableLooper.processAllMessages();
+        verifySingleActiveOps(nonMicOp);
+
+        // Re-enable the microphone, and verify the active op returns.
+        mController.onSensorBlockedChanged(MICROPHONE, false);
+        mTestableLooper.processAllMessages();
+        verifyActiveOps(micOp, nonMicOp);
+    }
+
+    @Test
+    public void testSandboxTriggerMicrophoneFilteredWhenMicDisabled() {
+        int micOp = AppOpsManager.OP_RECEIVE_SANDBOX_TRIGGER_AUDIO;
+        int nonMicOp = AppOpsManager.OP_CAMERA;
+
+        // Add callbacks for the micOp and nonMicOp, called for the micOp active state change,
+        // verify the micOp is the only active op returned.
+        mController.addCallback(new int[]{micOp, nonMicOp}, mCallback);
+        mTestableLooper.processAllMessages();
+        mController.onOpActiveChanged(
+                AppOpsManager.opToPublicName(micOp), TEST_UID_OTHER, TEST_PACKAGE_NAME, true);
+        mTestableLooper.processAllMessages();
+        verifySingleActiveOps(micOp);
+
+        // Add a non-mic op, and disable the microphone. The camera op should be the only active op
+        // returned.
+        mController.onSensorBlockedChanged(MICROPHONE, true);
+        mController.onOpActiveChanged(AppOpsManager.opToPublicName(nonMicOp), TEST_UID_OTHER,
+                TEST_PACKAGE_NAME, true);
+        mTestableLooper.processAllMessages();
+        verifySingleActiveOps(nonMicOp);
+
+        // Re-enable the microphone, and verify the active op returns.
+        mController.onSensorBlockedChanged(MICROPHONE, false);
+        mTestableLooper.processAllMessages();
+        verifyActiveOps(micOp, nonMicOp);
     }
 
     @Test
@@ -673,6 +721,57 @@
         assertEquals(AppOpsManager.OP_PHONE_CALL_CAMERA, list.get(cameraIdx).getCode());
     }
 
+    private void verifyUnPausedSentActive(int micOpCode) {
+        mController.addCallback(new int[]{micOpCode}, mCallback);
+        mTestableLooper.processAllMessages();
+        mController.onOpActiveChanged(AppOpsManager.opToPublicName(micOpCode), TEST_UID,
+                TEST_PACKAGE_NAME, true);
+
+        mTestableLooper.processAllMessages();
+        mRecordingCallback.onRecordingConfigChanged(Collections.emptyList());
+
+        mTestableLooper.processAllMessages();
+
+        verify(mCallback).onActiveStateChanged(micOpCode, TEST_UID, TEST_PACKAGE_NAME, true);
+    }
+
+    private void verifyAudioPausedSentInactive(int micOpCode) {
+        mController.addCallback(new int[]{micOpCode}, mCallback);
+        mTestableLooper.processAllMessages();
+        mController.onOpActiveChanged(AppOpsManager.opToPublicName(micOpCode), TEST_UID_OTHER,
+                TEST_PACKAGE_NAME, true);
+        mTestableLooper.processAllMessages();
+
+        AudioRecordingConfiguration mockARC = mock(AudioRecordingConfiguration.class);
+        when(mockARC.getClientUid()).thenReturn(TEST_UID_OTHER);
+        when(mockARC.isClientSilenced()).thenReturn(true);
+
+        mRecordingCallback.onRecordingConfigChanged(List.of(mockARC));
+        mTestableLooper.processAllMessages();
+
+        InOrder inOrder = inOrder(mCallback);
+        inOrder.verify(mCallback).onActiveStateChanged(
+                micOpCode, TEST_UID_OTHER, TEST_PACKAGE_NAME, true);
+        inOrder.verify(mCallback).onActiveStateChanged(
+                micOpCode, TEST_UID_OTHER, TEST_PACKAGE_NAME, false);
+    }
+
+    private void verifySingleActiveOps(int op) {
+        List<AppOpItem> list = mController.getActiveAppOps();
+        assertEquals(1, list.size());
+        assertEquals(op, list.get(0).getCode());
+        assertFalse(list.get(0).isDisabled());
+    }
+
+    private void verifyActiveOps(int micOp, int nonMicOp) {
+        List<AppOpItem> list = mController.getActiveAppOps();
+        assertEquals(2, list.size());
+        List<Integer> codes = Arrays.asList(list.get(0).getCode(), list.get(1).getCode());
+        assertThat(codes).containsExactly(micOp, nonMicOp);
+        assertFalse(list.get(0).isDisabled());
+        assertFalse(list.get(1).isDisabled());
+    }
+
     private class TestHandler extends AppOpsControllerImpl.H {
         TestHandler(Looper looper) {
             mController.super(looper);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/authentication/data/repository/AuthenticationRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/authentication/data/repository/AuthenticationRepositoryTest.kt
index 0056970..d3a2a73 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/authentication/data/repository/AuthenticationRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/authentication/data/repository/AuthenticationRepositoryTest.kt
@@ -18,23 +18,30 @@
 
 package com.android.systemui.authentication.data.repository
 
+import android.app.admin.DevicePolicyManager
+import android.content.Intent
 import android.content.pm.UserInfo
 import androidx.test.filters.SmallTest
 import com.android.internal.widget.LockPatternUtils
 import com.android.keyguard.KeyguardSecurityModel
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel
+import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.coroutines.collectValues
 import com.android.systemui.scene.SceneTestUtils
 import com.android.systemui.user.data.repository.FakeUserRepository
 import com.android.systemui.util.mockito.whenever
 import com.google.common.truth.Truth.assertThat
+import java.util.function.Function
 import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.test.runCurrent
 import kotlinx.coroutines.test.runTest
 import org.junit.Before
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.junit.runners.JUnit4
+import org.mockito.ArgumentMatchers.anyInt
 import org.mockito.Mock
 import org.mockito.MockitoAnnotations
 
@@ -43,6 +50,7 @@
 class AuthenticationRepositoryTest : SysuiTestCase() {
 
     @Mock private lateinit var lockPatternUtils: LockPatternUtils
+    @Mock private lateinit var getSecurityMode: Function<Int, KeyguardSecurityModel.SecurityMode>
 
     private val testUtils = SceneTestUtils(this)
     private val testScope = testUtils.testScope
@@ -50,24 +58,49 @@
 
     private lateinit var underTest: AuthenticationRepository
 
+    private var currentSecurityMode: KeyguardSecurityModel.SecurityMode =
+        KeyguardSecurityModel.SecurityMode.PIN
+
     @Before
     fun setUp() {
         MockitoAnnotations.initMocks(this)
         userRepository.setUserInfos(USER_INFOS)
         runBlocking { userRepository.setSelectedUserInfo(USER_INFOS[0]) }
+        whenever(getSecurityMode.apply(anyInt())).thenAnswer { currentSecurityMode }
 
         underTest =
             AuthenticationRepositoryImpl(
                 applicationScope = testScope.backgroundScope,
-                getSecurityMode = { KeyguardSecurityModel.SecurityMode.PIN },
+                getSecurityMode = getSecurityMode,
                 backgroundDispatcher = testUtils.testDispatcher,
                 userRepository = userRepository,
                 keyguardRepository = testUtils.keyguardRepository,
                 lockPatternUtils = lockPatternUtils,
+                broadcastDispatcher = fakeBroadcastDispatcher,
             )
     }
 
     @Test
+    fun authenticationMethod() =
+        testScope.runTest {
+            val authMethod by collectLastValue(underTest.authenticationMethod)
+            runCurrent()
+            dispatchBroadcast()
+            assertThat(authMethod).isEqualTo(AuthenticationMethodModel.Pin)
+            assertThat(underTest.getAuthenticationMethod()).isEqualTo(AuthenticationMethodModel.Pin)
+
+            setSecurityModeAndDispatchBroadcast(KeyguardSecurityModel.SecurityMode.Pattern)
+            assertThat(authMethod).isEqualTo(AuthenticationMethodModel.Pattern)
+            assertThat(underTest.getAuthenticationMethod())
+                .isEqualTo(AuthenticationMethodModel.Pattern)
+
+            setSecurityModeAndDispatchBroadcast(KeyguardSecurityModel.SecurityMode.None)
+            assertThat(authMethod).isEqualTo(AuthenticationMethodModel.None)
+            assertThat(underTest.getAuthenticationMethod())
+                .isEqualTo(AuthenticationMethodModel.None)
+        }
+
+    @Test
     fun isAutoConfirmEnabled() =
         testScope.runTest {
             whenever(lockPatternUtils.isAutoPinConfirmEnabled(USER_INFOS[0].id)).thenReturn(true)
@@ -95,6 +128,20 @@
             assertThat(values.last()).isTrue()
         }
 
+    private fun setSecurityModeAndDispatchBroadcast(
+        securityMode: KeyguardSecurityModel.SecurityMode,
+    ) {
+        currentSecurityMode = securityMode
+        dispatchBroadcast()
+    }
+
+    private fun dispatchBroadcast() {
+        fakeBroadcastDispatcher.sendIntentToMatchingReceiversOnly(
+            context,
+            Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED)
+        )
+    }
+
     companion object {
         private val USER_INFOS =
             listOf(
diff --git a/packages/SystemUI/tests/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractorTest.kt
index a86937f..fc7d20a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractorTest.kt
@@ -19,12 +19,16 @@
 import android.app.admin.DevicePolicyManager
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel as DataLayerAuthenticationMethodModel
 import com.android.systemui.authentication.data.repository.AuthenticationRepository
 import com.android.systemui.authentication.data.repository.FakeAuthenticationRepository
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.domain.model.AuthenticationMethodModel as DomainLayerAuthenticationMethodModel
+import com.android.systemui.authentication.shared.model.AuthenticationPatternCoordinate
 import com.android.systemui.authentication.shared.model.AuthenticationThrottlingModel
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.scene.SceneTestUtils
+import com.android.systemui.scene.shared.model.SceneKey
+import com.android.systemui.scene.shared.model.SceneModel
 import com.google.common.truth.Truth.assertThat
 import kotlin.time.Duration.Companion.milliseconds
 import kotlin.time.Duration.Companion.seconds
@@ -44,88 +48,147 @@
     private val utils = SceneTestUtils(this)
     private val testScope = utils.testScope
     private val repository: AuthenticationRepository = utils.authenticationRepository()
+    private val sceneInteractor = utils.sceneInteractor()
     private val underTest =
         utils.authenticationInteractor(
             repository = repository,
+            sceneInteractor = sceneInteractor,
         )
 
     @Test
-    fun getAuthenticationMethod() =
+    fun authenticationMethod() =
         testScope.runTest {
-            assertThat(underTest.getAuthenticationMethod()).isEqualTo(AuthenticationMethodModel.Pin)
+            val authMethod by collectLastValue(underTest.authenticationMethod)
+            runCurrent()
+            assertThat(authMethod).isEqualTo(DomainLayerAuthenticationMethodModel.Pin)
+            assertThat(underTest.getAuthenticationMethod())
+                .isEqualTo(DomainLayerAuthenticationMethodModel.Pin)
 
             utils.authenticationRepository.setAuthenticationMethod(
-                AuthenticationMethodModel.Password
+                DataLayerAuthenticationMethodModel.Password
             )
 
+            assertThat(authMethod).isEqualTo(DomainLayerAuthenticationMethodModel.Password)
             assertThat(underTest.getAuthenticationMethod())
-                .isEqualTo(AuthenticationMethodModel.Password)
+                .isEqualTo(DomainLayerAuthenticationMethodModel.Password)
         }
 
     @Test
-    fun getAuthenticationMethod_noneTreatedAsSwipe_whenLockscreenEnabled() =
+    fun authenticationMethod_noneTreatedAsSwipe_whenLockscreenEnabled() =
         testScope.runTest {
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.None)
-            utils.authenticationRepository.setLockscreenEnabled(true)
+            val authMethod by collectLastValue(underTest.authenticationMethod)
+            runCurrent()
 
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.None)
+                setLockscreenEnabled(true)
+            }
+
+            assertThat(authMethod).isEqualTo(DomainLayerAuthenticationMethodModel.Swipe)
             assertThat(underTest.getAuthenticationMethod())
-                .isEqualTo(AuthenticationMethodModel.Swipe)
+                .isEqualTo(DomainLayerAuthenticationMethodModel.Swipe)
         }
 
     @Test
-    fun getAuthenticationMethod_none_whenLockscreenDisabled() =
+    fun authenticationMethod_none_whenLockscreenDisabled() =
         testScope.runTest {
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.None)
-            utils.authenticationRepository.setLockscreenEnabled(false)
+            val authMethod by collectLastValue(underTest.authenticationMethod)
+            runCurrent()
 
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.None)
+                setLockscreenEnabled(false)
+            }
+
+            assertThat(authMethod).isEqualTo(DomainLayerAuthenticationMethodModel.None)
             assertThat(underTest.getAuthenticationMethod())
-                .isEqualTo(AuthenticationMethodModel.None)
+                .isEqualTo(DomainLayerAuthenticationMethodModel.None)
         }
 
     @Test
     fun isUnlocked_whenAuthMethodIsNoneAndLockscreenDisabled_isTrue() =
         testScope.runTest {
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.None)
-            utils.authenticationRepository.setLockscreenEnabled(false)
-
             val isUnlocked by collectLastValue(underTest.isUnlocked)
-            // Toggle isUnlocked, twice.
-            //
-            // This is done because the underTest.isUnlocked flow doesn't receive values from
-            // just changing the state above; the actual isUnlocked state needs to change to
-            // cause the logic under test to "pick up" the current state again.
-            //
-            // It is done twice to make sure that we don't actually change the isUnlocked
-            // state from what it originally was.
-            utils.authenticationRepository.setUnlocked(
-                !utils.authenticationRepository.isUnlocked.value
-            )
-            runCurrent()
-            utils.authenticationRepository.setUnlocked(
-                !utils.authenticationRepository.isUnlocked.value
-            )
-            runCurrent()
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.None)
+                setLockscreenEnabled(false)
+                // Toggle isUnlocked, twice.
+                //
+                // This is done because the underTest.isUnlocked flow doesn't receive values from
+                // just changing the state above; the actual isUnlocked state needs to change to
+                // cause the logic under test to "pick up" the current state again.
+                //
+                // It is done twice to make sure that we don't actually change the isUnlocked state
+                // from what it originally was.
+                setUnlocked(!utils.authenticationRepository.isUnlocked.value)
+                runCurrent()
+                setUnlocked(!utils.authenticationRepository.isUnlocked.value)
+                runCurrent()
+            }
+
             assertThat(isUnlocked).isTrue()
         }
 
     @Test
-    fun isUnlocked_whenAuthMethodIsNoneAndLockscreenEnabled_isFalse() =
+    fun isUnlocked_whenAuthMethodIsNoneAndLockscreenEnabled_isTrue() =
         testScope.runTest {
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.None)
-            utils.authenticationRepository.setLockscreenEnabled(true)
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.None)
+                setLockscreenEnabled(true)
+            }
 
             val isUnlocked by collectLastValue(underTest.isUnlocked)
-            assertThat(isUnlocked).isFalse()
+            assertThat(isUnlocked).isTrue()
+        }
+
+    @Test
+    fun canSwipeToDismiss_onLockscreenWithSwipe_isTrue() =
+        testScope.runTest {
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.None)
+                setLockscreenEnabled(true)
+            }
+            switchToScene(SceneKey.Lockscreen)
+
+            val canSwipeToDismiss by collectLastValue(underTest.canSwipeToDismiss)
+            assertThat(canSwipeToDismiss).isTrue()
+        }
+
+    @Test
+    fun canSwipeToDismiss_onLockscreenWithPin_isFalse() =
+        testScope.runTest {
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Pin)
+                setLockscreenEnabled(true)
+            }
+            switchToScene(SceneKey.Lockscreen)
+
+            val canSwipeToDismiss by collectLastValue(underTest.canSwipeToDismiss)
+            assertThat(canSwipeToDismiss).isFalse()
+        }
+
+    @Test
+    fun canSwipeToDismiss_afterLockscreenDismissedInSwipeMode_isFalse() =
+        testScope.runTest {
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.None)
+                setLockscreenEnabled(true)
+            }
+            switchToScene(SceneKey.Lockscreen)
+            switchToScene(SceneKey.Gone)
+
+            val canSwipeToDismiss by collectLastValue(underTest.canSwipeToDismiss)
+            assertThat(canSwipeToDismiss).isFalse()
         }
 
     @Test
     fun isAuthenticationRequired_lockedAndSecured_true() =
         testScope.runTest {
-            utils.authenticationRepository.setUnlocked(false)
-            runCurrent()
-            utils.authenticationRepository.setAuthenticationMethod(
-                AuthenticationMethodModel.Password
-            )
+            utils.authenticationRepository.apply {
+                setUnlocked(false)
+                runCurrent()
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Password)
+            }
 
             assertThat(underTest.isAuthenticationRequired()).isTrue()
         }
@@ -133,9 +196,11 @@
     @Test
     fun isAuthenticationRequired_lockedAndNotSecured_false() =
         testScope.runTest {
-            utils.authenticationRepository.setUnlocked(false)
-            runCurrent()
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Swipe)
+            utils.authenticationRepository.apply {
+                setUnlocked(false)
+                runCurrent()
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.None)
+            }
 
             assertThat(underTest.isAuthenticationRequired()).isFalse()
         }
@@ -143,11 +208,11 @@
     @Test
     fun isAuthenticationRequired_unlockedAndSecured_false() =
         testScope.runTest {
-            utils.authenticationRepository.setUnlocked(true)
-            runCurrent()
-            utils.authenticationRepository.setAuthenticationMethod(
-                AuthenticationMethodModel.Password
-            )
+            utils.authenticationRepository.apply {
+                setUnlocked(true)
+                runCurrent()
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Password)
+            }
 
             assertThat(underTest.isAuthenticationRequired()).isFalse()
         }
@@ -155,9 +220,11 @@
     @Test
     fun isAuthenticationRequired_unlockedAndNotSecured_false() =
         testScope.runTest {
-            utils.authenticationRepository.setUnlocked(true)
-            runCurrent()
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Swipe)
+            utils.authenticationRepository.apply {
+                setUnlocked(true)
+                runCurrent()
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.None)
+            }
 
             assertThat(underTest.isAuthenticationRequired()).isFalse()
         }
@@ -166,7 +233,9 @@
     fun authenticate_withCorrectPin_returnsTrue() =
         testScope.runTest {
             val isThrottled by collectLastValue(underTest.isThrottled)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
+            utils.authenticationRepository.setAuthenticationMethod(
+                DataLayerAuthenticationMethodModel.Pin
+            )
             assertThat(underTest.authenticate(FakeAuthenticationRepository.DEFAULT_PIN)).isTrue()
             assertThat(isThrottled).isFalse()
         }
@@ -174,23 +243,30 @@
     @Test
     fun authenticate_withIncorrectPin_returnsFalse() =
         testScope.runTest {
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
+            utils.authenticationRepository.setAuthenticationMethod(
+                DataLayerAuthenticationMethodModel.Pin
+            )
             assertThat(underTest.authenticate(listOf(9, 8, 7, 6, 5, 4))).isFalse()
         }
 
     @Test(expected = IllegalArgumentException::class)
     fun authenticate_withEmptyPin_throwsException() =
         testScope.runTest {
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
+            utils.authenticationRepository.setAuthenticationMethod(
+                DataLayerAuthenticationMethodModel.Pin
+            )
             underTest.authenticate(listOf())
         }
 
     @Test
     fun authenticate_withCorrectMaxLengthPin_returnsTrue() =
         testScope.runTest {
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             val pin = List(16) { 9 }
-            utils.authenticationRepository.overrideCredential(pin)
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Pin)
+                overrideCredential(pin)
+            }
+
             assertThat(underTest.authenticate(pin)).isTrue()
         }
 
@@ -203,7 +279,9 @@
             // If the policy changes, there is work to do in SysUI.
             assertThat(DevicePolicyManager.MAX_PASSWORD_LENGTH).isLessThan(17)
 
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
+            utils.authenticationRepository.setAuthenticationMethod(
+                DataLayerAuthenticationMethodModel.Pin
+            )
             assertThat(underTest.authenticate(List(17) { 9 })).isFalse()
         }
 
@@ -212,7 +290,7 @@
         testScope.runTest {
             val isThrottled by collectLastValue(underTest.isThrottled)
             utils.authenticationRepository.setAuthenticationMethod(
-                AuthenticationMethodModel.Password
+                DataLayerAuthenticationMethodModel.Password
             )
 
             assertThat(underTest.authenticate("password".toList())).isTrue()
@@ -223,7 +301,7 @@
     fun authenticate_withIncorrectPassword_returnsFalse() =
         testScope.runTest {
             utils.authenticationRepository.setAuthenticationMethod(
-                AuthenticationMethodModel.Password
+                DataLayerAuthenticationMethodModel.Password
             )
 
             assertThat(underTest.authenticate("alohomora".toList())).isFalse()
@@ -233,7 +311,7 @@
     fun authenticate_withCorrectPattern_returnsTrue() =
         testScope.runTest {
             utils.authenticationRepository.setAuthenticationMethod(
-                AuthenticationMethodModel.Pattern
+                DataLayerAuthenticationMethodModel.Pattern
             )
 
             assertThat(underTest.authenticate(FakeAuthenticationRepository.PATTERN)).isTrue()
@@ -243,21 +321,21 @@
     fun authenticate_withIncorrectPattern_returnsFalse() =
         testScope.runTest {
             utils.authenticationRepository.setAuthenticationMethod(
-                AuthenticationMethodModel.Pattern
+                DataLayerAuthenticationMethodModel.Pattern
             )
 
             assertThat(
                     underTest.authenticate(
                         listOf(
-                            AuthenticationMethodModel.Pattern.PatternCoordinate(
+                            AuthenticationPatternCoordinate(
                                 x = 2,
                                 y = 0,
                             ),
-                            AuthenticationMethodModel.Pattern.PatternCoordinate(
+                            AuthenticationPatternCoordinate(
                                 x = 2,
                                 y = 1,
                             ),
-                            AuthenticationMethodModel.Pattern.PatternCoordinate(
+                            AuthenticationPatternCoordinate(
                                 x = 2,
                                 y = 2,
                             ),
@@ -271,8 +349,10 @@
     fun tryAutoConfirm_withAutoConfirmPinAndShorterPin_returnsNullAndHasNoEffect() =
         testScope.runTest {
             val isThrottled by collectLastValue(underTest.isThrottled)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            utils.authenticationRepository.setAutoConfirmEnabled(true)
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Pin)
+                setAutoConfirmEnabled(true)
+            }
             assertThat(
                     underTest.authenticate(
                         FakeAuthenticationRepository.DEFAULT_PIN.toMutableList().apply {
@@ -289,8 +369,10 @@
     fun tryAutoConfirm_withAutoConfirmWrongPinCorrectLength_returnsFalseAndDoesNotUnlockDevice() =
         testScope.runTest {
             val isUnlocked by collectLastValue(underTest.isUnlocked)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            utils.authenticationRepository.setAutoConfirmEnabled(true)
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Pin)
+                setAutoConfirmEnabled(true)
+            }
             assertThat(
                     underTest.authenticate(
                         FakeAuthenticationRepository.DEFAULT_PIN.map { it + 1 },
@@ -305,8 +387,10 @@
     fun tryAutoConfirm_withAutoConfirmLongerPin_returnsFalseAndDoesNotUnlockDevice() =
         testScope.runTest {
             val isUnlocked by collectLastValue(underTest.isUnlocked)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            utils.authenticationRepository.setAutoConfirmEnabled(true)
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Pin)
+                setAutoConfirmEnabled(true)
+            }
             assertThat(
                     underTest.authenticate(
                         FakeAuthenticationRepository.DEFAULT_PIN + listOf(7),
@@ -321,8 +405,10 @@
     fun tryAutoConfirm_withAutoConfirmCorrectPin_returnsTrueAndUnlocksDevice() =
         testScope.runTest {
             val isUnlocked by collectLastValue(underTest.isUnlocked)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            utils.authenticationRepository.setAutoConfirmEnabled(true)
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Pin)
+                setAutoConfirmEnabled(true)
+            }
             assertThat(
                     underTest.authenticate(
                         FakeAuthenticationRepository.DEFAULT_PIN,
@@ -337,8 +423,10 @@
     fun tryAutoConfirm_withoutAutoConfirmButCorrectPin_returnsNullAndHasNoEffects() =
         testScope.runTest {
             val isUnlocked by collectLastValue(underTest.isUnlocked)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            utils.authenticationRepository.setAutoConfirmEnabled(false)
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Pin)
+                setAutoConfirmEnabled(false)
+            }
             assertThat(
                     underTest.authenticate(
                         FakeAuthenticationRepository.DEFAULT_PIN,
@@ -354,7 +442,7 @@
         testScope.runTest {
             val isUnlocked by collectLastValue(underTest.isUnlocked)
             utils.authenticationRepository.setAuthenticationMethod(
-                AuthenticationMethodModel.Password
+                DataLayerAuthenticationMethodModel.Password
             )
 
             assertThat(underTest.authenticate("password".toList(), tryAutoConfirm = true)).isNull()
@@ -367,7 +455,9 @@
             val isUnlocked by collectLastValue(underTest.isUnlocked)
             val throttling by collectLastValue(underTest.throttling)
             val isThrottled by collectLastValue(underTest.isThrottled)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
+            utils.authenticationRepository.setAuthenticationMethod(
+                DataLayerAuthenticationMethodModel.Pin
+            )
             underTest.authenticate(FakeAuthenticationRepository.DEFAULT_PIN)
             assertThat(isUnlocked).isTrue()
             assertThat(isThrottled).isFalse()
@@ -456,8 +546,10 @@
     fun hintedPinLength_withoutAutoConfirm_isNull() =
         testScope.runTest {
             val hintedPinLength by collectLastValue(underTest.hintedPinLength)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            utils.authenticationRepository.setAutoConfirmEnabled(false)
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Pin)
+                setAutoConfirmEnabled(false)
+            }
 
             assertThat(hintedPinLength).isNull()
         }
@@ -466,13 +558,15 @@
     fun hintedPinLength_withAutoConfirmPinTooShort_isNull() =
         testScope.runTest {
             val hintedPinLength by collectLastValue(underTest.hintedPinLength)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            utils.authenticationRepository.overrideCredential(
-                buildList {
-                    repeat(utils.authenticationRepository.hintedPinLength - 1) { add(it + 1) }
-                }
-            )
-            utils.authenticationRepository.setAutoConfirmEnabled(true)
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Pin)
+                overrideCredential(
+                    buildList {
+                        repeat(utils.authenticationRepository.hintedPinLength - 1) { add(it + 1) }
+                    }
+                )
+                setAutoConfirmEnabled(true)
+            }
 
             assertThat(hintedPinLength).isNull()
         }
@@ -481,11 +575,15 @@
     fun hintedPinLength_withAutoConfirmPinAtRightLength_isSameLength() =
         testScope.runTest {
             val hintedPinLength by collectLastValue(underTest.hintedPinLength)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            utils.authenticationRepository.setAutoConfirmEnabled(true)
-            utils.authenticationRepository.overrideCredential(
-                buildList { repeat(utils.authenticationRepository.hintedPinLength) { add(it + 1) } }
-            )
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Pin)
+                setAutoConfirmEnabled(true)
+                overrideCredential(
+                    buildList {
+                        repeat(utils.authenticationRepository.hintedPinLength) { add(it + 1) }
+                    }
+                )
+            }
 
             assertThat(hintedPinLength).isEqualTo(utils.authenticationRepository.hintedPinLength)
         }
@@ -494,14 +592,20 @@
     fun hintedPinLength_withAutoConfirmPinTooLong_isNull() =
         testScope.runTest {
             val hintedPinLength by collectLastValue(underTest.hintedPinLength)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            utils.authenticationRepository.overrideCredential(
-                buildList {
-                    repeat(utils.authenticationRepository.hintedPinLength + 1) { add(it + 1) }
-                }
-            )
-            utils.authenticationRepository.setAutoConfirmEnabled(true)
+            utils.authenticationRepository.apply {
+                setAuthenticationMethod(DataLayerAuthenticationMethodModel.Pin)
+                overrideCredential(
+                    buildList {
+                        repeat(utils.authenticationRepository.hintedPinLength + 1) { add(it + 1) }
+                    }
+                )
+                setAutoConfirmEnabled(true)
+            }
 
             assertThat(hintedPinLength).isNull()
         }
+
+    private fun switchToScene(sceneKey: SceneKey) {
+        sceneInteractor.changeScene(SceneModel(sceneKey), "reason")
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewControllerTest.java
index 40b5729..ec8be8e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewControllerTest.java
@@ -35,6 +35,7 @@
 
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
+import com.android.systemui.flags.FakeFeatureFlags;
 import com.android.systemui.settings.UserTracker;
 import com.android.systemui.statusbar.phone.StatusBarLocation;
 import com.android.systemui.statusbar.policy.BatteryController;
@@ -63,6 +64,7 @@
     private ContentResolver mContentResolver;
     @Mock
     private BatteryController mBatteryController;
+    private FakeFeatureFlags mFakeFeatureFlags = new FakeFeatureFlags();
 
     private BatteryMeterViewController mController;
 
@@ -160,6 +162,7 @@
                 mTunerService,
                 mHandler,
                 mContentResolver,
+                mFakeFeatureFlags,
                 mBatteryController
         );
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt
index c84efac..f0f4ca7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt
@@ -131,6 +131,16 @@
     }
 
     @Test
+    fun contentDescription_isIncompatibleCharging_notCharging() {
+        mBatteryMeterView.onBatteryLevelChanged(45, true)
+        mBatteryMeterView.onIsIncompatibleChargingChanged(true)
+
+        assertThat(mBatteryMeterView.contentDescription).isEqualTo(
+                context.getString(R.string.accessibility_battery_level, 45)
+        )
+    }
+
+    @Test
     fun changesFromEstimateToPercent_textAndContentDescriptionChanges() {
         mBatteryMeterView.onBatteryLevelChanged(15, false)
         mBatteryMeterView.setPercentShowMode(BatteryMeterView.MODE_ESTIMATE)
@@ -231,14 +241,33 @@
         assertThat(drawable.displayShield).isFalse()
     }
 
+    @Test
+    fun isIncompatibleChargingChanged_true_drawableGetsChargingFalse() {
+        mBatteryMeterView.onBatteryLevelChanged(45, true)
+        val drawable = getBatteryDrawable()
+
+        mBatteryMeterView.onIsIncompatibleChargingChanged(true)
+
+        assertThat(drawable.getCharging()).isFalse()
+    }
+
+    @Test
+    fun isIncompatibleChargingChanged_false_drawableGetsChargingTrue() {
+        mBatteryMeterView.onBatteryLevelChanged(45, true)
+        val drawable = getBatteryDrawable()
+
+        mBatteryMeterView.onIsIncompatibleChargingChanged(false)
+
+        assertThat(drawable.getCharging()).isTrue()
+    }
+
     private fun getBatteryDrawable(): AccessorizedBatteryDrawable {
         return (mBatteryMeterView.getChildAt(0) as ImageView)
                 .drawable as AccessorizedBatteryDrawable
     }
 
     private class Fetcher : BatteryEstimateFetcher {
-        override fun fetchBatteryTimeRemainingEstimate(
-                completion: EstimateFetchCompletion) {
+        override fun fetchBatteryTimeRemainingEstimate(completion: EstimateFetchCompletion) {
             completion.onBatteryRemainingEstimateRetrieved(ESTIMATE)
         }
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.kt
index e3e6130..4e52e64 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.kt
@@ -139,6 +139,7 @@
     @Before
     fun setup() {
         featureFlags.set(Flags.BIOMETRIC_BP_STRONG, useNewBiometricPrompt)
+        featureFlags.set(Flags.ONE_WAY_HAPTICS_API_MIGRATION, false)
     }
 
     @After
@@ -151,7 +152,10 @@
     @Test
     fun testNotifiesAnimatedIn() {
         initializeFingerprintContainer()
-        verify(callback).onDialogAnimatedIn(authContainer?.requestId ?: 0L, true /* startFingerprintNow */)
+        verify(callback).onDialogAnimatedIn(
+            authContainer?.requestId ?: 0L,
+            true /* startFingerprintNow */
+        )
     }
 
     @Test
@@ -196,7 +200,10 @@
         waitForIdleSync()
 
         // attaching the view resets the state and allows this to happen again
-        verify(callback).onDialogAnimatedIn(authContainer?.requestId ?: 0L, true /* startFingerprintNow */)
+        verify(callback).onDialogAnimatedIn(
+            authContainer?.requestId ?: 0L,
+            true /* startFingerprintNow */
+        )
     }
 
     @Test
@@ -211,7 +218,10 @@
 
         // the first time is triggered by initializeFingerprintContainer()
         // the second time was triggered by dismissWithoutCallback()
-        verify(callback, times(2)).onDialogAnimatedIn(authContainer?.requestId ?: 0L, true /* startFingerprintNow */)
+        verify(callback, times(2)).onDialogAnimatedIn(
+            authContainer?.requestId ?: 0L,
+            true /* startFingerprintNow */
+        )
     }
 
     @Test
@@ -517,10 +527,11 @@
         { authBiometricFingerprintViewModel },
         { promptSelectorInteractor },
         { bpCredentialInteractor },
-        PromptViewModel(promptSelectorInteractor, vibrator),
+        PromptViewModel(promptSelectorInteractor, vibrator, featureFlags),
         { credentialViewModel },
         Handler(TestableLooper.get(this).looper),
-        fakeExecutor
+        fakeExecutor,
+        vibrator
     ) {
         override fun postOnAnimation(runnable: Runnable) {
             runnable.run()
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 3d4171f..48e5131 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
@@ -197,6 +197,8 @@
     private ArgumentCaptor<String> mMessageCaptor;
     @Mock
     private Resources mResources;
+    @Mock
+    private VibratorHelper mVibratorHelper;
 
     private TestableContext mContextSpy;
     private Execution mExecution;
@@ -515,7 +517,7 @@
 
         assertThat(mModalityCaptor.getValue().intValue()).isEqualTo(modality);
         assertThat(mMessageCaptor.getValue()).isEqualTo(
-                mContext.getString(R.string.biometric_face_not_recognized));
+                mContext.getString(R.string.fingerprint_dialog_use_fingerprint_instead));
     }
 
     @Test
@@ -1097,7 +1099,7 @@
                     () -> mBiometricPromptCredentialInteractor, () -> mPromptSelectionInteractor,
                     () -> mCredentialViewModel, () -> mPromptViewModel,
                     mInteractionJankMonitor, mHandler,
-                    mBackgroundExecutor, mUdfpsUtils);
+                    mBackgroundExecutor, mUdfpsUtils, mVibratorHelper);
         }
 
         @Override
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/BiometricNotificationDialogFactoryTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/BiometricNotificationDialogFactoryTest.java
index 362d26b0..cf4e2c319 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/BiometricNotificationDialogFactoryTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/BiometricNotificationDialogFactoryTest.java
@@ -18,6 +18,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.junit.Assume.assumeTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.Mockito.never;
@@ -28,6 +29,7 @@
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.hardware.biometrics.BiometricSourceType;
 import android.hardware.face.FaceManager;
 import android.hardware.fingerprint.FingerprintManager;
@@ -86,6 +88,9 @@
 
     @Test
     public void testFingerprintReEnrollDialog_onRemovalSucceeded() {
+        assumeTrue(getContext().getPackageManager()
+                .hasSystemFeature(PackageManager.FEATURE_FINGERPRINT));
+
         mDialogFactory.createReenrollDialog(mContextSpy, mDialog,
                 BiometricSourceType.FINGERPRINT);
 
@@ -109,6 +114,9 @@
 
     @Test
     public void testFingerprintReEnrollDialog_onRemovalError() {
+        assumeTrue(getContext().getPackageManager()
+                .hasSystemFeature(PackageManager.FEATURE_FINGERPRINT));
+
         mDialogFactory.createReenrollDialog(mContextSpy, mDialog,
                 BiometricSourceType.FINGERPRINT);
 
@@ -130,6 +138,9 @@
 
     @Test
     public void testFaceReEnrollDialog_onRemovalSucceeded() {
+        assumeTrue(getContext().getPackageManager()
+                .hasSystemFeature(PackageManager.FEATURE_FACE));
+
         mDialogFactory.createReenrollDialog(mContextSpy, mDialog,
                 BiometricSourceType.FACE);
 
@@ -153,6 +164,9 @@
 
     @Test
     public void testFaceReEnrollDialog_onRemovalError() {
+        assumeTrue(getContext().getPackageManager()
+                .hasSystemFeature(PackageManager.FEATURE_FACE));
+
         mDialogFactory.createReenrollDialog(mContextSpy, mDialog,
                 BiometricSourceType.FACE);
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/SideFpsControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/SideFpsControllerTest.kt
index 2b08c66..994db46 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/SideFpsControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/SideFpsControllerTest.kt
@@ -164,7 +164,7 @@
         context.addMockSystemService(WindowManager::class.java, windowManager)
 
         whenEver(layoutInflater.inflate(R.layout.sidefps_view, null, false)).thenReturn(sideFpsView)
-        whenEver(sideFpsView.findViewById<LottieAnimationView>(eq(R.id.sidefps_animation)))
+        whenEver(sideFpsView.requireViewById<LottieAnimationView>(eq(R.id.sidefps_animation)))
             .thenReturn(mock(LottieAnimationView::class.java))
         with(mock(ViewPropertyAnimator::class.java)) {
             whenEver(sideFpsView.animate()).thenReturn(this)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
index 40b1f20..4d19543 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
@@ -19,6 +19,7 @@
 import android.hardware.biometrics.PromptInfo
 import android.hardware.face.FaceSensorPropertiesInternal
 import android.hardware.fingerprint.FingerprintSensorPropertiesInternal
+import android.view.HapticFeedbackConstants
 import androidx.test.filters.SmallTest
 import com.android.internal.widget.LockPatternUtils
 import com.android.systemui.SysuiTestCase
@@ -33,6 +34,8 @@
 import com.android.systemui.biometrics.shared.model.BiometricModality
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.coroutines.collectValues
+import com.android.systemui.flags.FakeFeatureFlags
+import com.android.systemui.flags.Flags.ONE_WAY_HAPTICS_API_MIGRATION
 import com.android.systemui.statusbar.VibratorHelper
 import com.android.systemui.util.mockito.any
 import com.google.common.truth.Truth.assertThat
@@ -71,13 +74,15 @@
 
     private lateinit var selector: PromptSelectorInteractor
     private lateinit var viewModel: PromptViewModel
+    private val featureFlags = FakeFeatureFlags()
 
     @Before
     fun setup() {
         selector = PromptSelectorInteractorImpl(promptRepository, lockPatternUtils)
         selector.resetPrompt()
 
-        viewModel = PromptViewModel(selector, vibrator)
+        viewModel = PromptViewModel(selector, vibrator, featureFlags)
+        featureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, false)
     }
 
     @Test
@@ -149,6 +154,29 @@
             verify(vibrator, never()).vibrateAuthError(any())
         }
 
+    @Test
+    fun playSuccessHaptic_onwayHapticsEnabled_SetsConfirmConstant() = runGenericTest {
+        featureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, true)
+        val expectConfirmation = testCase.expectConfirmation(atLeastOneFailure = false)
+        viewModel.showAuthenticated(testCase.authenticatedModality, 1_000L)
+
+        if (expectConfirmation) {
+            viewModel.confirmAuthenticated()
+        }
+
+        val currentConstant by collectLastValue(viewModel.hapticsToPlay)
+        assertThat(currentConstant).isEqualTo(HapticFeedbackConstants.CONFIRM)
+    }
+
+    @Test
+    fun playErrorHaptic_onwayHapticsEnabled_SetsRejectConstant() = runGenericTest {
+        featureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, true)
+        viewModel.showTemporaryError("test", "messageAfterError", false)
+
+        val currentConstant by collectLastValue(viewModel.hapticsToPlay)
+        assertThat(currentConstant).isEqualTo(HapticFeedbackConstants.REJECT)
+    }
+
     private suspend fun TestScope.showAuthenticated(
         authenticatedModality: BiometricModality,
         expectConfirmation: Boolean,
@@ -499,6 +527,7 @@
         val messageVisible by collectLastValue(viewModel.isIndicatorMessageVisible)
         val size by collectLastValue(viewModel.size)
         val legacyState by collectLastValue(viewModel.legacyState)
+        val confirmationRequired by collectLastValue(viewModel.isConfirmationRequired)
 
         if (testCase.isCoex && testCase.authenticatedByFingerprint) {
             viewModel.ensureFingerprintHasStarted(isDelayed = true)
@@ -507,7 +536,11 @@
         viewModel.showHelp(helpMessage)
 
         assertThat(size).isEqualTo(PromptSize.MEDIUM)
-        assertThat(legacyState).isEqualTo(AuthBiometricView.STATE_PENDING_CONFIRMATION)
+        if (confirmationRequired == true) {
+            assertThat(legacyState).isEqualTo(AuthBiometricView.STATE_PENDING_CONFIRMATION)
+        } else {
+            assertThat(legacyState).isEqualTo(AuthBiometricView.STATE_AUTHENTICATED)
+        }
         assertThat(message).isEqualTo(PromptMessage.Help(helpMessage))
         assertThat(messageVisible).isTrue()
         assertThat(authenticating).isFalse()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bouncer/data/factory/BouncerMessageFactoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/bouncer/data/factory/BouncerMessageFactoryTest.kt
index efae3fe..8eb274a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bouncer/data/factory/BouncerMessageFactoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/bouncer/data/factory/BouncerMessageFactoryTest.kt
@@ -24,13 +24,12 @@
 import com.android.keyguard.KeyguardSecurityModel.SecurityMode.Pattern
 import com.android.keyguard.KeyguardSecurityView.PROMPT_REASON_DEFAULT
 import com.android.keyguard.KeyguardSecurityView.PROMPT_REASON_INCORRECT_PRIMARY_AUTH_INPUT
-import com.android.keyguard.KeyguardUpdateMonitor
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.bouncer.shared.model.BouncerMessageModel
+import com.android.systemui.keyguard.data.repository.FakeBiometricSettingsRepository
 import com.android.systemui.util.mockito.whenever
 import com.google.common.truth.StringSubject
 import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.test.TestScope
 import kotlinx.coroutines.test.runTest
 import org.junit.Before
@@ -39,13 +38,12 @@
 import org.mockito.Mock
 import org.mockito.MockitoAnnotations
 
-@OptIn(ExperimentalCoroutinesApi::class)
 @SmallTest
 @RunWith(AndroidJUnit4::class)
 class BouncerMessageFactoryTest : SysuiTestCase() {
     private lateinit var underTest: BouncerMessageFactory
 
-    @Mock private lateinit var updateMonitor: KeyguardUpdateMonitor
+    @Mock private lateinit var biometricSettingsRepository: FakeBiometricSettingsRepository
 
     @Mock private lateinit var securityModel: KeyguardSecurityModel
 
@@ -55,7 +53,8 @@
     fun setUp() {
         MockitoAnnotations.initMocks(this)
         testScope = TestScope()
-        underTest = BouncerMessageFactory(updateMonitor, securityModel)
+        biometricSettingsRepository = FakeBiometricSettingsRepository()
+        underTest = BouncerMessageFactory(biometricSettingsRepository, securityModel)
     }
 
     @Test
@@ -167,7 +166,7 @@
         secondaryMessageOverride: String? = null,
     ): BouncerMessageModel? {
         whenever(securityModel.getSecurityMode(0)).thenReturn(mode)
-        whenever(updateMonitor.isUnlockingWithFingerprintAllowed).thenReturn(fpAuthAllowed)
+        biometricSettingsRepository.setIsFingerprintAuthCurrentlyAllowed(fpAuthAllowed)
 
         return underTest.createFromPromptReason(
             reason,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bouncer/data/repo/BouncerMessageRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/bouncer/data/repo/BouncerMessageRepositoryTest.kt
index 2be7d8a..562a8ef 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bouncer/data/repo/BouncerMessageRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/bouncer/data/repo/BouncerMessageRepositoryTest.kt
@@ -101,14 +101,15 @@
         fingerprintRepository = FakeDeviceEntryFingerprintAuthRepository()
         testScope = TestScope()
 
-        whenever(updateMonitor.isUnlockingWithFingerprintAllowed).thenReturn(false)
+        biometricSettingsRepository.setIsFingerprintAuthCurrentlyAllowed(false)
         whenever(securityModel.getSecurityMode(PRIMARY_USER_ID)).thenReturn(PIN)
         underTest =
             BouncerMessageRepositoryImpl(
                 trustRepository = trustRepository,
                 biometricSettingsRepository = biometricSettingsRepository,
                 updateMonitor = updateMonitor,
-                bouncerMessageFactory = BouncerMessageFactory(updateMonitor, securityModel),
+                bouncerMessageFactory =
+                    BouncerMessageFactory(biometricSettingsRepository, securityModel),
                 userRepository = userRepository,
                 fingerprintAuthRepository = fingerprintRepository,
                 systemPropertiesHelper = systemPropertiesHelper
@@ -222,8 +223,7 @@
             whenever(systemPropertiesHelper.get("sys.boot.reason.last"))
                 .thenReturn("reboot,mainline_update")
             userRepository.setSelectedUserInfo(PRIMARY_USER)
-            biometricSettingsRepository.setFaceEnrolled(true)
-            biometricSettingsRepository.setIsFaceAuthEnabled(true)
+            biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(true)
 
             verifyMessagesForAuthFlag(
                 STRONG_AUTH_REQUIRED_AFTER_BOOT to
@@ -236,8 +236,8 @@
         testScope.runTest {
             userRepository.setSelectedUserInfo(PRIMARY_USER)
             trustRepository.setCurrentUserTrustManaged(false)
-            biometricSettingsRepository.setFaceEnrolled(false)
-            biometricSettingsRepository.setFingerprintEnrolled(false)
+            biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(false)
+            biometricSettingsRepository.setIsFingerprintAuthEnrolledAndEnabled(false)
 
             verifyMessagesForAuthFlag(
                 STRONG_AUTH_NOT_REQUIRED to null,
@@ -258,8 +258,8 @@
     fun authFlagsChanges_withTrustManaged_providesDifferentMessages() =
         testScope.runTest {
             userRepository.setSelectedUserInfo(PRIMARY_USER)
-            biometricSettingsRepository.setFaceEnrolled(false)
-            biometricSettingsRepository.setFingerprintEnrolled(false)
+            biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(false)
+            biometricSettingsRepository.setIsFingerprintAuthEnrolledAndEnabled(false)
 
             trustRepository.setCurrentUserTrustManaged(true)
 
@@ -290,10 +290,9 @@
         testScope.runTest {
             userRepository.setSelectedUserInfo(PRIMARY_USER)
             trustRepository.setCurrentUserTrustManaged(false)
-            biometricSettingsRepository.setFingerprintEnrolled(false)
+            biometricSettingsRepository.setIsFingerprintAuthEnrolledAndEnabled(false)
 
-            biometricSettingsRepository.setIsFaceAuthEnabled(true)
-            biometricSettingsRepository.setFaceEnrolled(true)
+            biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(true)
 
             verifyMessagesForAuthFlag(
                 STRONG_AUTH_NOT_REQUIRED to null,
@@ -320,11 +319,9 @@
         testScope.runTest {
             userRepository.setSelectedUserInfo(PRIMARY_USER)
             trustRepository.setCurrentUserTrustManaged(false)
-            biometricSettingsRepository.setIsFaceAuthEnabled(false)
-            biometricSettingsRepository.setFaceEnrolled(false)
+            biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(false)
 
-            biometricSettingsRepository.setFingerprintEnrolled(true)
-            biometricSettingsRepository.setFingerprintEnabledByDevicePolicy(true)
+            biometricSettingsRepository.setIsFingerprintAuthEnrolledAndEnabled(true)
 
             verifyMessagesForAuthFlag(
                 STRONG_AUTH_NOT_REQUIRED to null,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/AlternateBouncerInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/AlternateBouncerInteractorTest.kt
index 186df02..0d17270 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/AlternateBouncerInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/AlternateBouncerInteractorTest.kt
@@ -94,9 +94,9 @@
     }
 
     @Test
-    fun canShowAlternateBouncerForFingerprint_noFingerprintsEnrolled() {
+    fun canShowAlternateBouncerForFingerprint_ifFingerprintIsNotUsuallyAllowed() {
         givenCanShowAlternateBouncer()
-        biometricSettingsRepository.setFingerprintEnrolled(false)
+        biometricSettingsRepository.setIsFingerprintAuthEnrolledAndEnabled(false)
 
         assertFalse(underTest.canShowAlternateBouncerForFingerprint())
     }
@@ -104,15 +104,7 @@
     @Test
     fun canShowAlternateBouncerForFingerprint_strongBiometricNotAllowed() {
         givenCanShowAlternateBouncer()
-        biometricSettingsRepository.setStrongBiometricAllowed(false)
-
-        assertFalse(underTest.canShowAlternateBouncerForFingerprint())
-    }
-
-    @Test
-    fun canShowAlternateBouncerForFingerprint_devicePolicyDoesNotAllowFingerprint() {
-        givenCanShowAlternateBouncer()
-        biometricSettingsRepository.setFingerprintEnabledByDevicePolicy(false)
+        biometricSettingsRepository.setIsFingerprintAuthCurrentlyAllowed(false)
 
         assertFalse(underTest.canShowAlternateBouncerForFingerprint())
     }
@@ -165,16 +157,37 @@
         assertFalse(bouncerRepository.alternateBouncerVisible.value)
     }
 
+    @Test
+    fun alternateBouncerUiAvailable_fromMultipleSources() {
+        assertFalse(bouncerRepository.alternateBouncerUIAvailable.value)
+
+        // GIVEN there are two different sources indicating the alternate bouncer is available
+        underTest.setAlternateBouncerUIAvailable(true, "source1")
+        underTest.setAlternateBouncerUIAvailable(true, "source2")
+        assertTrue(bouncerRepository.alternateBouncerUIAvailable.value)
+
+        // WHEN one of the sources no longer says the UI is available
+        underTest.setAlternateBouncerUIAvailable(false, "source1")
+
+        // THEN alternate bouncer UI is still available (from the other source)
+        assertTrue(bouncerRepository.alternateBouncerUIAvailable.value)
+
+        // WHEN all sources say the UI is not available
+        underTest.setAlternateBouncerUIAvailable(false, "source2")
+
+        // THEN alternate boucer UI is not available
+        assertFalse(bouncerRepository.alternateBouncerUIAvailable.value)
+    }
+
     private fun givenCanShowAlternateBouncer() {
         bouncerRepository.setAlternateBouncerUIAvailable(true)
-        biometricSettingsRepository.setFingerprintEnrolled(true)
-        biometricSettingsRepository.setStrongBiometricAllowed(true)
-        biometricSettingsRepository.setFingerprintEnabledByDevicePolicy(true)
+        biometricSettingsRepository.setIsFingerprintAuthEnrolledAndEnabled(true)
+        biometricSettingsRepository.setIsFingerprintAuthCurrentlyAllowed(true)
         whenever(keyguardUpdateMonitor.isFingerprintLockedOut).thenReturn(false)
         whenever(keyguardStateController.isUnlocked).thenReturn(false)
     }
 
     private fun givenCannotShowAlternateBouncer() {
-        biometricSettingsRepository.setFingerprintEnrolled(false)
+        biometricSettingsRepository.setIsFingerprintAuthEnrolledAndEnabled(false)
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/BouncerInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/BouncerInteractorTest.kt
index 14fc931..86e0c75 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/BouncerInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/BouncerInteractorTest.kt
@@ -19,8 +19,9 @@
 import androidx.test.filters.SmallTest
 import com.android.systemui.R
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel
 import com.android.systemui.authentication.data.repository.FakeAuthenticationRepository
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.shared.model.AuthenticationPatternCoordinate
 import com.android.systemui.authentication.shared.model.AuthenticationThrottlingModel
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.scene.SceneTestUtils
@@ -69,10 +70,11 @@
     @Test
     fun pinAuthMethod() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(underTest.message)
 
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
+            runCurrent()
             utils.authenticationRepository.setUnlocked(false)
             underTest.showOrUnlockDevice()
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
@@ -100,10 +102,11 @@
     @Test
     fun pinAuthMethod_tryAutoConfirm_withAutoConfirmPin() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(underTest.message)
 
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
+            runCurrent()
             utils.authenticationRepository.setAutoConfirmEnabled(true)
             utils.authenticationRepository.setUnlocked(false)
             underTest.showOrUnlockDevice()
@@ -136,10 +139,11 @@
     @Test
     fun pinAuthMethod_tryAutoConfirm_withoutAutoConfirmPin() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(underTest.message)
 
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
+            runCurrent()
             utils.authenticationRepository.setUnlocked(false)
             underTest.showOrUnlockDevice()
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
@@ -165,11 +169,12 @@
     @Test
     fun passwordAuthMethod() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(underTest.message)
             utils.authenticationRepository.setAuthenticationMethod(
                 AuthenticationMethodModel.Password
             )
+            runCurrent()
             utils.authenticationRepository.setUnlocked(false)
             underTest.showOrUnlockDevice()
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
@@ -197,11 +202,12 @@
     @Test
     fun patternAuthMethod() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(underTest.message)
             utils.authenticationRepository.setAuthenticationMethod(
                 AuthenticationMethodModel.Pattern
             )
+            runCurrent()
             utils.authenticationRepository.setUnlocked(false)
             underTest.showOrUnlockDevice()
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
@@ -214,11 +220,7 @@
             assertThat(message).isEqualTo(MESSAGE_ENTER_YOUR_PATTERN)
 
             // Wrong input.
-            assertThat(
-                    underTest.authenticate(
-                        listOf(AuthenticationMethodModel.Pattern.PatternCoordinate(1, 2))
-                    )
-                )
+            assertThat(underTest.authenticate(listOf(AuthenticationPatternCoordinate(1, 2))))
                 .isFalse()
             assertThat(message).isEqualTo(MESSAGE_WRONG_PATTERN)
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
@@ -234,7 +236,7 @@
     @Test
     fun showOrUnlockDevice_notLocked_switchesToGoneScene() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(true)
             runCurrent()
@@ -247,8 +249,9 @@
     @Test
     fun showOrUnlockDevice_authMethodNotSecure_switchesToGoneScene() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Swipe)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
+            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.None)
+            utils.authenticationRepository.setLockscreenEnabled(true)
             utils.authenticationRepository.setUnlocked(false)
 
             underTest.showOrUnlockDevice()
@@ -259,11 +262,12 @@
     @Test
     fun showOrUnlockDevice_customMessageShown() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(underTest.message)
             utils.authenticationRepository.setAuthenticationMethod(
                 AuthenticationMethodModel.Password
             )
+            runCurrent()
             utils.authenticationRepository.setUnlocked(false)
 
             val customMessage = "Hello there!"
@@ -279,7 +283,7 @@
             val isThrottled by collectLastValue(underTest.isThrottled)
             val throttling by collectLastValue(underTest.throttling)
             val message by collectLastValue(underTest.message)
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             runCurrent()
             underTest.showOrUnlockDevice()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/BouncerMessageInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/BouncerMessageInteractorTest.kt
index 3ca94aa..4089abe 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/BouncerMessageInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/bouncer/domain/interactor/BouncerMessageInteractorTest.kt
@@ -22,9 +22,8 @@
 import androidx.test.filters.SmallTest
 import com.android.keyguard.KeyguardSecurityModel
 import com.android.keyguard.KeyguardSecurityModel.SecurityMode.PIN
-import com.android.keyguard.KeyguardUpdateMonitor
-import com.android.systemui.R.string.keyguard_enter_pin
 import com.android.systemui.R.string.kg_too_many_failed_attempts_countdown
+import com.android.systemui.R.string.kg_unlock_with_pin_or_fp
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.bouncer.data.factory.BouncerMessageFactory
 import com.android.systemui.bouncer.data.repository.FakeBouncerMessageRepository
@@ -34,11 +33,11 @@
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.flags.FakeFeatureFlags
 import com.android.systemui.flags.Flags
+import com.android.systemui.keyguard.data.repository.FakeBiometricSettingsRepository
 import com.android.systemui.user.data.repository.FakeUserRepository
 import com.android.systemui.util.mockito.KotlinArgumentCaptor
 import com.android.systemui.util.mockito.whenever
 import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.test.TestScope
 import kotlinx.coroutines.test.runTest
 import org.junit.Before
@@ -49,14 +48,13 @@
 import org.mockito.Mockito.verify
 import org.mockito.MockitoAnnotations
 
-@OptIn(ExperimentalCoroutinesApi::class)
 @SmallTest
 @TestableLooper.RunWithLooper(setAsMainLooper = true)
 @RunWith(AndroidJUnit4::class)
 class BouncerMessageInteractorTest : SysuiTestCase() {
 
     @Mock private lateinit var securityModel: KeyguardSecurityModel
-    @Mock private lateinit var updateMonitor: KeyguardUpdateMonitor
+    @Mock private lateinit var biometricSettingsRepository: FakeBiometricSettingsRepository
     @Mock private lateinit var countDownTimerUtil: CountDownTimerUtil
     private lateinit var countDownTimerCallback: KotlinArgumentCaptor<CountDownTimerCallback>
     private lateinit var underTest: BouncerMessageInteractor
@@ -73,10 +71,11 @@
         userRepository.setUserInfos(listOf(PRIMARY_USER))
         testScope = TestScope()
         countDownTimerCallback = KotlinArgumentCaptor(CountDownTimerCallback::class.java)
+        biometricSettingsRepository = FakeBiometricSettingsRepository()
 
         allowTestableLooperAsMainThread()
         whenever(securityModel.getSecurityMode(PRIMARY_USER_ID)).thenReturn(PIN)
-        whenever(updateMonitor.isUnlockingWithFingerprintAllowed).thenReturn(false)
+        biometricSettingsRepository.setIsFingerprintAuthCurrentlyAllowed(true)
     }
 
     suspend fun TestScope.init() {
@@ -86,7 +85,7 @@
         underTest =
             BouncerMessageInteractor(
                 repository = repository,
-                factory = BouncerMessageFactory(updateMonitor, securityModel),
+                factory = BouncerMessageFactory(biometricSettingsRepository, securityModel),
                 userRepository = userRepository,
                 countDownTimerUtil = countDownTimerUtil,
                 featureFlags = featureFlags
@@ -151,7 +150,8 @@
             underTest.setCustomMessage("not empty")
 
             val customMessage = repository.customMessage
-            assertThat(customMessage.value!!.message!!.messageResId).isEqualTo(keyguard_enter_pin)
+            assertThat(customMessage.value!!.message!!.messageResId)
+                .isEqualTo(kg_unlock_with_pin_or_fp)
             assertThat(customMessage.value!!.secondaryMessage!!.message).isEqualTo("not empty")
 
             underTest.setCustomMessage(null)
@@ -168,7 +168,7 @@
             val faceAcquisitionMessage = repository.faceAcquisitionMessage
 
             assertThat(faceAcquisitionMessage.value!!.message!!.messageResId)
-                .isEqualTo(keyguard_enter_pin)
+                .isEqualTo(kg_unlock_with_pin_or_fp)
             assertThat(faceAcquisitionMessage.value!!.secondaryMessage!!.message)
                 .isEqualTo("not empty")
 
@@ -186,7 +186,7 @@
             val fingerprintAcquisitionMessage = repository.fingerprintAcquisitionMessage
 
             assertThat(fingerprintAcquisitionMessage.value!!.message!!.messageResId)
-                .isEqualTo(keyguard_enter_pin)
+                .isEqualTo(kg_unlock_with_pin_or_fp)
             assertThat(fingerprintAcquisitionMessage.value!!.secondaryMessage!!.message)
                 .isEqualTo("not empty")
 
@@ -275,7 +275,8 @@
             repository.setBiometricLockedOutMessage(null)
 
             // sets the default message if everything else is null
-            assertThat(bouncerMessage()!!.message!!.messageResId).isEqualTo(keyguard_enter_pin)
+            assertThat(bouncerMessage()!!.message!!.messageResId)
+                .isEqualTo(kg_unlock_with_pin_or_fp)
         }
 
     private fun message(value: String): BouncerMessageModel {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/AuthMethodBouncerViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/AuthMethodBouncerViewModelTest.kt
index 2cc9493..7af8a04 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/AuthMethodBouncerViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/AuthMethodBouncerViewModelTest.kt
@@ -18,19 +18,17 @@
 
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel
 import com.android.systemui.authentication.data.repository.FakeAuthenticationRepository
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.scene.SceneTestUtils
 import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.test.runTest
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.junit.runners.JUnit4
 
-@OptIn(ExperimentalCoroutinesApi::class)
 @SmallTest
 @RunWith(JUnit4::class)
 class AuthMethodBouncerViewModelTest : SysuiTestCase() {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/BouncerViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/BouncerViewModelTest.kt
index 0df0a17..2c96bcc 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/BouncerViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/BouncerViewModelTest.kt
@@ -18,8 +18,9 @@
 
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel as DataLayerAuthenticationMethodModel
 import com.android.systemui.authentication.data.repository.FakeAuthenticationRepository
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.domain.model.AuthenticationMethodModel as DomainLayerAuthenticationMethodModel
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.scene.SceneTestUtils
 import com.google.common.truth.Truth.assertThat
@@ -55,6 +56,7 @@
     private val underTest =
         utils.bouncerViewModel(
             bouncerInteractor = bouncerInteractor,
+            authenticationInteractor = authenticationInteractor,
         )
 
     @Test
@@ -86,7 +88,8 @@
     @Test
     fun authMethod_reusesInstances() =
         testScope.runTest {
-            val seen = mutableMapOf<AuthenticationMethodModel, AuthMethodBouncerViewModel>()
+            val seen =
+                mutableMapOf<DomainLayerAuthenticationMethodModel, AuthMethodBouncerViewModel>()
             val authMethodViewModel: AuthMethodBouncerViewModel? by
                 collectLastValue(underTest.authMethod)
             // First pass, populate our "seen" map:
@@ -105,7 +108,7 @@
     @Test
     fun authMethodsToTest_returnsCompleteSampleOfAllAuthMethodTypes() {
         assertThat(authMethodsToTest().map { it::class }.toSet())
-            .isEqualTo(AuthenticationMethodModel::class.sealedSubclasses.toSet())
+            .isEqualTo(DomainLayerAuthenticationMethodModel::class.sealedSubclasses.toSet())
     }
 
     @Test
@@ -113,7 +116,9 @@
         testScope.runTest {
             val message by collectLastValue(underTest.message)
             val throttling by collectLastValue(bouncerInteractor.throttling)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
+            utils.authenticationRepository.setAuthenticationMethod(
+                DataLayerAuthenticationMethodModel.Pin
+            )
             assertThat(message?.isUpdateAnimated).isTrue()
 
             repeat(FakeAuthenticationRepository.MAX_FAILED_AUTH_TRIES_BEFORE_THROTTLING) {
@@ -136,7 +141,9 @@
                     }
                 )
             val throttling by collectLastValue(bouncerInteractor.throttling)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
+            utils.authenticationRepository.setAuthenticationMethod(
+                DataLayerAuthenticationMethodModel.Pin
+            )
             assertThat(isInputEnabled).isTrue()
 
             repeat(FakeAuthenticationRepository.MAX_FAILED_AUTH_TRIES_BEFORE_THROTTLING) {
@@ -153,7 +160,9 @@
     fun throttlingDialogMessage() =
         testScope.runTest {
             val throttlingDialogMessage by collectLastValue(underTest.throttlingDialogMessage)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
+            utils.authenticationRepository.setAuthenticationMethod(
+                DataLayerAuthenticationMethodModel.Pin
+            )
 
             repeat(FakeAuthenticationRepository.MAX_FAILED_AUTH_TRIES_BEFORE_THROTTLING) {
                 // Wrong PIN.
@@ -166,13 +175,32 @@
             assertThat(throttlingDialogMessage).isNull()
         }
 
-    private fun authMethodsToTest(): List<AuthenticationMethodModel> {
+    private fun authMethodsToTest(): List<DomainLayerAuthenticationMethodModel> {
         return listOf(
-            AuthenticationMethodModel.None,
-            AuthenticationMethodModel.Swipe,
-            AuthenticationMethodModel.Pin,
-            AuthenticationMethodModel.Password,
-            AuthenticationMethodModel.Pattern,
+            DomainLayerAuthenticationMethodModel.None,
+            DomainLayerAuthenticationMethodModel.Swipe,
+            DomainLayerAuthenticationMethodModel.Pin,
+            DomainLayerAuthenticationMethodModel.Password,
+            DomainLayerAuthenticationMethodModel.Pattern,
         )
     }
+
+    private fun FakeAuthenticationRepository.setAuthenticationMethod(
+        model: DomainLayerAuthenticationMethodModel,
+    ) {
+        setAuthenticationMethod(
+            when (model) {
+                is DomainLayerAuthenticationMethodModel.None,
+                is DomainLayerAuthenticationMethodModel.Swipe ->
+                    DataLayerAuthenticationMethodModel.None
+                is DomainLayerAuthenticationMethodModel.Pin ->
+                    DataLayerAuthenticationMethodModel.Pin
+                is DomainLayerAuthenticationMethodModel.Password ->
+                    DataLayerAuthenticationMethodModel.Password
+                is DomainLayerAuthenticationMethodModel.Pattern ->
+                    DataLayerAuthenticationMethodModel.Pattern
+            }
+        )
+        setLockscreenEnabled(model !is DomainLayerAuthenticationMethodModel.None)
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PasswordBouncerViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PasswordBouncerViewModelTest.kt
index 7f8d54c..4380af8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PasswordBouncerViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PasswordBouncerViewModelTest.kt
@@ -19,7 +19,7 @@
 import androidx.test.filters.SmallTest
 import com.android.systemui.R
 import com.android.systemui.SysuiTestCase
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.scene.SceneTestUtils
 import com.android.systemui.scene.shared.model.SceneKey
@@ -55,6 +55,7 @@
     private val bouncerViewModel =
         utils.bouncerViewModel(
             bouncerInteractor = bouncerInteractor,
+            authenticationInteractor = authenticationInteractor,
         )
     private val underTest =
         PasswordBouncerViewModel(
@@ -72,14 +73,15 @@
     @Test
     fun onShown() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val password by collectLastValue(underTest.password)
             utils.authenticationRepository.setAuthenticationMethod(
                 AuthenticationMethodModel.Password
             )
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
 
             underTest.onShown()
@@ -92,14 +94,15 @@
     @Test
     fun onPasswordInputChanged() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val password by collectLastValue(underTest.password)
             utils.authenticationRepository.setAuthenticationMethod(
                 AuthenticationMethodModel.Password
             )
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             runCurrent()
@@ -114,12 +117,13 @@
     @Test
     fun onAuthenticateKeyPressed_whenCorrect() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(
                 AuthenticationMethodModel.Password
             )
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             underTest.onPasswordInputChanged("password")
@@ -132,14 +136,15 @@
     @Test
     fun onAuthenticateKeyPressed_whenWrong() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val password by collectLastValue(underTest.password)
             utils.authenticationRepository.setAuthenticationMethod(
                 AuthenticationMethodModel.Password
             )
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             underTest.onPasswordInputChanged("wrong")
@@ -154,14 +159,15 @@
     @Test
     fun onAuthenticateKeyPressed_correctAfterWrong() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val password by collectLastValue(underTest.password)
             utils.authenticationRepository.setAuthenticationMethod(
                 AuthenticationMethodModel.Password
             )
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             underTest.onPasswordInputChanged("wrong")
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PatternBouncerViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PatternBouncerViewModelTest.kt
index 57fcbe5..ea2cad2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PatternBouncerViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PatternBouncerViewModelTest.kt
@@ -19,8 +19,8 @@
 import androidx.test.filters.SmallTest
 import com.android.systemui.R
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel
 import com.android.systemui.authentication.data.repository.FakeAuthenticationRepository
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.scene.SceneTestUtils
 import com.android.systemui.scene.shared.model.SceneKey
@@ -57,6 +57,7 @@
     private val bouncerViewModel =
         utils.bouncerViewModel(
             bouncerInteractor = bouncerInteractor,
+            authenticationInteractor = authenticationInteractor,
         )
     private val underTest =
         PatternBouncerViewModel(
@@ -75,7 +76,7 @@
     @Test
     fun onShown() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val selectedDots by collectLastValue(underTest.selectedDots)
             val currentDot by collectLastValue(underTest.currentDot)
@@ -83,7 +84,8 @@
                 AuthenticationMethodModel.Pattern
             )
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
 
             underTest.onShown()
@@ -97,7 +99,7 @@
     @Test
     fun onDragStart() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val selectedDots by collectLastValue(underTest.selectedDots)
             val currentDot by collectLastValue(underTest.currentDot)
@@ -105,7 +107,8 @@
                 AuthenticationMethodModel.Pattern
             )
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             runCurrent()
@@ -121,14 +124,15 @@
     @Test
     fun onDragEnd_whenCorrect() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val selectedDots by collectLastValue(underTest.selectedDots)
             val currentDot by collectLastValue(underTest.currentDot)
             utils.authenticationRepository.setAuthenticationMethod(
                 AuthenticationMethodModel.Pattern
             )
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             underTest.onDragStart()
@@ -168,7 +172,7 @@
     @Test
     fun onDragEnd_whenWrong() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val selectedDots by collectLastValue(underTest.selectedDots)
             val currentDot by collectLastValue(underTest.currentDot)
@@ -176,7 +180,8 @@
                 AuthenticationMethodModel.Pattern
             )
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             underTest.onDragStart()
@@ -200,7 +205,7 @@
     @Test
     fun onDragEnd_correctAfterWrong() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val selectedDots by collectLastValue(underTest.selectedDots)
             val currentDot by collectLastValue(underTest.currentDot)
@@ -208,7 +213,8 @@
                 AuthenticationMethodModel.Pattern
             )
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             underTest.onDragStart()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PinBouncerViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PinBouncerViewModelTest.kt
index 81c68ed..531f86a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PinBouncerViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/bouncer/ui/viewmodel/PinBouncerViewModelTest.kt
@@ -19,8 +19,8 @@
 import androidx.test.filters.SmallTest
 import com.android.systemui.R
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel
 import com.android.systemui.authentication.data.repository.FakeAuthenticationRepository
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.scene.SceneTestUtils
 import com.android.systemui.scene.shared.model.SceneKey
@@ -57,6 +57,7 @@
     private val bouncerViewModel =
         utils.bouncerViewModel(
             bouncerInteractor = bouncerInteractor,
+            authenticationInteractor = authenticationInteractor,
         )
     private val underTest =
         PinBouncerViewModel(
@@ -75,11 +76,13 @@
     @Test
     fun onShown() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val pin by collectLastValue(underTest.pinInput.map { it.getPin() })
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
+
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
 
             underTest.onShown()
@@ -92,12 +95,14 @@
     @Test
     fun onPinButtonClicked() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val pin by collectLastValue(underTest.pinInput.map { it.getPin() })
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
+
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             runCurrent()
@@ -112,12 +117,14 @@
     @Test
     fun onBackspaceButtonClicked() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val pin by collectLastValue(underTest.pinInput.map { it.getPin() })
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
+
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             runCurrent()
@@ -134,11 +141,13 @@
     @Test
     fun onPinEdit() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val pin by collectLastValue(underTest.pinInput.map { it.getPin() })
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
+
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
 
@@ -156,12 +165,14 @@
     @Test
     fun onBackspaceButtonLongPressed() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val pin by collectLastValue(underTest.pinInput.map { it.getPin() })
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
+
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             runCurrent()
@@ -180,10 +191,12 @@
     @Test
     fun onAuthenticateButtonClicked_whenCorrect() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
+
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             FakeAuthenticationRepository.DEFAULT_PIN.forEach { digit ->
@@ -198,12 +211,14 @@
     @Test
     fun onAuthenticateButtonClicked_whenWrong() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val pin by collectLastValue(underTest.pinInput.map { it.getPin() })
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
+
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             underTest.onPinButtonClicked(1)
@@ -222,12 +237,14 @@
     @Test
     fun onAuthenticateButtonClicked_correctAfterWrong() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val pin by collectLastValue(underTest.pinInput.map { it.getPin() })
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
+
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             underTest.onPinButtonClicked(1)
@@ -254,11 +271,13 @@
     @Test
     fun onAutoConfirm_whenCorrect() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
             utils.authenticationRepository.setAutoConfirmEnabled(true)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
+
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             FakeAuthenticationRepository.DEFAULT_PIN.forEach { digit ->
@@ -271,13 +290,15 @@
     @Test
     fun onAutoConfirm_whenWrong() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             val message by collectLastValue(bouncerViewModel.message)
             val pin by collectLastValue(underTest.pinInput.map { it.getPin() })
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
             utils.authenticationRepository.setAutoConfirmEnabled(true)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Bouncer), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Bouncer), "reason")
+
             assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
             underTest.onShown()
             FakeAuthenticationRepository.DEFAULT_PIN.dropLast(1).forEach { digit ->
diff --git a/packages/SystemUI/tests/src/com/android/systemui/charging/WiredChargingRippleControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/charging/WiredChargingRippleControllerTest.kt
index d6cafcb..5a5c058 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/charging/WiredChargingRippleControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/charging/WiredChargingRippleControllerTest.kt
@@ -211,7 +211,7 @@
                 context.resources.getFloat(R.dimen.physical_charger_port_location_normalized_y)
         val expectedCenterX: Float
         val expectedCenterY: Float
-        when (context.display.rotation) {
+        when (checkNotNull(context.display).rotation) {
             Surface.ROTATION_90 -> {
                 expectedCenterX = width * normalizedPortPosY
                 expectedCenterY = height * (1 - normalizedPortPosX)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/clipboardoverlay/IntentCreatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/clipboardoverlay/IntentCreatorTest.java
index 7628be4..662c89c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/clipboardoverlay/IntentCreatorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/clipboardoverlay/IntentCreatorTest.java
@@ -80,6 +80,7 @@
         assertEquals(Intent.ACTION_EDIT, intent.getAction());
         assertEquals("image/*", intent.getType());
         assertEquals(null, intent.getComponent());
+        assertEquals("clipboard", intent.getStringExtra("edit_source"));
         assertFlags(intent, EXTERNAL_INTENT_FLAGS);
 
         // try again with an editor component
diff --git a/packages/SystemUI/tests/src/com/android/systemui/communal/data/repository/CommunalWidgetRepositoryImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/communal/data/repository/CommunalWidgetRepositoryImplTest.kt
new file mode 100644
index 0000000..3df9cbb
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/communal/data/repository/CommunalWidgetRepositoryImplTest.kt
@@ -0,0 +1,285 @@
+package com.android.systemui.communal.data.repository
+
+import android.appwidget.AppWidgetHost
+import android.appwidget.AppWidgetManager
+import android.appwidget.AppWidgetProviderInfo
+import android.content.BroadcastReceiver
+import android.content.pm.PackageManager
+import android.os.UserHandle
+import android.os.UserManager
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.broadcast.BroadcastDispatcher
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
+import com.android.systemui.log.LogBuffer
+import com.android.systemui.log.core.FakeLogBuffer
+import com.android.systemui.settings.UserTracker
+import com.android.systemui.util.mockito.any
+import com.android.systemui.util.mockito.kotlinArgumentCaptor
+import com.android.systemui.util.mockito.nullable
+import com.android.systemui.util.mockito.whenever
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mock
+import org.mockito.Mockito
+import org.mockito.Mockito.anyInt
+import org.mockito.MockitoAnnotations
+
+@OptIn(ExperimentalCoroutinesApi::class)
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class CommunalWidgetRepositoryImplTest : SysuiTestCase() {
+    @Mock private lateinit var appWidgetManager: AppWidgetManager
+
+    @Mock private lateinit var appWidgetHost: AppWidgetHost
+
+    @Mock private lateinit var broadcastDispatcher: BroadcastDispatcher
+
+    @Mock private lateinit var packageManager: PackageManager
+
+    @Mock private lateinit var userManager: UserManager
+
+    @Mock private lateinit var userHandle: UserHandle
+
+    @Mock private lateinit var userTracker: UserTracker
+
+    @Mock private lateinit var featureFlags: FeatureFlags
+
+    @Mock private lateinit var stopwatchProviderInfo: AppWidgetProviderInfo
+
+    private lateinit var logBuffer: LogBuffer
+
+    private val testDispatcher = StandardTestDispatcher()
+    private val testScope = TestScope(testDispatcher)
+
+    @Before
+    fun setUp() {
+        MockitoAnnotations.initMocks(this)
+
+        logBuffer = FakeLogBuffer.Factory.create()
+
+        featureFlagEnabled(true)
+        whenever(stopwatchProviderInfo.loadLabel(any())).thenReturn("Stopwatch")
+        whenever(userTracker.userHandle).thenReturn(userHandle)
+    }
+
+    @Test
+    fun broadcastReceiver_featureDisabled_doNotRegisterUserUnlockedBroadcastReceiver() =
+        testScope.runTest {
+            featureFlagEnabled(false)
+            val repository = initCommunalWidgetRepository()
+            collectLastValue(repository.stopwatchAppWidgetInfo)()
+            verifyBroadcastReceiverNeverRegistered()
+        }
+
+    @Test
+    fun broadcastReceiver_featureEnabledAndUserUnlocked_doNotRegisterBroadcastReceiver() =
+        testScope.runTest {
+            userUnlocked(true)
+            val repository = initCommunalWidgetRepository()
+            collectLastValue(repository.stopwatchAppWidgetInfo)()
+            verifyBroadcastReceiverNeverRegistered()
+        }
+
+    @Test
+    fun broadcastReceiver_featureEnabledAndUserLocked_registerBroadcastReceiver() =
+        testScope.runTest {
+            userUnlocked(false)
+            val repository = initCommunalWidgetRepository()
+            collectLastValue(repository.stopwatchAppWidgetInfo)()
+            verifyBroadcastReceiverRegistered()
+        }
+
+    @Test
+    fun broadcastReceiver_whenFlowFinishes_unregisterBroadcastReceiver() =
+        testScope.runTest {
+            userUnlocked(false)
+            val repository = initCommunalWidgetRepository()
+
+            val job = launch { repository.stopwatchAppWidgetInfo.collect() }
+            runCurrent()
+            val receiver = broadcastReceiverUpdate()
+
+            job.cancel()
+            runCurrent()
+
+            Mockito.verify(broadcastDispatcher).unregisterReceiver(receiver)
+        }
+
+    @Test
+    fun stopwatch_whenUserUnlocks_receiveProviderInfo() =
+        testScope.runTest {
+            userUnlocked(false)
+            val repository = initCommunalWidgetRepository()
+            val lastStopwatchProviderInfo = collectLastValue(repository.stopwatchAppWidgetInfo)
+            assertThat(lastStopwatchProviderInfo()).isNull()
+
+            userUnlocked(true)
+            installedProviders(listOf(stopwatchProviderInfo))
+            broadcastReceiverUpdate()
+
+            assertThat(lastStopwatchProviderInfo()?.providerInfo).isEqualTo(stopwatchProviderInfo)
+        }
+
+    @Test
+    fun stopwatch_userUnlockedButWidgetNotInstalled_noProviderInfo() =
+        testScope.runTest {
+            userUnlocked(true)
+            installedProviders(listOf())
+
+            val repository = initCommunalWidgetRepository()
+
+            val lastStopwatchProviderInfo = collectLastValue(repository.stopwatchAppWidgetInfo)
+            assertThat(lastStopwatchProviderInfo()).isNull()
+        }
+
+    @Test
+    fun appWidgetId_providerInfoAvailable_allocateAppWidgetId() =
+        testScope.runTest {
+            userUnlocked(true)
+            installedProviders(listOf(stopwatchProviderInfo))
+            val repository = initCommunalWidgetRepository()
+            collectLastValue(repository.stopwatchAppWidgetInfo)()
+            Mockito.verify(appWidgetHost).allocateAppWidgetId()
+        }
+
+    @Test
+    fun appWidgetId_userLockedAgainAfterProviderInfoAvailable_deleteAppWidgetId() =
+        testScope.runTest {
+            whenever(appWidgetHost.allocateAppWidgetId()).thenReturn(123456)
+            userUnlocked(false)
+            val repository = initCommunalWidgetRepository()
+            val lastStopwatchProviderInfo = collectLastValue(repository.stopwatchAppWidgetInfo)
+            assertThat(lastStopwatchProviderInfo()).isNull()
+
+            // User unlocks
+            userUnlocked(true)
+            installedProviders(listOf(stopwatchProviderInfo))
+            broadcastReceiverUpdate()
+
+            // Verify app widget id allocated
+            assertThat(lastStopwatchProviderInfo()?.appWidgetId).isEqualTo(123456)
+            Mockito.verify(appWidgetHost).allocateAppWidgetId()
+            Mockito.verify(appWidgetHost, Mockito.never()).deleteAppWidgetId(anyInt())
+
+            // User locked again
+            userUnlocked(false)
+            broadcastReceiverUpdate()
+
+            // Verify app widget id deleted
+            assertThat(lastStopwatchProviderInfo()).isNull()
+            Mockito.verify(appWidgetHost).deleteAppWidgetId(123456)
+        }
+
+    @Test
+    fun appWidgetHost_userUnlocked_startListening() =
+        testScope.runTest {
+            userUnlocked(false)
+            val repository = initCommunalWidgetRepository()
+            collectLastValue(repository.stopwatchAppWidgetInfo)()
+            Mockito.verify(appWidgetHost, Mockito.never()).startListening()
+
+            userUnlocked(true)
+            broadcastReceiverUpdate()
+            collectLastValue(repository.stopwatchAppWidgetInfo)()
+
+            Mockito.verify(appWidgetHost).startListening()
+        }
+
+    @Test
+    fun appWidgetHost_userLockedAgain_stopListening() =
+        testScope.runTest {
+            userUnlocked(false)
+            val repository = initCommunalWidgetRepository()
+            collectLastValue(repository.stopwatchAppWidgetInfo)()
+
+            userUnlocked(true)
+            broadcastReceiverUpdate()
+            collectLastValue(repository.stopwatchAppWidgetInfo)()
+
+            Mockito.verify(appWidgetHost).startListening()
+            Mockito.verify(appWidgetHost, Mockito.never()).stopListening()
+
+            userUnlocked(false)
+            broadcastReceiverUpdate()
+            collectLastValue(repository.stopwatchAppWidgetInfo)()
+
+            Mockito.verify(appWidgetHost).stopListening()
+        }
+
+    private fun initCommunalWidgetRepository(): CommunalWidgetRepositoryImpl {
+        return CommunalWidgetRepositoryImpl(
+            appWidgetManager,
+            appWidgetHost,
+            broadcastDispatcher,
+            packageManager,
+            userManager,
+            userTracker,
+            logBuffer,
+            featureFlags,
+        )
+    }
+
+    private fun verifyBroadcastReceiverRegistered() {
+        Mockito.verify(broadcastDispatcher)
+            .registerReceiver(
+                any(),
+                any(),
+                nullable(),
+                nullable(),
+                anyInt(),
+                nullable(),
+            )
+    }
+
+    private fun verifyBroadcastReceiverNeverRegistered() {
+        Mockito.verify(broadcastDispatcher, Mockito.never())
+            .registerReceiver(
+                any(),
+                any(),
+                nullable(),
+                nullable(),
+                anyInt(),
+                nullable(),
+            )
+    }
+
+    private fun broadcastReceiverUpdate(): BroadcastReceiver {
+        val broadcastReceiverCaptor = kotlinArgumentCaptor<BroadcastReceiver>()
+        Mockito.verify(broadcastDispatcher)
+            .registerReceiver(
+                broadcastReceiverCaptor.capture(),
+                any(),
+                nullable(),
+                nullable(),
+                anyInt(),
+                nullable(),
+            )
+        broadcastReceiverCaptor.value.onReceive(null, null)
+        return broadcastReceiverCaptor.value
+    }
+
+    private fun featureFlagEnabled(enabled: Boolean) {
+        whenever(featureFlags.isEnabled(Flags.WIDGET_ON_KEYGUARD)).thenReturn(enabled)
+    }
+
+    private fun userUnlocked(userUnlocked: Boolean) {
+        whenever(userManager.isUserUnlockingOrUnlocked(userHandle)).thenReturn(userUnlocked)
+    }
+
+    private fun installedProviders(providers: List<AppWidgetProviderInfo>) {
+        whenever(appWidgetManager.installedProviders).thenReturn(providers)
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/communal/domain/interactor/CommunalInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/communal/domain/interactor/CommunalInteractorTest.kt
new file mode 100644
index 0000000..d28f530
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/communal/domain/interactor/CommunalInteractorTest.kt
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.communal.domain.interactor
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.RoboPilotTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.communal.data.repository.FakeCommunalWidgetRepository
+import com.android.systemui.communal.shared.CommunalAppWidgetInfo
+import com.android.systemui.coroutines.collectLastValue
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mock
+import org.mockito.MockitoAnnotations
+
+@SmallTest
+@RoboPilotTest
+@OptIn(ExperimentalCoroutinesApi::class)
+@RunWith(AndroidJUnit4::class)
+class CommunalInteractorTest : SysuiTestCase() {
+    @Mock private lateinit var stopwatchAppWidgetInfo: CommunalAppWidgetInfo
+
+    private lateinit var testScope: TestScope
+
+    private lateinit var widgetRepository: FakeCommunalWidgetRepository
+    private lateinit var interactor: CommunalInteractor
+
+    @Before
+    fun setUp() {
+        MockitoAnnotations.initMocks(this)
+
+        testScope = TestScope()
+        widgetRepository = FakeCommunalWidgetRepository()
+        interactor = CommunalInteractor(widgetRepository)
+    }
+
+    @Test
+    fun testAppWidgetInfoFlow() =
+        testScope.runTest {
+            val lastAppWidgetInfo = collectLastValue(interactor.appWidgetInfo)
+            runCurrent()
+            assertThat(lastAppWidgetInfo()).isNull()
+
+            widgetRepository.setStopwatchAppWidgetInfo(stopwatchAppWidgetInfo)
+            runCurrent()
+            assertThat(lastAppWidgetInfo()).isEqualTo(stopwatchAppWidgetInfo)
+        }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/communal/ui/view/layout/blueprints/DefaultCommunalBlueprintTest.kt b/packages/SystemUI/tests/src/com/android/systemui/communal/ui/view/layout/blueprints/DefaultCommunalBlueprintTest.kt
new file mode 100644
index 0000000..e3a75f1
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/communal/ui/view/layout/blueprints/DefaultCommunalBlueprintTest.kt
@@ -0,0 +1,36 @@
+package com.android.systemui.communal.ui.view.layout.blueprints
+
+import android.testing.AndroidTestingRunner
+import android.testing.TestableLooper
+import androidx.constraintlayout.widget.ConstraintSet
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.communal.ui.view.layout.sections.DefaultCommunalWidgetSection
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mock
+import org.mockito.Mockito.verify
+import org.mockito.MockitoAnnotations
+
+@RunWith(AndroidTestingRunner::class)
+@TestableLooper.RunWithLooper(setAsMainLooper = true)
+@SmallTest
+class DefaultCommunalBlueprintTest : SysuiTestCase() {
+    @Mock private lateinit var widgetSection: DefaultCommunalWidgetSection
+
+    private lateinit var blueprint: DefaultCommunalBlueprint
+
+    @Before
+    fun setup() {
+        MockitoAnnotations.initMocks(this)
+        blueprint = DefaultCommunalBlueprint(widgetSection)
+    }
+
+    @Test
+    fun apply() {
+        val cs = ConstraintSet()
+        blueprint.apply(cs)
+        verify(widgetSection).apply(cs)
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlActionCoordinatorImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlActionCoordinatorImplTest.kt
index 692d794..8416c46 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlActionCoordinatorImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlActionCoordinatorImplTest.kt
@@ -18,12 +18,14 @@
 
 import android.test.suitebuilder.annotation.SmallTest
 import android.testing.AndroidTestingRunner
+import android.view.HapticFeedbackConstants
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.broadcast.BroadcastSender
 import com.android.systemui.controls.ControlsMetricsLogger
 import com.android.systemui.controls.settings.ControlsSettingsDialogManager
 import com.android.systemui.controls.settings.FakeControlsSettingsRepository
-import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.FakeFeatureFlags
+import com.android.systemui.flags.Flags.ONE_WAY_HAPTICS_API_MIGRATION
 import com.android.systemui.plugins.ActivityStarter
 import com.android.systemui.statusbar.VibratorHelper
 import com.android.systemui.statusbar.policy.KeyguardStateController
@@ -33,6 +35,7 @@
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.mockito.Answers
+import org.mockito.ArgumentMatchers.eq
 import org.mockito.Mock
 import org.mockito.Mockito
 import org.mockito.Mockito.anyBoolean
@@ -68,8 +71,6 @@
     @Mock
     private lateinit var metricsLogger: ControlsMetricsLogger
     @Mock
-    private lateinit var featureFlags: FeatureFlags
-    @Mock
     private lateinit var controlsSettingsDialogManager: ControlsSettingsDialogManager
 
     companion object {
@@ -82,6 +83,8 @@
     private lateinit var action: ControlActionCoordinatorImpl.Action
     private lateinit var controlsSettingsRepository: FakeControlsSettingsRepository
 
+    private val featureFlags = FakeFeatureFlags()
+
     @Before
     fun setUp() {
         MockitoAnnotations.initMocks(this)
@@ -101,6 +104,7 @@
                 metricsLogger,
                 vibratorHelper,
                 controlsSettingsRepository,
+                featureFlags
         ))
         coordinator.activityContext = mContext
 
@@ -194,4 +198,50 @@
         verify(coordinator).bouncerOrRun(action)
         verify(action, never()).invoke()
     }
+
+    @Test
+    fun drag_isEdge_oneWayHapticsDisabled_usesVibrate() {
+        featureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, false)
+
+        coordinator.drag(cvh, true)
+
+        verify(vibratorHelper).vibrate(
+            Vibrations.rangeEdgeEffect
+        )
+    }
+
+    @Test
+    fun drag_isNotEdge_oneWayHapticsDisabled_usesVibrate() {
+        featureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, false)
+
+        coordinator.drag(cvh, false)
+
+        verify(vibratorHelper).vibrate(
+            Vibrations.rangeMiddleEffect
+        )
+    }
+
+    @Test
+    fun drag_isEdge_oneWayHapticsEnabled_usesPerformHapticFeedback() {
+        featureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, true)
+
+        coordinator.drag(cvh, true)
+
+        verify(vibratorHelper).performHapticFeedback(
+            any(),
+            eq(HapticFeedbackConstants.SEGMENT_TICK)
+        )
+    }
+
+    @Test
+    fun drag_isNotEdge_oneWayHapticsEnabled_usesPerformHapticFeedback() {
+        featureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, true)
+
+        coordinator.drag(cvh, false)
+
+        verify(vibratorHelper).performHapticFeedback(
+            any(),
+            eq(HapticFeedbackConstants.SEGMENT_FREQUENT_TICK)
+        )
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlViewHolderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlViewHolderTest.kt
index 42f28c8..2ae342a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlViewHolderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlViewHolderTest.kt
@@ -125,7 +125,7 @@
             control
         )
         cvh.bindData(cws, false)
-        val chevronIcon = baseLayout.findViewById<View>(R.id.chevron_icon)
+        val chevronIcon = baseLayout.requireViewById<View>(R.id.chevron_icon)
 
         assertThat(chevronIcon.visibility).isEqualTo(View.VISIBLE)
     }
@@ -138,4 +138,4 @@
 private val DRAWABLE = GradientDrawable()
 private val COLOR = ColorStateList.valueOf(0xffff00)
 private val DEFAULT_CONTROL = Control.StatelessBuilder(
-        CONTROL_ID, mock(PendingIntent::class.java)).build()
\ No newline at end of file
+        CONTROL_ID, mock(PendingIntent::class.java)).build()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlsUiControllerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlsUiControllerImplTest.kt
index fcd6568..a400ff9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlsUiControllerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlsUiControllerImplTest.kt
@@ -365,7 +365,8 @@
         val selectedItems =
             listOf(
                 SelectedItem.StructureItem(
-                    StructureInfo(ComponentName.unflattenFromString("pkg/.cls1"), "a", ArrayList())
+                    StructureInfo(checkNotNull(ComponentName.unflattenFromString("pkg/.cls1")),
+                        "a", ArrayList())
                 ),
             )
         preferredPanelRepository.setSelectedComponent(
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 49cdfa7..7311f4a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeUiTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeUiTest.java
@@ -33,15 +33,14 @@
 import android.app.AlarmManager;
 import android.os.Handler;
 import android.os.HandlerThread;
+import android.testing.TestableLooper;
 
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
 
-import com.android.keyguard.KeyguardUpdateMonitor;
+import com.android.systemui.DejankUtils;
 import com.android.systemui.SysuiTestCase;
-import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.phone.DozeParameters;
-import com.android.systemui.tuner.TunerService;
 import com.android.systemui.util.wakelock.WakeLockFake;
 
 import org.junit.After;
@@ -53,6 +52,7 @@
 
 @RunWith(AndroidJUnit4.class)
 @SmallTest
+@TestableLooper.RunWithLooper
 public class DozeUiTest extends SysuiTestCase {
 
     @Mock
@@ -62,23 +62,19 @@
     @Mock
     private DozeParameters mDozeParameters;
     @Mock
-    private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
-    @Mock
     private DozeHost mHost;
     @Mock
     private DozeLog mDozeLog;
-    @Mock
-    private TunerService mTunerService;
     private WakeLockFake mWakeLock;
     private Handler mHandler;
     private HandlerThread mHandlerThread;
     private DozeUi mDozeUi;
-    @Mock
-    private StatusBarStateController mStatusBarStateController;
 
     @Before
     public void setUp() throws Exception {
+        allowTestableLooperAsMainThread();
         MockitoAnnotations.initMocks(this);
+        DejankUtils.setImmediate(true);
 
         mHandlerThread = new HandlerThread("DozeUiTest");
         mHandlerThread.start();
@@ -86,12 +82,13 @@
         mHandler = mHandlerThread.getThreadHandler();
 
         mDozeUi = new DozeUi(mContext, mAlarmManager, mWakeLock, mHost, mHandler,
-                mDozeParameters, mStatusBarStateController, mDozeLog);
+                mDozeParameters, mDozeLog);
         mDozeUi.setDozeMachine(mMachine);
     }
 
     @After
     public void tearDown() throws Exception {
+        DejankUtils.setImmediate(false);
         mHandlerThread.quit();
         mHandler = null;
         mHandlerThread = null;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/dreams/conditions/AssistantAttentionConditionTest.java b/packages/SystemUI/tests/src/com/android/systemui/dreams/conditions/AssistantAttentionConditionTest.java
index 07cb5d8..6a17889 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/dreams/conditions/AssistantAttentionConditionTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/dreams/conditions/AssistantAttentionConditionTest.java
@@ -22,17 +22,14 @@
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
 
-import android.os.RemoteException;
 import android.testing.AndroidTestingRunner;
 
 import androidx.test.filters.SmallTest;
 
-import com.android.internal.app.AssistUtils;
-import com.android.internal.app.IVisualQueryDetectionAttentionListener;
 import com.android.systemui.SysuiTestCase;
-import com.android.systemui.dreams.DreamOverlayStateController;
+import com.android.systemui.assist.AssistManager;
+import com.android.systemui.assist.AssistManager.VisualQueryAttentionListener;
 import com.android.systemui.shared.condition.Condition;
 
 import org.junit.Before;
@@ -50,9 +47,7 @@
     @Mock
     Condition.Callback mCallback;
     @Mock
-    AssistUtils mAssistUtils;
-    @Mock
-    DreamOverlayStateController mDreamOverlayStateController;
+    AssistManager mAssistManager;
     @Mock
     CoroutineScope mScope;
 
@@ -62,55 +57,34 @@
     public void setup() {
         MockitoAnnotations.initMocks(this);
 
-        mAssistantAttentionCondition =
-                new AssistantAttentionCondition(mScope, mDreamOverlayStateController, mAssistUtils);
+        mAssistantAttentionCondition = new AssistantAttentionCondition(mScope, mAssistManager);
         // Adding a callback also starts the condition.
         mAssistantAttentionCondition.addCallback(mCallback);
     }
 
     @Test
     public void testEnableVisualQueryDetection() {
-        final ArgumentCaptor<DreamOverlayStateController.Callback> argumentCaptor =
-                ArgumentCaptor.forClass(DreamOverlayStateController.Callback.class);
-        verify(mDreamOverlayStateController).addCallback(argumentCaptor.capture());
-
-        when(mDreamOverlayStateController.isDreamOverlayStatusBarVisible()).thenReturn(true);
-        argumentCaptor.getValue().onStateChanged();
-
-        verify(mAssistUtils).enableVisualQueryDetection(any());
+        verify(mAssistManager).addVisualQueryAttentionListener(
+                any(VisualQueryAttentionListener.class));
     }
 
     @Test
     public void testDisableVisualQueryDetection() {
-        final ArgumentCaptor<DreamOverlayStateController.Callback> argumentCaptor =
-                ArgumentCaptor.forClass(DreamOverlayStateController.Callback.class);
-        verify(mDreamOverlayStateController).addCallback(argumentCaptor.capture());
-
-        when(mDreamOverlayStateController.isDreamOverlayStatusBarVisible()).thenReturn(true);
-        argumentCaptor.getValue().onStateChanged();
-        when(mDreamOverlayStateController.isDreamOverlayStatusBarVisible()).thenReturn(false);
-        argumentCaptor.getValue().onStateChanged();
-
-        verify(mAssistUtils).disableVisualQueryDetection();
+        mAssistantAttentionCondition.stop();
+        verify(mAssistManager).removeVisualQueryAttentionListener(
+                any(VisualQueryAttentionListener.class));
     }
 
     @Test
-    public void testAttentionChangedTriggersCondition() throws RemoteException {
-        final ArgumentCaptor<DreamOverlayStateController.Callback> callbackCaptor =
-                ArgumentCaptor.forClass(DreamOverlayStateController.Callback.class);
-        verify(mDreamOverlayStateController).addCallback(callbackCaptor.capture());
+    public void testAttentionChangedTriggersCondition() {
+        final ArgumentCaptor<VisualQueryAttentionListener> argumentCaptor =
+                ArgumentCaptor.forClass(VisualQueryAttentionListener.class);
+        verify(mAssistManager).addVisualQueryAttentionListener(argumentCaptor.capture());
 
-        when(mDreamOverlayStateController.isDreamOverlayStatusBarVisible()).thenReturn(true);
-        callbackCaptor.getValue().onStateChanged();
-
-        final ArgumentCaptor<IVisualQueryDetectionAttentionListener> listenerCaptor =
-                ArgumentCaptor.forClass(IVisualQueryDetectionAttentionListener.class);
-        verify(mAssistUtils).enableVisualQueryDetection(listenerCaptor.capture());
-
-        listenerCaptor.getValue().onAttentionGained();
+        argumentCaptor.getValue().onAttentionGained();
         assertThat(mAssistantAttentionCondition.isConditionMet()).isTrue();
 
-        listenerCaptor.getValue().onAttentionLost();
+        argumentCaptor.getValue().onAttentionLost();
         assertThat(mAssistantAttentionCondition.isConditionMet()).isFalse();
 
         verify(mCallback, times(2)).onConditionChanged(eq(mAssistantAttentionCondition));
diff --git a/packages/SystemUI/tests/src/com/android/systemui/flags/FakeFeatureFlagsTest.kt b/packages/SystemUI/tests/src/com/android/systemui/flags/FakeFeatureFlagsTest.kt
index 35f0f6c..37c70d8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/flags/FakeFeatureFlagsTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/flags/FakeFeatureFlagsTest.kt
@@ -28,12 +28,12 @@
 @RunWith(AndroidTestingRunner::class)
 class FakeFeatureFlagsTest : SysuiTestCase() {
 
-    private val unreleasedFlag = UnreleasedFlag(-1000, "-1000", "test")
-    private val releasedFlag = ReleasedFlag(-1001, "-1001", "test")
-    private val stringFlag = StringFlag(-1002, "-1002", "test")
-    private val resourceBooleanFlag = ResourceBooleanFlag(-1003, "-1003", "test", resourceId = -1)
-    private val resourceStringFlag = ResourceStringFlag(-1004, "-1004", "test", resourceId = -1)
-    private val sysPropBooleanFlag = SysPropBooleanFlag(-1005, "test", "test")
+    private val unreleasedFlag = UnreleasedFlag("-1000", "test")
+    private val releasedFlag = ReleasedFlag("-1001", "test")
+    private val stringFlag = StringFlag("-1002", "test")
+    private val resourceBooleanFlag = ResourceBooleanFlag("-1003", "test", resourceId = -1)
+    private val resourceStringFlag = ResourceStringFlag("-1004", "test", resourceId = -1)
+    private val sysPropBooleanFlag = SysPropBooleanFlag("test", "test")
 
     /**
      * FakeFeatureFlags does not honor any default values. All flags which are accessed must be
@@ -46,43 +46,43 @@
             assertThat(flags.isEnabled(Flags.TEAMFOOD)).isFalse()
             fail("Expected an exception when accessing an unspecified flag.")
         } catch (ex: IllegalStateException) {
-            assertThat(ex.message).contains("id=1")
+            assertThat(ex.message).contains("UNKNOWN(teamfood)")
         }
         try {
             assertThat(flags.isEnabled(unreleasedFlag)).isFalse()
             fail("Expected an exception when accessing an unspecified flag.")
         } catch (ex: IllegalStateException) {
-            assertThat(ex.message).contains("UNKNOWN(id=-1000)")
+            assertThat(ex.message).contains("UNKNOWN(-1000)")
         }
         try {
             assertThat(flags.isEnabled(releasedFlag)).isFalse()
             fail("Expected an exception when accessing an unspecified flag.")
         } catch (ex: IllegalStateException) {
-            assertThat(ex.message).contains("UNKNOWN(id=-1001)")
+            assertThat(ex.message).contains("UNKNOWN(-1001)")
         }
         try {
             assertThat(flags.isEnabled(resourceBooleanFlag)).isFalse()
             fail("Expected an exception when accessing an unspecified flag.")
         } catch (ex: IllegalStateException) {
-            assertThat(ex.message).contains("UNKNOWN(id=-1003)")
+            assertThat(ex.message).contains("UNKNOWN(-1003)")
         }
         try {
             assertThat(flags.isEnabled(sysPropBooleanFlag)).isFalse()
             fail("Expected an exception when accessing an unspecified flag.")
         } catch (ex: IllegalStateException) {
-            assertThat(ex.message).contains("UNKNOWN(id=-1005)")
+            assertThat(ex.message).contains("UNKNOWN(test)")
         }
         try {
             assertThat(flags.getString(stringFlag)).isEmpty()
             fail("Expected an exception when accessing an unspecified flag.")
         } catch (ex: IllegalStateException) {
-            assertThat(ex.message).contains("UNKNOWN(id=-1002)")
+            assertThat(ex.message).contains("UNKNOWN(-1002)")
         }
         try {
             assertThat(flags.getString(resourceStringFlag)).isEmpty()
             fail("Expected an exception when accessing an unspecified flag.")
         } catch (ex: IllegalStateException) {
-            assertThat(ex.message).contains("UNKNOWN(id=-1004)")
+            assertThat(ex.message).contains("UNKNOWN(-1004)")
         }
     }
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsDebugTest.kt b/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsDebugTest.kt
index 18f7db1..ff15cb3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsDebugTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsDebugTest.kt
@@ -74,10 +74,10 @@
     private val serverFlagReader = ServerFlagReaderFake()
 
     private val teamfoodableFlagA = UnreleasedFlag(
-        500, name = "a", namespace = "test", teamfood = true
+        name = "a", namespace = "test", teamfood = true
     )
     private val teamfoodableFlagB = ReleasedFlag(
-        501, name = "b", namespace = "test", teamfood = true
+        name = "b", namespace = "test", teamfood = true
     )
 
     @Before
@@ -119,7 +119,6 @@
         assertThat(
             featureFlagsDebug.isEnabled(
                 ReleasedFlag(
-                    2,
                     name = "2",
                     namespace = "test"
                 )
@@ -128,7 +127,6 @@
         assertThat(
             featureFlagsDebug.isEnabled(
                 UnreleasedFlag(
-                    3,
                     name = "3",
                     namespace = "test"
                 )
@@ -137,7 +135,6 @@
         assertThat(
             featureFlagsDebug.isEnabled(
                 ReleasedFlag(
-                    4,
                     name = "4",
                     namespace = "test"
                 )
@@ -146,7 +143,6 @@
         assertThat(
             featureFlagsDebug.isEnabled(
                 UnreleasedFlag(
-                    5,
                     name = "5",
                     namespace = "test"
                 )
@@ -208,23 +204,22 @@
         assertThat(
             featureFlagsDebug.isEnabled(
                 ResourceBooleanFlag(
-                    1,
                     "1",
                     "test",
                     1001
                 )
             )
         ).isFalse()
-        assertThat(featureFlagsDebug.isEnabled(ResourceBooleanFlag(2, "2", "test", 1002))).isTrue()
-        assertThat(featureFlagsDebug.isEnabled(ResourceBooleanFlag(3, "3", "test", 1003))).isTrue()
+        assertThat(featureFlagsDebug.isEnabled(ResourceBooleanFlag("2", "test", 1002))).isTrue()
+        assertThat(featureFlagsDebug.isEnabled(ResourceBooleanFlag("3", "test", 1003))).isTrue()
 
         Assert.assertThrows(NameNotFoundException::class.java) {
-            featureFlagsDebug.isEnabled(ResourceBooleanFlag(4, "4", "test", 1004))
+            featureFlagsDebug.isEnabled(ResourceBooleanFlag("4", "test", 1004))
         }
         // Test that resource is loaded (and validated) even when the setting is set.
         //  This prevents developers from not noticing when they reference an invalid resource.
         Assert.assertThrows(NameNotFoundException::class.java) {
-            featureFlagsDebug.isEnabled(ResourceBooleanFlag(5, "5", "test", 1005))
+            featureFlagsDebug.isEnabled(ResourceBooleanFlag("5", "test", 1005))
         }
     }
 
@@ -237,30 +232,29 @@
             return@thenAnswer it.getArgument(1)
         }
 
-        assertThat(featureFlagsDebug.isEnabled(SysPropBooleanFlag(1, "a", "test"))).isFalse()
-        assertThat(featureFlagsDebug.isEnabled(SysPropBooleanFlag(2, "b", "test"))).isTrue()
-        assertThat(featureFlagsDebug.isEnabled(SysPropBooleanFlag(3, "c", "test", true))).isTrue()
+        assertThat(featureFlagsDebug.isEnabled(SysPropBooleanFlag("a", "test"))).isFalse()
+        assertThat(featureFlagsDebug.isEnabled(SysPropBooleanFlag("b", "test"))).isTrue()
+        assertThat(featureFlagsDebug.isEnabled(SysPropBooleanFlag("c", "test", true))).isTrue()
         assertThat(
             featureFlagsDebug.isEnabled(
                 SysPropBooleanFlag(
-                    4,
                     "d",
                     "test",
                     false
                 )
             )
         ).isFalse()
-        assertThat(featureFlagsDebug.isEnabled(SysPropBooleanFlag(5, "e", "test"))).isFalse()
+        assertThat(featureFlagsDebug.isEnabled(SysPropBooleanFlag("e", "test"))).isFalse()
     }
 
     @Test
     fun readStringFlag() {
         whenever(flagManager.readFlagValue<String>(eq("3"), any())).thenReturn("foo")
         whenever(flagManager.readFlagValue<String>(eq("4"), any())).thenReturn("bar")
-        assertThat(featureFlagsDebug.getString(StringFlag(1, "1", "test", "biz"))).isEqualTo("biz")
-        assertThat(featureFlagsDebug.getString(StringFlag(2, "2", "test", "baz"))).isEqualTo("baz")
-        assertThat(featureFlagsDebug.getString(StringFlag(3, "3", "test", "buz"))).isEqualTo("foo")
-        assertThat(featureFlagsDebug.getString(StringFlag(4, "4", "test", "buz"))).isEqualTo("bar")
+        assertThat(featureFlagsDebug.getString(StringFlag("1", "test", "biz"))).isEqualTo("biz")
+        assertThat(featureFlagsDebug.getString(StringFlag("2", "test", "baz"))).isEqualTo("baz")
+        assertThat(featureFlagsDebug.getString(StringFlag("3", "test", "buz"))).isEqualTo("foo")
+        assertThat(featureFlagsDebug.getString(StringFlag("4", "test", "buz"))).isEqualTo("bar")
     }
 
     @Test
@@ -279,7 +273,6 @@
         assertThat(
             featureFlagsDebug.getString(
                 ResourceStringFlag(
-                    1,
                     "1",
                     "test",
                     1001
@@ -289,7 +282,6 @@
         assertThat(
             featureFlagsDebug.getString(
                 ResourceStringFlag(
-                    2,
                     "2",
                     "test",
                     1002
@@ -299,7 +291,6 @@
         assertThat(
             featureFlagsDebug.getString(
                 ResourceStringFlag(
-                    3,
                     "3",
                     "test",
                     1003
@@ -308,15 +299,15 @@
         ).isEqualTo("override3")
 
         Assert.assertThrows(NullPointerException::class.java) {
-            featureFlagsDebug.getString(ResourceStringFlag(4, "4", "test", 1004))
+            featureFlagsDebug.getString(ResourceStringFlag("4", "test", 1004))
         }
         Assert.assertThrows(NameNotFoundException::class.java) {
-            featureFlagsDebug.getString(ResourceStringFlag(5, "5", "test", 1005))
+            featureFlagsDebug.getString(ResourceStringFlag("5", "test", 1005))
         }
         // Test that resource is loaded (and validated) even when the setting is set.
         //  This prevents developers from not noticing when they reference an invalid resource.
         Assert.assertThrows(NameNotFoundException::class.java) {
-            featureFlagsDebug.getString(ResourceStringFlag(6, "6", "test", 1005))
+            featureFlagsDebug.getString(ResourceStringFlag("6", "test", 1005))
         }
     }
 
@@ -324,10 +315,10 @@
     fun readIntFlag() {
         whenever(flagManager.readFlagValue<Int>(eq("3"), any())).thenReturn(22)
         whenever(flagManager.readFlagValue<Int>(eq("4"), any())).thenReturn(48)
-        assertThat(featureFlagsDebug.getInt(IntFlag(1, "1", "test", 12))).isEqualTo(12)
-        assertThat(featureFlagsDebug.getInt(IntFlag(2, "2", "test", 93))).isEqualTo(93)
-        assertThat(featureFlagsDebug.getInt(IntFlag(3, "3", "test", 8))).isEqualTo(22)
-        assertThat(featureFlagsDebug.getInt(IntFlag(4, "4", "test", 234))).isEqualTo(48)
+        assertThat(featureFlagsDebug.getInt(IntFlag("1", "test", 12))).isEqualTo(12)
+        assertThat(featureFlagsDebug.getInt(IntFlag("2", "test", 93))).isEqualTo(93)
+        assertThat(featureFlagsDebug.getInt(IntFlag("3", "test", 8))).isEqualTo(22)
+        assertThat(featureFlagsDebug.getInt(IntFlag("4", "test", 234))).isEqualTo(48)
     }
 
     @Test
@@ -339,30 +330,30 @@
         whenever(resources.getInteger(1005)).thenThrow(NotFoundException("unknown resource"))
         whenever(resources.getInteger(1006)).thenThrow(NotFoundException("unknown resource"))
 
-        whenever(flagManager.readFlagValue<Int>(eq(3), any())).thenReturn(20)
-        whenever(flagManager.readFlagValue<Int>(eq(4), any())).thenReturn(500)
-        whenever(flagManager.readFlagValue<Int>(eq(5), any())).thenReturn(9519)
+        whenever(flagManager.readFlagValue<Int>(eq("3"), any())).thenReturn(20)
+        whenever(flagManager.readFlagValue<Int>(eq("4"), any())).thenReturn(500)
+        whenever(flagManager.readFlagValue<Int>(eq("5"), any())).thenReturn(9519)
 
-        assertThat(featureFlagsDebug.getInt(ResourceIntFlag(1, "1", "test", 1001))).isEqualTo(88)
-        assertThat(featureFlagsDebug.getInt(ResourceIntFlag(2, "2", "test", 1002))).isEqualTo(61)
-        assertThat(featureFlagsDebug.getInt(ResourceIntFlag(3, "3", "test", 1003))).isEqualTo(20)
+        assertThat(featureFlagsDebug.getInt(ResourceIntFlag("1", "test", 1001))).isEqualTo(88)
+        assertThat(featureFlagsDebug.getInt(ResourceIntFlag("2", "test", 1002))).isEqualTo(61)
+        assertThat(featureFlagsDebug.getInt(ResourceIntFlag("3", "test", 1003))).isEqualTo(20)
 
         Assert.assertThrows(NotFoundException::class.java) {
-            featureFlagsDebug.getInt(ResourceIntFlag(4, "4", "test", 1004))
+            featureFlagsDebug.getInt(ResourceIntFlag("4", "test", 1004))
         }
         // Test that resource is loaded (and validated) even when the setting is set.
         //  This prevents developers from not noticing when they reference an invalid resource.
         Assert.assertThrows(NotFoundException::class.java) {
-            featureFlagsDebug.getInt(ResourceIntFlag(5, "5", "test", 1005))
+            featureFlagsDebug.getInt(ResourceIntFlag("5", "test", 1005))
         }
     }
 
     @Test
     fun broadcastReceiver_IgnoresInvalidData() {
-        addFlag(UnreleasedFlag(1, "1", "test"))
-        addFlag(ResourceBooleanFlag(2, "2", "test", 1002))
-        addFlag(StringFlag(3, "3", "test", "flag3"))
-        addFlag(ResourceStringFlag(4, "4", "test", 1004))
+        addFlag(UnreleasedFlag("1", "test"))
+        addFlag(ResourceBooleanFlag("2", "test", 1002))
+        addFlag(StringFlag("3", "test", "flag3"))
+        addFlag(ResourceStringFlag("4", "test", 1004))
 
         broadcastReceiver.onReceive(mockContext, null)
         broadcastReceiver.onReceive(mockContext, Intent())
@@ -378,7 +369,7 @@
 
     @Test
     fun intentWithId_NoValueKeyClears() {
-        addFlag(UnreleasedFlag(1, name = "1", namespace = "test"))
+        addFlag(UnreleasedFlag(name = "1", namespace = "test"))
 
         // trying to erase an id not in the map does nothing
         broadcastReceiver.onReceive(
@@ -397,10 +388,10 @@
 
     @Test
     fun setBooleanFlag() {
-        addFlag(UnreleasedFlag(1, "1", "test"))
-        addFlag(UnreleasedFlag(2, "2", "test"))
-        addFlag(ResourceBooleanFlag(3, "3", "test", 1003))
-        addFlag(ResourceBooleanFlag(4, "4", "test", 1004))
+        addFlag(UnreleasedFlag("1", "test"))
+        addFlag(UnreleasedFlag("2", "test"))
+        addFlag(ResourceBooleanFlag("3", "test", 1003))
+        addFlag(ResourceBooleanFlag("4", "test", 1004))
 
         setByBroadcast("1", false)
         verifyPutData("1", "{\"type\":\"boolean\",\"value\":false}")
@@ -417,8 +408,8 @@
 
     @Test
     fun setStringFlag() {
-        addFlag(StringFlag(1, "1", "1", "test"))
-        addFlag(ResourceStringFlag(2, "2", "test", 1002))
+        addFlag(StringFlag("1", "1", "test"))
+        addFlag(ResourceStringFlag("2", "test", 1002))
 
         setByBroadcast("1", "override1")
         verifyPutData("1", "{\"type\":\"string\",\"value\":\"override1\"}")
@@ -429,7 +420,7 @@
 
     @Test
     fun setFlag_ClearsCache() {
-        val flag1 = addFlag(StringFlag(1, "1", "test", "flag1"))
+        val flag1 = addFlag(StringFlag("1", "test", "flag1"))
         whenever(flagManager.readFlagValue<String>(eq("1"), any())).thenReturn("original")
 
         // gets the flag & cache it
@@ -451,7 +442,7 @@
 
     @Test
     fun serverSide_Overrides_MakesFalse() {
-        val flag = ReleasedFlag(100, "100", "test")
+        val flag = ReleasedFlag("100", "test")
 
         serverFlagReader.setFlagValue(flag.namespace, flag.name, false)
 
@@ -460,7 +451,7 @@
 
     @Test
     fun serverSide_Overrides_MakesTrue() {
-        val flag = UnreleasedFlag(100, name = "100", namespace = "test")
+        val flag = UnreleasedFlag(name = "100", namespace = "test")
 
         serverFlagReader.setFlagValue(flag.namespace, flag.name, true)
         assertThat(featureFlagsDebug.isEnabled(flag)).isTrue()
@@ -494,18 +485,18 @@
 
     @Test
     fun dumpFormat() {
-        val flag1 = ReleasedFlag(1, "1", "test")
-        val flag2 = ResourceBooleanFlag(2, "2", "test", 1002)
-        val flag3 = UnreleasedFlag(3, "3", "test")
-        val flag4 = StringFlag(4, "4", "test", "")
-        val flag5 = StringFlag(5, "5", "test", "flag5default")
-        val flag6 = ResourceStringFlag(6, "6", "test", 1006)
-        val flag7 = ResourceStringFlag(7, "7", "test", 1007)
+        val flag1 = ReleasedFlag("1", "test")
+        val flag2 = ResourceBooleanFlag("2", "test", 1002)
+        val flag3 = UnreleasedFlag("3", "test")
+        val flag4 = StringFlag("4", "test", "")
+        val flag5 = StringFlag("5", "test", "flag5default")
+        val flag6 = ResourceStringFlag("6", "test", 1006)
+        val flag7 = ResourceStringFlag("7", "test", 1007)
 
         whenever(resources.getBoolean(1002)).thenReturn(true)
         whenever(resources.getString(1006)).thenReturn("resource1006")
         whenever(resources.getString(1007)).thenReturn("resource1007")
-        whenever(flagManager.readFlagValue(eq(7), eq(StringFlagSerializer)))
+        whenever(flagManager.readFlagValue(eq("7"), eq(StringFlagSerializer)))
             .thenReturn("override7")
 
         // WHEN the flags have been accessed
diff --git a/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsReleaseTest.kt b/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsReleaseTest.kt
index 917147b..16b4595 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsReleaseTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsReleaseTest.kt
@@ -44,7 +44,7 @@
     private val serverFlagReader = ServerFlagReaderFake()
 
 
-    private val flagA = ReleasedFlag(501, name = "a", namespace = "test")
+    private val flagA = ReleasedFlag(name = "a", namespace = "test")
 
     @Before
     fun setup() {
@@ -62,11 +62,10 @@
 
     @Test
     fun testBooleanResourceFlag() {
-        val flagId = 213
         val flagResourceId = 3
         val flagName = "213"
         val flagNamespace = "test"
-        val flag = ResourceBooleanFlag(flagId, flagName, flagNamespace, flagResourceId)
+        val flag = ResourceBooleanFlag(flagName, flagNamespace, flagResourceId)
         whenever(mResources.getBoolean(flagResourceId)).thenReturn(true)
         assertThat(featureFlagsRelease.isEnabled(flag)).isTrue()
     }
@@ -79,33 +78,32 @@
         whenever(mResources.getString(1004)).thenAnswer { throw NameNotFoundException() }
 
         assertThat(featureFlagsRelease.getString(
-            ResourceStringFlag(1, "1", "test", 1001))).isEqualTo("")
+            ResourceStringFlag("1", "test", 1001))).isEqualTo("")
         assertThat(featureFlagsRelease.getString(
-            ResourceStringFlag(2, "2", "test", 1002))).isEqualTo("res2")
+            ResourceStringFlag("2", "test", 1002))).isEqualTo("res2")
 
         assertThrows(NullPointerException::class.java) {
-            featureFlagsRelease.getString(ResourceStringFlag(3, "3", "test", 1003))
+            featureFlagsRelease.getString(ResourceStringFlag("3", "test", 1003))
         }
         assertThrows(NameNotFoundException::class.java) {
-            featureFlagsRelease.getString(ResourceStringFlag(4, "4", "test", 1004))
+            featureFlagsRelease.getString(ResourceStringFlag("4", "test", 1004))
         }
     }
 
     @Test
     fun testSysPropBooleanFlag() {
-        val flagId = 213
         val flagName = "sys_prop_flag"
         val flagNamespace = "test"
         val flagDefault = true
 
-        val flag = SysPropBooleanFlag(flagId, flagName, flagNamespace, flagDefault)
+        val flag = SysPropBooleanFlag(flagName, flagNamespace, flagDefault)
         whenever(mSystemProperties.getBoolean(flagName, flagDefault)).thenReturn(flagDefault)
         assertThat(featureFlagsRelease.isEnabled(flag)).isEqualTo(flagDefault)
     }
 
     @Test
     fun serverSide_OverridesReleased_MakesFalse() {
-        val flag = ReleasedFlag(100, "100", "test")
+        val flag = ReleasedFlag("100", "test")
 
         serverFlagReader.setFlagValue(flag.namespace, flag.name, false)
 
@@ -114,7 +112,7 @@
 
     @Test
     fun serverSide_OverridesUnreleased_Ignored() {
-        val flag = UnreleasedFlag(100, "100", "test")
+        val flag = UnreleasedFlag("100", "test")
 
         serverFlagReader.setFlagValue(flag.namespace, flag.name, true)
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/flags/FlagCommandTest.kt b/packages/SystemUI/tests/src/com/android/systemui/flags/FlagCommandTest.kt
index 28131b5..b02baa7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/flags/FlagCommandTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/flags/FlagCommandTest.kt
@@ -33,10 +33,10 @@
     @Mock private lateinit var featureFlags: FeatureFlagsDebug
     @Mock private lateinit var pw: PrintWriter
     private val flagMap = mutableMapOf<String, Flag<*>>()
-    private val flagA = UnreleasedFlag(500, "500", "test")
-    private val flagB = ReleasedFlag(501, "501", "test")
-    private val stringFlag = StringFlag(502, "502", "test", "abracadabra")
-    private val intFlag = IntFlag(503, "503", "test", 12)
+    private val flagA = UnreleasedFlag("500", "test")
+    private val flagB = ReleasedFlag("501", "test")
+    private val stringFlag = StringFlag("502", "test", "abracadabra")
+    private val intFlag = IntFlag("503", "test", 12)
 
     private lateinit var cmd: FlagCommand
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/flags/FlagManagerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/flags/FlagManagerTest.kt
index e679d47..303aaa1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/flags/FlagManagerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/flags/FlagManagerTest.kt
@@ -64,14 +64,14 @@
         verifyNoMoreInteractions(mFlagSettingsHelper)
 
         // adding the first listener registers the observer
-        mFlagManager.addListener(ReleasedFlag(1, "1", "test"), listener1)
+        mFlagManager.addListener(ReleasedFlag("1", "test"), listener1)
         val observer = withArgCaptor<ContentObserver> {
             verify(mFlagSettingsHelper).registerContentObserver(any(), any(), capture())
         }
         verifyNoMoreInteractions(mFlagSettingsHelper)
 
         // adding another listener does nothing
-        mFlagManager.addListener(ReleasedFlag(2, "2", "test"), listener2)
+        mFlagManager.addListener(ReleasedFlag("2", "test"), listener2)
         verifyNoMoreInteractions(mFlagSettingsHelper)
 
         // removing the original listener does nothing with second one still present
@@ -89,7 +89,7 @@
         val listener = mock<FlagListenable.Listener>()
         val clearCacheAction = mock<Consumer<String>>()
         mFlagManager.clearCacheAction = clearCacheAction
-        mFlagManager.addListener(ReleasedFlag(1, "1", "test"), listener)
+        mFlagManager.addListener(ReleasedFlag("1", "test"), listener)
         val observer = withArgCaptor<ContentObserver> {
             verify(mFlagSettingsHelper).registerContentObserver(any(), any(), capture())
         }
@@ -101,8 +101,8 @@
     fun testObserverInvokesListeners() {
         val listener1 = mock<FlagListenable.Listener>()
         val listener10 = mock<FlagListenable.Listener>()
-        mFlagManager.addListener(ReleasedFlag(1, "1", "test"), listener1)
-        mFlagManager.addListener(ReleasedFlag(10, "10", "test"), listener10)
+        mFlagManager.addListener(ReleasedFlag("1", "test"), listener1)
+        mFlagManager.addListener(ReleasedFlag("10", "test"), listener10)
         val observer = withArgCaptor<ContentObserver> {
             verify(mFlagSettingsHelper).registerContentObserver(any(), any(), capture())
         }
@@ -127,8 +127,8 @@
     fun testOnlySpecificFlagListenerIsInvoked() {
         val listener1 = mock<FlagListenable.Listener>()
         val listener10 = mock<FlagListenable.Listener>()
-        mFlagManager.addListener(ReleasedFlag(1, "1", "test"), listener1)
-        mFlagManager.addListener(ReleasedFlag(10, "10", "test"), listener10)
+        mFlagManager.addListener(ReleasedFlag("1", "test"), listener1)
+        mFlagManager.addListener(ReleasedFlag("10", "test"), listener10)
 
         mFlagManager.dispatchListenersAndMaybeRestart("1", null)
         val flagEvent1 = withArgCaptor<FlagListenable.FlagEvent> {
@@ -148,8 +148,8 @@
     @Test
     fun testSameListenerCanBeUsedForMultipleFlags() {
         val listener = mock<FlagListenable.Listener>()
-        mFlagManager.addListener(ReleasedFlag(1, "1", "test"), listener)
-        mFlagManager.addListener(ReleasedFlag(10, "10", "test"), listener)
+        mFlagManager.addListener(ReleasedFlag("1", "test"), listener)
+        mFlagManager.addListener(ReleasedFlag("10", "test"), listener)
 
         mFlagManager.dispatchListenersAndMaybeRestart("1", null)
         val flagEvent1 = withArgCaptor<FlagListenable.FlagEvent> {
@@ -177,7 +177,7 @@
     @Test
     fun testListenerCanSuppressRestart() {
         val restartAction = mock<Consumer<Boolean>>()
-        mFlagManager.addListener(ReleasedFlag(1, "1", "test")) { event ->
+        mFlagManager.addListener(ReleasedFlag("1", "test")) { event ->
             event.requestNoRestart()
         }
         mFlagManager.dispatchListenersAndMaybeRestart("1", restartAction)
@@ -188,7 +188,7 @@
     @Test
     fun testListenerOnlySuppressesRestartForOwnFlag() {
         val restartAction = mock<Consumer<Boolean>>()
-        mFlagManager.addListener(ReleasedFlag(10, "10", "test")) { event ->
+        mFlagManager.addListener(ReleasedFlag("10", "test")) { event ->
             event.requestNoRestart()
         }
         mFlagManager.dispatchListenersAndMaybeRestart("1", restartAction)
@@ -199,10 +199,10 @@
     @Test
     fun testRestartWhenNotAllListenersRequestSuppress() {
         val restartAction = mock<Consumer<Boolean>>()
-        mFlagManager.addListener(ReleasedFlag(10, "10", "test")) { event ->
+        mFlagManager.addListener(ReleasedFlag("10", "test")) { event ->
             event.requestNoRestart()
         }
-        mFlagManager.addListener(ReleasedFlag(10, "10", "test")) {
+        mFlagManager.addListener(ReleasedFlag("10", "test")) {
             // do not request
         }
         mFlagManager.dispatchListenersAndMaybeRestart("1", restartAction)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/flags/ServerFlagReaderImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/flags/ServerFlagReaderImplTest.kt
index 953b7fb..1d1949d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/flags/ServerFlagReaderImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/flags/ServerFlagReaderImplTest.kt
@@ -53,7 +53,7 @@
 
     @Test
     fun testChange_alertsListener() {
-        val flag = ReleasedFlag(1, "flag_1", "test")
+        val flag = ReleasedFlag("flag_1", "test")
         serverFlagReader.listenForChanges(listOf(flag), changeListener)
 
         deviceConfig.setProperty(NAMESPACE, "flag_1", "1", false)
@@ -65,7 +65,7 @@
     @Test
     fun testChange_ignoresListenersDuringTest() {
         val serverFlagReader = ServerFlagReaderImpl(NAMESPACE, deviceConfig, executor, true)
-        val flag = ReleasedFlag(1, "1", "   test")
+        val flag = ReleasedFlag("1", "   test")
         serverFlagReader.listenForChanges(listOf(flag), changeListener)
 
         deviceConfig.setProperty(NAMESPACE, "flag_override_1", "1", false)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyevent/domain/interactor/KeyEventInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyevent/domain/interactor/KeyEventInteractorTest.kt
new file mode 100644
index 0000000..632d149
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyevent/domain/interactor/KeyEventInteractorTest.kt
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyevent.domain.interactor
+
+import android.view.KeyEvent
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.back.domain.interactor.BackActionInteractor
+import com.android.systemui.keyguard.domain.interactor.KeyguardInteractorFactory
+import com.android.systemui.keyguard.domain.interactor.KeyguardKeyEventInteractor
+import com.android.systemui.util.mockito.eq
+import com.android.systemui.util.mockito.whenever
+import com.google.common.truth.Truth.assertThat
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mock
+import org.mockito.Mockito.never
+import org.mockito.Mockito.verify
+import org.mockito.junit.MockitoJUnit
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class KeyEventInteractorTest : SysuiTestCase() {
+    @JvmField @Rule var mockitoRule = MockitoJUnit.rule()
+
+    private lateinit var keyguardInteractorWithDependencies:
+        KeyguardInteractorFactory.WithDependencies
+    @Mock private lateinit var keyguardKeyEventInteractor: KeyguardKeyEventInteractor
+    @Mock private lateinit var backActionInteractor: BackActionInteractor
+
+    private lateinit var underTest: KeyEventInteractor
+
+    @Before
+    fun setup() {
+        keyguardInteractorWithDependencies = KeyguardInteractorFactory.create()
+        underTest =
+            KeyEventInteractor(
+                backActionInteractor,
+                keyguardKeyEventInteractor,
+            )
+    }
+
+    @Test
+    fun dispatchBackKey_notHandledByKeyguardKeyEventInteractor_handledByBackActionInteractor() {
+        val backKeyEventActionDown = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)
+        val backKeyEventActionUp = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK)
+
+        // GIVEN back key ACTION_DOWN and ACTION_UP aren't handled by the keyguardKeyEventInteractor
+        whenever(keyguardKeyEventInteractor.dispatchKeyEvent(backKeyEventActionDown))
+            .thenReturn(false)
+        whenever(keyguardKeyEventInteractor.dispatchKeyEvent(backKeyEventActionUp))
+            .thenReturn(false)
+
+        // WHEN back key event ACTION_DOWN, the event is handled even though back isn't requested
+        assertThat(underTest.dispatchKeyEvent(backKeyEventActionDown)).isTrue()
+        // THEN back event isn't handled on ACTION_DOWN
+        verify(backActionInteractor, never()).onBackRequested()
+
+        // WHEN back key event ACTION_UP
+        assertThat(underTest.dispatchKeyEvent(backKeyEventActionUp)).isTrue()
+        // THEN back event is handled on ACTION_UP
+        verify(backActionInteractor).onBackRequested()
+    }
+
+    @Test
+    fun dispatchKeyEvent_isNotHandledByKeyguardKeyEventInteractor() {
+        val keyEvent =
+            KeyEvent(
+                KeyEvent.ACTION_UP,
+                KeyEvent.KEYCODE_SPACE,
+            )
+        whenever(keyguardKeyEventInteractor.dispatchKeyEvent(eq(keyEvent))).thenReturn(false)
+        assertThat(underTest.dispatchKeyEvent(keyEvent)).isFalse()
+    }
+
+    @Test
+    fun dispatchKeyEvent_handledByKeyguardKeyEventInteractor() {
+        val keyEvent =
+            KeyEvent(
+                KeyEvent.ACTION_UP,
+                KeyEvent.KEYCODE_SPACE,
+            )
+        whenever(keyguardKeyEventInteractor.dispatchKeyEvent(eq(keyEvent))).thenReturn(true)
+        assertThat(underTest.dispatchKeyEvent(keyEvent)).isTrue()
+    }
+
+    @Test
+    fun interceptMediaKey_isNotHandledByKeyguardKeyEventInteractor() {
+        val keyEvent =
+            KeyEvent(
+                KeyEvent.ACTION_UP,
+                KeyEvent.KEYCODE_SPACE,
+            )
+        whenever(keyguardKeyEventInteractor.interceptMediaKey(eq(keyEvent))).thenReturn(false)
+        assertThat(underTest.interceptMediaKey(keyEvent)).isFalse()
+    }
+
+    @Test
+    fun interceptMediaKey_handledByKeyguardKeyEventInteractor() {
+        val keyEvent =
+            KeyEvent(
+                KeyEvent.ACTION_UP,
+                KeyEvent.KEYCODE_SPACE,
+            )
+        whenever(keyguardKeyEventInteractor.interceptMediaKey(eq(keyEvent))).thenReturn(true)
+        assertThat(underTest.interceptMediaKey(keyEvent)).isTrue()
+    }
+
+    @Test
+    fun dispatchKeyEventPreIme_isNotHandledByKeyguardKeyEventInteractor() {
+        val keyEvent =
+            KeyEvent(
+                KeyEvent.ACTION_UP,
+                KeyEvent.KEYCODE_SPACE,
+            )
+        whenever(keyguardKeyEventInteractor.dispatchKeyEventPreIme(eq(keyEvent))).thenReturn(false)
+        assertThat(underTest.dispatchKeyEventPreIme(keyEvent)).isFalse()
+    }
+
+    @Test
+    fun dispatchKeyEventPreIme_handledByKeyguardKeyEventInteractor() {
+        val keyEvent =
+            KeyEvent(
+                KeyEvent.ACTION_UP,
+                KeyEvent.KEYCODE_SPACE,
+            )
+        whenever(keyguardKeyEventInteractor.dispatchKeyEventPreIme(eq(keyEvent))).thenReturn(true)
+        assertThat(underTest.dispatchKeyEventPreIme(keyEvent)).isTrue()
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java
index 28328c2..4a79a21 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java
@@ -236,7 +236,7 @@
                 mScreenOffAnimationController, mAuthController, mShadeExpansionStateManager,
                 mShadeWindowLogger);
         mFeatureFlags = new FakeFeatureFlags();
-
+        mFeatureFlags.set(Flags.KEYGUARD_WM_STATE_REFACTOR, false);
 
         DejankUtils.setImmediate(true);
 
@@ -634,6 +634,7 @@
         TestableLooper.get(this).processAllMessages();
 
         assertFalse(mViewMediator.isShowingAndNotOccluded());
+        verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(false);
     }
 
     @Test
@@ -650,6 +651,7 @@
         TestableLooper.get(this).processAllMessages();
 
         assertTrue(mViewMediator.isShowingAndNotOccluded());
+        verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(true);
     }
 
     @Test
@@ -658,6 +660,9 @@
         startMockKeyguardExitAnimation();
         cancelMockKeyguardExitAnimation();
 
+        // Calling cancel above results in keyguard not visible, as there is no pending lock
+        verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(false);
+
         mViewMediator.maybeHandlePendingLock();
         TestableLooper.get(this).processAllMessages();
 
@@ -672,10 +677,15 @@
 
     @Test
     @TestableLooper.RunWithLooper(setAsMainLooper = true)
-    public void testStartKeyguardExitAnimation_expectSurfaceBehindRemoteAnimation() {
+    public void testStartKeyguardExitAnimation_expectSurfaceBehindRemoteAnimationAndExits() {
         startMockKeyguardExitAnimation();
         assertTrue(mViewMediator.isAnimatingBetweenKeyguardAndSurfaceBehind());
 
+        mViewMediator.mViewMediatorCallback.keyguardDonePending(true,
+                mUpdateMonitor.getCurrentUser());
+        mViewMediator.mViewMediatorCallback.readyForKeyguardDone();
+        TestableLooper.get(this).processAllMessages();
+        verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(false);
     }
 
     @Test
@@ -1058,7 +1068,8 @@
                 mSystemClock,
                 mDispatcher,
                 () -> mDreamingToLockscreenTransitionViewModel,
-                mSystemPropertiesHelper);
+                mSystemPropertiesHelper,
+                () -> mock(WindowManagerLockscreenVisibilityManager.class));
         mViewMediator.start();
 
         mViewMediator.registerCentralSurfaces(mCentralSurfaces, null, null, null, null, null);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/quickaffordance/QrCodeScannerKeyguardQuickAffordanceConfigTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/quickaffordance/QrCodeScannerKeyguardQuickAffordanceConfigTest.kt
index 7510373..9d983b8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/quickaffordance/QrCodeScannerKeyguardQuickAffordanceConfigTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/quickaffordance/QrCodeScannerKeyguardQuickAffordanceConfigTest.kt
@@ -137,27 +137,18 @@
     }
 
     @Test
-    fun getPickerScreenState_enabledIfConfiguredOnDevice_canOpenCamera() = runTest {
-        whenever(controller.isAvailableOnDevice).thenReturn(true)
-        whenever(controller.isAbleToOpenCameraApp).thenReturn(true)
+    fun getPickerScreenState_enabledIfConfiguredOnDevice_isEnabledForPickerState() = runTest {
+        whenever(controller.isAllowedOnLockScreen).thenReturn(true)
+        whenever(controller.isAbleToLaunchScannerActivity).thenReturn(true)
 
         assertThat(underTest.getPickerScreenState())
             .isEqualTo(KeyguardQuickAffordanceConfig.PickerScreenState.Default())
     }
 
     @Test
-    fun getPickerScreenState_disabledIfConfiguredOnDevice_cannotOpenCamera() = runTest {
-        whenever(controller.isAvailableOnDevice).thenReturn(true)
-        whenever(controller.isAbleToOpenCameraApp).thenReturn(false)
-
-        assertThat(underTest.getPickerScreenState())
-            .isInstanceOf(KeyguardQuickAffordanceConfig.PickerScreenState.Disabled::class.java)
-    }
-
-    @Test
-    fun getPickerScreenState_unavailableIfNotConfiguredOnDevice() = runTest {
-        whenever(controller.isAvailableOnDevice).thenReturn(false)
-        whenever(controller.isAbleToOpenCameraApp).thenReturn(true)
+    fun getPickerScreenState_disabledIfConfiguredOnDevice_isDisabledForPickerState() = runTest {
+        whenever(controller.isAllowedOnLockScreen).thenReturn(true)
+        whenever(controller.isAbleToLaunchScannerActivity).thenReturn(false)
 
         assertThat(underTest.getPickerScreenState())
             .isEqualTo(KeyguardQuickAffordanceConfig.PickerScreenState.UnavailableOnDevice)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/BiometricSettingsRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/BiometricSettingsRepositoryTest.kt
index c6a2fa5..a6930d5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/BiometricSettingsRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/BiometricSettingsRepositoryTest.kt
@@ -36,6 +36,11 @@
 import com.android.systemui.RoboPilotTest
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.biometrics.AuthController
+import com.android.systemui.biometrics.data.repository.FaceSensorInfo
+import com.android.systemui.biometrics.data.repository.FakeFacePropertyRepository
+import com.android.systemui.biometrics.data.repository.FakeFingerprintPropertyRepository
+import com.android.systemui.biometrics.shared.model.FingerprintSensorType
+import com.android.systemui.biometrics.shared.model.SensorStrength
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.dump.DumpManager
 import com.android.systemui.keyguard.data.repository.BiometricType.FACE
@@ -63,6 +68,7 @@
 import org.mockito.ArgumentMatchers.isNull
 import org.mockito.Captor
 import org.mockito.Mock
+import org.mockito.Mockito.atLeastOnce
 import org.mockito.Mockito.clearInvocations
 import org.mockito.Mockito.times
 import org.mockito.Mockito.verify
@@ -89,6 +95,8 @@
         ArgumentCaptor<IBiometricEnabledOnKeyguardCallback.Stub>
     private lateinit var userRepository: FakeUserRepository
     private lateinit var devicePostureRepository: FakeDevicePostureRepository
+    private lateinit var facePropertyRepository: FakeFacePropertyRepository
+    private lateinit var fingerprintPropertyRepository: FakeFingerprintPropertyRepository
 
     private lateinit var testDispatcher: TestDispatcher
     private lateinit var testScope: TestScope
@@ -102,6 +110,8 @@
         testScope = TestScope(testDispatcher)
         userRepository = FakeUserRepository()
         devicePostureRepository = FakeDevicePostureRepository()
+        facePropertyRepository = FakeFacePropertyRepository()
+        fingerprintPropertyRepository = FakeFingerprintPropertyRepository()
     }
 
     private suspend fun createBiometricSettingsRepository() {
@@ -120,74 +130,110 @@
                 biometricManager = biometricManager,
                 devicePostureRepository = devicePostureRepository,
                 dumpManager = dumpManager,
+                facePropertyRepository = facePropertyRepository,
+                fingerprintPropertyRepository = fingerprintPropertyRepository,
             )
         testScope.runCurrent()
+        fingerprintPropertyRepository.setProperties(
+            1,
+            SensorStrength.STRONG,
+            FingerprintSensorType.UDFPS_OPTICAL,
+            emptyMap()
+        )
         verify(lockPatternUtils).registerStrongAuthTracker(strongAuthTracker.capture())
+        verify(authController, atLeastOnce()).addCallback(authControllerCallback.capture())
     }
 
     @Test
     fun fingerprintEnrollmentChange() =
         testScope.runTest {
             createBiometricSettingsRepository()
-            val fingerprintEnrolled = collectLastValue(underTest.isFingerprintEnrolled)
+            val fingerprintAllowed = collectLastValue(underTest.isFingerprintEnrolledAndEnabled)
             runCurrent()
 
-            verify(authController).addCallback(authControllerCallback.capture())
             whenever(authController.isFingerprintEnrolled(anyInt())).thenReturn(true)
             enrollmentChange(UNDER_DISPLAY_FINGERPRINT, PRIMARY_USER_ID, true)
-            assertThat(fingerprintEnrolled()).isTrue()
+            assertThat(fingerprintAllowed()).isTrue()
 
             whenever(authController.isFingerprintEnrolled(anyInt())).thenReturn(false)
             enrollmentChange(UNDER_DISPLAY_FINGERPRINT, ANOTHER_USER_ID, false)
-            assertThat(fingerprintEnrolled()).isTrue()
+            assertThat(fingerprintAllowed()).isTrue()
 
             enrollmentChange(UNDER_DISPLAY_FINGERPRINT, PRIMARY_USER_ID, false)
-            assertThat(fingerprintEnrolled()).isFalse()
+            assertThat(fingerprintAllowed()).isFalse()
         }
 
     @Test
     fun strongBiometricAllowedChange() =
         testScope.runTest {
+            fingerprintIsEnrolled()
+            doNotDisableKeyguardAuthFeatures()
             createBiometricSettingsRepository()
-            val strongBiometricAllowed = collectLastValue(underTest.isStrongBiometricAllowed)
+
+            val strongBiometricAllowed by
+                collectLastValue(underTest.isFingerprintAuthCurrentlyAllowed)
             runCurrent()
 
             onStrongAuthChanged(STRONG_AUTH_NOT_REQUIRED, PRIMARY_USER_ID)
-            assertThat(strongBiometricAllowed()).isTrue()
+            assertThat(strongBiometricAllowed).isTrue()
 
             onStrongAuthChanged(STRONG_AUTH_REQUIRED_AFTER_BOOT, PRIMARY_USER_ID)
-            assertThat(strongBiometricAllowed()).isFalse()
+            assertThat(strongBiometricAllowed).isFalse()
         }
 
     @Test
     fun convenienceBiometricAllowedChange() =
         testScope.runTest {
             overrideResource(com.android.internal.R.bool.config_strongAuthRequiredOnBoot, false)
+            deviceIsInPostureThatSupportsFaceAuth()
+            faceAuthIsEnrolled()
+            faceAuthIsNonStrongBiometric()
             createBiometricSettingsRepository()
-            val convenienceBiometricAllowed =
-                collectLastValue(underTest.isNonStrongBiometricAllowed)
-            runCurrent()
+            val convenienceFaceAuthAllowed by collectLastValue(underTest.isFaceAuthCurrentlyAllowed)
+            doNotDisableKeyguardAuthFeatures()
+            faceAuthIsEnabledByBiometricManager()
+
+            onStrongAuthChanged(STRONG_AUTH_NOT_REQUIRED, PRIMARY_USER_ID)
             onNonStrongAuthChanged(true, PRIMARY_USER_ID)
-            assertThat(convenienceBiometricAllowed()).isTrue()
+            runCurrent()
+            assertThat(convenienceFaceAuthAllowed).isTrue()
 
             onNonStrongAuthChanged(false, ANOTHER_USER_ID)
-            assertThat(convenienceBiometricAllowed()).isTrue()
+            assertThat(convenienceFaceAuthAllowed).isTrue()
 
             onNonStrongAuthChanged(false, PRIMARY_USER_ID)
-            assertThat(convenienceBiometricAllowed()).isFalse()
+            assertThat(convenienceFaceAuthAllowed).isFalse()
             mContext.orCreateTestableResources.removeOverride(
                 com.android.internal.R.bool.config_strongAuthRequiredOnBoot
             )
         }
 
+    private fun faceAuthIsNonStrongBiometric() {
+        facePropertyRepository.setSensorInfo(FaceSensorInfo(1, SensorStrength.CONVENIENCE))
+    }
+
+    private fun faceAuthIsStrongBiometric() {
+        facePropertyRepository.setSensorInfo(FaceSensorInfo(1, SensorStrength.STRONG))
+    }
+
+    private fun deviceIsInPostureThatSupportsFaceAuth() {
+        overrideResource(
+            R.integer.config_face_auth_supported_posture,
+            DevicePostureController.DEVICE_POSTURE_FLIPPED
+        )
+        devicePostureRepository.setCurrentPosture(DevicePosture.FLIPPED)
+    }
+
     @Test
     fun whenStrongAuthRequiredAfterBoot_nonStrongBiometricNotAllowed() =
         testScope.runTest {
             overrideResource(com.android.internal.R.bool.config_strongAuthRequiredOnBoot, true)
             createBiometricSettingsRepository()
+            faceAuthIsNonStrongBiometric()
+            faceAuthIsEnrolled()
+            doNotDisableKeyguardAuthFeatures()
 
-            val convenienceBiometricAllowed =
-                collectLastValue(underTest.isNonStrongBiometricAllowed)
+            val convenienceBiometricAllowed = collectLastValue(underTest.isFaceAuthCurrentlyAllowed)
             runCurrent()
             onNonStrongAuthChanged(true, PRIMARY_USER_ID)
 
@@ -201,16 +247,24 @@
     fun whenStrongBiometricAuthIsNotAllowed_nonStrongBiometrics_alsoNotAllowed() =
         testScope.runTest {
             overrideResource(com.android.internal.R.bool.config_strongAuthRequiredOnBoot, false)
+            faceAuthIsNonStrongBiometric()
+            deviceIsInPostureThatSupportsFaceAuth()
+            faceAuthIsEnrolled()
             createBiometricSettingsRepository()
-
-            val convenienceBiometricAllowed =
-                collectLastValue(underTest.isNonStrongBiometricAllowed)
+            doNotDisableKeyguardAuthFeatures()
+            faceAuthIsEnabledByBiometricManager()
             runCurrent()
+
+            val convenienceBiometricAllowed by
+                collectLastValue(underTest.isFaceAuthCurrentlyAllowed)
+
+            onStrongAuthChanged(STRONG_AUTH_NOT_REQUIRED, PRIMARY_USER_ID)
             onNonStrongAuthChanged(true, PRIMARY_USER_ID)
-            assertThat(convenienceBiometricAllowed()).isTrue()
+            runCurrent()
+            assertThat(convenienceBiometricAllowed).isTrue()
 
             onStrongAuthChanged(STRONG_AUTH_REQUIRED_AFTER_TIMEOUT, PRIMARY_USER_ID)
-            assertThat(convenienceBiometricAllowed()).isFalse()
+            assertThat(convenienceBiometricAllowed).isFalse()
             mContext.orCreateTestableResources.removeOverride(
                 com.android.internal.R.bool.config_strongAuthRequiredOnBoot
             )
@@ -229,9 +283,11 @@
     @Test
     fun fingerprintDisabledByDpmChange() =
         testScope.runTest {
+            fingerprintIsEnrolled(PRIMARY_USER_ID)
             createBiometricSettingsRepository()
+
             val fingerprintEnabledByDevicePolicy =
-                collectLastValue(underTest.isFingerprintEnabledByDevicePolicy)
+                collectLastValue(underTest.isFingerprintEnrolledAndEnabled)
             runCurrent()
 
             whenever(devicePolicyManager.getKeyguardDisabledFeatures(any(), anyInt()))
@@ -244,43 +300,57 @@
             assertThat(fingerprintEnabledByDevicePolicy()).isTrue()
         }
 
+    private fun fingerprintIsEnrolled(userId: Int = PRIMARY_USER_ID) {
+        whenever(authController.isFingerprintEnrolled(userId)).thenReturn(true)
+    }
+
     @Test
     fun faceEnrollmentChangeIsPropagatedForTheCurrentUser() =
         testScope.runTest {
             createBiometricSettingsRepository()
+            faceAuthIsEnabledByBiometricManager()
+
+            doNotDisableKeyguardAuthFeatures(PRIMARY_USER_ID)
+
             runCurrent()
             clearInvocations(authController)
 
             whenever(authController.isFaceAuthEnrolled(PRIMARY_USER_ID)).thenReturn(false)
-            val faceEnrolled = collectLastValue(underTest.isFaceEnrolled)
+            val faceAuthAllowed = collectLastValue(underTest.isFaceAuthEnrolledAndEnabled)
 
-            assertThat(faceEnrolled()).isFalse()
+            assertThat(faceAuthAllowed()).isFalse()
             verify(authController).addCallback(authControllerCallback.capture())
             enrollmentChange(REAR_FINGERPRINT, PRIMARY_USER_ID, true)
 
-            assertThat(faceEnrolled()).isFalse()
+            assertThat(faceAuthAllowed()).isFalse()
 
             enrollmentChange(SIDE_FINGERPRINT, PRIMARY_USER_ID, true)
 
-            assertThat(faceEnrolled()).isFalse()
+            assertThat(faceAuthAllowed()).isFalse()
 
             enrollmentChange(UNDER_DISPLAY_FINGERPRINT, PRIMARY_USER_ID, true)
 
-            assertThat(faceEnrolled()).isFalse()
+            assertThat(faceAuthAllowed()).isFalse()
 
             whenever(authController.isFaceAuthEnrolled(ANOTHER_USER_ID)).thenReturn(true)
 
             enrollmentChange(FACE, ANOTHER_USER_ID, true)
 
-            assertThat(faceEnrolled()).isFalse()
+            assertThat(faceAuthAllowed()).isFalse()
 
-            whenever(authController.isFaceAuthEnrolled(PRIMARY_USER_ID)).thenReturn(true)
+            faceAuthIsEnrolled()
 
             enrollmentChange(FACE, PRIMARY_USER_ID, true)
 
-            assertThat(faceEnrolled()).isTrue()
+            assertThat(faceAuthAllowed()).isTrue()
         }
 
+    private fun faceAuthIsEnabledByBiometricManager(userId: Int = PRIMARY_USER_ID) {
+        verify(biometricManager, atLeastOnce())
+            .registerEnabledOnKeyguardCallback(biometricManagerCallback.capture())
+        biometricManagerCallback.value.onChanged(true, userId)
+    }
+
     @Test
     fun faceEnrollmentStatusOfNewUserUponUserSwitch() =
         testScope.runTest {
@@ -290,21 +360,26 @@
 
             whenever(authController.isFaceAuthEnrolled(PRIMARY_USER_ID)).thenReturn(false)
             whenever(authController.isFaceAuthEnrolled(ANOTHER_USER_ID)).thenReturn(true)
-            val faceEnrolled = collectLastValue(underTest.isFaceEnrolled)
+            val faceAuthAllowed = collectLastValue(underTest.isFaceAuthEnrolledAndEnabled)
 
-            assertThat(faceEnrolled()).isFalse()
+            assertThat(faceAuthAllowed()).isFalse()
         }
 
     @Test
     fun faceEnrollmentChangesArePropagatedAfterUserSwitch() =
         testScope.runTest {
             createBiometricSettingsRepository()
+            verify(biometricManager)
+                .registerEnabledOnKeyguardCallback(biometricManagerCallback.capture())
 
             userRepository.setSelectedUserInfo(ANOTHER_USER)
+            doNotDisableKeyguardAuthFeatures(ANOTHER_USER_ID)
+            biometricManagerCallback.value.onChanged(true, ANOTHER_USER_ID)
+
             runCurrent()
             clearInvocations(authController)
 
-            val faceEnrolled = collectLastValue(underTest.isFaceEnrolled)
+            val faceAuthAllowed = collectLastValue(underTest.isFaceAuthEnrolledAndEnabled)
             runCurrent()
 
             verify(authController).addCallback(authControllerCallback.capture())
@@ -312,12 +387,14 @@
             whenever(authController.isFaceAuthEnrolled(ANOTHER_USER_ID)).thenReturn(true)
             enrollmentChange(FACE, ANOTHER_USER_ID, true)
 
-            assertThat(faceEnrolled()).isTrue()
+            assertThat(faceAuthAllowed()).isTrue()
         }
 
     @Test
     fun devicePolicyControlsFaceAuthenticationEnabledState() =
         testScope.runTest {
+            faceAuthIsEnrolled()
+
             createBiometricSettingsRepository()
             verify(biometricManager)
                 .registerEnabledOnKeyguardCallback(biometricManagerCallback.capture())
@@ -325,62 +402,70 @@
             whenever(devicePolicyManager.getKeyguardDisabledFeatures(isNull(), eq(PRIMARY_USER_ID)))
                 .thenReturn(KEYGUARD_DISABLE_FINGERPRINT or KEYGUARD_DISABLE_FACE)
 
-            val isFaceAuthEnabled = collectLastValue(underTest.isFaceAuthenticationEnabled)
+            val isFaceAuthAllowed = collectLastValue(underTest.isFaceAuthEnrolledAndEnabled)
             runCurrent()
 
             broadcastDPMStateChange()
 
-            assertThat(isFaceAuthEnabled()).isFalse()
+            assertThat(isFaceAuthAllowed()).isFalse()
 
             biometricManagerCallback.value.onChanged(true, PRIMARY_USER_ID)
             runCurrent()
-            assertThat(isFaceAuthEnabled()).isFalse()
+            assertThat(isFaceAuthAllowed()).isFalse()
 
             whenever(devicePolicyManager.getKeyguardDisabledFeatures(isNull(), eq(PRIMARY_USER_ID)))
                 .thenReturn(KEYGUARD_DISABLE_FINGERPRINT)
             broadcastDPMStateChange()
 
-            assertThat(isFaceAuthEnabled()).isTrue()
+            assertThat(isFaceAuthAllowed()).isTrue()
         }
 
     @Test
     fun biometricManagerControlsFaceAuthenticationEnabledStatus() =
         testScope.runTest {
+            faceAuthIsEnrolled()
+
             createBiometricSettingsRepository()
             verify(biometricManager)
                 .registerEnabledOnKeyguardCallback(biometricManagerCallback.capture())
             whenever(devicePolicyManager.getKeyguardDisabledFeatures(isNull(), eq(PRIMARY_USER_ID)))
                 .thenReturn(0)
             broadcastDPMStateChange()
-            val isFaceAuthEnabled = collectLastValue(underTest.isFaceAuthenticationEnabled)
+            val isFaceAuthAllowed = collectLastValue(underTest.isFaceAuthEnrolledAndEnabled)
 
-            assertThat(isFaceAuthEnabled()).isFalse()
+            assertThat(isFaceAuthAllowed()).isFalse()
 
             // Value changes for another user
             biometricManagerCallback.value.onChanged(true, ANOTHER_USER_ID)
 
-            assertThat(isFaceAuthEnabled()).isFalse()
+            assertThat(isFaceAuthAllowed()).isFalse()
 
             // Value changes for current user.
             biometricManagerCallback.value.onChanged(true, PRIMARY_USER_ID)
 
-            assertThat(isFaceAuthEnabled()).isTrue()
+            assertThat(isFaceAuthAllowed()).isTrue()
         }
 
+    private fun faceAuthIsEnrolled(userId: Int = PRIMARY_USER_ID) {
+        whenever(authController.isFaceAuthEnrolled(userId)).thenReturn(true)
+    }
+
     @Test
     fun userChange_biometricEnabledChange_handlesRaceCondition() =
         testScope.runTest {
             createBiometricSettingsRepository()
+            whenever(authController.isFaceAuthEnrolled(ANOTHER_USER_ID)).thenReturn(true)
+
             verify(biometricManager)
                 .registerEnabledOnKeyguardCallback(biometricManagerCallback.capture())
-            val isFaceAuthEnabled = collectLastValue(underTest.isFaceAuthenticationEnabled)
+            val isFaceAuthAllowed = collectLastValue(underTest.isFaceAuthEnrolledAndEnabled)
             biometricManagerCallback.value.onChanged(true, ANOTHER_USER_ID)
             runCurrent()
 
             userRepository.setSelectedUserInfo(ANOTHER_USER)
             runCurrent()
 
-            assertThat(isFaceAuthEnabled()).isTrue()
+            assertThat(isFaceAuthAllowed()).isTrue()
         }
 
     @Test
@@ -388,9 +473,9 @@
         testScope.runTest {
             createBiometricSettingsRepository()
 
-            collectLastValue(underTest.isFaceAuthenticationEnabled)()
-            collectLastValue(underTest.isFaceAuthenticationEnabled)()
-            collectLastValue(underTest.isFaceAuthenticationEnabled)()
+            collectLastValue(underTest.isFaceAuthEnrolledAndEnabled)()
+            collectLastValue(underTest.isFaceAuthEnrolledAndEnabled)()
+            collectLastValue(underTest.isFaceAuthEnrolledAndEnabled)()
 
             verify(biometricManager, times(1)).registerEnabledOnKeyguardCallback(any())
         }
@@ -495,10 +580,138 @@
             assertThat(authFlags()!!.flag).isEqualTo(STRONG_AUTH_REQUIRED_AFTER_TIMEOUT)
         }
 
+    @Test
+    fun faceAuthCurrentlyAllowed_dependsOnStrongAuthBiometricSetting_ifFaceIsClass3() =
+        testScope.runTest {
+            createBiometricSettingsRepository()
+            val isFaceAuthCurrentlyAllowed by collectLastValue(underTest.isFaceAuthCurrentlyAllowed)
+
+            faceAuthIsEnrolled()
+            deviceIsInPostureThatSupportsFaceAuth()
+            doNotDisableKeyguardAuthFeatures()
+            faceAuthIsStrongBiometric()
+            faceAuthIsEnabledByBiometricManager()
+
+            onStrongAuthChanged(STRONG_AUTH_NOT_REQUIRED, PRIMARY_USER_ID)
+            onNonStrongAuthChanged(false, PRIMARY_USER_ID)
+
+            assertThat(isFaceAuthCurrentlyAllowed).isTrue()
+
+            onStrongAuthChanged(STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN, PRIMARY_USER_ID)
+            onNonStrongAuthChanged(true, PRIMARY_USER_ID)
+
+            assertThat(isFaceAuthCurrentlyAllowed).isFalse()
+        }
+
+    @Test
+    fun faceAuthCurrentlyAllowed_dependsOnNonStrongAuthBiometricSetting_ifFaceIsNotStrong() =
+        testScope.runTest {
+            createBiometricSettingsRepository()
+            val isFaceAuthCurrentlyAllowed by collectLastValue(underTest.isFaceAuthCurrentlyAllowed)
+
+            faceAuthIsEnrolled()
+            deviceIsInPostureThatSupportsFaceAuth()
+            doNotDisableKeyguardAuthFeatures()
+            faceAuthIsNonStrongBiometric()
+            faceAuthIsEnabledByBiometricManager()
+
+            onStrongAuthChanged(STRONG_AUTH_NOT_REQUIRED, PRIMARY_USER_ID)
+            onNonStrongAuthChanged(false, PRIMARY_USER_ID)
+
+            assertThat(isFaceAuthCurrentlyAllowed).isFalse()
+
+            onStrongAuthChanged(STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN, PRIMARY_USER_ID)
+            onNonStrongAuthChanged(true, PRIMARY_USER_ID)
+
+            assertThat(isFaceAuthCurrentlyAllowed).isFalse()
+
+            onStrongAuthChanged(STRONG_AUTH_NOT_REQUIRED, PRIMARY_USER_ID)
+            onNonStrongAuthChanged(true, PRIMARY_USER_ID)
+
+            assertThat(isFaceAuthCurrentlyAllowed).isTrue()
+        }
+
+    @Test
+    fun fpAuthCurrentlyAllowed_dependsOnNonStrongAuthBiometricSetting_ifFpIsNotStrong() =
+        testScope.runTest {
+            createBiometricSettingsRepository()
+            val isFingerprintCurrentlyAllowed by
+                collectLastValue(underTest.isFingerprintAuthCurrentlyAllowed)
+
+            fingerprintIsEnrolled(PRIMARY_USER_ID)
+            enrollmentChange(UNDER_DISPLAY_FINGERPRINT, PRIMARY_USER_ID, true)
+            doNotDisableKeyguardAuthFeatures(PRIMARY_USER_ID)
+            runCurrent()
+
+            fingerprintPropertyRepository.setProperties(
+                1,
+                SensorStrength.STRONG,
+                FingerprintSensorType.UDFPS_OPTICAL,
+                emptyMap()
+            )
+            // Non strong auth is not allowed now, FP is marked strong
+            onStrongAuthChanged(STRONG_AUTH_NOT_REQUIRED, PRIMARY_USER_ID)
+            onNonStrongAuthChanged(false, PRIMARY_USER_ID)
+
+            assertThat(isFingerprintCurrentlyAllowed).isTrue()
+
+            fingerprintPropertyRepository.setProperties(
+                1,
+                SensorStrength.CONVENIENCE,
+                FingerprintSensorType.UDFPS_OPTICAL,
+                emptyMap()
+            )
+            assertThat(isFingerprintCurrentlyAllowed).isFalse()
+
+            fingerprintPropertyRepository.setProperties(
+                1,
+                SensorStrength.WEAK,
+                FingerprintSensorType.UDFPS_OPTICAL,
+                emptyMap()
+            )
+            assertThat(isFingerprintCurrentlyAllowed).isFalse()
+        }
+
+    @Test
+    fun fpAuthCurrentlyAllowed_dependsOnStrongAuthBiometricSetting_ifFpIsStrong() =
+        testScope.runTest {
+            createBiometricSettingsRepository()
+            val isFingerprintCurrentlyAllowed by
+                collectLastValue(underTest.isFingerprintAuthCurrentlyAllowed)
+
+            fingerprintIsEnrolled(PRIMARY_USER_ID)
+            enrollmentChange(UNDER_DISPLAY_FINGERPRINT, PRIMARY_USER_ID, true)
+            doNotDisableKeyguardAuthFeatures(PRIMARY_USER_ID)
+            runCurrent()
+
+            fingerprintPropertyRepository.setProperties(
+                1,
+                SensorStrength.STRONG,
+                FingerprintSensorType.UDFPS_OPTICAL,
+                emptyMap()
+            )
+            // Non strong auth is not allowed now, FP is marked strong
+            onStrongAuthChanged(STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN, PRIMARY_USER_ID)
+            onNonStrongAuthChanged(true, PRIMARY_USER_ID)
+
+            assertThat(isFingerprintCurrentlyAllowed).isFalse()
+
+            onStrongAuthChanged(STRONG_AUTH_NOT_REQUIRED, PRIMARY_USER_ID)
+            onNonStrongAuthChanged(false, PRIMARY_USER_ID)
+
+            assertThat(isFingerprintCurrentlyAllowed).isTrue()
+        }
+
     private fun enrollmentChange(biometricType: BiometricType, userId: Int, enabled: Boolean) {
         authControllerCallback.value.onEnrollmentsChanged(biometricType, userId, enabled)
     }
 
+    private fun doNotDisableKeyguardAuthFeatures(userId: Int = PRIMARY_USER_ID) {
+        whenever(devicePolicyManager.getKeyguardDisabledFeatures(isNull(), eq(userId)))
+            .thenReturn(0)
+        broadcastDPMStateChange()
+    }
+
     private fun broadcastDPMStateChange() {
         fakeBroadcastDispatcher.sendIntentToMatchingReceiversOnly(
             context,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/DeviceEntryFaceAuthRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/DeviceEntryFaceAuthRepositoryTest.kt
index 85ee0e4..64b9470 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/DeviceEntryFaceAuthRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/DeviceEntryFaceAuthRepositoryTest.kt
@@ -40,9 +40,7 @@
 import com.android.systemui.R
 import com.android.systemui.RoboPilotTest
 import com.android.systemui.SysuiTestCase
-import com.android.systemui.biometrics.data.repository.FaceSensorInfo
 import com.android.systemui.biometrics.data.repository.FakeFacePropertyRepository
-import com.android.systemui.biometrics.shared.model.SensorStrength
 import com.android.systemui.bouncer.data.repository.FakeKeyguardBouncerRepository
 import com.android.systemui.bouncer.domain.interactor.AlternateBouncerInteractor
 import com.android.systemui.coroutines.FlowValue
@@ -52,6 +50,7 @@
 import com.android.systemui.dump.logcatLogBuffer
 import com.android.systemui.flags.FakeFeatureFlags
 import com.android.systemui.flags.Flags.FACE_AUTH_REFACTOR
+import com.android.systemui.flags.Flags.KEYGUARD_WM_STATE_REFACTOR
 import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor
 import com.android.systemui.keyguard.domain.interactor.KeyguardInteractorFactory
 import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractorFactory
@@ -168,7 +167,11 @@
         biometricSettingsRepository = FakeBiometricSettingsRepository()
         deviceEntryFingerprintAuthRepository = FakeDeviceEntryFingerprintAuthRepository()
         trustRepository = FakeTrustRepository()
-        featureFlags = FakeFeatureFlags().apply { set(FACE_AUTH_REFACTOR, true) }
+        featureFlags =
+            FakeFeatureFlags().apply {
+                set(FACE_AUTH_REFACTOR, true)
+                set(KEYGUARD_WM_STATE_REFACTOR, false)
+            }
         val withDeps =
             KeyguardInteractorFactory.create(
                 featureFlags = featureFlags,
@@ -250,7 +253,6 @@
             faceAuthBuffer,
             keyguardTransitionInteractor,
             featureFlags,
-            fakeFacePropertyRepository,
             dumpManager,
         )
     }
@@ -332,9 +334,6 @@
                 )
                 .isFalse()
 
-            whenever(faceManager.sensorPropertiesInternal).thenReturn(null)
-            assertThat(createDeviceEntryFaceAuthRepositoryImpl().isDetectionSupported).isFalse()
-
             whenever(faceManager.sensorPropertiesInternal).thenReturn(listOf())
             assertThat(createDeviceEntryFaceAuthRepositoryImpl().isDetectionSupported).isFalse()
 
@@ -523,15 +522,11 @@
         }
 
     @Test
-    fun authenticateDoesNotRunIfFaceIsNotEnrolled() =
+    fun authenticateDoesNotRunIfFaceIsNotUsuallyAllowed() =
         testScope.runTest {
-            testGatingCheckForFaceAuth { biometricSettingsRepository.setFaceEnrolled(false) }
-        }
-
-    @Test
-    fun authenticateDoesNotRunIfFaceIsNotEnabled() =
-        testScope.runTest {
-            testGatingCheckForFaceAuth { biometricSettingsRepository.setIsFaceAuthEnabled(false) }
+            testGatingCheckForFaceAuth {
+                biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(false)
+            }
         }
 
     @Test
@@ -587,21 +582,10 @@
         }
 
     @Test
-    fun authenticateDoesNotRunWhenNonStrongBiometricIsNotAllowed() =
+    fun authenticateDoesNotRunWhenFaceAuthIsNotCurrentlyAllowedToRun() =
         testScope.runTest {
             testGatingCheckForFaceAuth {
-                biometricSettingsRepository.setIsNonStrongBiometricAllowed(false)
-            }
-        }
-
-    @Test
-    fun authenticateDoesNotRunWhenStrongBiometricIsNotAllowedAndFaceSensorIsStrong() =
-        testScope.runTest {
-            fakeFacePropertyRepository.setSensorInfo(FaceSensorInfo(1, SensorStrength.STRONG))
-            runCurrent()
-
-            testGatingCheckForFaceAuth(isFaceStrong = true) {
-                biometricSettingsRepository.setIsStrongBiometricAllowed(false)
+                biometricSettingsRepository.setIsFaceAuthCurrentlyAllowed(false)
             }
         }
 
@@ -660,7 +644,7 @@
             allPreconditionsToRunFaceAuthAreTrue()
 
             // Flip one precondition to false.
-            biometricSettingsRepository.setIsNonStrongBiometricAllowed(false)
+            biometricSettingsRepository.setIsFaceAuthCurrentlyAllowed(false)
             assertThat(canFaceAuthRun()).isFalse()
             underTest.authenticate(
                 FACE_AUTH_TRIGGERED_SWIPE_UP_ON_BOUNCER,
@@ -825,15 +809,11 @@
         }
 
     @Test
-    fun detectDoesNotRunWhenFaceIsNotEnrolled() =
+    fun detectDoesNotRunWhenFaceIsNotUsuallyAllowed() =
         testScope.runTest {
-            testGatingCheckForDetect { biometricSettingsRepository.setFaceEnrolled(false) }
-        }
-
-    @Test
-    fun detectDoesNotRunWhenFaceIsNotEnabled() =
-        testScope.runTest {
-            testGatingCheckForDetect { biometricSettingsRepository.setIsFaceAuthEnabled(false) }
+            testGatingCheckForDetect {
+                biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(false)
+            }
         }
 
     @Test
@@ -930,23 +910,10 @@
         }
 
     @Test
-    fun detectDoesNotRunWhenNonStrongBiometricIsAllowed() =
+    fun detectDoesNotRunWhenFaceAuthIsCurrentlyAllowedToRun() =
         testScope.runTest {
             testGatingCheckForDetect {
-                biometricSettingsRepository.setIsNonStrongBiometricAllowed(true)
-            }
-        }
-
-    @Test
-    fun detectDoesNotRunWhenStrongBiometricIsAllowedAndFaceAuthSensorStrengthIsStrong() =
-        testScope.runTest {
-            fakeFacePropertyRepository.setSensorInfo(FaceSensorInfo(1, SensorStrength.STRONG))
-            runCurrent()
-
-            testGatingCheckForDetect(isFaceStrong = true) {
-                biometricSettingsRepository.setIsStrongBiometricAllowed(true)
-                // this shouldn't matter as face is set as a strong sensor
-                biometricSettingsRepository.setIsNonStrongBiometricAllowed(false)
+                biometricSettingsRepository.setIsFaceAuthCurrentlyAllowed(true)
             }
         }
 
@@ -1041,12 +1008,9 @@
             faceAuthenticateIsCalled()
         }
 
-    private suspend fun TestScope.testGatingCheckForFaceAuth(
-        isFaceStrong: Boolean = false,
-        gatingCheckModifier: () -> Unit
-    ) {
+    private suspend fun TestScope.testGatingCheckForFaceAuth(gatingCheckModifier: () -> Unit) {
         initCollectors()
-        allPreconditionsToRunFaceAuthAreTrue(isFaceStrong)
+        allPreconditionsToRunFaceAuthAreTrue()
 
         gatingCheckModifier()
         runCurrent()
@@ -1055,7 +1019,7 @@
         assertThat(underTest.canRunFaceAuth.value).isFalse()
 
         // flip the gating check back on.
-        allPreconditionsToRunFaceAuthAreTrue(isFaceStrong)
+        allPreconditionsToRunFaceAuthAreTrue()
 
         triggerFaceAuth(false)
 
@@ -1074,19 +1038,12 @@
         faceAuthenticateIsNotCalled()
     }
 
-    private suspend fun TestScope.testGatingCheckForDetect(
-        isFaceStrong: Boolean = false,
-        gatingCheckModifier: () -> Unit
-    ) {
+    private suspend fun TestScope.testGatingCheckForDetect(gatingCheckModifier: () -> Unit) {
         initCollectors()
         allPreconditionsToRunFaceAuthAreTrue()
 
-        if (isFaceStrong) {
-            biometricSettingsRepository.setStrongBiometricAllowed(false)
-        } else {
-            // This will stop face auth from running but is required to be false for detect.
-            biometricSettingsRepository.setIsNonStrongBiometricAllowed(false)
-        }
+        // This will stop face auth from running but is required to be false for detect.
+        biometricSettingsRepository.setIsFaceAuthCurrentlyAllowed(false)
         runCurrent()
 
         assertThat(canFaceAuthRun()).isFalse()
@@ -1121,13 +1078,9 @@
         cancellationSignal.value.setOnCancelListener { wasAuthCancelled = true }
     }
 
-    private suspend fun TestScope.allPreconditionsToRunFaceAuthAreTrue(
-        isFaceStrong: Boolean = false
-    ) {
+    private suspend fun TestScope.allPreconditionsToRunFaceAuthAreTrue() {
         verify(faceManager, atLeastOnce())
             .addLockoutResetCallback(faceLockoutResetCallback.capture())
-        biometricSettingsRepository.setFaceEnrolled(true)
-        biometricSettingsRepository.setIsFaceAuthEnabled(true)
         underTest.resumeFaceAuth()
         trustRepository.setCurrentUserTrusted(false)
         keyguardRepository.setKeyguardGoingAway(false)
@@ -1138,14 +1091,11 @@
                 WakeSleepReason.OTHER
             )
         )
-        if (isFaceStrong) {
-            biometricSettingsRepository.setStrongBiometricAllowed(true)
-        } else {
-            biometricSettingsRepository.setIsNonStrongBiometricAllowed(true)
-        }
+        biometricSettingsRepository.setIsFaceAuthEnrolledAndEnabled(true)
+        biometricSettingsRepository.setIsFaceAuthSupportedInCurrentPosture(true)
+        biometricSettingsRepository.setIsFaceAuthCurrentlyAllowed(true)
         biometricSettingsRepository.setIsUserInLockdown(false)
         fakeUserRepository.setSelectedUserInfo(primaryUser)
-        biometricSettingsRepository.setIsFaceAuthSupportedInCurrentPosture(true)
         faceLockoutResetCallback.value.onLockoutReset(0)
         bouncerRepository.setAlternateVisible(true)
         keyguardRepository.setKeyguardShowing(true)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/KeyguardRepositoryImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/KeyguardRepositoryImplTest.kt
index 5e3376a..5ead16b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/KeyguardRepositoryImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/KeyguardRepositoryImplTest.kt
@@ -63,6 +63,7 @@
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.mockito.Mock
+import org.mockito.Mockito.atLeastOnce
 import org.mockito.Mockito.verify
 import org.mockito.MockitoAnnotations
 
@@ -193,7 +194,7 @@
             assertThat(underTest.isKeyguardShowing()).isFalse()
 
             val captor = argumentCaptor<KeyguardStateController.Callback>()
-            verify(keyguardStateController).addCallback(captor.capture())
+            verify(keyguardStateController, atLeastOnce()).addCallback(captor.capture())
 
             whenever(keyguardStateController.isShowing).thenReturn(true)
             captor.value.onKeyguardShowingChanged()
@@ -255,7 +256,7 @@
             assertThat(latest).isFalse()
 
             val captor = argumentCaptor<KeyguardStateController.Callback>()
-            verify(keyguardStateController).addCallback(captor.capture())
+            verify(keyguardStateController, atLeastOnce()).addCallback(captor.capture())
 
             whenever(keyguardStateController.isOccluded).thenReturn(true)
             captor.value.onKeyguardShowingChanged()
@@ -280,7 +281,7 @@
             assertThat(isKeyguardUnlocked).isFalse()
 
             val captor = argumentCaptor<KeyguardStateController.Callback>()
-            verify(keyguardStateController).addCallback(captor.capture())
+            verify(keyguardStateController, atLeastOnce()).addCallback(captor.capture())
 
             whenever(keyguardStateController.isUnlocked).thenReturn(true)
             captor.value.onUnlockedChanged()
@@ -454,7 +455,7 @@
             assertThat(latest).isFalse()
 
             val captor = argumentCaptor<KeyguardStateController.Callback>()
-            verify(keyguardStateController).addCallback(captor.capture())
+            verify(keyguardStateController, atLeastOnce()).addCallback(captor.capture())
 
             whenever(keyguardStateController.isKeyguardGoingAway).thenReturn(true)
             captor.value.onKeyguardGoingAwayChanged()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/KeyguardSurfaceBehindRepositoryImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/KeyguardSurfaceBehindRepositoryImplTest.kt
new file mode 100644
index 0000000..bed959f
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/KeyguardSurfaceBehindRepositoryImplTest.kt
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.data.repository
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectValues
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@OptIn(ExperimentalCoroutinesApi::class)
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class KeyguardSurfaceBehindRepositoryImplTest : SysuiTestCase() {
+    private val testScope = TestScope()
+
+    private lateinit var underTest: KeyguardSurfaceBehindRepositoryImpl
+
+    @Before
+    fun setUp() {
+        underTest = KeyguardSurfaceBehindRepositoryImpl()
+    }
+
+    @Test
+    fun testSetAnimatingSurface() {
+        testScope.runTest {
+            val values by collectValues(underTest.isAnimatingSurface)
+
+            runCurrent()
+            underTest.setAnimatingSurface(true)
+            runCurrent()
+            underTest.setAnimatingSurface(false)
+            runCurrent()
+
+            // Default (first) value should be false.
+            assertThat(values).isEqualTo(listOf(false, true, false))
+        }
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepositoryTest.kt
index dcaafe8..6fcf54c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepositoryTest.kt
@@ -17,8 +17,8 @@
 package com.android.systemui.keyguard.data.repository
 
 import android.graphics.Point
-import android.testing.AndroidTestingRunner
 import android.testing.TestableLooper
+import androidx.test.ext.junit.runners.AndroidJUnit4
 import androidx.test.filters.SmallTest
 import com.android.systemui.RoboPilotTest
 import com.android.systemui.SysuiTestCase
@@ -47,7 +47,7 @@
 @SmallTest
 @RoboPilotTest
 @OptIn(ExperimentalCoroutinesApi::class)
-@RunWith(AndroidTestingRunner::class)
+@RunWith(AndroidJUnit4::class)
 class LightRevealScrimRepositoryTest : SysuiTestCase() {
     private lateinit var fakeKeyguardRepository: FakeKeyguardRepository
     private lateinit var underTest: LightRevealScrimRepositoryImpl
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractorTest.kt
new file mode 100644
index 0000000..e2bf2f8
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/FromLockscreenTransitionInteractorTest.kt
@@ -0,0 +1,190 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.domain.interactor
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.coroutines.collectValues
+import com.android.systemui.flags.FakeFeatureFlags
+import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.keyguard.shared.model.TransitionState
+import com.android.systemui.keyguard.shared.model.TransitionStep
+import com.android.systemui.shade.data.repository.FakeShadeRepository
+import dagger.Lazy
+import junit.framework.Assert.assertEquals
+import junit.framework.Assert.assertTrue
+import junit.framework.Assert.fail
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@OptIn(ExperimentalCoroutinesApi::class)
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class FromLockscreenTransitionInteractorTest : KeyguardTransitionInteractorTestCase() {
+    private lateinit var underTest: FromLockscreenTransitionInteractor
+
+    // Override the fromLockscreenTransitionInteractor provider from the superclass so our underTest
+    // interactor is provided to any classes that need it.
+    override var fromLockscreenTransitionInteractorLazy: Lazy<FromLockscreenTransitionInteractor>? =
+        Lazy {
+            underTest
+        }
+
+    @Before
+    override fun setUp() {
+        super.setUp()
+
+        underTest =
+            FromLockscreenTransitionInteractor(
+                transitionRepository = super.transitionRepository,
+                transitionInteractor = super.transitionInteractor,
+                scope = super.testScope.backgroundScope,
+                keyguardInteractor = super.keyguardInteractor,
+                flags = FakeFeatureFlags(),
+                shadeRepository = FakeShadeRepository(),
+            )
+    }
+
+    @Test
+    fun testSurfaceBehindVisibility_nonNullOnlyForRelevantTransitions() =
+        testScope.runTest {
+            val values by collectValues(underTest.surfaceBehindVisibility)
+            runCurrent()
+
+            // Transition-specific surface visibility should be null ("don't care") initially.
+            assertEquals(
+                listOf(
+                    null,
+                ),
+                values
+            )
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.AOD,
+                )
+            )
+
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    null, // LOCKSCREEN -> AOD does not have any specific surface visibility.
+                ),
+                values
+            )
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.GONE,
+                )
+            )
+
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    null,
+                    true, // Surface is made visible immediately during LOCKSCREEN -> GONE
+                ),
+                values
+            )
+        }
+
+    @Test
+    fun testSurfaceBehindModel() =
+        testScope.runTest {
+            val values by collectValues(underTest.surfaceBehindModel)
+            runCurrent()
+
+            assertEquals(
+                values,
+                listOf(
+                    null, // We should start null ("don't care").
+                )
+            )
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.AOD,
+                )
+            )
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    null, // LOCKSCREEN -> AOD does not have specific view params.
+                ),
+                values
+            )
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.GONE,
+                )
+            )
+            runCurrent()
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.RUNNING,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.GONE,
+                    value = 0.01f,
+                )
+            )
+            runCurrent()
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.RUNNING,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.GONE,
+                    value = 0.99f,
+                )
+            )
+            runCurrent()
+
+            assertEquals(3, values.size)
+            val model1percent = values[1]
+            val model99percent = values[2]
+
+            try {
+                // We should initially have an alpha of 0f when unlocking, so the surface is not
+                // visible
+                // while lockscreen UI animates out.
+                assertEquals(0f, model1percent!!.alpha)
+
+                // By the end it should probably be visible.
+                assertTrue(model99percent!!.alpha > 0f)
+            } catch (e: NullPointerException) {
+                fail("surfaceBehindModel was unexpectedly null.")
+            }
+        }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractorTest.kt
new file mode 100644
index 0000000..85bc374
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractorTest.kt
@@ -0,0 +1,214 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.domain.interactor
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.coroutines.collectValues
+import com.android.systemui.flags.FakeFeatureFlags
+import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.keyguard.shared.model.TransitionState
+import com.android.systemui.keyguard.shared.model.TransitionStep
+import com.android.systemui.util.mockito.mock
+import dagger.Lazy
+import junit.framework.Assert.assertEquals
+import junit.framework.Assert.assertTrue
+import junit.framework.Assert.fail
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@OptIn(ExperimentalCoroutinesApi::class)
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class FromPrimaryBouncerTransitionInteractorTest : KeyguardTransitionInteractorTestCase() {
+    private lateinit var underTest: FromPrimaryBouncerTransitionInteractor
+
+    // Override the fromPrimaryBouncerTransitionInteractor provider from the superclass so our
+    // underTest interactor is provided to any classes that need it.
+    override var fromPrimaryBouncerTransitionInteractorLazy:
+        Lazy<FromPrimaryBouncerTransitionInteractor>? =
+        Lazy {
+            underTest
+        }
+
+    @Before
+    override fun setUp() {
+        super.setUp()
+
+        underTest =
+            FromPrimaryBouncerTransitionInteractor(
+                transitionRepository = super.transitionRepository,
+                transitionInteractor = super.transitionInteractor,
+                scope = super.testScope.backgroundScope,
+                keyguardInteractor = super.keyguardInteractor,
+                flags = FakeFeatureFlags(),
+                keyguardSecurityModel = mock(),
+            )
+    }
+
+    @Test
+    fun testSurfaceBehindVisibility() =
+        testScope.runTest {
+            val values by collectValues(underTest.surfaceBehindVisibility)
+            runCurrent()
+
+            // Transition-specific surface visibility should be null ("don't care") initially.
+            assertEquals(
+                listOf(
+                    null,
+                ),
+                values
+            )
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.PRIMARY_BOUNCER,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    null, // PRIMARY_BOUNCER -> LOCKSCREEN does not have any specific visibility.
+                ),
+                values
+            )
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.PRIMARY_BOUNCER,
+                    to = KeyguardState.GONE,
+                )
+            )
+
+            runCurrent()
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.RUNNING,
+                    from = KeyguardState.PRIMARY_BOUNCER,
+                    to = KeyguardState.GONE,
+                    value = 0.01f,
+                )
+            )
+
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    null,
+                    false, // Surface is only made visible once the bouncer UI animates out.
+                ),
+                values
+            )
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.PRIMARY_BOUNCER,
+                    to = KeyguardState.GONE,
+                    value = 0.99f,
+                )
+            )
+
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    null,
+                    false,
+                    true, // Surface should eventually be visible.
+                ),
+                values
+            )
+        }
+
+    @Test
+    fun testSurfaceBehindModel() =
+        testScope.runTest {
+            val values by collectValues(underTest.surfaceBehindModel)
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.PRIMARY_BOUNCER,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    null, // PRIMARY_BOUNCER -> LOCKSCREEN does not have specific view params.
+                ),
+                values
+            )
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.PRIMARY_BOUNCER,
+                    to = KeyguardState.GONE,
+                )
+            )
+            runCurrent()
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.RUNNING,
+                    from = KeyguardState.PRIMARY_BOUNCER,
+                    to = KeyguardState.GONE,
+                    value = 0.01f,
+                )
+            )
+            runCurrent()
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.RUNNING,
+                    from = KeyguardState.PRIMARY_BOUNCER,
+                    to = KeyguardState.GONE,
+                    value = 0.99f,
+                )
+            )
+            runCurrent()
+
+            assertEquals(3, values.size)
+            val model1percent = values[1]
+            val model99percent = values[2]
+
+            try {
+                // We should initially have an alpha of 0f when unlocking, so the surface is not
+                // visible
+                // while lockscreen UI animates out.
+                assertEquals(0f, model1percent!!.alpha)
+
+                // By the end it should probably be visible.
+                assertTrue(model99percent!!.alpha > 0f)
+            } catch (e: NullPointerException) {
+                fail("surfaceBehindModel was unexpectedly null.")
+            }
+        }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractorTest.kt
new file mode 100644
index 0000000..a3f7fc5
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractorTest.kt
@@ -0,0 +1,255 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.domain.interactor
+
+import android.media.AudioManager
+import android.media.session.MediaSessionLegacyHelper
+import android.view.KeyEvent
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.back.domain.interactor.BackActionInteractor
+import com.android.systemui.keyguard.shared.model.WakeSleepReason
+import com.android.systemui.keyguard.shared.model.WakefulnessModel
+import com.android.systemui.keyguard.shared.model.WakefulnessState
+import com.android.systemui.media.controls.util.MediaSessionLegacyHelperWrapper
+import com.android.systemui.plugins.statusbar.StatusBarStateController
+import com.android.systemui.shade.ShadeController
+import com.android.systemui.statusbar.StatusBarState
+import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager
+import com.android.systemui.util.mockito.any
+import com.android.systemui.util.mockito.whenever
+import com.google.common.truth.Truth.assertThat
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.eq
+import org.mockito.Mock
+import org.mockito.Mockito.clearInvocations
+import org.mockito.Mockito.never
+import org.mockito.Mockito.verify
+import org.mockito.junit.MockitoJUnit
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class KeyguardKeyEventInteractorTest : SysuiTestCase() {
+    @JvmField @Rule var mockitoRule = MockitoJUnit.rule()
+
+    private val actionDownVolumeDownKeyEvent =
+        KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_VOLUME_DOWN)
+    private val actionDownVolumeUpKeyEvent =
+        KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_VOLUME_UP)
+    private val backKeyEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK)
+    private val awakeWakefulnessMode =
+        WakefulnessModel(WakefulnessState.AWAKE, WakeSleepReason.OTHER, WakeSleepReason.OTHER)
+    private val asleepWakefulnessMode =
+        WakefulnessModel(WakefulnessState.ASLEEP, WakeSleepReason.OTHER, WakeSleepReason.OTHER)
+
+    private lateinit var keyguardInteractorWithDependencies:
+        KeyguardInteractorFactory.WithDependencies
+    @Mock private lateinit var statusBarStateController: StatusBarStateController
+    @Mock private lateinit var statusBarKeyguardViewManager: StatusBarKeyguardViewManager
+    @Mock private lateinit var shadeController: ShadeController
+    @Mock private lateinit var mediaSessionLegacyHelperWrapper: MediaSessionLegacyHelperWrapper
+    @Mock private lateinit var mediaSessionLegacyHelper: MediaSessionLegacyHelper
+    @Mock private lateinit var backActionInteractor: BackActionInteractor
+
+    private lateinit var underTest: KeyguardKeyEventInteractor
+
+    @Before
+    fun setup() {
+        whenever(mediaSessionLegacyHelperWrapper.getHelper(any()))
+            .thenReturn(mediaSessionLegacyHelper)
+        keyguardInteractorWithDependencies = KeyguardInteractorFactory.create()
+        underTest =
+            KeyguardKeyEventInteractor(
+                context,
+                statusBarStateController,
+                keyguardInteractorWithDependencies.keyguardInteractor,
+                statusBarKeyguardViewManager,
+                shadeController,
+                mediaSessionLegacyHelperWrapper,
+                backActionInteractor,
+            )
+    }
+
+    @Test
+    fun dispatchKeyEvent_volumeKey_dozing_handlesEvents() {
+        whenever(statusBarStateController.isDozing).thenReturn(true)
+
+        assertThat(underTest.dispatchKeyEvent(actionDownVolumeDownKeyEvent)).isTrue()
+        verify(mediaSessionLegacyHelper)
+            .sendVolumeKeyEvent(
+                eq(actionDownVolumeDownKeyEvent),
+                eq(AudioManager.USE_DEFAULT_STREAM_TYPE),
+                eq(true)
+            )
+
+        assertThat(underTest.dispatchKeyEvent(actionDownVolumeUpKeyEvent)).isTrue()
+        verify(mediaSessionLegacyHelper)
+            .sendVolumeKeyEvent(
+                eq(actionDownVolumeUpKeyEvent),
+                eq(AudioManager.USE_DEFAULT_STREAM_TYPE),
+                eq(true)
+            )
+    }
+
+    @Test
+    fun dispatchKeyEvent_volumeKey_notDozing_doesNotHandleEvents() {
+        whenever(statusBarStateController.isDozing).thenReturn(false)
+
+        assertThat(underTest.dispatchKeyEvent(actionDownVolumeDownKeyEvent)).isFalse()
+        verify(mediaSessionLegacyHelper, never())
+            .sendVolumeKeyEvent(
+                eq(actionDownVolumeDownKeyEvent),
+                eq(AudioManager.USE_DEFAULT_STREAM_TYPE),
+                eq(true)
+            )
+
+        assertThat(underTest.dispatchKeyEvent(actionDownVolumeUpKeyEvent)).isFalse()
+        verify(mediaSessionLegacyHelper, never())
+            .sendVolumeKeyEvent(
+                eq(actionDownVolumeUpKeyEvent),
+                eq(AudioManager.USE_DEFAULT_STREAM_TYPE),
+                eq(true)
+            )
+    }
+
+    @Test
+    fun dispatchKeyEvent_menuActionUp_interactiveKeyguard_collapsesShade() {
+        keyguardInteractorWithDependencies.repository.setWakefulnessModel(awakeWakefulnessMode)
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.KEYGUARD)
+        whenever(statusBarKeyguardViewManager.shouldDismissOnMenuPressed()).thenReturn(true)
+
+        val actionUpMenuKeyEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU)
+        assertThat(underTest.dispatchKeyEvent(actionUpMenuKeyEvent)).isTrue()
+        verify(shadeController).animateCollapseShadeForced()
+    }
+
+    @Test
+    fun dispatchKeyEvent_menuActionUp_interactiveShadeLocked_collapsesShade() {
+        keyguardInteractorWithDependencies.repository.setWakefulnessModel(awakeWakefulnessMode)
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.SHADE_LOCKED)
+        whenever(statusBarKeyguardViewManager.shouldDismissOnMenuPressed()).thenReturn(true)
+
+        // action down: does NOT collapse the shade
+        val actionDownMenuKeyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU)
+        assertThat(underTest.dispatchKeyEvent(actionDownMenuKeyEvent)).isFalse()
+        verify(shadeController, never()).animateCollapseShadeForced()
+
+        // action up: collapses the shade
+        val actionUpMenuKeyEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU)
+        assertThat(underTest.dispatchKeyEvent(actionUpMenuKeyEvent)).isTrue()
+        verify(shadeController).animateCollapseShadeForced()
+    }
+
+    @Test
+    fun dispatchKeyEvent_menuActionUp_nonInteractiveKeyguard_neverCollapsesShade() {
+        keyguardInteractorWithDependencies.repository.setWakefulnessModel(asleepWakefulnessMode)
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.KEYGUARD)
+        whenever(statusBarKeyguardViewManager.shouldDismissOnMenuPressed()).thenReturn(true)
+
+        val actionUpMenuKeyEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU)
+        assertThat(underTest.dispatchKeyEvent(actionUpMenuKeyEvent)).isFalse()
+        verify(shadeController, never()).animateCollapseShadeForced()
+    }
+
+    @Test
+    fun dispatchKeyEvent_spaceActionUp_interactiveKeyguard_collapsesShade() {
+        keyguardInteractorWithDependencies.repository.setWakefulnessModel(awakeWakefulnessMode)
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.KEYGUARD)
+
+        // action down: does NOT collapse the shade
+        val actionDownMenuKeyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SPACE)
+        assertThat(underTest.dispatchKeyEvent(actionDownMenuKeyEvent)).isFalse()
+        verify(shadeController, never()).animateCollapseShadeForced()
+
+        // action up: collapses the shade
+        val actionUpMenuKeyEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SPACE)
+        assertThat(underTest.dispatchKeyEvent(actionUpMenuKeyEvent)).isTrue()
+        verify(shadeController).animateCollapseShadeForced()
+    }
+
+    @Test
+    fun dispatchKeyEventPreIme_back_keyguard_onBackRequested() {
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.KEYGUARD)
+        whenever(statusBarKeyguardViewManager.dispatchBackKeyEventPreIme()).thenReturn(true)
+
+        whenever(backActionInteractor.onBackRequested()).thenReturn(false)
+        assertThat(underTest.dispatchKeyEventPreIme(backKeyEvent)).isFalse()
+        verify(backActionInteractor).onBackRequested()
+        clearInvocations(backActionInteractor)
+
+        whenever(backActionInteractor.onBackRequested()).thenReturn(true)
+        assertThat(underTest.dispatchKeyEventPreIme(backKeyEvent)).isTrue()
+        verify(backActionInteractor).onBackRequested()
+    }
+
+    @Test
+    fun dispatchKeyEventPreIme_back_keyguard_SBKVMdoesNotHandle_neverOnBackRequested() {
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.KEYGUARD)
+        whenever(statusBarKeyguardViewManager.dispatchBackKeyEventPreIme()).thenReturn(false)
+        whenever(backActionInteractor.onBackRequested()).thenReturn(true)
+
+        assertThat(underTest.dispatchKeyEventPreIme(backKeyEvent)).isFalse()
+        verify(backActionInteractor, never()).onBackRequested()
+    }
+
+    @Test
+    fun dispatchKeyEventPreIme_back_shade_neverOnBackRequested() {
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.SHADE)
+        whenever(statusBarKeyguardViewManager.dispatchBackKeyEventPreIme()).thenReturn(true)
+        whenever(backActionInteractor.onBackRequested()).thenReturn(true)
+
+        assertThat(underTest.dispatchKeyEventPreIme(backKeyEvent)).isFalse()
+        verify(backActionInteractor, never()).onBackRequested()
+    }
+
+    @Test
+    fun interceptMediaKey_keyguard_SBKVMdoesNotHandle_doesNotHandleMediaKey() {
+        val keyEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_VOLUME_UP)
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.KEYGUARD)
+        whenever(statusBarKeyguardViewManager.interceptMediaKey(eq(keyEvent))).thenReturn(false)
+
+        assertThat(underTest.interceptMediaKey(keyEvent)).isFalse()
+        verify(statusBarKeyguardViewManager).interceptMediaKey(eq(keyEvent))
+    }
+
+    @Test
+    fun interceptMediaKey_keyguard_handleMediaKey() {
+        val keyEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_VOLUME_UP)
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.KEYGUARD)
+        whenever(statusBarKeyguardViewManager.interceptMediaKey(eq(keyEvent))).thenReturn(true)
+
+        assertThat(underTest.interceptMediaKey(keyEvent)).isTrue()
+        verify(statusBarKeyguardViewManager).interceptMediaKey(eq(keyEvent))
+    }
+
+    @Test
+    fun interceptMediaKey_shade_doesNotHandleMediaKey() {
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.SHADE)
+
+        assertThat(
+                underTest.interceptMediaKey(
+                    KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_VOLUME_UP)
+                )
+            )
+            .isFalse()
+        verify(statusBarKeyguardViewManager, never()).interceptMediaKey(any())
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardSurfaceBehindInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardSurfaceBehindInteractorTest.kt
new file mode 100644
index 0000000..fdcc66b
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardSurfaceBehindInteractorTest.kt
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.domain.interactor
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.RoboPilotTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectValues
+import com.android.systemui.keyguard.data.repository.FakeKeyguardSurfaceBehindRepository
+import com.android.systemui.keyguard.data.repository.FakeKeyguardTransitionRepository
+import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.keyguard.shared.model.KeyguardSurfaceBehindModel
+import com.android.systemui.keyguard.shared.model.TransitionState
+import com.android.systemui.keyguard.shared.model.TransitionStep
+import com.android.systemui.util.mockito.whenever
+import junit.framework.Assert.assertEquals
+import junit.framework.Assert.assertTrue
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mock
+import org.mockito.MockitoAnnotations.initMocks
+
+@SmallTest
+@RoboPilotTest
+@RunWith(AndroidJUnit4::class)
+@kotlinx.coroutines.ExperimentalCoroutinesApi
+class KeyguardSurfaceBehindInteractorTest : SysuiTestCase() {
+
+    private lateinit var underTest: KeyguardSurfaceBehindInteractor
+    private lateinit var repository: FakeKeyguardSurfaceBehindRepository
+
+    @Mock
+    private lateinit var fromLockscreenTransitionInteractor: FromLockscreenTransitionInteractor
+    @Mock
+    private lateinit var fromPrimaryBouncerTransitionInteractor:
+        FromPrimaryBouncerTransitionInteractor
+
+    private val lockscreenSurfaceBehindModel = KeyguardSurfaceBehindModel(alpha = 0.33f)
+    private val primaryBouncerSurfaceBehindModel = KeyguardSurfaceBehindModel(alpha = 0.66f)
+
+    private val testScope = TestScope()
+
+    private lateinit var transitionRepository: FakeKeyguardTransitionRepository
+    private lateinit var transitionInteractor: KeyguardTransitionInteractor
+
+    @Before
+    fun setUp() {
+        initMocks(this)
+
+        whenever(fromLockscreenTransitionInteractor.surfaceBehindModel)
+            .thenReturn(flowOf(lockscreenSurfaceBehindModel))
+        whenever(fromPrimaryBouncerTransitionInteractor.surfaceBehindModel)
+            .thenReturn(flowOf(primaryBouncerSurfaceBehindModel))
+
+        transitionRepository = FakeKeyguardTransitionRepository()
+
+        transitionInteractor =
+            KeyguardTransitionInteractorFactory.create(
+                    scope = testScope.backgroundScope,
+                    repository = transitionRepository,
+                )
+                .keyguardTransitionInteractor
+
+        repository = FakeKeyguardSurfaceBehindRepository()
+        underTest =
+            KeyguardSurfaceBehindInteractor(
+                repository = repository,
+                fromLockscreenInteractor = fromLockscreenTransitionInteractor,
+                fromPrimaryBouncerInteractor = fromPrimaryBouncerTransitionInteractor,
+                transitionInteractor = transitionInteractor,
+            )
+    }
+
+    @Test
+    fun viewParamsSwitchToCorrectFlow() =
+        testScope.runTest {
+            val values by collectValues(underTest.viewParams)
+
+            // Start on the LOCKSCREEN.
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.AOD,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+
+            runCurrent()
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.FINISHED,
+                    from = KeyguardState.AOD,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+
+            runCurrent()
+
+            // We're on LOCKSCREEN; we should be using the default params.
+            assertEquals(1, values.size)
+            assertTrue(values[0].alpha == 0f)
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.GONE,
+                )
+            )
+
+            runCurrent()
+
+            // We're going from LOCKSCREEN -> GONE, we should be using the lockscreen interactor's
+            // surface behind model.
+            assertEquals(2, values.size)
+            assertEquals(values[1], lockscreenSurfaceBehindModel)
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.PRIMARY_BOUNCER,
+                    to = KeyguardState.GONE,
+                )
+            )
+
+            runCurrent()
+
+            // We're going from PRIMARY_BOUNCER -> GONE, we should be using the bouncer interactor's
+            // surface behind model.
+            assertEquals(3, values.size)
+            assertEquals(values[2], primaryBouncerSurfaceBehindModel)
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.FINISHED,
+                    from = KeyguardState.PRIMARY_BOUNCER,
+                    to = KeyguardState.GONE,
+                )
+            )
+
+            runCurrent()
+
+            // Once PRIMARY_BOUNCER -> GONE finishes, we should be using default params, which is
+            // alpha=1f when we're GONE.
+            assertEquals(4, values.size)
+            assertEquals(1f, values[3].alpha)
+        }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractorTestCase.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractorTestCase.kt
new file mode 100644
index 0000000..8db19ae
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractorTestCase.kt
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.domain.interactor
+
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.keyguard.data.repository.FakeKeyguardRepository
+import com.android.systemui.keyguard.data.repository.FakeKeyguardTransitionRepository
+import com.android.systemui.util.mockito.mock
+import dagger.Lazy
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.TestScope
+
+open class KeyguardTransitionInteractorTestCase : SysuiTestCase() {
+    val testDispatcher = StandardTestDispatcher()
+    val testScope = TestScope(testDispatcher)
+
+    lateinit var keyguardRepository: FakeKeyguardRepository
+    lateinit var transitionRepository: FakeKeyguardTransitionRepository
+
+    lateinit var keyguardInteractor: KeyguardInteractor
+    lateinit var transitionInteractor: KeyguardTransitionInteractor
+
+    /**
+     * Replace these lazy providers with non-null ones if you want test dependencies to use a real
+     * instance of the interactor for the test.
+     */
+    open var fromLockscreenTransitionInteractorLazy: Lazy<FromLockscreenTransitionInteractor>? =
+        null
+    open var fromPrimaryBouncerTransitionInteractorLazy:
+        Lazy<FromPrimaryBouncerTransitionInteractor>? =
+        null
+
+    open fun setUp() {
+        keyguardRepository = FakeKeyguardRepository()
+        transitionRepository = FakeKeyguardTransitionRepository()
+
+        keyguardInteractor =
+            KeyguardInteractorFactory.create(repository = keyguardRepository).keyguardInteractor
+
+        transitionInteractor =
+            KeyguardTransitionInteractorFactory.create(
+                    repository = transitionRepository,
+                    keyguardInteractor = keyguardInteractor,
+                    scope = testScope.backgroundScope,
+                    fromLockscreenTransitionInteractor = fromLockscreenTransitionInteractorLazy
+                            ?: Lazy { mock() },
+                    fromPrimaryBouncerTransitionInteractor =
+                        fromPrimaryBouncerTransitionInteractorLazy ?: Lazy { mock() },
+                )
+                .also {
+                    fromLockscreenTransitionInteractorLazy = it.fromLockscreenTransitionInteractor
+                    fromPrimaryBouncerTransitionInteractorLazy =
+                        it.fromPrimaryBouncerTransitionInteractor
+                }
+                .keyguardTransitionInteractor
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionScenariosTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionScenariosTest.kt
index aa6bd4e..ca93246 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionScenariosTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionScenariosTest.kt
@@ -16,6 +16,7 @@
 
 package com.android.systemui.keyguard.domain.interactor
 
+import android.app.StatusBarManager
 import androidx.test.filters.SmallTest
 import com.android.keyguard.KeyguardSecurityModel
 import com.android.keyguard.KeyguardSecurityModel.SecurityMode.PIN
@@ -24,6 +25,7 @@
 import com.android.systemui.bouncer.data.repository.FakeKeyguardBouncerRepository
 import com.android.systemui.flags.FakeFeatureFlags
 import com.android.systemui.flags.Flags
+import com.android.systemui.keyguard.data.repository.FakeCommandQueue
 import com.android.systemui.keyguard.data.repository.FakeKeyguardRepository
 import com.android.systemui.keyguard.data.repository.FakeKeyguardTransitionRepository
 import com.android.systemui.keyguard.shared.model.BiometricUnlockModel
@@ -71,6 +73,7 @@
 
     private lateinit var keyguardRepository: FakeKeyguardRepository
     private lateinit var bouncerRepository: FakeKeyguardBouncerRepository
+    private lateinit var commandQueue: FakeCommandQueue
     private lateinit var shadeRepository: ShadeRepository
     private lateinit var transitionRepository: FakeKeyguardTransitionRepository
     private lateinit var transitionInteractor: KeyguardTransitionInteractor
@@ -99,17 +102,27 @@
 
         keyguardRepository = FakeKeyguardRepository()
         bouncerRepository = FakeKeyguardBouncerRepository()
+        commandQueue = FakeCommandQueue()
         shadeRepository = FakeShadeRepository()
         transitionRepository = spy(FakeKeyguardTransitionRepository())
 
         whenever(keyguardSecurityModel.getSecurityMode(anyInt())).thenReturn(PIN)
 
-        featureFlags = FakeFeatureFlags().apply { set(Flags.FACE_AUTH_REFACTOR, true) }
+        featureFlags =
+            FakeFeatureFlags().apply {
+                set(Flags.FACE_AUTH_REFACTOR, true)
+                set(Flags.KEYGUARD_WM_STATE_REFACTOR, false)
+            }
 
         transitionInteractor =
             KeyguardTransitionInteractorFactory.create(
                     scope = testScope,
                     repository = transitionRepository,
+                    keyguardInteractor = createKeyguardInteractor(),
+                    fromLockscreenTransitionInteractor = { fromLockscreenTransitionInteractor },
+                    fromPrimaryBouncerTransitionInteractor = {
+                        fromPrimaryBouncerTransitionInteractor
+                    },
                 )
                 .keyguardTransitionInteractor
 
@@ -119,6 +132,7 @@
                     keyguardInteractor = createKeyguardInteractor(),
                     transitionRepository = transitionRepository,
                     transitionInteractor = transitionInteractor,
+                    flags = featureFlags,
                     shadeRepository = shadeRepository,
                 )
                 .apply { start() }
@@ -129,6 +143,7 @@
                     keyguardInteractor = createKeyguardInteractor(),
                     transitionRepository = transitionRepository,
                     transitionInteractor = transitionInteractor,
+                    flags = featureFlags,
                     keyguardSecurityModel = keyguardSecurityModel,
                 )
                 .apply { start() }
@@ -1141,6 +1156,39 @@
             coroutineContext.cancelChildren()
         }
 
+    @Test
+    fun lockscreenToOccluded_fromCameraGesture() =
+        testScope.runTest {
+            // GIVEN a prior transition has run to LOCKSCREEN
+            runTransition(KeyguardState.AOD, KeyguardState.LOCKSCREEN)
+            runCurrent()
+
+            // WHEN the device begins to sleep (first power button press)...
+            keyguardRepository.setWakefulnessModel(startingToSleep())
+            runCurrent()
+            reset(transitionRepository)
+
+            // ...AND WHEN the camera gesture is detected quickly afterwards
+            commandQueue.doForEachCallback {
+                it.onCameraLaunchGestureDetected(
+                    StatusBarManager.CAMERA_LAUNCH_SOURCE_POWER_DOUBLE_TAP
+                )
+            }
+            runCurrent()
+
+            // THEN a transition from LOCKSCREEN => OCCLUDED should occur
+            val info =
+                withArgCaptor<TransitionInfo> {
+                    verify(transitionRepository).startTransition(capture(), anyBoolean())
+                }
+            assertThat(info.ownerName).isEqualTo("FromLockscreenTransitionInteractor")
+            assertThat(info.from).isEqualTo(KeyguardState.LOCKSCREEN)
+            assertThat(info.to).isEqualTo(KeyguardState.OCCLUDED)
+            assertThat(info.animator).isNotNull()
+
+            coroutineContext.cancelChildren()
+        }
+
     private fun startingToWake() =
         WakefulnessModel(
             WakefulnessState.STARTING_TO_WAKE,
@@ -1159,6 +1207,7 @@
         return KeyguardInteractorFactory.create(
                 featureFlags = featureFlags,
                 repository = keyguardRepository,
+                commandQueue = commandQueue,
                 bouncerRepository = bouncerRepository,
             )
             .keyguardInteractor
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/LockscreenSceneInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/LockscreenSceneInteractorTest.kt
deleted file mode 100644
index 86e56bf..0000000
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/LockscreenSceneInteractorTest.kt
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Copyright (C) 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.domain.interactor
-
-import androidx.test.filters.SmallTest
-import com.android.systemui.SysuiTestCase
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
-import com.android.systemui.coroutines.collectLastValue
-import com.android.systemui.scene.SceneTestUtils
-import com.android.systemui.scene.shared.model.SceneKey
-import com.android.systemui.scene.shared.model.SceneModel
-import com.google.common.truth.Truth.assertThat
-import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.test.runCurrent
-import kotlinx.coroutines.test.runTest
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.junit.runners.JUnit4
-
-@OptIn(ExperimentalCoroutinesApi::class)
-@SmallTest
-@RunWith(JUnit4::class)
-class LockscreenSceneInteractorTest : SysuiTestCase() {
-
-    private val utils = SceneTestUtils(this)
-    private val testScope = utils.testScope
-    private val sceneInteractor = utils.sceneInteractor()
-    private val authenticationInteractor =
-        utils.authenticationInteractor(
-            repository = utils.authenticationRepository(),
-        )
-    private val underTest =
-        utils.lockScreenSceneInteractor(
-            authenticationInteractor = authenticationInteractor,
-            bouncerInteractor =
-                utils.bouncerInteractor(
-                    authenticationInteractor = authenticationInteractor,
-                    sceneInteractor = sceneInteractor,
-                ),
-        )
-
-    @Test
-    fun isDeviceLocked() =
-        testScope.runTest {
-            val isDeviceLocked by collectLastValue(underTest.isDeviceLocked)
-
-            utils.authenticationRepository.setUnlocked(false)
-            assertThat(isDeviceLocked).isTrue()
-
-            utils.authenticationRepository.setUnlocked(true)
-            assertThat(isDeviceLocked).isFalse()
-        }
-
-    @Test
-    fun isSwipeToDismissEnabled_deviceLockedAndAuthMethodSwipe_true() =
-        testScope.runTest {
-            val isSwipeToDismissEnabled by collectLastValue(underTest.isSwipeToDismissEnabled)
-
-            utils.authenticationRepository.setUnlocked(false)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Swipe)
-
-            assertThat(isSwipeToDismissEnabled).isTrue()
-        }
-
-    @Test
-    fun isSwipeToDismissEnabled_deviceUnlockedAndAuthMethodSwipe_false() =
-        testScope.runTest {
-            val isSwipeToDismissEnabled by collectLastValue(underTest.isSwipeToDismissEnabled)
-
-            utils.authenticationRepository.setUnlocked(true)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Swipe)
-
-            assertThat(isSwipeToDismissEnabled).isFalse()
-        }
-
-    @Test
-    fun dismissLockScreen_deviceLockedWithSecureAuthMethod_switchesToBouncer() =
-        testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
-            utils.authenticationRepository.setUnlocked(false)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Lockscreen))
-
-            underTest.dismissLockscreen()
-
-            assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Bouncer))
-        }
-
-    @Test
-    fun dismissLockScreen_deviceUnlocked_switchesToGone() =
-        testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
-            utils.authenticationRepository.setUnlocked(true)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Lockscreen))
-
-            underTest.dismissLockscreen()
-
-            assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Gone))
-        }
-
-    @Test
-    fun dismissLockScreen_deviceLockedWithInsecureAuthMethod_switchesToGone() =
-        testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
-            utils.authenticationRepository.setUnlocked(false)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Swipe)
-            assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Lockscreen))
-
-            underTest.dismissLockscreen()
-
-            assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Gone))
-        }
-
-    @Test
-    fun switchFromLockScreenToGone_authMethodNotSwipe_doesNotUnlockDevice() =
-        testScope.runTest {
-            val isUnlocked by collectLastValue(authenticationInteractor.isUnlocked)
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Lockscreen), "reason")
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
-            assertThat(isUnlocked).isFalse()
-
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Gone), "reason")
-
-            assertThat(isUnlocked).isFalse()
-        }
-
-    @Test
-    fun switchFromNonLockScreenToGone_authMethodSwipe_doesNotUnlockDevice() =
-        testScope.runTest {
-            val isUnlocked by collectLastValue(authenticationInteractor.isUnlocked)
-            runCurrent()
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Shade), "reason")
-            runCurrent()
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Swipe)
-            runCurrent()
-            assertThat(isUnlocked).isFalse()
-
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Gone), "reason")
-
-            assertThat(isUnlocked).isFalse()
-        }
-
-    @Test
-    fun authMethodChangedToNone_notOnLockScreenScene_doesNotDismissLockScreen() =
-        testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Swipe)
-            runCurrent()
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.QuickSettings), "reason")
-            runCurrent()
-            assertThat(currentScene).isEqualTo(SceneModel(SceneKey.QuickSettings))
-
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.None)
-
-            assertThat(currentScene).isEqualTo(SceneModel(SceneKey.QuickSettings))
-        }
-}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/OccludingAppDeviceEntryInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/OccludingAppDeviceEntryInteractorTest.kt
index baa5ee8..1dcb55d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/OccludingAppDeviceEntryInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/OccludingAppDeviceEntryInteractorTest.kt
@@ -44,6 +44,8 @@
 import com.android.systemui.keyguard.util.IndicationHelper
 import com.android.systemui.plugins.ActivityStarter
 import com.android.systemui.plugins.ActivityStarter.OnDismissAction
+import com.android.systemui.power.data.repository.FakePowerRepository
+import com.android.systemui.power.domain.interactor.PowerInteractor
 import com.android.systemui.util.mockito.any
 import com.android.systemui.util.mockito.mock
 import com.android.systemui.util.mockito.whenever
@@ -80,6 +82,7 @@
     private lateinit var configurationRepository: FakeConfigurationRepository
     private lateinit var featureFlags: FakeFeatureFlags
     private lateinit var trustRepository: FakeTrustRepository
+    private lateinit var powerRepository: FakePowerRepository
 
     @Mock private lateinit var indicationHelper: IndicationHelper
     @Mock private lateinit var keyguardUpdateMonitor: KeyguardUpdateMonitor
@@ -102,6 +105,7 @@
                 set(Flags.DELAY_BOUNCER, false)
             }
         trustRepository = FakeTrustRepository()
+        powerRepository = FakePowerRepository()
         underTest =
             OccludingAppDeviceEntryInteractor(
                 BiometricMessageInteractor(
@@ -145,6 +149,14 @@
                 testScope.backgroundScope,
                 mockedContext,
                 activityStarter,
+                PowerInteractor(
+                    powerRepository,
+                    keyguardRepository,
+                    falsingCollector = mock(),
+                    screenOffAnimationController = mock(),
+                    statusBarStateController = mock(),
+                ),
+                FakeFeatureFlags().apply { set(Flags.FP_LISTEN_OCCLUDING_APPS, true) },
             )
     }
 
@@ -160,6 +172,18 @@
         }
 
     @Test
+    fun fingerprintSuccess_notInteractive_doesNotGoToHomeScreen() =
+        testScope.runTest {
+            givenOnOccludingApp(true)
+            powerRepository.setInteractive(false)
+            fingerprintAuthRepository.setAuthenticationStatus(
+                SuccessFingerprintAuthenticationStatus(0, true)
+            )
+            runCurrent()
+            verifyNeverGoToHomeScreen()
+        }
+
+    @Test
     fun fingerprintSuccess_notOnOccludingApp_doesNotGoToHomeScreen() =
         testScope.runTest {
             givenOnOccludingApp(false)
@@ -291,6 +315,7 @@
         }
 
     private fun givenOnOccludingApp(isOnOccludingApp: Boolean) {
+        powerRepository.setInteractive(true)
         keyguardRepository.setKeyguardOccluded(isOnOccludingApp)
         keyguardRepository.setKeyguardShowing(isOnOccludingApp)
         bouncerRepository.setPrimaryShow(!isOnOccludingApp)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractorTest.kt
new file mode 100644
index 0000000..73ecae5
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/WindowManagerLockscreenVisibilityInteractorTest.kt
@@ -0,0 +1,412 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.domain.interactor
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.RoboPilotTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectValues
+import com.android.systemui.keyguard.data.repository.FakeKeyguardTransitionRepository
+import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.keyguard.shared.model.TransitionState
+import com.android.systemui.keyguard.shared.model.TransitionStep
+import com.android.systemui.util.mockito.whenever
+import junit.framework.Assert.assertEquals
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mock
+import org.mockito.MockitoAnnotations.initMocks
+
+@SmallTest
+@RoboPilotTest
+@RunWith(AndroidJUnit4::class)
+@kotlinx.coroutines.ExperimentalCoroutinesApi
+class WindowManagerLockscreenVisibilityInteractorTest : SysuiTestCase() {
+
+    private lateinit var underTest: WindowManagerLockscreenVisibilityInteractor
+
+    @Mock private lateinit var surfaceBehindInteractor: KeyguardSurfaceBehindInteractor
+    @Mock
+    private lateinit var fromLockscreenTransitionInteractor: FromLockscreenTransitionInteractor
+    @Mock
+    private lateinit var fromPrimaryBouncerTransitionInteractor:
+        FromPrimaryBouncerTransitionInteractor
+
+    private val lockscreenSurfaceVisibilityFlow = MutableStateFlow<Boolean?>(false)
+    private val primaryBouncerSurfaceVisibilityFlow = MutableStateFlow<Boolean?>(false)
+    private val surfaceBehindIsAnimatingFlow = MutableStateFlow(false)
+
+    private val testScope = TestScope()
+
+    private lateinit var keyguardInteractor: KeyguardInteractor
+    private lateinit var transitionRepository: FakeKeyguardTransitionRepository
+    private lateinit var transitionInteractor: KeyguardTransitionInteractor
+
+    @Before
+    fun setUp() {
+        initMocks(this)
+
+        whenever(fromLockscreenTransitionInteractor.surfaceBehindVisibility)
+            .thenReturn(lockscreenSurfaceVisibilityFlow)
+        whenever(fromPrimaryBouncerTransitionInteractor.surfaceBehindVisibility)
+            .thenReturn(primaryBouncerSurfaceVisibilityFlow)
+        whenever(surfaceBehindInteractor.isAnimatingSurface)
+            .thenReturn(surfaceBehindIsAnimatingFlow)
+
+        transitionRepository = FakeKeyguardTransitionRepository()
+
+        transitionInteractor =
+            KeyguardTransitionInteractorFactory.create(
+                    scope = testScope.backgroundScope,
+                    repository = transitionRepository,
+                )
+                .also { keyguardInteractor = it.keyguardInteractor }
+                .keyguardTransitionInteractor
+
+        underTest =
+            WindowManagerLockscreenVisibilityInteractor(
+                keyguardInteractor = keyguardInteractor,
+                transitionInteractor = transitionInteractor,
+                surfaceBehindInteractor = surfaceBehindInteractor,
+                fromLockscreenTransitionInteractor,
+                fromPrimaryBouncerTransitionInteractor,
+            )
+    }
+
+    @Test
+    fun surfaceBehindVisibility_switchesToCorrectFlow() =
+        testScope.runTest {
+            val values by collectValues(underTest.surfaceBehindVisibility)
+
+            // Start on LOCKSCREEN.
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.AOD,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+
+            runCurrent()
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.FINISHED,
+                    from = KeyguardState.AOD,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    false, // We should start with the surface invisible on LOCKSCREEN.
+                ),
+                values
+            )
+
+            val lockscreenSpecificSurfaceVisibility = true
+            lockscreenSurfaceVisibilityFlow.emit(lockscreenSpecificSurfaceVisibility)
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.GONE,
+                )
+            )
+
+            runCurrent()
+
+            // We started a transition from LOCKSCREEN, we should be using the value emitted by the
+            // lockscreenSurfaceVisibilityFlow.
+            assertEquals(
+                listOf(
+                    false,
+                    lockscreenSpecificSurfaceVisibility,
+                ),
+                values
+            )
+
+            // Go back to LOCKSCREEN, since we won't emit 'true' twice in a row.
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.GONE,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+            runCurrent()
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.FINISHED,
+                    from = KeyguardState.GONE,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    false,
+                    lockscreenSpecificSurfaceVisibility,
+                    false, // FINISHED (LOCKSCREEN)
+                ),
+                values
+            )
+
+            val bouncerSpecificVisibility = true
+            primaryBouncerSurfaceVisibilityFlow.emit(bouncerSpecificVisibility)
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.PRIMARY_BOUNCER,
+                    to = KeyguardState.GONE,
+                )
+            )
+
+            runCurrent()
+
+            // We started a transition from PRIMARY_BOUNCER, we should be using the value emitted by
+            // the
+            // primaryBouncerSurfaceVisibilityFlow.
+            assertEquals(
+                listOf(
+                    false,
+                    lockscreenSpecificSurfaceVisibility,
+                    false,
+                    bouncerSpecificVisibility,
+                ),
+                values
+            )
+        }
+
+    @Test
+    fun testUsingGoingAwayAnimation_duringTransitionToGone() =
+        testScope.runTest {
+            val values by collectValues(underTest.usingKeyguardGoingAwayAnimation)
+
+            // Start on LOCKSCREEN.
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.AOD,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+            runCurrent()
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.FINISHED,
+                    from = KeyguardState.AOD,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    false, // Not using the animation when we're just sitting on LOCKSCREEN.
+                ),
+                values
+            )
+
+            surfaceBehindIsAnimatingFlow.emit(true)
+            runCurrent()
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.FINISHED,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.GONE,
+                )
+            )
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    false,
+                    true, // Still true when we're FINISHED -> GONE, since we're still animating.
+                ),
+                values
+            )
+
+            surfaceBehindIsAnimatingFlow.emit(false)
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    false,
+                    true,
+                    false, // False once the animation ends.
+                ),
+                values
+            )
+        }
+
+    @Test
+    fun testNotUsingGoingAwayAnimation_evenWhenAnimating_ifStateIsNotGone() =
+        testScope.runTest {
+            val values by collectValues(underTest.usingKeyguardGoingAwayAnimation)
+
+            // Start on LOCKSCREEN.
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.AOD,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+            runCurrent()
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.FINISHED,
+                    from = KeyguardState.AOD,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    false, // Not using the animation when we're just sitting on LOCKSCREEN.
+                ),
+                values
+            )
+
+            surfaceBehindIsAnimatingFlow.emit(true)
+            runCurrent()
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.GONE,
+                )
+            )
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    false,
+                    true, // We're happily animating while transitioning to gone.
+                ),
+                values
+            )
+
+            // Oh no, we're still surfaceBehindAnimating=true, but no longer transitioning to GONE.
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.AOD,
+                )
+            )
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    false,
+                    true,
+                    false, // Despite the animator still running, this should be false.
+                ),
+                values
+            )
+
+            surfaceBehindIsAnimatingFlow.emit(false)
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    false,
+                    true,
+                    false, // The animator ending should have no effect.
+                ),
+                values
+            )
+        }
+
+    @Test
+    fun lockscreenVisibility_visibleWhenGone() =
+        testScope.runTest {
+            val values by collectValues(underTest.lockscreenVisibility)
+
+            // Start on LOCKSCREEN.
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.AOD,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+            runCurrent()
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.FINISHED,
+                    from = KeyguardState.AOD,
+                    to = KeyguardState.LOCKSCREEN,
+                )
+            )
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    true, // Unsurprisingly, we should start with the lockscreen visible on
+                    // LOCKSCREEN.
+                ),
+                values
+            )
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.STARTED,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.GONE,
+                )
+            )
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    true, // Lockscreen remains visible while we're transitioning to GONE.
+                ),
+                values
+            )
+
+            transitionRepository.sendTransitionStep(
+                TransitionStep(
+                    transitionState = TransitionState.FINISHED,
+                    from = KeyguardState.LOCKSCREEN,
+                    to = KeyguardState.GONE,
+                )
+            )
+            runCurrent()
+
+            assertEquals(
+                listOf(
+                    true,
+                    false, // Once we're fully GONE, the lockscreen should not be visible.
+                ),
+                values
+            )
+        }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindParamsApplierTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindParamsApplierTest.kt
new file mode 100644
index 0000000..a22f603
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindParamsApplierTest.kt
@@ -0,0 +1,160 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.ui.binder
+
+import android.testing.TestableLooper.RunWithLooper
+import android.view.RemoteAnimationTarget
+import androidx.test.filters.SmallTest
+import com.android.keyguard.KeyguardViewController
+import com.android.systemui.RoboPilotTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.animation.AnimatorTestRule
+import com.android.systemui.keyguard.domain.interactor.KeyguardSurfaceBehindInteractor
+import com.android.systemui.keyguard.shared.model.KeyguardSurfaceBehindModel
+import com.android.systemui.util.concurrency.FakeExecutor
+import com.android.systemui.util.mockito.whenever
+import com.android.systemui.util.time.FakeSystemClock
+import junit.framework.Assert.assertFalse
+import junit.framework.Assert.assertNull
+import junit.framework.Assert.assertTrue
+import org.junit.After
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.mockito.Mock
+import org.mockito.Mockito.anyBoolean
+import org.mockito.Mockito.doAnswer
+import org.mockito.MockitoAnnotations
+
+@SmallTest
+@RoboPilotTest
+@RunWithLooper(setAsMainLooper = true)
+@kotlinx.coroutines.ExperimentalCoroutinesApi
+class KeyguardSurfaceBehindParamsApplierTest : SysuiTestCase() {
+    @get:Rule val animatorTestRule = AnimatorTestRule()
+
+    private lateinit var underTest: KeyguardSurfaceBehindParamsApplier
+    private lateinit var executor: FakeExecutor
+
+    @Mock private lateinit var keyguardViewController: KeyguardViewController
+
+    @Mock private lateinit var interactor: KeyguardSurfaceBehindInteractor
+
+    @Mock private lateinit var remoteAnimationTarget: RemoteAnimationTarget
+
+    private var isAnimatingSurface: Boolean? = null
+
+    @Before
+    fun setUp() {
+        MockitoAnnotations.initMocks(this)
+        executor = FakeExecutor(FakeSystemClock())
+        underTest =
+            KeyguardSurfaceBehindParamsApplier(
+                executor = executor,
+                keyguardViewController = keyguardViewController,
+                interactor = interactor,
+            )
+
+        doAnswer {
+                (it.arguments[0] as Boolean).let { animating -> isAnimatingSurface = animating }
+            }
+            .whenever(interactor)
+            .setAnimatingSurface(anyBoolean())
+    }
+
+    @After
+    fun tearDown() {
+        animatorTestRule.advanceTimeBy(1000.toLong())
+    }
+
+    @Test
+    fun testNotAnimating_setParamsWithNoAnimation() {
+        underTest.viewParams =
+            KeyguardSurfaceBehindModel(
+                alpha = 0.3f,
+                translationY = 300f,
+            )
+
+        // A surface has not yet been provided, so we shouldn't have set animating to false OR true
+        // just yet.
+        assertNull(isAnimatingSurface)
+
+        underTest.applyParamsToSurface(remoteAnimationTarget)
+
+        // We should now explicitly not be animating the surface.
+        assertFalse(checkNotNull(isAnimatingSurface))
+    }
+
+    @Test
+    fun testAnimating_paramsThenSurfaceProvided() {
+        underTest.viewParams =
+            KeyguardSurfaceBehindModel(
+                animateFromAlpha = 0f,
+                alpha = 0.3f,
+                animateFromTranslationY = 0f,
+                translationY = 300f,
+            )
+
+        // A surface has not yet been provided, so we shouldn't have set animating to false OR true
+        // just yet.
+        assertNull(isAnimatingSurface)
+
+        underTest.applyParamsToSurface(remoteAnimationTarget)
+
+        // We should now be animating the surface.
+        assertTrue(checkNotNull(isAnimatingSurface))
+    }
+
+    @Test
+    fun testAnimating_surfaceThenParamsProvided() {
+        underTest.applyParamsToSurface(remoteAnimationTarget)
+
+        // The default params (which do not animate) should have been applied, so we're explicitly
+        // NOT animating yet.
+        assertFalse(checkNotNull(isAnimatingSurface))
+
+        underTest.viewParams =
+            KeyguardSurfaceBehindModel(
+                animateFromAlpha = 0f,
+                alpha = 0.3f,
+                animateFromTranslationY = 0f,
+                translationY = 300f,
+            )
+
+        // We should now be animating the surface.
+        assertTrue(checkNotNull(isAnimatingSurface))
+    }
+
+    @Test
+    fun testAnimating_thenReleased_animatingIsFalse() {
+        underTest.viewParams =
+            KeyguardSurfaceBehindModel(
+                animateFromAlpha = 0f,
+                alpha = 0.3f,
+                animateFromTranslationY = 0f,
+                translationY = 300f,
+            )
+        underTest.applyParamsToSurface(remoteAnimationTarget)
+
+        assertTrue(checkNotNull(isAnimatingSurface))
+
+        underTest.notifySurfaceReleased()
+
+        // Releasing the surface should immediately cancel animators.
+        assertFalse(checkNotNull(isAnimatingSurface))
+    }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/binder/WindowManagerLockscreenVisibilityManagerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/binder/WindowManagerLockscreenVisibilityManagerTest.kt
new file mode 100644
index 0000000..623c877
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/binder/WindowManagerLockscreenVisibilityManagerTest.kt
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.ui.binder
+
+import android.app.IActivityTaskManager
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.RoboPilotTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.keyguard.WindowManagerLockscreenVisibilityManager
+import com.android.systemui.statusbar.policy.KeyguardStateController
+import com.android.systemui.util.concurrency.FakeExecutor
+import com.android.systemui.util.time.FakeSystemClock
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mock
+import org.mockito.Mockito.anyInt
+import org.mockito.Mockito.verify
+import org.mockito.Mockito.verifyNoMoreInteractions
+import org.mockito.MockitoAnnotations
+
+@SmallTest
+@RoboPilotTest
+@RunWith(AndroidJUnit4::class)
+@kotlinx.coroutines.ExperimentalCoroutinesApi
+class WindowManagerLockscreenVisibilityManagerTest : SysuiTestCase() {
+    private lateinit var underTest: WindowManagerLockscreenVisibilityManager
+    private lateinit var executor: FakeExecutor
+
+    @Mock private lateinit var activityTaskManagerService: IActivityTaskManager
+
+    @Mock private lateinit var keyguardStateController: KeyguardStateController
+
+    @Mock private lateinit var keyguardSurfaceBehindAnimator: KeyguardSurfaceBehindParamsApplier
+
+    @Before
+    fun setUp() {
+        MockitoAnnotations.initMocks(this)
+        executor = FakeExecutor(FakeSystemClock())
+
+        underTest =
+            WindowManagerLockscreenVisibilityManager(
+                executor = executor,
+                activityTaskManagerService = activityTaskManagerService,
+                keyguardStateController = keyguardStateController,
+                keyguardSurfaceBehindAnimator = keyguardSurfaceBehindAnimator,
+            )
+    }
+
+    @Test
+    fun testLockscreenVisible_andAodVisible() {
+        underTest.setLockscreenShown(true)
+        underTest.setAodVisible(true)
+
+        verify(activityTaskManagerService).setLockScreenShown(true, true)
+        verifyNoMoreInteractions(activityTaskManagerService)
+    }
+
+    @Test
+    fun testGoingAway_whenLockscreenVisible_thenSurfaceMadeVisible() {
+        underTest.setLockscreenShown(true)
+        underTest.setAodVisible(true)
+
+        verify(activityTaskManagerService).setLockScreenShown(true, true)
+        verifyNoMoreInteractions(activityTaskManagerService)
+
+        underTest.setSurfaceBehindVisibility(true)
+
+        verify(activityTaskManagerService).keyguardGoingAway(anyInt())
+        verifyNoMoreInteractions(activityTaskManagerService)
+    }
+
+    @Test
+    fun testSurfaceVisible_whenLockscreenNotShowing_doesNotTriggerGoingAway() {
+        underTest.setLockscreenShown(false)
+        underTest.setAodVisible(false)
+
+        verify(activityTaskManagerService).setLockScreenShown(false, false)
+        verifyNoMoreInteractions(activityTaskManagerService)
+
+        underTest.setSurfaceBehindVisibility(true)
+
+        verifyNoMoreInteractions(activityTaskManagerService)
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/view/layout/blueprints/DefaultKeyguardBlueprintTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/view/layout/blueprints/DefaultKeyguardBlueprintTest.kt
index 66631dc..addb181 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/view/layout/blueprints/DefaultKeyguardBlueprintTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/view/layout/blueprints/DefaultKeyguardBlueprintTest.kt
@@ -17,6 +17,8 @@
 
 package com.android.systemui.keyguard.ui.view.layout.blueprints
 
+import android.testing.AndroidTestingRunner
+import android.testing.TestableLooper.RunWithLooper
 import androidx.constraintlayout.widget.ConstraintSet
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
@@ -26,15 +28,17 @@
 import com.android.systemui.keyguard.ui.view.layout.sections.DefaultLockIconSection
 import com.android.systemui.keyguard.ui.view.layout.sections.DefaultSettingsPopupMenuSection
 import com.android.systemui.keyguard.ui.view.layout.sections.DefaultShortcutsSection
+import com.android.systemui.keyguard.ui.view.layout.sections.DefaultStatusViewSection
+import com.android.systemui.keyguard.ui.view.layout.sections.SplitShadeGuidelines
 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.verify
 import org.mockito.MockitoAnnotations
 
-@RunWith(JUnit4::class)
+@RunWith(AndroidTestingRunner::class)
+@RunWithLooper(setAsMainLooper = true)
 @SmallTest
 class DefaultKeyguardBlueprintTest : SysuiTestCase() {
     private lateinit var underTest: DefaultKeyguardBlueprint
@@ -45,6 +49,8 @@
     @Mock
     private lateinit var defaultAmbientIndicationAreaSection: DefaultAmbientIndicationAreaSection
     @Mock private lateinit var defaultSettingsPopupMenuSection: DefaultSettingsPopupMenuSection
+    @Mock private lateinit var defaultStatusViewSection: DefaultStatusViewSection
+    @Mock private lateinit var splitShadeGuidelines: SplitShadeGuidelines
 
     @Before
     fun setup() {
@@ -57,6 +63,8 @@
                 defaultShortcutsSection,
                 defaultAmbientIndicationAreaSection,
                 defaultSettingsPopupMenuSection,
+                defaultStatusViewSection,
+                splitShadeGuidelines,
             )
     }
 
@@ -69,5 +77,7 @@
         verify(defaultShortcutsSection).apply(cs)
         verify(defaultAmbientIndicationAreaSection).apply(cs)
         verify(defaultSettingsPopupMenuSection).apply(cs)
+        verify(defaultStatusViewSection).apply(cs)
+        verify(splitShadeGuidelines).apply(cs)
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/view/layout/sections/DefaultLockIconSectionTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/view/layout/sections/DefaultLockIconSectionTest.kt
index 1444f8d..379c03c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/view/layout/sections/DefaultLockIconSectionTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/view/layout/sections/DefaultLockIconSectionTest.kt
@@ -25,6 +25,7 @@
 import com.android.systemui.R
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.biometrics.AuthController
+import com.android.systemui.keyguard.ui.view.KeyguardRootView
 import com.google.common.truth.Truth.assertThat
 import org.junit.Before
 import org.junit.Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToLockscreenTransitionViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToLockscreenTransitionViewModelTest.kt
index c67f535..bfc6f31 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToLockscreenTransitionViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToLockscreenTransitionViewModelTest.kt
@@ -21,9 +21,7 @@
 import com.android.systemui.RoboPilotTest
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.keyguard.data.repository.FakeKeyguardTransitionRepository
-import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
 import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractorFactory
-import com.android.systemui.keyguard.shared.model.KeyguardState
 import com.android.systemui.keyguard.shared.model.KeyguardState.AOD
 import com.android.systemui.keyguard.shared.model.KeyguardState.DOZING
 import com.android.systemui.keyguard.shared.model.KeyguardState.DREAMING
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordancesCombinedViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordancesCombinedViewModelTest.kt
index ef38d54..3576ec9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordancesCombinedViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordancesCombinedViewModelTest.kt
@@ -281,11 +281,7 @@
             underTest.onPreviewSlotSelected(
                 KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START
             )
-            keyguardInteractor.previewMode.value =
-                KeyguardInteractor.PreviewMode(
-                    isInPreviewMode = true,
-                    shouldHighlightSelectedAffordance = true,
-                )
+            underTest.enablePreviewMode(KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START, true)
 
             repository.setKeyguardShowing(false)
             val latest = collectLastValue(underTest.startButton)
@@ -330,11 +326,7 @@
             underTest.onPreviewSlotSelected(
                 KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START
             )
-            keyguardInteractor.previewMode.value =
-                KeyguardInteractor.PreviewMode(
-                    isInPreviewMode = true,
-                    shouldHighlightSelectedAffordance = true,
-                )
+            underTest.enablePreviewMode(KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START, true)
 
             repository.setKeyguardShowing(false)
             val endButton = collectLastValue(underTest.endButton)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
index 05e933b..a14a1c5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
@@ -45,7 +45,6 @@
     private lateinit var testScope: TestScope
     private lateinit var repository: FakeKeyguardRepository
     private lateinit var keyguardInteractor: KeyguardInteractor
-    @Mock private lateinit var keyguardQuickAffordancesCombinedViewModel: KeyguardQuickAffordancesCombinedViewModel
 
     @Before
     fun setUp() {
@@ -63,10 +62,7 @@
         keyguardInteractor = withDeps.keyguardInteractor
         repository = withDeps.repository
 
-        underTest = KeyguardRootViewModel(
-            keyguardInteractor,
-            keyguardQuickAffordancesCombinedViewModel,
-        )
+        underTest = KeyguardRootViewModel(keyguardInteractor)
     }
 
     @Test
@@ -89,10 +85,7 @@
     fun alpha_inPreviewMode_doesNotChange() =
         testScope.runTest {
             val value = collectLastValue(underTest.alpha)
-            underTest.enablePreviewMode(
-                initiallySelectedSlotId = null,
-                shouldHighlightSelectedAffordance = false,
-            )
+            underTest.enablePreviewMode()
 
             Truth.assertThat(value()).isEqualTo(1f)
             repository.setKeyguardAlpha(0.1f)
@@ -104,4 +97,4 @@
             repository.setKeyguardAlpha(0f)
             Truth.assertThat(value()).isEqualTo(1f)
         }
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModelTest.kt
index 63ee240..23f243c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenSceneViewModelTest.kt
@@ -19,7 +19,7 @@
 import androidx.test.filters.SmallTest
 import com.android.systemui.R
 import com.android.systemui.SysuiTestCase
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel
 import com.android.systemui.common.shared.model.Icon
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.scene.SceneTestUtils
@@ -49,14 +49,11 @@
     private val underTest =
         LockscreenSceneViewModel(
             applicationScope = testScope.backgroundScope,
-            interactor =
-                utils.lockScreenSceneInteractor(
+            authenticationInteractor = authenticationInteractor,
+            bouncerInteractor =
+                utils.bouncerInteractor(
                     authenticationInteractor = authenticationInteractor,
-                    bouncerInteractor =
-                        utils.bouncerInteractor(
-                            authenticationInteractor = authenticationInteractor,
-                            sceneInteractor = sceneInteractor,
-                        ),
+                    sceneInteractor = sceneInteractor,
                 ),
         )
 
@@ -87,21 +84,24 @@
         }
 
     @Test
-    fun upTransitionSceneKey_swipeToUnlockedEnabled_gone() =
+    fun upTransitionSceneKey_canSwipeToUnlock_gone() =
         testScope.runTest {
             val upTransitionSceneKey by collectLastValue(underTest.upDestinationSceneKey)
-            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Swipe)
-            utils.authenticationRepository.setUnlocked(false)
+            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.None)
+            utils.authenticationRepository.setLockscreenEnabled(true)
+            utils.authenticationRepository.setUnlocked(true)
+            sceneInteractor.changeScene(SceneModel(SceneKey.Lockscreen), "reason")
 
             assertThat(upTransitionSceneKey).isEqualTo(SceneKey.Gone)
         }
 
     @Test
-    fun upTransitionSceneKey_swipeToUnlockedNotEnabled_bouncer() =
+    fun upTransitionSceneKey_cannotSwipeToUnlock_bouncer() =
         testScope.runTest {
             val upTransitionSceneKey by collectLastValue(underTest.upDestinationSceneKey)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
+            sceneInteractor.changeScene(SceneModel(SceneKey.Lockscreen), "reason")
 
             assertThat(upTransitionSceneKey).isEqualTo(SceneKey.Bouncer)
         }
@@ -109,7 +109,7 @@
     @Test
     fun onLockButtonClicked_deviceLockedSecurely_switchesToBouncer() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
             runCurrent()
@@ -122,7 +122,7 @@
     @Test
     fun onContentClicked_deviceUnlocked_switchesToGone() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(true)
             runCurrent()
@@ -135,7 +135,7 @@
     @Test
     fun onContentClicked_deviceLockedSecurely_switchesToBouncer() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
             runCurrent()
@@ -148,7 +148,7 @@
     @Test
     fun onLockButtonClicked_deviceUnlocked_switchesToGone() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(true)
             runCurrent()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/UdfpsFingerprintViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/UdfpsFingerprintViewModelTest.kt
index 80ab418..0ad14d0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/UdfpsFingerprintViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/UdfpsFingerprintViewModelTest.kt
@@ -31,7 +31,7 @@
 import com.android.systemui.keyguard.data.repository.FakeKeyguardTransitionRepository
 import com.android.systemui.keyguard.domain.interactor.BurnInInteractor
 import com.android.systemui.keyguard.domain.interactor.KeyguardInteractorFactory
-import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
+import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractorFactory
 import com.android.systemui.keyguard.domain.interactor.UdfpsKeyguardInteractor
 import com.android.systemui.shade.data.repository.FakeShadeRepository
 import com.android.systemui.statusbar.phone.SystemUIDialogManager
@@ -83,16 +83,21 @@
         bouncerRepository = FakeKeyguardBouncerRepository()
         transitionRepository = FakeKeyguardTransitionRepository()
         shadeRepository = FakeShadeRepository()
-        val transitionInteractor =
-            KeyguardTransitionInteractor(
-                transitionRepository,
-                testScope.backgroundScope,
-            )
         val keyguardInteractor =
             KeyguardInteractorFactory.create(
+                    repository = keyguardRepository,
                     featureFlags = featureFlags,
                 )
                 .keyguardInteractor
+
+        val transitionInteractor =
+            KeyguardTransitionInteractorFactory.create(
+                    scope = testScope.backgroundScope,
+                    repository = transitionRepository,
+                    keyguardInteractor = keyguardInteractor,
+                )
+                .keyguardTransitionInteractor
+
         underTest =
             FingerprintViewModel(
                 context,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/UdfpsLockscreenViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/UdfpsLockscreenViewModelTest.kt
index 0456824..edcaa1d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/UdfpsLockscreenViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/UdfpsLockscreenViewModelTest.kt
@@ -30,7 +30,7 @@
 import com.android.systemui.keyguard.domain.interactor.BurnInInteractor
 import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor
 import com.android.systemui.keyguard.domain.interactor.KeyguardInteractorFactory
-import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
+import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractorFactory
 import com.android.systemui.keyguard.domain.interactor.UdfpsKeyguardInteractor
 import com.android.systemui.keyguard.shared.model.KeyguardState
 import com.android.systemui.keyguard.shared.model.StatusBarState
@@ -98,15 +98,20 @@
                 bouncerRepository = it.bouncerRepository
             }
 
+        val transitionInteractor =
+            KeyguardTransitionInteractorFactory.create(
+                    scope = testScope.backgroundScope,
+                    repository = transitionRepository,
+                    keyguardInteractor = keyguardInteractor,
+                )
+                .keyguardTransitionInteractor
+
         underTest =
             UdfpsLockscreenViewModel(
                 context,
                 lockscreenColorResId,
                 alternateBouncerResId,
-                KeyguardTransitionInteractor(
-                    transitionRepository,
-                    testScope.backgroundScope,
-                ),
+                transitionInteractor,
                 UdfpsKeyguardInteractor(
                     configRepository,
                     BurnInInteractor(
diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/controls/ui/MediaCarouselControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/media/controls/ui/MediaCarouselControllerTest.kt
index 5b8272b0..ef51e47 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/media/controls/ui/MediaCarouselControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/media/controls/ui/MediaCarouselControllerTest.kt
@@ -30,6 +30,7 @@
 import com.android.internal.logging.InstanceId
 import com.android.keyguard.KeyguardUpdateMonitor
 import com.android.keyguard.KeyguardUpdateMonitorCallback
+import com.android.keyguard.TestScopeProvider
 import com.android.systemui.R
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.classifier.FalsingCollector
@@ -37,6 +38,7 @@
 import com.android.systemui.dump.DumpManager
 import com.android.systemui.keyguard.data.repository.FakeKeyguardTransitionRepository
 import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
+import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractorFactory
 import com.android.systemui.keyguard.shared.model.KeyguardState
 import com.android.systemui.keyguard.shared.model.TransitionState
 import com.android.systemui.keyguard.shared.model.TransitionStep
@@ -66,7 +68,6 @@
 import junit.framework.Assert.assertFalse
 import junit.framework.Assert.assertTrue
 import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.test.TestScope
 import kotlinx.coroutines.test.UnconfinedTestDispatcher
 import kotlinx.coroutines.test.runTest
 import org.junit.Before
@@ -132,7 +133,7 @@
     @Before
     fun setup() {
         MockitoAnnotations.initMocks(this)
-        context.resources.configuration.locales = LocaleList(Locale.US, Locale.UK)
+        context.resources.configuration.setLocales(LocaleList(Locale.US, Locale.UK))
         transitionRepository = FakeKeyguardTransitionRepository()
         mediaCarouselController =
             MediaCarouselController(
@@ -152,7 +153,11 @@
                 debugLogger,
                 mediaFlags,
                 keyguardUpdateMonitor,
-                KeyguardTransitionInteractor(transitionRepository, TestScope().backgroundScope),
+                KeyguardTransitionInteractorFactory.create(
+                        scope = TestScopeProvider.getTestScope().backgroundScope,
+                        repository = transitionRepository,
+                    )
+                    .keyguardTransitionInteractor,
                 globalSettings
             )
         verify(configurationController).addCallback(capture(configListener))
@@ -730,13 +735,13 @@
 
     @Test
     fun testOnLocaleListChanged_playersAreAddedBack() {
-        context.resources.configuration.locales = LocaleList(Locale.US, Locale.UK, Locale.CANADA)
+        context.resources.configuration.setLocales(LocaleList(Locale.US, Locale.UK, Locale.CANADA))
         testConfigurationChange(configListener.value::onLocaleListChanged)
 
         verify(pageIndicator, never()).tintList =
             ColorStateList.valueOf(context.getColor(R.color.media_paging_indicator))
 
-        context.resources.configuration.locales = LocaleList(Locale.UK, Locale.US, Locale.CANADA)
+        context.resources.configuration.setLocales(LocaleList(Locale.UK, Locale.US, Locale.CANADA))
         testConfigurationChange(configListener.value::onLocaleListChanged)
 
         verify(pageIndicator).tintList =
diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputBaseDialogTest.java b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputBaseDialogTest.java
index ab24c46..db00e09 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputBaseDialogTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputBaseDialogTest.java
@@ -278,6 +278,21 @@
     }
 
     @Test
+    public void
+            whenNotBroadcasting_verifyLeBroadcastServiceCallBackIsUnregisteredIfProfileEnabled() {
+        when(mLocalBluetoothProfileManager.getLeAudioBroadcastProfile()).thenReturn(
+                mLocalBluetoothLeBroadcast);
+        mIsBroadcasting = true;
+
+        mMediaOutputBaseDialogImpl.start();
+        verify(mLocalBluetoothLeBroadcast).registerServiceCallBack(any(), any());
+
+        mIsBroadcasting = false;
+        mMediaOutputBaseDialogImpl.stop();
+        verify(mLocalBluetoothLeBroadcast).unregisterServiceCallBack(any());
+    }
+
+    @Test
     public void refresh_checkStopText() {
         mStopText = "test_string";
         mMediaOutputBaseDialogImpl.refresh();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogTest.java b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogTest.java
index 3e69a29..bfc8c83 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogTest.java
@@ -256,6 +256,30 @@
     }
 
     @Test
+    public void isBroadcastSupported_noBleDeviceAndEnabledBroadcast_returnsTrue() {
+        when(mLocalBluetoothProfileManager.getLeAudioBroadcastProfile()).thenReturn(
+                mLocalBluetoothLeBroadcast);
+        when(mLocalBluetoothLeBroadcast.isEnabled(any())).thenReturn(true);
+        FeatureFlagUtils.setEnabled(mContext,
+                FeatureFlagUtils.SETTINGS_NEED_CONNECTED_BLE_DEVICE_FOR_BROADCAST, true);
+        when(mMediaDevice.isBLEDevice()).thenReturn(false);
+
+        assertThat(mMediaOutputDialog.isBroadcastSupported()).isTrue();
+    }
+
+    @Test
+    public void isBroadcastSupported_noBleDeviceAndDisabledBroadcast_returnsFalse() {
+        when(mLocalBluetoothProfileManager.getLeAudioBroadcastProfile()).thenReturn(
+                mLocalBluetoothLeBroadcast);
+        when(mLocalBluetoothLeBroadcast.isEnabled(any())).thenReturn(false);
+        FeatureFlagUtils.setEnabled(mContext,
+                FeatureFlagUtils.SETTINGS_NEED_CONNECTED_BLE_DEVICE_FOR_BROADCAST, true);
+        when(mMediaDevice.isBLEDevice()).thenReturn(false);
+
+        assertThat(mMediaOutputDialog.isBroadcastSupported()).isFalse();
+    }
+
+    @Test
     public void getBroadcastIconVisibility_isBroadcasting_returnVisible() {
         when(mLocalBluetoothProfileManager.getLeAudioBroadcastProfile()).thenReturn(
                 mLocalBluetoothLeBroadcast);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/mediaprojection/appselector/view/TaskPreviewSizeProviderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/mediaprojection/appselector/view/TaskPreviewSizeProviderTest.kt
index ee3b80a..906420d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/mediaprojection/appselector/view/TaskPreviewSizeProviderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/mediaprojection/appselector/view/TaskPreviewSizeProviderTest.kt
@@ -123,7 +123,7 @@
 
     private fun givenDisplay(width: Int, height: Int, isTablet: Boolean = false) {
         val bounds = Rect(0, 0, width, height)
-        val windowMetrics = WindowMetrics(bounds, null)
+        val windowMetrics = WindowMetrics(bounds, { null }, 1.0f)
         whenever(windowManager.maximumWindowMetrics).thenReturn(windowMetrics)
         whenever(windowManager.currentWindowMetrics).thenReturn(windowMetrics)
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/mediaprojection/taskswitcher/data/repository/MediaProjectionManagerRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/mediaprojection/taskswitcher/data/repository/MediaProjectionManagerRepositoryTest.kt
index 3a74c72..7bd97ce 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/mediaprojection/taskswitcher/data/repository/MediaProjectionManagerRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/mediaprojection/taskswitcher/data/repository/MediaProjectionManagerRepositoryTest.kt
@@ -108,20 +108,6 @@
         }
 
     @Test
-    fun mediaProjectionState_onSessionSet_tokenNull_emitsEntireScreen() =
-        testScope.runTest {
-            val state by collectLastValue(repo.mediaProjectionState)
-            runCurrent()
-
-            fakeMediaProjectionManager.dispatchOnSessionSet(
-                session =
-                    ContentRecordingSession.createTaskSession(/* taskWindowContainerToken= */ null)
-            )
-
-            assertThat(state).isEqualTo(MediaProjectionState.EntireScreen)
-        }
-
-    @Test
     fun mediaProjectionState_sessionSet_taskWithToken_noMatchingRunningTask_emitsEntireScreen() =
         testScope.runTest {
             val state by collectLastValue(repo.mediaProjectionState)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/navigationbar/gestural/BackPanelControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/navigationbar/gestural/BackPanelControllerTest.kt
index fab1de0..2d3dc58 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/navigationbar/gestural/BackPanelControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/navigationbar/gestural/BackPanelControllerTest.kt
@@ -73,7 +73,7 @@
                 context,
                 windowManager,
                 ViewConfiguration.get(context),
-                Handler.createAsync(Looper.myLooper()),
+                Handler.createAsync(checkNotNull(Looper.myLooper())),
                 vibratorHelper,
                 configurationController,
                 latencyTracker,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/notetask/NoteTaskControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/notetask/NoteTaskControllerTest.kt
index d933b57..1536c17 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/notetask/NoteTaskControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/notetask/NoteTaskControllerTest.kt
@@ -69,6 +69,7 @@
 import com.android.wm.shell.bubbles.Bubbles
 import com.google.common.truth.Truth.assertThat
 import java.util.Optional
+import kotlin.test.assertNotNull
 import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.test.TestScope
 import kotlinx.coroutines.test.UnconfinedTestDispatcher
@@ -672,7 +673,7 @@
             extras().bool(EXTRA_USE_STYLUS_MODE).isTrue()
         }
         iconCaptor.value?.let { icon ->
-            assertThat(icon).isNotNull()
+            assertNotNull(icon)
             assertThat(icon.resId).isEqualTo(R.drawable.ic_note_task_shortcut_widget)
         }
     }
@@ -755,7 +756,7 @@
             assertThat(shortLabel).isEqualTo(NOTE_TASK_SHORT_LABEL)
             assertThat(longLabel).isEqualTo(NOTE_TASK_LONG_LABEL)
             assertThat(isLongLived).isEqualTo(true)
-            assertThat(icon.resId).isEqualTo(R.drawable.ic_note_task_shortcut_widget)
+            assertThat(icon?.resId).isEqualTo(R.drawable.ic_note_task_shortcut_widget)
             assertThat(extras?.getString(EXTRA_SHORTCUT_BADGE_OVERRIDE_PACKAGE))
                 .isEqualTo(NOTE_TASK_PACKAGE_NAME)
         }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/privacy/AppOpsPrivacyItemMonitorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/privacy/AppOpsPrivacyItemMonitorTest.kt
index db96d55..14ecf93 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/privacy/AppOpsPrivacyItemMonitorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/privacy/AppOpsPrivacyItemMonitorTest.kt
@@ -143,6 +143,16 @@
     }
 
     @Test
+    fun testVoiceActivationPrivacyItems() {
+        doReturn(listOf(AppOpItem(AppOpsManager.OP_RECEIVE_SANDBOX_TRIGGER_AUDIO, TEST_UID,
+                TEST_PACKAGE_NAME, 0)))
+                .`when`(appOpsController).getActiveAppOps(anyBoolean())
+        val privacyItems = appOpsPrivacyItemMonitor.getActivePrivacyItems()
+        assertEquals(1, privacyItems.size)
+        assertEquals(PrivacyType.TYPE_MICROPHONE, privacyItems[0].privacyType)
+    }
+
+    @Test
     fun testSimilarItemsDifferentTimeStamp() {
         doReturn(listOf(AppOpItem(AppOpsManager.OP_CAMERA, TEST_UID, TEST_PACKAGE_NAME, 0),
                 AppOpItem(AppOpsManager.OP_CAMERA, TEST_UID, TEST_PACKAGE_NAME, 1)))
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerControllerTest.java
index 65210d6..e905e9c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerControllerTest.java
@@ -132,7 +132,7 @@
                 /* enableOnLockScreen */ true);
         verifyActivityDetails(null);
         assertThat(mController.isEnabledForLockScreenButton()).isFalse();
-        assertThat(mController.isAbleToOpenCameraApp()).isFalse();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isFalse();
     }
 
     @Test
@@ -151,7 +151,7 @@
                 /* enableOnLockScreen */ true);
         verifyActivityDetails("abc/.def");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
     }
 
     @Test
@@ -161,7 +161,7 @@
                 /* enableOnLockScreen */ true);
         verifyActivityDetails("abc/.def");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
     }
 
     @Test
@@ -171,7 +171,7 @@
                 /* enableOnLockScreen */ true);
         verifyActivityDetails("abc/.def");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
     }
 
     @Test
@@ -181,7 +181,7 @@
                 /* enableOnLockScreen */ true);
         verifyActivityDetails("abc/abc.def");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
     }
 
     @Test
@@ -191,7 +191,7 @@
                 /* enableOnLockScreen */ true);
         verifyActivityDetails(null);
         assertThat(mController.isEnabledForLockScreenButton()).isFalse();
-        assertThat(mController.isAbleToOpenCameraApp()).isFalse();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isFalse();
     }
 
     @Test
@@ -201,24 +201,24 @@
                 /* enableOnLockScreen */ true);
         verifyActivityDetails("abc/.def");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
 
         mProxyFake.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
                 SystemUiDeviceConfigFlags.DEFAULT_QR_CODE_SCANNER,
                 "def/.ijk", false);
         verifyActivityDetails("def/.ijk");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
 
         mProxyFake.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
                 SystemUiDeviceConfigFlags.DEFAULT_QR_CODE_SCANNER,
                 null, false);
         verifyActivityDetails("abc/.def");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
 
-        // Once from setup + twice from this function
-        verify(mCallback, times(3)).onQRCodeScannerActivityChanged();
+        // twice from this function
+        verify(mCallback, times(2)).onQRCodeScannerActivityChanged();
     }
 
     @Test
@@ -228,7 +228,7 @@
                 /* enableOnLockScreen */ true);
         verifyActivityDetails(null);
         assertThat(mController.isEnabledForLockScreenButton()).isFalse();
-        assertThat(mController.isAbleToOpenCameraApp()).isFalse();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isFalse();
 
         mProxyFake.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
                 SystemUiDeviceConfigFlags.DEFAULT_QR_CODE_SCANNER,
@@ -236,14 +236,14 @@
 
         verifyActivityDetails("def/.ijk");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
 
         mProxyFake.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
                 SystemUiDeviceConfigFlags.DEFAULT_QR_CODE_SCANNER,
                 null, false);
         verifyActivityDetails(null);
         assertThat(mController.isEnabledForLockScreenButton()).isFalse();
-        assertThat(mController.isAbleToOpenCameraApp()).isFalse();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isFalse();
         verify(mCallback, times(2)).onQRCodeScannerActivityChanged();
     }
 
@@ -295,19 +295,20 @@
                 /* enableOnLockScreen */ true);
         verifyActivityDetails("abc/.def");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
 
         mSecureSettings.putStringForUser(LOCK_SCREEN_SHOW_QR_CODE_SCANNER, "0",
                 UserHandle.USER_CURRENT);
         verifyActivityDetails("abc/.def");
         assertThat(mController.isEnabledForLockScreenButton()).isFalse();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAllowedOnLockScreen()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
 
         mSecureSettings.putStringForUser(LOCK_SCREEN_SHOW_QR_CODE_SCANNER, "1",
                 UserHandle.USER_CURRENT);
         verifyActivityDetails("abc/.def");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
         // Once from setup + twice from this function
         verify(mCallback, times(3)).onQRCodeScannerPreferenceChanged();
     }
@@ -319,13 +320,13 @@
                 /* enableOnLockScreen */ true);
         verifyActivityDetails("abc/.def");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
 
+        // even if unregistered, intent and activity details are retained
         mController.unregisterQRCodeScannerChangeObservers(DEFAULT_QR_CODE_SCANNER_CHANGE,
                 QR_CODE_SCANNER_PREFERENCE_CHANGE);
-        verifyActivityDetails(null);
-        assertThat(mController.isEnabledForLockScreenButton()).isFalse();
-        assertThat(mController.isAbleToOpenCameraApp()).isFalse();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
+        assertThat(mController.isAllowedOnLockScreen()).isTrue();
 
         // Unregister once again and make sure it affects the next register event
         mController.unregisterQRCodeScannerChangeObservers(DEFAULT_QR_CODE_SCANNER_CHANGE,
@@ -334,7 +335,7 @@
                 QR_CODE_SCANNER_PREFERENCE_CHANGE);
         verifyActivityDetails("abc/.def");
         assertThat(mController.isEnabledForLockScreenButton()).isTrue();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
     }
 
     @Test
@@ -344,7 +345,7 @@
                 /* enableOnLockScreen */ false);
         assertThat(mController.getIntent()).isNotNull();
         assertThat(mController.isEnabledForLockScreenButton()).isFalse();
-        assertThat(mController.isAbleToOpenCameraApp()).isTrue();
+        assertThat(mController.isAbleToLaunchScannerActivity()).isTrue();
         assertThat(getSettingsQRCodeDefaultComponent()).isNull();
     }
 }
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 9781baa..64d3b82 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
@@ -53,7 +53,6 @@
 import com.android.systemui.classifier.FalsingManagerFake;
 import com.android.systemui.dump.nano.SystemUIProtoDump;
 import com.android.systemui.flags.FakeFeatureFlags;
-import com.android.systemui.flags.FeatureFlags;
 import com.android.systemui.flags.Flags;
 import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.plugins.PluginManager;
@@ -65,6 +64,7 @@
 import com.android.systemui.qs.external.TileLifecycleManager;
 import com.android.systemui.qs.external.TileServiceKey;
 import com.android.systemui.qs.logging.QSLogger;
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository;
 import com.android.systemui.qs.tileimpl.QSTileImpl;
 import com.android.systemui.settings.UserFileManager;
 import com.android.systemui.settings.UserTracker;
@@ -131,6 +131,8 @@
 
     private FakeFeatureFlags mFeatureFlags;
 
+    private QSPipelineFlagsRepository mQSPipelineFlagsRepository;
+
     private FakeExecutor mMainExecutor;
 
     private QSTileHost mQSTileHost;
@@ -142,6 +144,7 @@
 
         mFeatureFlags.set(Flags.QS_PIPELINE_NEW_HOST, false);
         mFeatureFlags.set(Flags.QS_PIPELINE_AUTO_ADD, false);
+        mQSPipelineFlagsRepository = new QSPipelineFlagsRepository(mFeatureFlags);
 
         mMainExecutor = new FakeExecutor(new FakeSystemClock());
 
@@ -164,7 +167,7 @@
         mQSTileHost = new TestQSTileHost(mContext, mDefaultFactory, mMainExecutor,
                 mPluginManager, mTunerService, () -> mAutoTiles, mShadeController,
                 mQSLogger, mUserTracker, mSecureSettings, mCustomTileStatePersister,
-                mTileLifecycleManagerFactory, mUserFileManager, mFeatureFlags);
+                mTileLifecycleManagerFactory, mUserFileManager, mQSPipelineFlagsRepository);
         mMainExecutor.runAllReady();
 
         mSecureSettings.registerContentObserverForUser(SETTING, new ContentObserver(null) {
@@ -708,7 +711,7 @@
                 UserTracker userTracker, SecureSettings secureSettings,
                 CustomTileStatePersister customTileStatePersister,
                 TileLifecycleManager.Factory tileLifecycleManagerFactory,
-                UserFileManager userFileManager, FeatureFlags featureFlags) {
+                UserFileManager userFileManager, QSPipelineFlagsRepository featureFlags) {
             super(context, defaultFactory, mainExecutor, pluginManager,
                     tunerService, autoTiles,  shadeController, qsLogger,
                     userTracker, secureSettings, customTileStatePersister,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/data/repository/TileSpecSettingsRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/data/repository/TileSpecSettingsRepositoryTest.kt
index fda63ed..72c31b1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/data/repository/TileSpecSettingsRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/data/repository/TileSpecSettingsRepositoryTest.kt
@@ -32,6 +32,7 @@
 import kotlinx.coroutines.coroutineScope
 import kotlinx.coroutines.test.StandardTestDispatcher
 import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
 import kotlinx.coroutines.test.runTest
 import org.junit.Before
 import org.junit.Test
@@ -372,12 +373,23 @@
             assertThat(loadTilesForUser(0)).isNull()
         }
 
+    @Test
+    fun emptyTilesReplacedByDefaultInSettings() =
+        testScope.runTest {
+            val tiles by collectLastValue(underTest.tilesSpecs(0))
+            runCurrent()
+
+            assertThat(loadTilesForUser(0))
+                .isEqualTo(getDefaultTileSpecs().map { it.spec }.joinToString(","))
+        }
+
     private fun getDefaultTileSpecs(): List<TileSpec> {
         return QSHost.getDefaultSpecs(context.resources).map(TileSpec::create)
     }
 
-    private fun storeTilesForUser(specs: String, forUser: Int) {
+    private fun TestScope.storeTilesForUser(specs: String, forUser: Int) {
         secureSettings.putStringForUser(SETTING, specs, forUser)
+        runCurrent()
     }
 
     private fun loadTilesForUser(forUser: Int): String? {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractorImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractorImplTest.kt
index 30cea2d..54a9360 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractorImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractorImplTest.kt
@@ -42,6 +42,7 @@
 import com.android.systemui.qs.pipeline.data.repository.FakeTileSpecRepository
 import com.android.systemui.qs.pipeline.data.repository.TileSpecRepository
 import com.android.systemui.qs.pipeline.domain.model.TileModel
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository
 import com.android.systemui.qs.pipeline.shared.TileSpec
 import com.android.systemui.qs.pipeline.shared.logging.QSPipelineLogger
 import com.android.systemui.qs.toProto
@@ -79,6 +80,7 @@
     private val customTileAddedRepository: CustomTileAddedRepository =
         FakeCustomTileAddedRepository()
     private val featureFlags = FakeFeatureFlags()
+    private val pipelineFlags = QSPipelineFlagsRepository(featureFlags)
     private val tileLifecycleManagerFactory = TLMFactory()
 
     @Mock private lateinit var customTileStatePersister: CustomTileStatePersister
@@ -120,7 +122,7 @@
                 backgroundDispatcher = testDispatcher,
                 scope = testScope.backgroundScope,
                 logger = logger,
-                featureFlags = featureFlags,
+                featureFlags = pipelineFlags,
             )
     }
 
@@ -648,6 +650,22 @@
             assertThat(tiles!![1].spec).isEqualTo(CUSTOM_TILE_SPEC)
         }
 
+    @Test
+    fun tileAddedOnEmptyList_blocked() =
+        testScope.runTest(USER_INFO_0) {
+            val tiles by collectLastValue(underTest.currentTiles)
+            val specs = listOf(TileSpec.create("a"), TileSpec.create("b"))
+            val newTile = TileSpec.create("c")
+
+            underTest.addTile(newTile)
+
+            assertThat(tiles!!.isEmpty()).isTrue()
+
+            tileSpecRepository.setTiles(USER_INFO_0.id, specs)
+
+            assertThat(tiles!!.size).isEqualTo(3)
+        }
+
     private fun QSTile.State.fillIn(state: Int, label: CharSequence, secondaryLabel: CharSequence) {
         this.state = state
         this.label = label
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepositoryTest.kt
new file mode 100644
index 0000000..489221e
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepositoryTest.kt
@@ -0,0 +1,61 @@
+package com.android.systemui.qs.pipeline.shared
+
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.flags.FakeFeatureFlags
+import com.android.systemui.flags.Flags
+import com.google.common.truth.Truth.assertThat
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+import org.junit.runners.Parameterized.Parameter
+import org.junit.runners.Parameterized.Parameters
+
+@SmallTest
+@RunWith(Parameterized::class)
+class QSPipelineFlagsRepositoryTest : SysuiTestCase() {
+    companion object {
+        @Parameters(
+            name =
+                """
+WHEN: qs_pipeline_new_host = {0}, qs_pipeline_auto_add = {1}
+THEN: pipelineNewHost = {2}, pipelineAutoAdd = {3}
+                """
+        )
+        @JvmStatic
+        fun data(): List<Array<Boolean>> =
+            (0 until 4).map { combination ->
+                val qs_pipeline_new_host = combination and 0b10 != 0
+                val qs_pipeline_auto_add = combination and 0b01 != 0
+                arrayOf(
+                    qs_pipeline_new_host,
+                    qs_pipeline_auto_add,
+                    /* pipelineNewHost = */ qs_pipeline_new_host,
+                    /* pipelineAutoAdd = */ qs_pipeline_new_host && qs_pipeline_auto_add,
+                )
+            }
+    }
+
+    @JvmField @Parameter(0) var qsPipelineNewHostFlag: Boolean = false
+    @JvmField @Parameter(1) var qsPipelineAutoAddFlag: Boolean = false
+    @JvmField @Parameter(2) var pipelineNewHostExpected: Boolean = false
+    @JvmField @Parameter(3) var pipelineAutoAddExpected: Boolean = false
+
+    private val featureFlags = FakeFeatureFlags()
+    private val pipelineFlags = QSPipelineFlagsRepository(featureFlags)
+
+    @Before
+    fun setUp() {
+        featureFlags.apply {
+            set(Flags.QS_PIPELINE_NEW_HOST, qsPipelineNewHostFlag)
+            set(Flags.QS_PIPELINE_AUTO_ADD, qsPipelineAutoAddFlag)
+        }
+    }
+
+    @Test
+    fun flagLogic() {
+        assertThat(pipelineFlags.pipelineHostEnabled).isEqualTo(pipelineNewHostExpected)
+        assertThat(pipelineFlags.pipelineAutoAddEnabled).isEqualTo(pipelineAutoAddExpected)
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/QRCodeScannerTileTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/QRCodeScannerTileTest.java
index 6f2d904..71aa7a8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/QRCodeScannerTileTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/QRCodeScannerTileTest.java
@@ -117,7 +117,7 @@
 
     @Test
     public void testQRCodeTileUnavailable() {
-        when(mController.isAbleToOpenCameraApp()).thenReturn(false);
+        when(mController.isAbleToLaunchScannerActivity()).thenReturn(false);
         QSTile.State state = new QSTile.State();
         mTile.handleUpdateState(state, null);
         assertEquals(state.state, Tile.STATE_UNAVAILABLE);
@@ -127,7 +127,7 @@
 
     @Test
     public void testQRCodeTileAvailable() {
-        when(mController.isAbleToOpenCameraApp()).thenReturn(true);
+        when(mController.isAbleToLaunchScannerActivity()).thenReturn(true);
         QSTile.State state = new QSTile.State();
         mTile.handleUpdateState(state, null);
         assertEquals(state.state, Tile.STATE_INACTIVE);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/ui/viewmodel/QuickSettingsSceneViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/ui/viewmodel/QuickSettingsSceneViewModelTest.kt
index ee42a70..2cb0205 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/ui/viewmodel/QuickSettingsSceneViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/ui/viewmodel/QuickSettingsSceneViewModelTest.kt
@@ -18,7 +18,7 @@
 
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.scene.SceneTestUtils
 import com.android.systemui.scene.shared.model.SceneKey
@@ -46,21 +46,17 @@
 
     private val underTest =
         QuickSettingsSceneViewModel(
-            lockscreenSceneInteractor =
-                utils.lockScreenSceneInteractor(
+            bouncerInteractor =
+                utils.bouncerInteractor(
                     authenticationInteractor = authenticationInteractor,
-                    bouncerInteractor =
-                        utils.bouncerInteractor(
-                            authenticationInteractor = authenticationInteractor,
-                            sceneInteractor = sceneInteractor,
-                        ),
+                    sceneInteractor = sceneInteractor,
                 ),
         )
 
     @Test
     fun onContentClicked_deviceUnlocked_switchesToGone() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(true)
             runCurrent()
@@ -73,7 +69,7 @@
     @Test
     fun onContentClicked_deviceLockedSecurely_switchesToBouncer() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
             runCurrent()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt b/packages/SystemUI/tests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt
new file mode 100644
index 0000000..53c04cc
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt
@@ -0,0 +1,538 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+@file:OptIn(ExperimentalCoroutinesApi::class)
+
+package com.android.systemui.scene
+
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.data.repository.FakeAuthenticationRepository
+import com.android.systemui.authentication.domain.model.AuthenticationMethodModel as DomainLayerAuthenticationMethodModel
+import com.android.systemui.authentication.domain.model.AuthenticationMethodModel
+import com.android.systemui.bouncer.ui.viewmodel.PinBouncerViewModel
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.flags.FakeFeatureFlags
+import com.android.systemui.flags.Flags
+import com.android.systemui.keyguard.shared.model.WakefulnessState
+import com.android.systemui.keyguard.ui.viewmodel.LockscreenSceneViewModel
+import com.android.systemui.model.SysUiState
+import com.android.systemui.scene.SceneTestUtils.Companion.toDataLayer
+import com.android.systemui.scene.domain.startable.SceneContainerStartable
+import com.android.systemui.scene.shared.model.ObservableTransitionState
+import com.android.systemui.scene.shared.model.SceneKey
+import com.android.systemui.scene.shared.model.SceneModel
+import com.android.systemui.scene.ui.viewmodel.SceneContainerViewModel
+import com.android.systemui.settings.FakeDisplayTracker
+import com.android.systemui.shade.ui.viewmodel.ShadeSceneViewModel
+import com.android.systemui.util.mockito.mock
+import com.google.common.truth.Truth.assertThat
+import com.google.common.truth.Truth.assertWithMessage
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+
+/**
+ * Integration test cases for the Scene Framework.
+ *
+ * **Principles**
+ * * All test cases here should be done from the perspective of the view-models of the system.
+ * * Focus on happy paths, let smaller unit tests focus on failure cases.
+ * * These are _integration_ tests and, as such, are larger and harder to maintain than unit tests.
+ *   Therefore, when adding or modifying test cases, consider whether what you're testing is better
+ *   covered by a more granular unit test.
+ * * Please reuse the helper methods in this class (for example, [putDeviceToSleep] or
+ *   [emulateUserDrivenTransition]).
+ * * All tests start with the device locked and with a PIN auth method. The class offers useful
+ *   methods like [setAuthMethod], [unlockDevice], [lockDevice], etc. to help you set up a starting
+ *   state that makes more sense for your test case.
+ * * All helper methods in this class make assertions that are meant to make sure that they're only
+ *   being used when the state is as required (e.g. cannot unlock an already unlocked device, cannot
+ *   put to sleep a device that's already asleep, etc.).
+ */
+@SmallTest
+@RunWith(JUnit4::class)
+class SceneFrameworkIntegrationTest : SysuiTestCase() {
+
+    private val utils = SceneTestUtils(this)
+    private val testScope = utils.testScope
+
+    private val sceneContainerConfig = utils.fakeSceneContainerConfig()
+    private val sceneRepository =
+        utils.fakeSceneContainerRepository(
+            containerConfig = sceneContainerConfig,
+        )
+    private val sceneInteractor =
+        utils.sceneInteractor(
+            repository = sceneRepository,
+        )
+
+    private val authenticationRepository = utils.authenticationRepository()
+    private val authenticationInteractor =
+        utils.authenticationInteractor(
+            repository = authenticationRepository,
+            sceneInteractor = sceneInteractor,
+        )
+
+    private val transitionState =
+        MutableStateFlow<ObservableTransitionState>(
+            ObservableTransitionState.Idle(sceneContainerConfig.initialSceneKey)
+        )
+    private val sceneContainerViewModel =
+        SceneContainerViewModel(
+                interactor = sceneInteractor,
+            )
+            .apply { setTransitionState(transitionState) }
+
+    private val bouncerInteractor =
+        utils.bouncerInteractor(
+            authenticationInteractor = authenticationInteractor,
+            sceneInteractor = sceneInteractor,
+        )
+    private val bouncerViewModel =
+        utils.bouncerViewModel(
+            bouncerInteractor = bouncerInteractor,
+            authenticationInteractor = authenticationInteractor,
+        )
+
+    private val lockscreenSceneViewModel =
+        LockscreenSceneViewModel(
+            applicationScope = testScope.backgroundScope,
+            authenticationInteractor = authenticationInteractor,
+            bouncerInteractor = bouncerInteractor,
+        )
+
+    private val shadeSceneViewModel =
+        ShadeSceneViewModel(
+            applicationScope = testScope.backgroundScope,
+            authenticationInteractor = authenticationInteractor,
+            bouncerInteractor = bouncerInteractor,
+        )
+
+    private val keyguardRepository = utils.keyguardRepository()
+    private val keyguardInteractor =
+        utils.keyguardInteractor(
+            repository = keyguardRepository,
+        )
+
+    @Before
+    fun setUp() {
+        val featureFlags = FakeFeatureFlags().apply { set(Flags.SCENE_CONTAINER, true) }
+
+        authenticationRepository.setUnlocked(false)
+
+        val displayTracker = FakeDisplayTracker(context)
+        val sysUiState = SysUiState(displayTracker)
+        val startable =
+            SceneContainerStartable(
+                applicationScope = testScope.backgroundScope,
+                sceneInteractor = sceneInteractor,
+                authenticationInteractor = authenticationInteractor,
+                keyguardInteractor = keyguardInteractor,
+                featureFlags = featureFlags,
+                sysUiState = sysUiState,
+                displayId = displayTracker.defaultDisplayId,
+                sceneLogger = mock(),
+            )
+        startable.start()
+
+        assertWithMessage("Initial scene key mismatch!")
+            .that(sceneContainerViewModel.currentScene.value.key)
+            .isEqualTo(sceneContainerConfig.initialSceneKey)
+        assertWithMessage("Initial scene container visibility mismatch!")
+            .that(sceneContainerViewModel.isVisible.value)
+            .isTrue()
+    }
+
+    @Test
+    fun clickLockButtonAndEnterCorrectPin_unlocksDevice() =
+        testScope.runTest {
+            lockscreenSceneViewModel.onLockButtonClicked()
+            assertCurrentScene(SceneKey.Bouncer)
+            emulateUiSceneTransition()
+
+            enterPin()
+            assertCurrentScene(SceneKey.Gone)
+            emulateUiSceneTransition(
+                expectedVisible = false,
+            )
+        }
+
+    @Test
+    fun swipeUpOnLockscreen_enterCorrectPin_unlocksDevice() =
+        testScope.runTest {
+            val upDestinationSceneKey by
+                collectLastValue(lockscreenSceneViewModel.upDestinationSceneKey)
+            assertThat(upDestinationSceneKey).isEqualTo(SceneKey.Bouncer)
+            emulateUserDrivenTransition(
+                to = upDestinationSceneKey,
+            )
+
+            enterPin()
+            assertCurrentScene(SceneKey.Gone)
+            emulateUiSceneTransition(
+                expectedVisible = false,
+            )
+        }
+
+    @Test
+    fun swipeUpOnLockscreen_withAuthMethodSwipe_dismissesLockscreen() =
+        testScope.runTest {
+            setAuthMethod(DomainLayerAuthenticationMethodModel.Swipe)
+
+            val upDestinationSceneKey by
+                collectLastValue(lockscreenSceneViewModel.upDestinationSceneKey)
+            assertThat(upDestinationSceneKey).isEqualTo(SceneKey.Gone)
+            emulateUserDrivenTransition(
+                to = upDestinationSceneKey,
+            )
+        }
+
+    @Test
+    fun swipeUpOnShadeScene_withAuthMethodSwipe_lockscreenNotDismissed_goesToLockscreen() =
+        testScope.runTest {
+            val upDestinationSceneKey by collectLastValue(shadeSceneViewModel.upDestinationSceneKey)
+            setAuthMethod(DomainLayerAuthenticationMethodModel.Swipe)
+            assertCurrentScene(SceneKey.Lockscreen)
+
+            // Emulate a user swipe to the shade scene.
+            emulateUserDrivenTransition(to = SceneKey.Shade)
+            assertCurrentScene(SceneKey.Shade)
+
+            assertThat(upDestinationSceneKey).isEqualTo(SceneKey.Lockscreen)
+            emulateUserDrivenTransition(
+                to = upDestinationSceneKey,
+            )
+        }
+
+    @Test
+    fun swipeUpOnShadeScene_withAuthMethodSwipe_lockscreenDismissed_goesToGone() =
+        testScope.runTest {
+            val upDestinationSceneKey by collectLastValue(shadeSceneViewModel.upDestinationSceneKey)
+            setAuthMethod(DomainLayerAuthenticationMethodModel.Swipe)
+            assertCurrentScene(SceneKey.Lockscreen)
+
+            // Emulate a user swipe to dismiss the lockscreen.
+            emulateUserDrivenTransition(to = SceneKey.Gone)
+            assertCurrentScene(SceneKey.Gone)
+
+            // Emulate a user swipe to the shade scene.
+            emulateUserDrivenTransition(to = SceneKey.Shade)
+            assertCurrentScene(SceneKey.Shade)
+
+            assertThat(upDestinationSceneKey).isEqualTo(SceneKey.Gone)
+            emulateUserDrivenTransition(
+                to = upDestinationSceneKey,
+            )
+        }
+
+    @Test
+    fun withAuthMethodNone_deviceWakeUp_skipsLockscreen() =
+        testScope.runTest {
+            setAuthMethod(AuthenticationMethodModel.None)
+            putDeviceToSleep(instantlyLockDevice = false)
+            assertCurrentScene(SceneKey.Lockscreen)
+
+            wakeUpDevice()
+            assertCurrentScene(SceneKey.Gone)
+        }
+
+    @Test
+    fun withAuthMethodSwipe_deviceWakeUp_doesNotSkipLockscreen() =
+        testScope.runTest {
+            setAuthMethod(AuthenticationMethodModel.Swipe)
+            putDeviceToSleep(instantlyLockDevice = false)
+            assertCurrentScene(SceneKey.Lockscreen)
+
+            wakeUpDevice()
+            assertCurrentScene(SceneKey.Lockscreen)
+        }
+
+    @Test
+    fun deviceGoesToSleep_switchesToLockscreen() =
+        testScope.runTest {
+            unlockDevice()
+            assertCurrentScene(SceneKey.Gone)
+
+            putDeviceToSleep()
+            assertCurrentScene(SceneKey.Lockscreen)
+        }
+
+    @Test
+    fun deviceGoesToSleep_wakeUp_unlock() =
+        testScope.runTest {
+            unlockDevice()
+            assertCurrentScene(SceneKey.Gone)
+            putDeviceToSleep()
+            assertCurrentScene(SceneKey.Lockscreen)
+            wakeUpDevice()
+            assertCurrentScene(SceneKey.Lockscreen)
+
+            unlockDevice()
+            assertCurrentScene(SceneKey.Gone)
+        }
+
+    @Test
+    fun deviceWakesUpWhileUnlocked_dismissesLockscreen() =
+        testScope.runTest {
+            unlockDevice()
+            assertCurrentScene(SceneKey.Gone)
+            putDeviceToSleep(instantlyLockDevice = false)
+            assertCurrentScene(SceneKey.Lockscreen)
+            wakeUpDevice()
+            assertCurrentScene(SceneKey.Gone)
+        }
+
+    @Test
+    fun swipeUpOnLockscreenWhileUnlocked_dismissesLockscreen() =
+        testScope.runTest {
+            unlockDevice()
+            val upDestinationSceneKey by
+                collectLastValue(lockscreenSceneViewModel.upDestinationSceneKey)
+            assertThat(upDestinationSceneKey).isEqualTo(SceneKey.Gone)
+        }
+
+    @Test
+    fun deviceGoesToSleep_withLockTimeout_staysOnLockscreen() =
+        testScope.runTest {
+            unlockDevice()
+            assertCurrentScene(SceneKey.Gone)
+            putDeviceToSleep(instantlyLockDevice = false)
+            assertCurrentScene(SceneKey.Lockscreen)
+
+            // Pretend like the timeout elapsed and now lock the device.
+            lockDevice()
+            assertCurrentScene(SceneKey.Lockscreen)
+        }
+
+    /**
+     * Asserts that the current scene in the view-model matches what's expected.
+     *
+     * Note that this doesn't assert what the current scene is in the UI.
+     */
+    private fun TestScope.assertCurrentScene(expected: SceneKey) {
+        runCurrent()
+        assertWithMessage("Current scene mismatch!")
+            .that(sceneContainerViewModel.currentScene.value.key)
+            .isEqualTo(expected)
+    }
+
+    /**
+     * Returns the [SceneKey] of the current scene as displayed in the UI.
+     *
+     * This can be different than the value in [SceneContainerViewModel.currentScene], by design, as
+     * the UI must gradually transition between scenes.
+     */
+    private fun getCurrentSceneInUi(): SceneKey {
+        return when (val state = transitionState.value) {
+            is ObservableTransitionState.Idle -> state.scene
+            is ObservableTransitionState.Transition -> state.fromScene
+        }
+    }
+
+    /** Updates the current authentication method and related states in the data layer. */
+    private fun TestScope.setAuthMethod(
+        authMethod: DomainLayerAuthenticationMethodModel,
+    ) {
+        // Set the lockscreen enabled bit _before_ set the auth method as the code picks up on the
+        // lockscreen enabled bit _after_ the auth method is changed and the lockscreen enabled bit
+        // is not an observable that can trigger a new evaluation.
+        authenticationRepository.setLockscreenEnabled(authMethod !is AuthenticationMethodModel.None)
+        authenticationRepository.setAuthenticationMethod(authMethod.toDataLayer())
+        if (!authMethod.isSecure) {
+            // When the auth method is not secure, the device is never considered locked.
+            authenticationRepository.setUnlocked(true)
+        }
+        runCurrent()
+    }
+
+    /**
+     * Emulates a complete transition in the UI from whatever the current scene is in the UI to
+     * whatever the current scene should be, based on the value in
+     * [SceneContainerViewModel.onSceneChanged].
+     *
+     * This should post a series of values into [transitionState] to emulate a gradual scene
+     * transition and culminate with a call to [SceneContainerViewModel.onSceneChanged].
+     *
+     * The method asserts that a transition is actually required. E.g. it will fail if the current
+     * scene in [transitionState] is already caught up with the scene in
+     * [SceneContainerViewModel.currentScene].
+     *
+     * @param expectedVisible Whether [SceneContainerViewModel.isVisible] should be set at the end
+     *   of the UI transition.
+     */
+    private fun TestScope.emulateUiSceneTransition(
+        expectedVisible: Boolean = true,
+    ) {
+        val to = sceneContainerViewModel.currentScene.value
+        val from = getCurrentSceneInUi()
+        assertWithMessage("Cannot transition to ${to.key} as the UI is already on that scene!")
+            .that(to.key)
+            .isNotEqualTo(from)
+
+        // Begin to transition.
+        val progressFlow = MutableStateFlow(0f)
+        transitionState.value =
+            ObservableTransitionState.Transition(
+                fromScene = getCurrentSceneInUi(),
+                toScene = to.key,
+                progress = progressFlow,
+            )
+        runCurrent()
+
+        // Report progress of transition.
+        while (progressFlow.value < 1f) {
+            progressFlow.value += 0.2f
+            runCurrent()
+        }
+
+        // End the transition and report the change.
+        transitionState.value = ObservableTransitionState.Idle(to.key)
+
+        sceneContainerViewModel.onSceneChanged(to)
+        runCurrent()
+
+        assertWithMessage("Visibility mismatch after scene transition from $from to ${to.key}!")
+            .that(sceneContainerViewModel.isVisible.value)
+            .isEqualTo(expectedVisible)
+    }
+
+    /**
+     * Emulates a fire-and-forget user action (a fling or back, not a pointer-tracking swipe) that
+     * causes a scene change to the [to] scene.
+     *
+     * This also includes the emulation of the resulting UI transition that culminates with the UI
+     * catching up with the requested scene change (see [emulateUiSceneTransition]).
+     *
+     * @param to The scene to transition to.
+     */
+    private fun TestScope.emulateUserDrivenTransition(
+        to: SceneKey?,
+    ) {
+        checkNotNull(to)
+
+        sceneInteractor.changeScene(SceneModel(to), "reason")
+        assertThat(sceneContainerViewModel.currentScene.value.key).isEqualTo(to)
+
+        emulateUiSceneTransition(
+            expectedVisible = to != SceneKey.Gone,
+        )
+    }
+
+    /**
+     * Locks the device immediately (without delay).
+     *
+     * Asserts the device to be lockable (e.g. that the current authentication is secure).
+     *
+     * Not to be confused with [putDeviceToSleep], which may also instantly lock the device.
+     */
+    private suspend fun TestScope.lockDevice() {
+        val authMethod = authenticationInteractor.getAuthenticationMethod()
+        assertWithMessage("The authentication method of $authMethod is not secure, cannot lock!")
+            .that(authMethod.isSecure)
+            .isTrue()
+
+        authenticationRepository.setUnlocked(false)
+        runCurrent()
+    }
+
+    /** Unlocks the device by entering the correct PIN. Ends up in the Gone scene. */
+    private fun TestScope.unlockDevice() {
+        assertWithMessage("Cannot unlock a device that's already unlocked!")
+            .that(authenticationInteractor.isUnlocked.value)
+            .isFalse()
+
+        lockscreenSceneViewModel.onLockButtonClicked()
+        runCurrent()
+        emulateUiSceneTransition()
+
+        enterPin()
+        emulateUiSceneTransition(
+            expectedVisible = false,
+        )
+    }
+
+    /**
+     * Enters the correct PIN in the bouncer UI.
+     *
+     * Asserts that the current scene is [SceneKey.Bouncer] and that the current bouncer UI is a PIN
+     * before proceeding.
+     *
+     * Does not assert that the device is locked or unlocked.
+     */
+    private fun TestScope.enterPin() {
+        assertWithMessage("Cannot enter PIN when not on the Bouncer scene!")
+            .that(getCurrentSceneInUi())
+            .isEqualTo(SceneKey.Bouncer)
+        val authMethodViewModel by collectLastValue(bouncerViewModel.authMethod)
+        assertWithMessage("Cannot enter PIN when not using a PIN authentication method!")
+            .that(authMethodViewModel)
+            .isInstanceOf(PinBouncerViewModel::class.java)
+
+        val pinBouncerViewModel = authMethodViewModel as PinBouncerViewModel
+        FakeAuthenticationRepository.DEFAULT_PIN.forEach { digit ->
+            pinBouncerViewModel.onPinButtonClicked(digit)
+        }
+        pinBouncerViewModel.onAuthenticateButtonClicked()
+        runCurrent()
+    }
+
+    /** Changes device wakefulness state from asleep to awake, going through intermediary states. */
+    private fun TestScope.wakeUpDevice() {
+        val wakefulnessModel = keyguardRepository.wakefulness.value
+        assertWithMessage("Cannot wake up device as it's already awake!")
+            .that(wakefulnessModel.isStartingToWakeOrAwake())
+            .isFalse()
+
+        keyguardRepository.setWakefulnessModel(
+            wakefulnessModel.copy(state = WakefulnessState.STARTING_TO_WAKE)
+        )
+        runCurrent()
+        keyguardRepository.setWakefulnessModel(
+            wakefulnessModel.copy(state = WakefulnessState.AWAKE)
+        )
+        runCurrent()
+    }
+
+    /** Changes device wakefulness state from awake to asleep, going through intermediary states. */
+    private suspend fun TestScope.putDeviceToSleep(
+        instantlyLockDevice: Boolean = true,
+    ) {
+        val wakefulnessModel = keyguardRepository.wakefulness.value
+        assertWithMessage("Cannot put device to sleep as it's already asleep!")
+            .that(wakefulnessModel.isStartingToWakeOrAwake())
+            .isTrue()
+
+        keyguardRepository.setWakefulnessModel(
+            wakefulnessModel.copy(state = WakefulnessState.STARTING_TO_SLEEP)
+        )
+        runCurrent()
+        keyguardRepository.setWakefulnessModel(
+            wakefulnessModel.copy(state = WakefulnessState.ASLEEP)
+        )
+        runCurrent()
+
+        if (instantlyLockDevice) {
+            lockDevice()
+        }
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/scene/data/repository/SceneContainerRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/scene/data/repository/SceneContainerRepositoryTest.kt
index 56e3e96..181f8a7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/scene/data/repository/SceneContainerRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/scene/data/repository/SceneContainerRepositoryTest.kt
@@ -25,7 +25,6 @@
 import com.android.systemui.scene.shared.model.ObservableTransitionState
 import com.android.systemui.scene.shared.model.SceneKey
 import com.android.systemui.scene.shared.model.SceneModel
-import com.android.systemui.scene.shared.model.SceneTransitionModel
 import com.google.common.truth.Truth.assertThat
 import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.MutableStateFlow
@@ -39,6 +38,7 @@
 class SceneContainerRepositoryTest : SysuiTestCase() {
 
     private val utils = SceneTestUtils(this)
+    private val testScope = utils.testScope
 
     @Test
     fun allSceneKeys() {
@@ -56,97 +56,82 @@
     }
 
     @Test
-    fun currentScene() = runTest {
-        val underTest = utils.fakeSceneContainerRepository()
-        val currentScene by collectLastValue(underTest.currentScene)
-        assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Lockscreen))
+    fun desiredScene() =
+        testScope.runTest {
+            val underTest = utils.fakeSceneContainerRepository()
+            val currentScene by collectLastValue(underTest.desiredScene)
+            assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Lockscreen))
 
-        underTest.setCurrentScene(SceneModel(SceneKey.Shade))
-        assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Shade))
-    }
+            underTest.setDesiredScene(SceneModel(SceneKey.Shade))
+            assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Shade))
+        }
 
     @Test(expected = IllegalStateException::class)
-    fun setCurrentScene_noSuchSceneInContainer_throws() {
+    fun setDesiredScene_noSuchSceneInContainer_throws() {
         val underTest =
             utils.fakeSceneContainerRepository(
                 utils.fakeSceneContainerConfig(listOf(SceneKey.QuickSettings, SceneKey.Lockscreen)),
             )
-        underTest.setCurrentScene(SceneModel(SceneKey.Shade))
+        underTest.setDesiredScene(SceneModel(SceneKey.Shade))
     }
 
     @Test
-    fun isVisible() = runTest {
-        val underTest = utils.fakeSceneContainerRepository()
-        val isVisible by collectLastValue(underTest.isVisible)
-        assertThat(isVisible).isTrue()
+    fun isVisible() =
+        testScope.runTest {
+            val underTest = utils.fakeSceneContainerRepository()
+            val isVisible by collectLastValue(underTest.isVisible)
+            assertThat(isVisible).isTrue()
 
-        underTest.setVisible(false)
-        assertThat(isVisible).isFalse()
+            underTest.setVisible(false)
+            assertThat(isVisible).isFalse()
 
-        underTest.setVisible(true)
-        assertThat(isVisible).isTrue()
-    }
+            underTest.setVisible(true)
+            assertThat(isVisible).isTrue()
+        }
 
     @Test
-    fun transitionProgress() = runTest {
-        val underTest = utils.fakeSceneContainerRepository()
-        val sceneTransitionProgress by collectLastValue(underTest.transitionProgress)
-        assertThat(sceneTransitionProgress).isEqualTo(1f)
+    fun transitionState_defaultsToIdle() =
+        testScope.runTest {
+            val underTest = utils.fakeSceneContainerRepository()
+            val transitionState by collectLastValue(underTest.transitionState)
 
-        val transitionState =
-            MutableStateFlow<ObservableTransitionState>(
-                ObservableTransitionState.Idle(SceneKey.Lockscreen)
-            )
-        underTest.setTransitionState(transitionState)
-        assertThat(sceneTransitionProgress).isEqualTo(1f)
-
-        val progress = MutableStateFlow(1f)
-        transitionState.value =
-            ObservableTransitionState.Transition(
-                fromScene = SceneKey.Lockscreen,
-                toScene = SceneKey.Shade,
-                progress = progress,
-            )
-        assertThat(sceneTransitionProgress).isEqualTo(1f)
-
-        progress.value = 0.1f
-        assertThat(sceneTransitionProgress).isEqualTo(0.1f)
-
-        progress.value = 0.9f
-        assertThat(sceneTransitionProgress).isEqualTo(0.9f)
-
-        underTest.setTransitionState(null)
-        assertThat(sceneTransitionProgress).isEqualTo(1f)
-    }
+            assertThat(transitionState)
+                .isEqualTo(
+                    ObservableTransitionState.Idle(utils.fakeSceneContainerConfig().initialSceneKey)
+                )
+        }
 
     @Test
-    fun setSceneTransition() = runTest {
-        val underTest = utils.fakeSceneContainerRepository()
-        val sceneTransition by collectLastValue(underTest.transitions)
-        assertThat(sceneTransition).isNull()
+    fun transitionState_reflectsUpdates() =
+        testScope.runTest {
+            val underTest = utils.fakeSceneContainerRepository()
+            val transitionState =
+                MutableStateFlow<ObservableTransitionState>(
+                    ObservableTransitionState.Idle(SceneKey.Lockscreen)
+                )
+            underTest.setTransitionState(transitionState)
+            val reflectedTransitionState by collectLastValue(underTest.transitionState)
+            assertThat(reflectedTransitionState).isEqualTo(transitionState.value)
 
-        underTest.setSceneTransition(SceneKey.Lockscreen, SceneKey.QuickSettings)
-        assertThat(sceneTransition)
-            .isEqualTo(
-                SceneTransitionModel(from = SceneKey.Lockscreen, to = SceneKey.QuickSettings)
-            )
-    }
+            val progress = MutableStateFlow(1f)
+            transitionState.value =
+                ObservableTransitionState.Transition(
+                    fromScene = SceneKey.Lockscreen,
+                    toScene = SceneKey.Shade,
+                    progress = progress,
+                )
+            assertThat(reflectedTransitionState).isEqualTo(transitionState.value)
 
-    @Test(expected = IllegalStateException::class)
-    fun setSceneTransition_noFromSceneInContainer_throws() {
-        val underTest =
-            utils.fakeSceneContainerRepository(
-                utils.fakeSceneContainerConfig(listOf(SceneKey.QuickSettings, SceneKey.Lockscreen)),
-            )
-        underTest.setSceneTransition(SceneKey.Shade, SceneKey.Lockscreen)
-    }
+            progress.value = 0.1f
+            assertThat(reflectedTransitionState).isEqualTo(transitionState.value)
 
-    @Test(expected = IllegalStateException::class)
-    fun setSceneTransition_noToSceneInContainer_throws() {
-        val underTest =
-            utils.fakeSceneContainerRepository(
-                utils.fakeSceneContainerConfig(listOf(SceneKey.QuickSettings, SceneKey.Lockscreen)),
-            )
-        underTest.setSceneTransition(SceneKey.Shade, SceneKey.Lockscreen)
-    }
+            progress.value = 0.9f
+            assertThat(reflectedTransitionState).isEqualTo(transitionState.value)
+
+            underTest.setTransitionState(null)
+            assertThat(reflectedTransitionState)
+                .isEqualTo(
+                    ObservableTransitionState.Idle(utils.fakeSceneContainerConfig().initialSceneKey)
+                )
+        }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/scene/domain/interactor/SceneInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/scene/domain/interactor/SceneInteractorTest.kt
index 4facc7a..713c602 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/scene/domain/interactor/SceneInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/scene/domain/interactor/SceneInteractorTest.kt
@@ -25,7 +25,6 @@
 import com.android.systemui.scene.shared.model.ObservableTransitionState
 import com.android.systemui.scene.shared.model.SceneKey
 import com.android.systemui.scene.shared.model.SceneModel
-import com.android.systemui.scene.shared.model.SceneTransitionModel
 import com.google.common.truth.Truth.assertThat
 import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.flow.MutableStateFlow
@@ -39,6 +38,7 @@
 class SceneInteractorTest : SysuiTestCase() {
 
     private val utils = SceneTestUtils(this)
+    private val testScope = utils.testScope
     private val repository = utils.fakeSceneContainerRepository()
     private val underTest = utils.sceneInteractor(repository = repository)
 
@@ -48,77 +48,103 @@
     }
 
     @Test
-    fun currentScene() = runTest {
-        val currentScene by collectLastValue(underTest.currentScene)
-        assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Lockscreen))
+    fun changeScene() =
+        testScope.runTest {
+            val desiredScene by collectLastValue(underTest.desiredScene)
+            assertThat(desiredScene).isEqualTo(SceneModel(SceneKey.Lockscreen))
 
-        underTest.setCurrentScene(SceneModel(SceneKey.Shade), "reason")
-        assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Shade))
-    }
+            underTest.changeScene(SceneModel(SceneKey.Shade), "reason")
+            assertThat(desiredScene).isEqualTo(SceneModel(SceneKey.Shade))
+        }
 
     @Test
-    fun sceneTransitionProgress() = runTest {
-        val transitionProgress by collectLastValue(underTest.transitionProgress)
-        assertThat(transitionProgress).isEqualTo(1f)
+    fun onSceneChanged() =
+        testScope.runTest {
+            val desiredScene by collectLastValue(underTest.desiredScene)
+            assertThat(desiredScene).isEqualTo(SceneModel(SceneKey.Lockscreen))
 
-        val progress = MutableStateFlow(0.55f)
-        repository.setTransitionState(
-            MutableStateFlow(
+            underTest.onSceneChanged(SceneModel(SceneKey.Shade), "reason")
+            assertThat(desiredScene).isEqualTo(SceneModel(SceneKey.Shade))
+        }
+
+    @Test
+    fun transitionState() =
+        testScope.runTest {
+            val underTest = utils.fakeSceneContainerRepository()
+            val transitionState =
+                MutableStateFlow<ObservableTransitionState>(
+                    ObservableTransitionState.Idle(SceneKey.Lockscreen)
+                )
+            underTest.setTransitionState(transitionState)
+            val reflectedTransitionState by collectLastValue(underTest.transitionState)
+            assertThat(reflectedTransitionState).isEqualTo(transitionState.value)
+
+            val progress = MutableStateFlow(1f)
+            transitionState.value =
                 ObservableTransitionState.Transition(
                     fromScene = SceneKey.Lockscreen,
                     toScene = SceneKey.Shade,
                     progress = progress,
-                ),
-            )
-        )
-        assertThat(transitionProgress).isEqualTo(0.55f)
-    }
-
-    @Test
-    fun isVisible() = runTest {
-        val isVisible by collectLastValue(underTest.isVisible)
-        assertThat(isVisible).isTrue()
-
-        underTest.setVisible(false, "reason")
-        assertThat(isVisible).isFalse()
-
-        underTest.setVisible(true, "reason")
-        assertThat(isVisible).isTrue()
-    }
-
-    @Test
-    fun sceneTransitions() = runTest {
-        val transitions by collectLastValue(underTest.transitions)
-        assertThat(transitions).isNull()
-
-        val initialSceneKey = underTest.currentScene.value.key
-        underTest.setCurrentScene(SceneModel(SceneKey.Shade), "reason")
-        assertThat(transitions)
-            .isEqualTo(
-                SceneTransitionModel(
-                    from = initialSceneKey,
-                    to = SceneKey.Shade,
                 )
-            )
+            assertThat(reflectedTransitionState).isEqualTo(transitionState.value)
 
-        underTest.setCurrentScene(SceneModel(SceneKey.QuickSettings), "reason")
-        assertThat(transitions)
-            .isEqualTo(
-                SceneTransitionModel(
-                    from = SceneKey.Shade,
-                    to = SceneKey.QuickSettings,
+            progress.value = 0.1f
+            assertThat(reflectedTransitionState).isEqualTo(transitionState.value)
+
+            progress.value = 0.9f
+            assertThat(reflectedTransitionState).isEqualTo(transitionState.value)
+
+            underTest.setTransitionState(null)
+            assertThat(reflectedTransitionState)
+                .isEqualTo(
+                    ObservableTransitionState.Idle(utils.fakeSceneContainerConfig().initialSceneKey)
                 )
-            )
-    }
-
-    @Test
-    fun remoteUserInput() = runTest {
-        val remoteUserInput by collectLastValue(underTest.remoteUserInput)
-        assertThat(remoteUserInput).isNull()
-
-        for (input in SceneTestUtils.REMOTE_INPUT_DOWN_GESTURE) {
-            underTest.onRemoteUserInput(input)
-            assertThat(remoteUserInput).isEqualTo(input)
         }
-    }
+
+    @Test
+    fun transitioningTo() =
+        testScope.runTest {
+            val transitionState =
+                MutableStateFlow<ObservableTransitionState>(
+                    ObservableTransitionState.Idle(underTest.desiredScene.value.key)
+                )
+            underTest.setTransitionState(transitionState)
+
+            val transitionTo by collectLastValue(underTest.transitioningTo)
+            assertThat(transitionTo).isNull()
+
+            underTest.changeScene(SceneModel(SceneKey.Shade), "reason")
+            assertThat(transitionTo).isNull()
+
+            val progress = MutableStateFlow(0f)
+            transitionState.value =
+                ObservableTransitionState.Transition(
+                    fromScene = underTest.desiredScene.value.key,
+                    toScene = SceneKey.Shade,
+                    progress = progress,
+                )
+            assertThat(transitionTo).isEqualTo(SceneKey.Shade)
+
+            progress.value = 0.5f
+            assertThat(transitionTo).isEqualTo(SceneKey.Shade)
+
+            progress.value = 1f
+            assertThat(transitionTo).isEqualTo(SceneKey.Shade)
+
+            transitionState.value = ObservableTransitionState.Idle(SceneKey.Shade)
+            assertThat(transitionTo).isNull()
+        }
+
+    @Test
+    fun isVisible() =
+        testScope.runTest {
+            val isVisible by collectLastValue(underTest.isVisible)
+            assertThat(isVisible).isTrue()
+
+            underTest.setVisible(false, "reason")
+            assertThat(isVisible).isFalse()
+
+            underTest.setVisible(true, "reason")
+            assertThat(isVisible).isTrue()
+        }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt b/packages/SystemUI/tests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
index 6be19b9..951cadd 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
@@ -21,6 +21,7 @@
 import android.view.Display
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.domain.model.AuthenticationMethodModel
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.flags.Flags
 import com.android.systemui.keyguard.shared.model.WakeSleepReason
@@ -28,15 +29,18 @@
 import com.android.systemui.keyguard.shared.model.WakefulnessState
 import com.android.systemui.model.SysUiState
 import com.android.systemui.scene.SceneTestUtils
+import com.android.systemui.scene.SceneTestUtils.Companion.toDataLayer
+import com.android.systemui.scene.shared.model.ObservableTransitionState
 import com.android.systemui.scene.shared.model.SceneKey
 import com.android.systemui.scene.shared.model.SceneModel
 import com.android.systemui.util.mockito.mock
 import com.google.common.truth.Truth.assertThat
 import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.flowOf
 import kotlinx.coroutines.flow.map
 import kotlinx.coroutines.test.runCurrent
 import kotlinx.coroutines.test.runTest
-import org.junit.Before
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.junit.runners.JUnit4
@@ -76,61 +80,53 @@
             sceneLogger = mock(),
         )
 
-    @Before
-    fun setUp() {
-        prepareState()
-    }
-
     @Test
-    fun hydrateVisibility_featureEnabled() =
+    fun hydrateVisibility() =
         testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
+            val currentDesiredSceneKey by
+                collectLastValue(sceneInteractor.desiredScene.map { it.key })
             val isVisible by collectLastValue(sceneInteractor.isVisible)
-            prepareState(
-                isFeatureEnabled = true,
-                isDeviceUnlocked = true,
-                initialSceneKey = SceneKey.Gone,
-            )
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Gone)
+            val transitionStateFlow =
+                prepareState(
+                    isDeviceUnlocked = true,
+                    initialSceneKey = SceneKey.Gone,
+                )
+            assertThat(currentDesiredSceneKey).isEqualTo(SceneKey.Gone)
             assertThat(isVisible).isTrue()
 
             underTest.start()
-
             assertThat(isVisible).isFalse()
 
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Shade), "reason")
+            sceneInteractor.changeScene(SceneModel(SceneKey.Shade), "reason")
+            transitionStateFlow.value =
+                ObservableTransitionState.Transition(
+                    fromScene = SceneKey.Gone,
+                    toScene = SceneKey.Shade,
+                    progress = flowOf(0.5f),
+                )
             assertThat(isVisible).isTrue()
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Shade), "reason")
+            transitionStateFlow.value = ObservableTransitionState.Idle(SceneKey.Shade)
+            assertThat(isVisible).isTrue()
+
+            sceneInteractor.changeScene(SceneModel(SceneKey.Gone), "reason")
+            transitionStateFlow.value =
+                ObservableTransitionState.Transition(
+                    fromScene = SceneKey.Shade,
+                    toScene = SceneKey.Gone,
+                    progress = flowOf(0.5f),
+                )
+            assertThat(isVisible).isTrue()
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Gone), "reason")
+            transitionStateFlow.value = ObservableTransitionState.Idle(SceneKey.Gone)
+            assertThat(isVisible).isFalse()
         }
 
     @Test
-    fun hydrateVisibility_featureDisabled() =
+    fun switchToLockscreenWhenDeviceLocks() =
         testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
-            val isVisible by collectLastValue(sceneInteractor.isVisible)
+            val currentSceneKey by collectLastValue(sceneInteractor.desiredScene.map { it.key })
             prepareState(
-                isFeatureEnabled = false,
-                isDeviceUnlocked = true,
-                initialSceneKey = SceneKey.Lockscreen,
-            )
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Lockscreen)
-            assertThat(isVisible).isTrue()
-
-            underTest.start()
-            assertThat(isVisible).isTrue()
-
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Gone), "reason")
-            assertThat(isVisible).isTrue()
-
-            sceneInteractor.setCurrentScene(SceneModel(SceneKey.Shade), "reason")
-            assertThat(isVisible).isTrue()
-        }
-
-    @Test
-    fun switchToLockscreenWhenDeviceLocks_featureEnabled() =
-        testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
-            prepareState(
-                isFeatureEnabled = true,
                 isDeviceUnlocked = true,
                 initialSceneKey = SceneKey.Gone,
             )
@@ -143,28 +139,10 @@
         }
 
     @Test
-    fun switchToLockscreenWhenDeviceLocks_featureDisabled() =
+    fun switchFromBouncerToGoneWhenDeviceUnlocked() =
         testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
+            val currentSceneKey by collectLastValue(sceneInteractor.desiredScene.map { it.key })
             prepareState(
-                isFeatureEnabled = false,
-                isDeviceUnlocked = false,
-                initialSceneKey = SceneKey.Gone,
-            )
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Gone)
-            underTest.start()
-
-            authenticationRepository.setUnlocked(false)
-
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Gone)
-        }
-
-    @Test
-    fun switchFromBouncerToGoneWhenDeviceUnlocked_featureEnabled() =
-        testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
-            prepareState(
-                isFeatureEnabled = true,
                 isDeviceUnlocked = false,
                 initialSceneKey = SceneKey.Bouncer,
             )
@@ -177,28 +155,10 @@
         }
 
     @Test
-    fun switchFromBouncerToGoneWhenDeviceUnlocked_featureDisabled() =
+    fun switchFromLockscreenToGoneWhenDeviceUnlocksWithBypassOn() =
         testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
+            val currentSceneKey by collectLastValue(sceneInteractor.desiredScene.map { it.key })
             prepareState(
-                isFeatureEnabled = false,
-                isDeviceUnlocked = false,
-                initialSceneKey = SceneKey.Bouncer,
-            )
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Bouncer)
-            underTest.start()
-
-            authenticationRepository.setUnlocked(true)
-
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Bouncer)
-        }
-
-    @Test
-    fun switchFromLockscreenToGoneWhenDeviceUnlocksWithBypassOn_featureOn_bypassOn() =
-        testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
-            prepareState(
-                isFeatureEnabled = true,
                 isBypassEnabled = true,
                 initialSceneKey = SceneKey.Lockscreen,
             )
@@ -211,11 +171,10 @@
         }
 
     @Test
-    fun switchFromLockscreenToGoneWhenDeviceUnlocksWithBypassOn_featureOn_bypassOff() =
+    fun stayOnLockscreenWhenDeviceUnlocksWithBypassOff() =
         testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
+            val currentSceneKey by collectLastValue(sceneInteractor.desiredScene.map { it.key })
             prepareState(
-                isFeatureEnabled = true,
                 isBypassEnabled = false,
                 initialSceneKey = SceneKey.Lockscreen,
             )
@@ -228,93 +187,25 @@
         }
 
     @Test
-    fun switchFromLockscreenToGoneWhenDeviceUnlocksWithBypassOn_featureOff_bypassOn() =
+    fun switchToLockscreenWhenDeviceSleepsLocked() =
         testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
+            val currentSceneKey by collectLastValue(sceneInteractor.desiredScene.map { it.key })
             prepareState(
-                isFeatureEnabled = false,
-                isBypassEnabled = true,
-                initialSceneKey = SceneKey.Lockscreen,
-            )
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Lockscreen)
-            underTest.start()
-
-            authenticationRepository.setUnlocked(true)
-
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Lockscreen)
-        }
-
-    @Test
-    fun switchToGoneWhenDeviceSleepsUnlocked_featureEnabled() =
-        testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
-            prepareState(
-                isFeatureEnabled = true,
-                isDeviceUnlocked = true,
-                initialSceneKey = SceneKey.Shade,
-            )
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Shade)
-            underTest.start()
-
-            keyguardRepository.setWakefulnessModel(ASLEEP)
-
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Gone)
-        }
-
-    @Test
-    fun switchToGoneWhenDeviceSleepsUnlocked_featureDisabled() =
-        testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
-            prepareState(
-                isFeatureEnabled = false,
-                isDeviceUnlocked = true,
-                initialSceneKey = SceneKey.Shade,
-            )
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Shade)
-            underTest.start()
-
-            keyguardRepository.setWakefulnessModel(ASLEEP)
-
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Shade)
-        }
-
-    @Test
-    fun switchToLockscreenWhenDeviceSleepsLocked_featureEnabled() =
-        testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
-            prepareState(
-                isFeatureEnabled = true,
                 isDeviceUnlocked = false,
                 initialSceneKey = SceneKey.Shade,
             )
             assertThat(currentSceneKey).isEqualTo(SceneKey.Shade)
             underTest.start()
 
-            keyguardRepository.setWakefulnessModel(ASLEEP)
+            keyguardRepository.setWakefulnessModel(STARTING_TO_SLEEP)
 
             assertThat(currentSceneKey).isEqualTo(SceneKey.Lockscreen)
         }
 
     @Test
-    fun switchToLockscreenWhenDeviceSleepsLocked_featureDisabled() =
-        testScope.runTest {
-            val currentSceneKey by collectLastValue(sceneInteractor.currentScene.map { it.key })
-            prepareState(
-                isFeatureEnabled = false,
-                isDeviceUnlocked = false,
-                initialSceneKey = SceneKey.Shade,
-            )
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Shade)
-            underTest.start()
-
-            keyguardRepository.setWakefulnessModel(ASLEEP)
-
-            assertThat(currentSceneKey).isEqualTo(SceneKey.Shade)
-        }
-
-    @Test
     fun hydrateSystemUiState() =
         testScope.runTest {
+            val transitionStateFlow = prepareState()
             underTest.start()
             runCurrent()
             clearInvocations(sysUiState)
@@ -327,29 +218,125 @@
                     SceneKey.QuickSettings,
                 )
                 .forEachIndexed { index, sceneKey ->
-                    sceneInteractor.setCurrentScene(SceneModel(sceneKey), "reason")
+                    sceneInteractor.changeScene(SceneModel(sceneKey), "reason")
                     runCurrent()
+                    verify(sysUiState, times(index)).commitUpdate(Display.DEFAULT_DISPLAY)
 
+                    sceneInteractor.onSceneChanged(SceneModel(sceneKey), "reason")
+                    runCurrent()
+                    verify(sysUiState, times(index)).commitUpdate(Display.DEFAULT_DISPLAY)
+
+                    transitionStateFlow.value = ObservableTransitionState.Idle(sceneKey)
+                    runCurrent()
                     verify(sysUiState, times(index + 1)).commitUpdate(Display.DEFAULT_DISPLAY)
                 }
         }
 
+    @Test
+    fun switchToGoneWhenDeviceStartsToWakeUp_authMethodNone() =
+        testScope.runTest {
+            val currentSceneKey by collectLastValue(sceneInteractor.desiredScene.map { it.key })
+            prepareState(
+                initialSceneKey = SceneKey.Lockscreen,
+                authenticationMethod = AuthenticationMethodModel.None,
+            )
+            assertThat(currentSceneKey).isEqualTo(SceneKey.Lockscreen)
+            underTest.start()
+
+            keyguardRepository.setWakefulnessModel(STARTING_TO_WAKE)
+
+            assertThat(currentSceneKey).isEqualTo(SceneKey.Gone)
+        }
+
+    @Test
+    fun stayOnLockscreenWhenDeviceStartsToWakeUp_authMethodSwipe() =
+        testScope.runTest {
+            val currentSceneKey by collectLastValue(sceneInteractor.desiredScene.map { it.key })
+            prepareState(
+                initialSceneKey = SceneKey.Lockscreen,
+                authenticationMethod = AuthenticationMethodModel.Swipe,
+            )
+            assertThat(currentSceneKey).isEqualTo(SceneKey.Lockscreen)
+            underTest.start()
+
+            keyguardRepository.setWakefulnessModel(STARTING_TO_WAKE)
+
+            assertThat(currentSceneKey).isEqualTo(SceneKey.Lockscreen)
+        }
+
+    @Test
+    fun doesNotSwitchToGoneWhenDeviceStartsToWakeUp_authMethodSecure() =
+        testScope.runTest {
+            val currentSceneKey by collectLastValue(sceneInteractor.desiredScene.map { it.key })
+            prepareState(
+                initialSceneKey = SceneKey.Lockscreen,
+                authenticationMethod = AuthenticationMethodModel.Pin,
+            )
+            assertThat(currentSceneKey).isEqualTo(SceneKey.Lockscreen)
+            underTest.start()
+
+            keyguardRepository.setWakefulnessModel(STARTING_TO_WAKE)
+
+            assertThat(currentSceneKey).isEqualTo(SceneKey.Lockscreen)
+        }
+
+    @Test
+    fun switchToGoneWhenDeviceStartsToWakeUp_authMethodSecure_deviceUnlocked() =
+        testScope.runTest {
+            val currentSceneKey by collectLastValue(sceneInteractor.desiredScene.map { it.key })
+            prepareState(
+                initialSceneKey = SceneKey.Lockscreen,
+                authenticationMethod = AuthenticationMethodModel.Pin,
+                isDeviceUnlocked = false,
+            )
+            assertThat(currentSceneKey).isEqualTo(SceneKey.Lockscreen)
+            underTest.start()
+
+            authenticationRepository.setUnlocked(true)
+            runCurrent()
+            keyguardRepository.setWakefulnessModel(STARTING_TO_WAKE)
+
+            assertThat(currentSceneKey).isEqualTo(SceneKey.Gone)
+        }
+
     private fun prepareState(
-        isFeatureEnabled: Boolean = true,
         isDeviceUnlocked: Boolean = false,
         isBypassEnabled: Boolean = false,
         initialSceneKey: SceneKey? = null,
-    ) {
-        featureFlags.set(Flags.SCENE_CONTAINER, isFeatureEnabled)
+        authenticationMethod: AuthenticationMethodModel? = null,
+    ): MutableStateFlow<ObservableTransitionState> {
+        featureFlags.set(Flags.SCENE_CONTAINER, true)
         authenticationRepository.setUnlocked(isDeviceUnlocked)
         keyguardRepository.setBypassEnabled(isBypassEnabled)
-        initialSceneKey?.let { sceneInteractor.setCurrentScene(SceneModel(it), "reason") }
+        val transitionStateFlow =
+            MutableStateFlow<ObservableTransitionState>(
+                ObservableTransitionState.Idle(SceneKey.Lockscreen)
+            )
+        sceneInteractor.setTransitionState(transitionStateFlow)
+        initialSceneKey?.let {
+            transitionStateFlow.value = ObservableTransitionState.Idle(it)
+            sceneInteractor.changeScene(SceneModel(it), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(it), "reason")
+        }
+        authenticationMethod?.let {
+            authenticationRepository.setAuthenticationMethod(authenticationMethod.toDataLayer())
+            authenticationRepository.setLockscreenEnabled(
+                authenticationMethod != AuthenticationMethodModel.None
+            )
+        }
+        return transitionStateFlow
     }
 
     companion object {
-        private val ASLEEP =
+        private val STARTING_TO_SLEEP =
             WakefulnessModel(
-                state = WakefulnessState.ASLEEP,
+                state = WakefulnessState.STARTING_TO_SLEEP,
+                lastWakeReason = WakeSleepReason.POWER_BUTTON,
+                lastSleepReason = WakeSleepReason.POWER_BUTTON
+            )
+        private val STARTING_TO_WAKE =
+            WakefulnessModel(
+                state = WakefulnessState.STARTING_TO_WAKE,
                 lastWakeReason = WakeSleepReason.POWER_BUTTON,
                 lastSleepReason = WakeSleepReason.POWER_BUTTON
             )
diff --git a/packages/SystemUI/tests/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModelTest.kt
index 9f3b12b..88abb642 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModelTest.kt
@@ -18,19 +18,14 @@
 
 package com.android.systemui.scene.ui.viewmodel
 
-import android.view.MotionEvent
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.scene.SceneTestUtils
-import com.android.systemui.scene.shared.model.RemoteUserInput
-import com.android.systemui.scene.shared.model.RemoteUserInputAction
 import com.android.systemui.scene.shared.model.SceneKey
 import com.android.systemui.scene.shared.model.SceneModel
 import com.google.common.truth.Truth.assertThat
 import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.test.TestScope
-import kotlinx.coroutines.test.currentTime
 import kotlinx.coroutines.test.runTest
 import org.junit.Test
 import org.junit.runner.RunWith
@@ -69,38 +64,8 @@
         val currentScene by collectLastValue(underTest.currentScene)
         assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Lockscreen))
 
-        underTest.setCurrentScene(SceneModel(SceneKey.Shade))
+        underTest.onSceneChanged(SceneModel(SceneKey.Shade))
+
         assertThat(currentScene).isEqualTo(SceneModel(SceneKey.Shade))
     }
-
-    @Test
-    fun onRemoteUserInput() = runTest {
-        val remoteUserInput by collectLastValue(underTest.remoteUserInput)
-        assertThat(remoteUserInput).isNull()
-
-        val inputs =
-            SceneTestUtils.REMOTE_INPUT_DOWN_GESTURE.map { remoteUserInputToMotionEvent(it) }
-
-        inputs.forEachIndexed { index, input ->
-            underTest.onRemoteUserInput(input)
-            assertThat(remoteUserInput).isEqualTo(SceneTestUtils.REMOTE_INPUT_DOWN_GESTURE[index])
-        }
-    }
-
-    private fun TestScope.remoteUserInputToMotionEvent(input: RemoteUserInput): MotionEvent {
-        return MotionEvent.obtain(
-            currentTime,
-            currentTime,
-            when (input.action) {
-                RemoteUserInputAction.DOWN -> MotionEvent.ACTION_DOWN
-                RemoteUserInputAction.MOVE -> MotionEvent.ACTION_MOVE
-                RemoteUserInputAction.UP -> MotionEvent.ACTION_UP
-                RemoteUserInputAction.CANCEL -> MotionEvent.ACTION_CANCEL
-                RemoteUserInputAction.UNKNOWN -> MotionEvent.ACTION_OUTSIDE
-            },
-            input.x,
-            input.y,
-            0
-        )
-    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/screenrecord/ScreenRecordPermissionDialogTest.kt b/packages/SystemUI/tests/src/com/android/systemui/screenrecord/ScreenRecordPermissionDialogTest.kt
index 07feedf..ad6909d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/screenrecord/ScreenRecordPermissionDialogTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/screenrecord/ScreenRecordPermissionDialogTest.kt
@@ -126,6 +126,7 @@
 
     private fun onSpinnerItemSelected(position: Int) {
         val spinner = dialog.requireViewById<Spinner>(R.id.screen_share_mode_spinner)
-        spinner.onItemSelectedListener.onItemSelected(spinner, mock(), position, /* id= */ 0)
+        checkNotNull(spinner.onItemSelectedListener)
+            .onItemSelected(spinner, mock(), position, /* id= */ 0)
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/screenshot/ActionIntentCreatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/screenshot/ActionIntentCreatorTest.kt
index 77e4d89..ca4486b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/screenshot/ActionIntentCreatorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/screenshot/ActionIntentCreatorTest.kt
@@ -20,12 +20,13 @@
 import android.content.Context
 import android.content.Intent
 import android.net.Uri
-import androidx.test.ext.truth.content.IntentSubject.assertThat
+import androidx.test.ext.truth.content.IntentSubject.assertThat as assertThatIntent
 import androidx.test.filters.SmallTest
 import com.android.systemui.R
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.util.mockito.eq
 import com.android.systemui.util.mockito.mock
+import com.google.common.truth.Truth.assertThat
 import com.google.common.truth.Truth.assertWithMessage
 import org.junit.Test
 import org.mockito.Mockito.`when` as whenever
@@ -34,39 +35,49 @@
 class ActionIntentCreatorTest : SysuiTestCase() {
 
     @Test
-    fun testCreateShareIntent() {
+    fun testCreateShare() {
         val uri = Uri.parse("content://fake")
 
         val output = ActionIntentCreator.createShare(uri)
 
-        assertThat(output).hasAction(Intent.ACTION_CHOOSER)
-        assertThat(output)
+        assertThatIntent(output).hasAction(Intent.ACTION_CHOOSER)
+        assertThatIntent(output)
             .hasFlags(
                 Intent.FLAG_ACTIVITY_NEW_TASK or
                     Intent.FLAG_ACTIVITY_CLEAR_TASK or
                     Intent.FLAG_GRANT_READ_URI_PERMISSION
             )
 
-        assertThat(output).extras().parcelable<Intent>(Intent.EXTRA_INTENT).isNotNull()
+        assertThatIntent(output).extras().parcelable<Intent>(Intent.EXTRA_INTENT).isNotNull()
         val wrappedIntent = output.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
 
-        assertThat(wrappedIntent).hasAction(Intent.ACTION_SEND)
-        assertThat(wrappedIntent).hasData(uri)
-        assertThat(wrappedIntent).hasType("image/png")
-        assertThat(wrappedIntent).extras().doesNotContainKey(Intent.EXTRA_SUBJECT)
-        assertThat(wrappedIntent).extras().doesNotContainKey(Intent.EXTRA_TEXT)
-        assertThat(wrappedIntent).extras().parcelable<Uri>(Intent.EXTRA_STREAM).isEqualTo(uri)
+        assertThatIntent(wrappedIntent).hasAction(Intent.ACTION_SEND)
+        assertThatIntent(wrappedIntent).hasData(uri)
+        assertThatIntent(wrappedIntent).hasType("image/png")
+        assertThatIntent(wrappedIntent).extras().doesNotContainKey(Intent.EXTRA_SUBJECT)
+        assertThatIntent(wrappedIntent).extras().doesNotContainKey(Intent.EXTRA_TEXT)
+        assertThatIntent(wrappedIntent).extras().parcelable<Uri>(Intent.EXTRA_STREAM).isEqualTo(uri)
     }
 
     @Test
-    fun testCreateShareIntentWithSubject() {
+    fun testCreateShare_embeddedUserIdRemoved() {
+        val uri = Uri.parse("content://555@fake")
+
+        val output = ActionIntentCreator.createShare(uri)
+
+        assertThatIntent(output.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java))
+            .hasData(Uri.parse("content://fake"))
+    }
+
+    @Test
+    fun testCreateShareWithSubject() {
         val uri = Uri.parse("content://fake")
         val subject = "Example subject"
 
         val output = ActionIntentCreator.createShareWithSubject(uri, subject)
 
-        assertThat(output).hasAction(Intent.ACTION_CHOOSER)
-        assertThat(output)
+        assertThatIntent(output).hasAction(Intent.ACTION_CHOOSER)
+        assertThatIntent(output)
             .hasFlags(
                 Intent.FLAG_ACTIVITY_NEW_TASK or
                     Intent.FLAG_ACTIVITY_CLEAR_TASK or
@@ -74,23 +85,23 @@
             )
 
         val wrappedIntent = output.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
-        assertThat(wrappedIntent).hasAction(Intent.ACTION_SEND)
-        assertThat(wrappedIntent).hasData(uri)
-        assertThat(wrappedIntent).hasType("image/png")
-        assertThat(wrappedIntent).extras().string(Intent.EXTRA_SUBJECT).isEqualTo(subject)
-        assertThat(wrappedIntent).extras().doesNotContainKey(Intent.EXTRA_TEXT)
-        assertThat(wrappedIntent).extras().parcelable<Uri>(Intent.EXTRA_STREAM).isEqualTo(uri)
+        assertThatIntent(wrappedIntent).hasAction(Intent.ACTION_SEND)
+        assertThatIntent(wrappedIntent).hasData(uri)
+        assertThatIntent(wrappedIntent).hasType("image/png")
+        assertThatIntent(wrappedIntent).extras().string(Intent.EXTRA_SUBJECT).isEqualTo(subject)
+        assertThatIntent(wrappedIntent).extras().doesNotContainKey(Intent.EXTRA_TEXT)
+        assertThatIntent(wrappedIntent).extras().parcelable<Uri>(Intent.EXTRA_STREAM).isEqualTo(uri)
     }
 
     @Test
-    fun testCreateShareIntentWithExtraText() {
+    fun testCreateShareWithText() {
         val uri = Uri.parse("content://fake")
         val extraText = "Extra text"
 
         val output = ActionIntentCreator.createShareWithText(uri, extraText)
 
-        assertThat(output).hasAction(Intent.ACTION_CHOOSER)
-        assertThat(output)
+        assertThatIntent(output).hasAction(Intent.ACTION_CHOOSER)
+        assertThatIntent(output)
             .hasFlags(
                 Intent.FLAG_ACTIVITY_NEW_TASK or
                     Intent.FLAG_ACTIVITY_CLEAR_TASK or
@@ -98,28 +109,29 @@
             )
 
         val wrappedIntent = output.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
-        assertThat(wrappedIntent).hasAction(Intent.ACTION_SEND)
-        assertThat(wrappedIntent).hasData(uri)
-        assertThat(wrappedIntent).hasType("image/png")
-        assertThat(wrappedIntent).extras().doesNotContainKey(Intent.EXTRA_SUBJECT)
-        assertThat(wrappedIntent).extras().string(Intent.EXTRA_TEXT).isEqualTo(extraText)
-        assertThat(wrappedIntent).extras().parcelable<Uri>(Intent.EXTRA_STREAM).isEqualTo(uri)
+        assertThatIntent(wrappedIntent).hasAction(Intent.ACTION_SEND)
+        assertThatIntent(wrappedIntent).hasData(uri)
+        assertThatIntent(wrappedIntent).hasType("image/png")
+        assertThatIntent(wrappedIntent).extras().doesNotContainKey(Intent.EXTRA_SUBJECT)
+        assertThatIntent(wrappedIntent).extras().string(Intent.EXTRA_TEXT).isEqualTo(extraText)
+        assertThatIntent(wrappedIntent).extras().parcelable<Uri>(Intent.EXTRA_STREAM).isEqualTo(uri)
     }
 
     @Test
-    fun testCreateEditIntent() {
+    fun testCreateEdit() {
         val uri = Uri.parse("content://fake")
         val context = mock<Context>()
 
         whenever(context.getString(eq(R.string.config_screenshotEditor))).thenReturn("")
 
-        val output = ActionIntentCreator.createEditIntent(uri, context)
+        val output = ActionIntentCreator.createEdit(uri, context)
 
-        assertThat(output).hasAction(Intent.ACTION_EDIT)
-        assertThat(output).hasData(uri)
-        assertThat(output).hasType("image/png")
+        assertThatIntent(output).hasAction(Intent.ACTION_EDIT)
+        assertThatIntent(output).hasData(uri)
+        assertThatIntent(output).hasType("image/png")
         assertWithMessage("getComponent()").that(output.component).isNull()
-        assertThat(output)
+        assertThat(output.getStringExtra("edit_source")).isEqualTo("screenshot")
+        assertThatIntent(output)
             .hasFlags(
                 Intent.FLAG_GRANT_READ_URI_PERMISSION or
                     Intent.FLAG_GRANT_WRITE_URI_PERMISSION or
@@ -129,7 +141,18 @@
     }
 
     @Test
-    fun testCreateEditIntent_withEditor() {
+    fun testCreateEdit_embeddedUserIdRemoved() {
+        val uri = Uri.parse("content://555@fake")
+        val context = mock<Context>()
+        whenever(context.getString(eq(R.string.config_screenshotEditor))).thenReturn("")
+
+        val output = ActionIntentCreator.createEdit(uri, context)
+
+        assertThatIntent(output).hasData(Uri.parse("content://fake"))
+    }
+
+    @Test
+    fun testCreateEdit_withEditor() {
         val uri = Uri.parse("content://fake")
         val context = mock<Context>()
         val component = ComponentName("com.android.foo", "com.android.foo.Something")
@@ -137,8 +160,8 @@
         whenever(context.getString(eq(R.string.config_screenshotEditor)))
             .thenReturn(component.flattenToString())
 
-        val output = ActionIntentCreator.createEditIntent(uri, context)
+        val output = ActionIntentCreator.createEdit(uri, context)
 
-        assertThat(output).hasComponent(component)
+        assertThatIntent(output).hasComponent(component)
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
index c3540cf..981e44b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerBaseTest.java
@@ -424,6 +424,10 @@
         when(mView.findViewById(R.id.qs_frame)).thenReturn(mQsFrame);
         when(mView.findViewById(R.id.keyguard_status_view))
                 .thenReturn(mock(KeyguardStatusView.class));
+        View rootView = mock(View.class);
+        when(mView.getRootView()).thenReturn(rootView);
+        when(rootView.findViewById(R.id.keyguard_status_view))
+                .thenReturn(mock(KeyguardStatusView.class));
         mNotificationContainerParent = new NotificationsQuickSettingsContainer(getContext(), null);
         mNotificationContainerParent.addView(keyguardStatusView);
         mNotificationContainerParent.onFinishInflate();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java
index eb4ae1a..7aeafeb 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java
@@ -539,6 +539,23 @@
     }
 
     @Test
+    public void onKeyguardStatusViewHeightChange_animatesNextTopPaddingChangeForNSSL() {
+        ArgumentCaptor<View.OnLayoutChangeListener> captor =
+                ArgumentCaptor.forClass(View.OnLayoutChangeListener.class);
+        verify(mKeyguardStatusView).addOnLayoutChangeListener(captor.capture());
+        View.OnLayoutChangeListener listener = captor.getValue();
+
+        clearInvocations(mNotificationStackScrollLayoutController);
+
+        when(mKeyguardStatusView.getHeight()).thenReturn(0);
+        listener.onLayoutChange(mKeyguardStatusView, /* left= */ 0, /* top= */ 0, /* right= */
+                0, /* bottom= */ 0, /* oldLeft= */ 0, /* oldTop= */ 0, /* oldRight= */
+                0, /* oldBottom = */ 200);
+
+        verify(mNotificationStackScrollLayoutController).animateNextTopPaddingChange();
+    }
+
+    @Test
     public void testCanCollapsePanelOnTouch_trueForKeyGuard() {
         mStatusBarStateController.setState(KEYGUARD);
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewControllerTest.kt
index 7b3e89d..1edeeff 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewControllerTest.kt
@@ -95,7 +95,7 @@
     @Mock private lateinit var notificationShadeDepthController: NotificationShadeDepthController
     @Mock private lateinit var notificationShadeWindowController: NotificationShadeWindowController
     @Mock private lateinit var keyguardUnlockAnimationController: KeyguardUnlockAnimationController
-    @Mock private lateinit var shadeController: ShadeController
+    @Mock private lateinit var shadeLogger: ShadeLogger
     @Mock private lateinit var ambientState: AmbientState
     @Mock private lateinit var keyguardBouncerViewModel: KeyguardBouncerViewModel
     @Mock private lateinit var stackScrollLayoutController: NotificationStackScrollLayoutController
@@ -150,44 +150,45 @@
         testScope = TestScope()
         underTest =
             NotificationShadeWindowViewController(
-                lockscreenShadeTransitionController,
-                FalsingCollectorFake(),
-                sysuiStatusBarStateController,
-                dockManager,
-                notificationShadeDepthController,
-                view,
-                notificationPanelViewController,
-                ShadeExpansionStateManager(),
-                stackScrollLayoutController,
-                statusBarKeyguardViewManager,
-                statusBarWindowStateController,
-                lockIconViewController,
-                centralSurfaces,
-                backActionInteractor,
-                powerInteractor,
-                notificationShadeWindowController,
-                unfoldTransitionProgressProvider,
-                keyguardUnlockAnimationController,
-                notificationInsetsController,
-                ambientState,
-                pulsingGestureListener,
-                mLockscreenHostedDreamGestureListener,
-                keyguardBouncerViewModel,
-                keyguardBouncerComponentFactory,
-                mock(KeyguardMessageAreaController.Factory::class.java),
-                keyguardTransitionInteractor,
-                primaryBouncerToGoneTransitionViewModel,
-                notificationExpansionRepository,
-                featureFlags,
-                FakeSystemClock(),
-                BouncerMessageInteractor(
-                    FakeBouncerMessageRepository(),
-                    mock(BouncerMessageFactory::class.java),
-                    FakeUserRepository(),
-                    CountDownTimerUtil(),
-                    featureFlags
-                ),
-                BouncerLogger(logcatLogBuffer("BouncerLog"))
+                    lockscreenShadeTransitionController,
+                    FalsingCollectorFake(),
+                    sysuiStatusBarStateController,
+                    dockManager,
+                    notificationShadeDepthController,
+                    view,
+                    notificationPanelViewController,
+                    ShadeExpansionStateManager(),
+                    stackScrollLayoutController,
+                    statusBarKeyguardViewManager,
+                    statusBarWindowStateController,
+                    lockIconViewController,
+                    centralSurfaces,
+                    backActionInteractor,
+                    powerInteractor,
+                    notificationShadeWindowController,
+                    unfoldTransitionProgressProvider,
+                    keyguardUnlockAnimationController,
+                    notificationInsetsController,
+                    ambientState,
+                    shadeLogger,
+                    pulsingGestureListener,
+                    mLockscreenHostedDreamGestureListener,
+                    keyguardBouncerViewModel,
+                    keyguardBouncerComponentFactory,
+                    mock(KeyguardMessageAreaController.Factory::class.java),
+                    keyguardTransitionInteractor,
+                    primaryBouncerToGoneTransitionViewModel,
+                    notificationExpansionRepository,
+                    featureFlags,
+                    FakeSystemClock(),
+                    BouncerMessageInteractor(
+                        FakeBouncerMessageRepository(),
+                        mock(BouncerMessageFactory::class.java),
+                        FakeUserRepository(),
+                        CountDownTimerUtil(),
+                        featureFlags
+                    ),
+                    BouncerLogger(logcatLogBuffer("BouncerLog"))
             )
         underTest.setupExpandedStatusBar()
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt
index 5c3ce71..829184c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt
@@ -105,6 +105,7 @@
     @Mock private lateinit var lockIconViewController: LockIconViewController
     @Mock private lateinit var keyguardUnlockAnimationController: KeyguardUnlockAnimationController
     @Mock private lateinit var ambientState: AmbientState
+    @Mock private lateinit var shadeLogger: ShadeLogger
     @Mock private lateinit var pulsingGestureListener: PulsingGestureListener
     @Mock
     private lateinit var mLockscreenHostedDreamGestureListener: LockscreenHostedDreamGestureListener
@@ -179,6 +180,7 @@
                 keyguardUnlockAnimationController,
                 notificationInsetsController,
                 ambientState,
+                shadeLogger,
                 pulsingGestureListener,
                 mLockscreenHostedDreamGestureListener,
                 keyguardBouncerViewModel,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerLegacyTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerLegacyTest.kt
index 112a09b..577b6e0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerLegacyTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerLegacyTest.kt
@@ -584,7 +584,7 @@
     private fun emptyInsets() = mock(WindowInsets::class.java)
 
     private fun WindowInsets.withCutout(): WindowInsets {
-        whenever(displayCutout.safeInsetBottom).thenReturn(CUTOUT_HEIGHT)
+        whenever(checkNotNull(displayCutout).safeInsetBottom).thenReturn(CUTOUT_HEIGHT)
         return this
     }
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerTest.kt
index 8d3c4b2..405199e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerTest.kt
@@ -567,7 +567,7 @@
     private fun emptyInsets() = mock(WindowInsets::class.java)
 
     private fun WindowInsets.withCutout(): WindowInsets {
-        whenever(displayCutout.safeInsetBottom).thenReturn(CUTOUT_HEIGHT)
+        whenever(checkNotNull(displayCutout).safeInsetBottom).thenReturn(CUTOUT_HEIGHT)
         return this
     }
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/ShadeControllerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/ShadeControllerImplTest.kt
index 52e0c9c..6a14a00 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/ShadeControllerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/ShadeControllerImplTest.kt
@@ -22,6 +22,7 @@
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.assist.AssistManager
+import com.android.systemui.log.LogBuffer
 import com.android.systemui.plugins.statusbar.StatusBarStateController
 import com.android.systemui.statusbar.CommandQueue
 import com.android.systemui.statusbar.NotificationShadeWindowController
@@ -59,6 +60,7 @@
     @Mock private lateinit var shadeViewController: ShadeViewController
     @Mock private lateinit var nswvc: NotificationShadeWindowViewController
     @Mock private lateinit var display: Display
+    @Mock private lateinit var touchLog: LogBuffer
 
     private lateinit var shadeController: ShadeControllerImpl
 
@@ -71,6 +73,7 @@
             ShadeControllerImpl(
                 commandQueue,
                 FakeExecutor(FakeSystemClock()),
+                touchLog,
                 keyguardStateController,
                 statusBarStateController,
                 statusBarKeyguardViewManager,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/ShadeHeaderControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/ShadeHeaderControllerTest.kt
index 2501f85..8f8b840 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/ShadeHeaderControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/ShadeHeaderControllerTest.kt
@@ -138,19 +138,19 @@
 
     @Before
     fun setup() {
-        whenever<Clock>(view.findViewById(R.id.clock)).thenReturn(clock)
+        whenever<Clock>(view.requireViewById(R.id.clock)).thenReturn(clock)
         whenever(clock.context).thenReturn(mockedContext)
 
-        whenever<TextView>(view.findViewById(R.id.date)).thenReturn(date)
+        whenever<TextView>(view.requireViewById(R.id.date)).thenReturn(date)
         whenever(date.context).thenReturn(mockedContext)
 
-        whenever<ShadeCarrierGroup>(view.findViewById(R.id.carrier_group)).thenReturn(carrierGroup)
+        whenever<ShadeCarrierGroup>(view.requireViewById(R.id.carrier_group)).thenReturn(carrierGroup)
 
-        whenever<BatteryMeterView>(view.findViewById(R.id.batteryRemainingIcon))
+        whenever<BatteryMeterView>(view.requireViewById(R.id.batteryRemainingIcon))
             .thenReturn(batteryMeterView)
 
-        whenever<StatusIconContainer>(view.findViewById(R.id.statusIcons)).thenReturn(statusIcons)
-        whenever<View>(view.findViewById(R.id.shade_header_system_icons)).thenReturn(systemIcons)
+        whenever<StatusIconContainer>(view.requireViewById(R.id.statusIcons)).thenReturn(statusIcons)
+        whenever<View>(view.requireViewById(R.id.shade_header_system_icons)).thenReturn(systemIcons)
 
         viewContext = Mockito.spy(context)
         whenever(view.context).thenReturn(viewContext)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/ui/viewmodel/ShadeSceneViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/ui/viewmodel/ShadeSceneViewModelTest.kt
index 8739b28..69b9525 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/ui/viewmodel/ShadeSceneViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/ui/viewmodel/ShadeSceneViewModelTest.kt
@@ -18,7 +18,7 @@
 
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel
 import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.scene.SceneTestUtils
 import com.android.systemui.scene.shared.model.SceneKey
@@ -42,19 +42,17 @@
     private val authenticationInteractor =
         utils.authenticationInteractor(
             repository = utils.authenticationRepository(),
+            sceneInteractor = sceneInteractor,
         )
 
     private val underTest =
         ShadeSceneViewModel(
             applicationScope = testScope.backgroundScope,
-            lockscreenSceneInteractor =
-                utils.lockScreenSceneInteractor(
+            authenticationInteractor = authenticationInteractor,
+            bouncerInteractor =
+                utils.bouncerInteractor(
                     authenticationInteractor = authenticationInteractor,
-                    bouncerInteractor =
-                        utils.bouncerInteractor(
-                            authenticationInteractor = authenticationInteractor,
-                            sceneInteractor = sceneInteractor,
-                        ),
+                    sceneInteractor = sceneInteractor,
                 ),
         )
 
@@ -79,9 +77,33 @@
         }
 
     @Test
+    fun upTransitionSceneKey_authMethodSwipe_lockscreenNotDismissed_goesToLockscreen() =
+        testScope.runTest {
+            val upTransitionSceneKey by collectLastValue(underTest.upDestinationSceneKey)
+            utils.authenticationRepository.setLockscreenEnabled(true)
+            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.None)
+            sceneInteractor.changeScene(SceneModel(SceneKey.Lockscreen), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Lockscreen), "reason")
+
+            assertThat(upTransitionSceneKey).isEqualTo(SceneKey.Lockscreen)
+        }
+
+    @Test
+    fun upTransitionSceneKey_authMethodSwipe_lockscreenDismissed_goesToGone() =
+        testScope.runTest {
+            val upTransitionSceneKey by collectLastValue(underTest.upDestinationSceneKey)
+            utils.authenticationRepository.setLockscreenEnabled(true)
+            utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.None)
+            sceneInteractor.changeScene(SceneModel(SceneKey.Gone), "reason")
+            sceneInteractor.onSceneChanged(SceneModel(SceneKey.Gone), "reason")
+
+            assertThat(upTransitionSceneKey).isEqualTo(SceneKey.Gone)
+        }
+
+    @Test
     fun onContentClicked_deviceUnlocked_switchesToGone() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(true)
             runCurrent()
@@ -94,7 +116,7 @@
     @Test
     fun onContentClicked_deviceLockedSecurely_switchesToBouncer() =
         testScope.runTest {
-            val currentScene by collectLastValue(sceneInteractor.currentScene)
+            val currentScene by collectLastValue(sceneInteractor.desiredScene)
             utils.authenticationRepository.setAuthenticationMethod(AuthenticationMethodModel.Pin)
             utils.authenticationRepository.setUnlocked(false)
             runCurrent()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shared/clocks/ClockRegistryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shared/clocks/ClockRegistryTest.kt
index 9495fdd..ecaf137 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shared/clocks/ClockRegistryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shared/clocks/ClockRegistryTest.kt
@@ -227,6 +227,25 @@
     }
 
     @Test
+    fun activeClockId_changeAfterPluginConnected() {
+        val plugin1 = FakeClockPlugin()
+            .addClock("clock_1", "clock 1")
+            .addClock("clock_2", "clock 2")
+
+        val plugin2 = FakeClockPlugin()
+            .addClock("clock_3", "clock 3", { mockClock })
+            .addClock("clock_4", "clock 4")
+
+        registry.applySettings(ClockSettings("clock_3", null))
+
+        pluginListener.onPluginLoaded(plugin1, mockContext, mockPluginLifecycle)
+        assertEquals(DEFAULT_CLOCK_ID, registry.activeClockId)
+
+        pluginListener.onPluginLoaded(plugin2, mockContext, mockPluginLifecycle)
+        assertEquals("clock_3", registry.activeClockId)
+    }
+
+    @Test
     fun createDefaultClock_pluginDisconnected() {
         val plugin1 = FakeClockPlugin()
             .addClock("clock_1", "clock 1")
diff --git a/packages/SystemUI/tests/src/com/android/systemui/smartspace/DreamSmartspaceControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/smartspace/DreamSmartspaceControllerTest.kt
index 58b44ae..19dc72d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/smartspace/DreamSmartspaceControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/smartspace/DreamSmartspaceControllerTest.kt
@@ -236,7 +236,8 @@
         `when`(precondition.conditionsMet()).thenReturn(true)
 
         // Given a session is created
-        val weatherView = controller.buildAndConnectWeatherView(fakeParent, customView)
+        val weatherView =
+            checkNotNull(controller.buildAndConnectWeatherView(fakeParent, customView))
         controller.stateChangeListener.onViewAttachedToWindow(weatherView)
         verify(smartspaceManager).createSmartspaceSession(any())
 
@@ -258,7 +259,8 @@
 
         // Given a session is created
         val customView = Mockito.mock(TestView::class.java)
-        val weatherView = controller.buildAndConnectWeatherView(fakeParent, customView)
+        val weatherView =
+            checkNotNull(controller.buildAndConnectWeatherView(fakeParent, customView))
         controller.stateChangeListener.onViewAttachedToWindow(weatherView)
         verify(smartspaceManager).createSmartspaceSession(any())
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java
index b6da20f..280897d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java
@@ -17,21 +17,19 @@
 
 package com.android.systemui.statusbar;
 
-import static android.app.Notification.FLAG_FSI_REQUESTED_BUT_DENIED;
-
 import static com.android.systemui.dump.LogBufferHelperKt.logcatLogBuffer;
 import static com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.FLAG_CONTENT_VIEW_CONTRACTED;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import static junit.framework.Assert.assertFalse;
 import static junit.framework.Assert.assertTrue;
 
 import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 
 import android.app.ActivityManager;
 import android.app.Notification;
-import android.app.PendingIntent;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.UserHandle;
@@ -67,17 +65,15 @@
     private static final String TEST_PACKAGE_NAME = "test";
     private static final int TEST_UID = 0;
 
-    protected static final int TEST_MINIMUM_DISPLAY_TIME = 200;
-    protected static final int TEST_STICKY_DISPLAY_TIME = 1000;
-    protected static final int TEST_AUTO_DISMISS_TIME = 500;
+    protected static final int TEST_MINIMUM_DISPLAY_TIME = 400;
+    protected static final int TEST_AUTO_DISMISS_TIME = 600;
+    protected static final int TEST_STICKY_AUTO_DISMISS_TIME = 800;
     // Number of notifications to use in tests requiring multiple notifications
     private static final int TEST_NUM_NOTIFICATIONS = 4;
-    protected static final int TEST_TIMEOUT_TIME = 15000;
+    protected static final int TEST_TIMEOUT_TIME = 2_000;
     protected final Runnable mTestTimeoutRunnable = () -> mTimedOut = true;
 
-    protected NotificationEntry mEntry;
     protected Handler mTestHandler;
-    private StatusBarNotification mSbn;
     protected boolean mTimedOut = false;
 
     @Mock protected ExpandableNotificationRow mRow;
@@ -88,8 +84,8 @@
         private TestableAlertingNotificationManager(Handler handler) {
             super(new HeadsUpManagerLogger(logcatLogBuffer()), handler);
             mMinimumDisplayTime = TEST_MINIMUM_DISPLAY_TIME;
-            mStickyDisplayTime = TEST_STICKY_DISPLAY_TIME;
             mAutoDismissNotificationDecay = TEST_AUTO_DISMISS_TIME;
+            mStickyDisplayTime = TEST_STICKY_AUTO_DISMISS_TIME;
         }
 
         @Override
@@ -114,7 +110,7 @@
         return new TestableAlertingNotificationManager(mTestHandler);
     }
 
-    protected StatusBarNotification createNewSbn(int id, Notification n) {
+    protected StatusBarNotification createSbn(int id, Notification n) {
         return new StatusBarNotification(
                 TEST_PACKAGE_NAME /* pkg */,
                 TEST_PACKAGE_NAME,
@@ -128,45 +124,53 @@
                 0 /* postTime */);
     }
 
-    protected StatusBarNotification createNewSbn(int id, Notification.Builder n) {
-        return new StatusBarNotification(
-                TEST_PACKAGE_NAME /* pkg */,
-                TEST_PACKAGE_NAME,
-                id,
-                null /* tag */,
-                TEST_UID,
-                0 /* initialPid */,
-                n.build(),
-                new UserHandle(ActivityManager.getCurrentUser()),
-                null /* overrideGroupKey */,
-                0 /* postTime */);
+    protected StatusBarNotification createSbn(int id, Notification.Builder n) {
+        return createSbn(id, n.build());
     }
 
-    protected StatusBarNotification createNewNotification(int id) {
-        Notification.Builder n = new Notification.Builder(mContext, "")
+    protected StatusBarNotification createSbn(int id) {
+        final Notification.Builder b = new Notification.Builder(mContext, "")
                 .setSmallIcon(R.drawable.ic_person)
                 .setContentTitle("Title")
                 .setContentText("Text");
-        return createNewSbn(id, n);
+        return createSbn(id, b);
     }
 
-    protected StatusBarNotification createStickySbn(int id) {
-        Notification stickyHun = new Notification.Builder(mContext, "")
-                .setSmallIcon(R.drawable.ic_person)
-                .setFullScreenIntent(mock(PendingIntent.class), /* highPriority */ true)
-                .build();
-        stickyHun.flags |= FLAG_FSI_REQUESTED_BUT_DENIED;
-        return createNewSbn(id, stickyHun);
+    protected NotificationEntry createEntry(int id, Notification n) {
+        return new NotificationEntryBuilder().setSbn(createSbn(id, n)).build();
+    }
+
+    protected NotificationEntry createEntry(int id) {
+        return new NotificationEntryBuilder().setSbn(createSbn(id)).build();
+    }
+
+    protected void verifyAlertingAtTime(AlertingNotificationManager anm, NotificationEntry entry,
+            boolean shouldBeAlerting, int whenToCheckAlertingMillis, String whenCondition) {
+        final Boolean[] wasAlerting = {null};
+        final Runnable checkAlerting =
+                () -> wasAlerting[0] = anm.isAlerting(entry.getKey());
+
+        mTestHandler.postDelayed(checkAlerting, whenToCheckAlertingMillis);
+        mTestHandler.postDelayed(mTestTimeoutRunnable, TEST_TIMEOUT_TIME);
+        TestableLooper.get(this).processMessages(2);
+
+        assertFalse("Test timed out", mTimedOut);
+        if (shouldBeAlerting) {
+            assertTrue("Should still be alerting after " + whenCondition, wasAlerting[0]);
+        } else {
+            assertFalse("Should not still be alerting after " + whenCondition, wasAlerting[0]);
+        }
+        assertFalse("Should not still be alerting after processing",
+                anm.isAlerting(entry.getKey()));
     }
 
     @Before
     public void setUp() {
         mTestHandler = Handler.createAsync(Looper.myLooper());
-        mSbn = createNewNotification(0 /* id */);
-        mEntry = new NotificationEntryBuilder()
-                .setSbn(mSbn)
-                .build();
-        mEntry.setRow(mRow);
+
+        assertThat(TEST_MINIMUM_DISPLAY_TIME).isLessThan(TEST_AUTO_DISMISS_TIME);
+        assertThat(TEST_AUTO_DISMISS_TIME).isLessThan(TEST_STICKY_AUTO_DISMISS_TIME);
+        assertThat(TEST_STICKY_AUTO_DISMISS_TIME).isLessThan(TEST_TIMEOUT_TIME);
     }
 
     @After
@@ -176,59 +180,64 @@
 
     @Test
     public void testShowNotification_addsEntry() {
-        AlertingNotificationManager alm = createAlertingNotificationManager();
+        final AlertingNotificationManager alm = createAlertingNotificationManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
 
-        alm.showNotification(mEntry);
+        alm.showNotification(entry);
 
-        assertTrue(alm.isAlerting(mEntry.getKey()));
+        assertTrue(alm.isAlerting(entry.getKey()));
         assertTrue(alm.hasNotifications());
-        assertEquals(mEntry, alm.getEntry(mEntry.getKey()));
+        assertEquals(entry, alm.getEntry(entry.getKey()));
     }
 
     @Test
     public void testShowNotification_autoDismisses() {
-        AlertingNotificationManager alm = createAlertingNotificationManager();
+        final AlertingNotificationManager alm = createAlertingNotificationManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
 
-        alm.showNotification(mEntry);
-        mTestHandler.postDelayed(mTestTimeoutRunnable, TEST_TIMEOUT_TIME);
+        alm.showNotification(entry);
 
-        // Wait for remove runnable and then process it immediately
-        TestableLooper.get(this).processMessages(1);
+        verifyAlertingAtTime(alm, entry, false, TEST_AUTO_DISMISS_TIME * 3 / 2,
+                "auto dismiss time");
 
-        assertFalse("Test timed out", mTimedOut);
-        assertFalse(alm.isAlerting(mEntry.getKey()));
+        assertFalse(alm.isAlerting(entry.getKey()));
     }
 
     @Test
     public void testRemoveNotification_removeDeferred() {
-        AlertingNotificationManager alm = createAlertingNotificationManager();
-        alm.showNotification(mEntry);
+        final AlertingNotificationManager alm = createAlertingNotificationManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
+
+        alm.showNotification(entry);
 
         // Try to remove but defer, since the notification has not been shown long enough.
-        alm.removeNotification(mEntry.getKey(), false /* releaseImmediately */);
+        final boolean removedImmediately = alm.removeNotification(entry.getKey(),
+                false /* releaseImmediately */);
 
-        assertTrue(alm.isAlerting(mEntry.getKey()));
+        assertFalse(removedImmediately);
+        assertTrue(alm.isAlerting(entry.getKey()));
     }
 
     @Test
     public void testRemoveNotification_forceRemove() {
-        AlertingNotificationManager alm = createAlertingNotificationManager();
-        alm.showNotification(mEntry);
+        final AlertingNotificationManager alm = createAlertingNotificationManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
+
+        alm.showNotification(entry);
 
         // Remove forcibly with releaseImmediately = true.
-        alm.removeNotification(mEntry.getKey(), true /* releaseImmediately */);
+        final boolean removedImmediately = alm.removeNotification(entry.getKey(),
+                true /* releaseImmediately */);
 
-        assertFalse(alm.isAlerting(mEntry.getKey()));
+        assertTrue(removedImmediately);
+        assertFalse(alm.isAlerting(entry.getKey()));
     }
 
     @Test
     public void testReleaseAllImmediately() {
-        AlertingNotificationManager alm = createAlertingNotificationManager();
+        final AlertingNotificationManager alm = createAlertingNotificationManager();
         for (int i = 0; i < TEST_NUM_NOTIFICATIONS; i++) {
-            StatusBarNotification sbn = createNewNotification(i);
-            NotificationEntry entry = new NotificationEntryBuilder()
-                    .setSbn(sbn)
-                    .build();
+            final NotificationEntry entry = createEntry(i);
             entry.setRow(mRow);
             alm.showNotification(entry);
         }
@@ -240,10 +249,12 @@
 
     @Test
     public void testCanRemoveImmediately_notShownLongEnough() {
-        AlertingNotificationManager alm = createAlertingNotificationManager();
-        alm.showNotification(mEntry);
+        final AlertingNotificationManager alm = createAlertingNotificationManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
+
+        alm.showNotification(entry);
 
         // The entry has just been added so we should not remove immediately.
-        assertFalse(alm.canRemoveImmediately(mEntry.getKey()));
+        assertFalse(alm.canRemoveImmediately(entry.getKey()));
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/MediaArtworkProcessorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/MediaArtworkProcessorTest.kt
index 724ea02..e4da53a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/MediaArtworkProcessorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/MediaArtworkProcessorTest.kt
@@ -47,7 +47,7 @@
         processor = MediaArtworkProcessor()
 
         val point = Point()
-        context.display.getSize(point)
+        checkNotNull(context.display).getSize(point)
         screenWidth = point.x
         screenHeight = point.y
     }
@@ -106,4 +106,4 @@
         // THEN the processed bitmap is null
         assertThat(background).isNull()
     }
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImplTest.kt
index 414256f..6be2fa5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImplTest.kt
@@ -400,15 +400,16 @@
 
         // remove persistent dot
         systemStatusAnimationScheduler.removePersistentDot()
-        testScheduler.runCurrent()
+
+        // verify that the onHidePersistentDot callback is invoked
+        verify(listener, times(1)).onHidePersistentDot()
 
         // skip disappear animation
         animatorTestRule.advanceTimeBy(DISAPPEAR_ANIMATION_DURATION)
         testScheduler.runCurrent()
 
-        // verify that animationState changes to IDLE and onHidePersistentDot callback is invoked
+        // verify that animationState changes to IDLE
         assertEquals(IDLE, systemStatusAnimationScheduler.getAnimationState())
-        verify(listener, times(1)).onHidePersistentDot()
     }
 
     @Test
@@ -473,7 +474,6 @@
 
         // request removal of persistent dot
         systemStatusAnimationScheduler.removePersistentDot()
-        testScheduler.runCurrent()
 
         // schedule another high priority event while the event is animating out
         createAndScheduleFakePrivacyEvent()
@@ -489,6 +489,42 @@
         verify(listener, times(1)).onHidePersistentDot()
     }
 
+    @Test
+    fun testDotIsRemoved_evenIfAnimatorCallbackIsDelayed() = runTest {
+        // Instantiate class under test with TestScope from runTest
+        initializeSystemStatusAnimationScheduler(testScope = this)
+
+        // create and schedule high priority event
+        createAndScheduleFakePrivacyEvent()
+
+        // skip chip animation lifecycle and fast forward to ANIMATING_OUT state
+        fastForwardAnimationToState(ANIMATING_OUT)
+        assertEquals(ANIMATING_OUT, systemStatusAnimationScheduler.getAnimationState())
+        verify(listener, times(1)).onSystemStatusAnimationTransitionToPersistentDot(any())
+
+        // request removal of persistent dot
+        systemStatusAnimationScheduler.removePersistentDot()
+
+        // verify that the state is still ANIMATING_OUT
+        assertEquals(ANIMATING_OUT, systemStatusAnimationScheduler.getAnimationState())
+
+        // skip disappear animation duration
+        testScheduler.advanceTimeBy(DISAPPEAR_ANIMATION_DURATION + 1)
+        // In an old implementation this would trigger a coroutine timeout causing the
+        // onHidePersistentDot callback to be missed.
+        testScheduler.runCurrent()
+
+        // advance animator time to invoke onAnimationEnd callback
+        animatorTestRule.advanceTimeBy(DISAPPEAR_ANIMATION_DURATION)
+        testScheduler.runCurrent()
+
+        // verify that onHidePersistentDot is invoked despite the animator callback being delayed
+        // (it's invoked more than DISAPPEAR_ANIMATION_DURATION after the dot removal was requested)
+        verify(listener, times(1)).onHidePersistentDot()
+        // verify that animationState is IDLE
+        assertEquals(IDLE, systemStatusAnimationScheduler.getAnimationState())
+    }
+
     private fun TestScope.fastForwardAnimationToState(@SystemAnimationState animationState: Int) {
         // this function should only be called directly after posting a status event
         assertEquals(ANIMATION_QUEUED, systemStatusAnimationScheduler.getAnimationState())
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceControllerTest.kt
index 2de5705..9036f22 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceControllerTest.kt
@@ -278,7 +278,7 @@
         `when`(deviceProvisionedController.isCurrentUserSetup).thenReturn(false)
 
         // WHEN a connection attempt is made and view is attached
-        val view = controller.buildAndConnectView(fakeParent)
+        val view = controller.buildAndConnectView(fakeParent)!!
         controller.stateChangeListener.onViewAttachedToWindow(view)
 
         // THEN no session is created
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/AppOpsCoordinatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ColorizedFgsCoordinatorTest.java
similarity index 69%
rename from packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/AppOpsCoordinatorTest.java
rename to packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ColorizedFgsCoordinatorTest.java
index bc32759..f2207af 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/AppOpsCoordinatorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ColorizedFgsCoordinatorTest.java
@@ -24,97 +24,53 @@
 import static junit.framework.Assert.assertFalse;
 import static junit.framework.Assert.assertTrue;
 
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 import android.app.Notification;
 import android.app.PendingIntent;
 import android.app.Person;
 import android.content.Intent;
 import android.graphics.Color;
 import android.os.UserHandle;
-import android.service.notification.StatusBarNotification;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
 import androidx.test.filters.SmallTest;
 
-import com.android.systemui.ForegroundServiceController;
 import com.android.systemui.SysuiTestCase;
-import com.android.systemui.appops.AppOpsController;
 import com.android.systemui.statusbar.notification.collection.NotifPipeline;
-import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
-import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifFilter;
 import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifSectioner;
-import com.android.systemui.util.concurrency.FakeExecutor;
-import com.android.systemui.util.time.FakeSystemClock;
 
 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;
 
 @SmallTest
 @RunWith(AndroidTestingRunner.class)
 @TestableLooper.RunWithLooper
-public class AppOpsCoordinatorTest extends SysuiTestCase {
-    private static final String TEST_PKG = "test_pkg";
-    private static final int NOTIF_USER_ID = 0;
+public class ColorizedFgsCoordinatorTest extends SysuiTestCase {
 
-    @Mock private ForegroundServiceController mForegroundServiceController;
-    @Mock private AppOpsController mAppOpsController;
+    private static final int NOTIF_USER_ID = 0;
     @Mock private NotifPipeline mNotifPipeline;
 
     private NotificationEntryBuilder mEntryBuilder;
-    private AppOpsCoordinator mAppOpsCoordinator;
-    private NotifFilter mForegroundFilter;
+    private ColorizedFgsCoordinator mColorizedFgsCoordinator;
     private NotifSectioner mFgsSection;
 
-    private FakeSystemClock mClock = new FakeSystemClock();
-    private FakeExecutor mExecutor = new FakeExecutor(mClock);
-
     @Before
     public void setup() {
         MockitoAnnotations.initMocks(this);
         allowTestableLooperAsMainThread();
 
-        mAppOpsCoordinator =
-                new AppOpsCoordinator(
-                        mForegroundServiceController,
-                        mAppOpsController,
-                        mExecutor);
+        mColorizedFgsCoordinator = new ColorizedFgsCoordinator();
 
         mEntryBuilder = new NotificationEntryBuilder()
                 .setUser(new UserHandle(NOTIF_USER_ID));
 
-        mAppOpsCoordinator.attach(mNotifPipeline);
+        mColorizedFgsCoordinator.attach(mNotifPipeline);
 
-        // capture filter
-        ArgumentCaptor<NotifFilter> filterCaptor = ArgumentCaptor.forClass(NotifFilter.class);
-        verify(mNotifPipeline, times(1)).addPreGroupFilter(filterCaptor.capture());
-        mForegroundFilter = filterCaptor.getValue();
-
-        mFgsSection = mAppOpsCoordinator.getSectioner();
-    }
-
-    @Test
-    public void filterTest_disclosureUnnecessary() {
-        NotificationEntry entry = mEntryBuilder.build();
-        StatusBarNotification sbn = entry.getSbn();
-
-        // GIVEN the notification is a disclosure notification
-        when(mForegroundServiceController.isDisclosureNotification(sbn)).thenReturn(true);
-
-        // GIVEN the disclosure isn't needed for this user
-        when(mForegroundServiceController.isDisclosureNeededForUser(sbn.getUserId()))
-                .thenReturn(false);
-
-        // THEN filter out the notification
-        assertTrue(mForegroundFilter.shouldFilterOut(entry, 0));
+        mFgsSection = mColorizedFgsCoordinator.getSectioner();
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerTest.kt
index 4a94dc8..38a8f414 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerTest.kt
@@ -21,11 +21,21 @@
 import com.android.systemui.dump.DumpManager
 import com.android.systemui.flags.FakeFeatureFlags
 import com.android.systemui.flags.Flags
+import com.android.systemui.statusbar.notification.collection.GroupEntryBuilder
+import com.android.systemui.statusbar.notification.collection.ListEntry
+import com.android.systemui.statusbar.notification.collection.NotifPipeline
 import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder
+import com.android.systemui.statusbar.notification.collection.listbuilder.OnBeforeRenderListListener
+import com.android.systemui.statusbar.notification.collection.render.GroupExpansionManager.OnGroupExpansionChangeListener
+import com.android.systemui.util.mockito.any
 import com.android.systemui.util.mockito.mock
+import com.android.systemui.util.mockito.withArgCaptor
 import org.junit.Assert
 import org.junit.Before
 import org.junit.Test
+import org.mockito.Mockito.never
+import org.mockito.Mockito.verify
+import org.mockito.Mockito.verifyNoMoreInteractions
 import org.mockito.Mockito.`when` as whenever
 
 @SmallTest
@@ -36,13 +46,43 @@
     private val groupMembershipManager: GroupMembershipManager = mock()
     private val featureFlags = FakeFeatureFlags()
 
-    private val entry1 = NotificationEntryBuilder().build()
-    private val entry2 = NotificationEntryBuilder().build()
+    private val pipeline: NotifPipeline = mock()
+    private lateinit var beforeRenderListListener: OnBeforeRenderListListener
+
+    private val summary1 = notificationEntry("foo", 1)
+    private val summary2 = notificationEntry("bar", 1)
+    private val entries =
+        listOf<ListEntry>(
+            GroupEntryBuilder()
+                .setSummary(summary1)
+                .setChildren(
+                    listOf(
+                        notificationEntry("foo", 2),
+                        notificationEntry("foo", 3),
+                        notificationEntry("foo", 4)
+                    )
+                )
+                .build(),
+            GroupEntryBuilder()
+                .setSummary(summary2)
+                .setChildren(
+                    listOf(
+                        notificationEntry("bar", 2),
+                        notificationEntry("bar", 3),
+                        notificationEntry("bar", 4)
+                    )
+                )
+                .build(),
+            notificationEntry("baz", 1)
+        )
+
+    private fun notificationEntry(pkg: String, id: Int) =
+        NotificationEntryBuilder().setPkg(pkg).setId(id).build().apply { row = mock() }
 
     @Before
     fun setUp() {
-        whenever(groupMembershipManager.getGroupSummary(entry1)).thenReturn(entry1)
-        whenever(groupMembershipManager.getGroupSummary(entry2)).thenReturn(entry2)
+        whenever(groupMembershipManager.getGroupSummary(summary1)).thenReturn(summary1)
+        whenever(groupMembershipManager.getGroupSummary(summary2)).thenReturn(summary2)
 
         gem = GroupExpansionManagerImpl(dumpManager, groupMembershipManager, featureFlags)
     }
@@ -54,15 +94,15 @@
         var listenerCalledCount = 0
         gem.registerGroupExpansionChangeListener { _, _ -> listenerCalledCount++ }
 
-        gem.setGroupExpanded(entry1, false)
+        gem.setGroupExpanded(summary1, false)
         Assert.assertEquals(0, listenerCalledCount)
-        gem.setGroupExpanded(entry1, true)
+        gem.setGroupExpanded(summary1, true)
         Assert.assertEquals(1, listenerCalledCount)
-        gem.setGroupExpanded(entry2, true)
+        gem.setGroupExpanded(summary2, true)
         Assert.assertEquals(2, listenerCalledCount)
-        gem.setGroupExpanded(entry1, true)
+        gem.setGroupExpanded(summary1, true)
         Assert.assertEquals(2, listenerCalledCount)
-        gem.setGroupExpanded(entry2, false)
+        gem.setGroupExpanded(summary2, false)
         Assert.assertEquals(3, listenerCalledCount)
     }
 
@@ -73,15 +113,39 @@
         var listenerCalledCount = 0
         gem.registerGroupExpansionChangeListener { _, _ -> listenerCalledCount++ }
 
-        gem.setGroupExpanded(entry1, false)
+        gem.setGroupExpanded(summary1, false)
         Assert.assertEquals(1, listenerCalledCount)
-        gem.setGroupExpanded(entry1, true)
+        gem.setGroupExpanded(summary1, true)
         Assert.assertEquals(2, listenerCalledCount)
-        gem.setGroupExpanded(entry2, true)
+        gem.setGroupExpanded(summary2, true)
         Assert.assertEquals(3, listenerCalledCount)
-        gem.setGroupExpanded(entry1, true)
+        gem.setGroupExpanded(summary1, true)
         Assert.assertEquals(4, listenerCalledCount)
-        gem.setGroupExpanded(entry2, false)
+        gem.setGroupExpanded(summary2, false)
         Assert.assertEquals(5, listenerCalledCount)
     }
+
+    @Test
+    fun testSyncWithPipeline() {
+        featureFlags.set(Flags.NOTIFICATION_GROUP_EXPANSION_CHANGE, true)
+        gem.attach(pipeline)
+        beforeRenderListListener = withArgCaptor {
+            verify(pipeline).addOnBeforeRenderListListener(capture())
+        }
+
+        val listener: OnGroupExpansionChangeListener = mock()
+        gem.registerGroupExpansionChangeListener(listener)
+
+        beforeRenderListListener.onBeforeRenderList(entries)
+        verify(listener, never()).onGroupExpansionChange(any(), any())
+
+        // Expand one of the groups.
+        gem.setGroupExpanded(summary1, true)
+        verify(listener).onGroupExpansionChange(summary1.row, true)
+
+        // Empty the pipeline list and verify that the group is no longer expanded.
+        beforeRenderListListener.onBeforeRenderList(emptyList())
+        verify(listener).onGroupExpansionChange(summary1.row, false)
+        verifyNoMoreInteractions(listener)
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconAreaControllerViewBinderWrapperImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconAreaControllerViewBinderWrapperImplTest.kt
new file mode 100644
index 0000000..b8792a8
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/icon/ui/viewbinder/NotificationIconAreaControllerViewBinderWrapperImplTest.kt
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.icon.ui.viewbinder
+
+import android.testing.AndroidTestingRunner
+import android.testing.TestableLooper.RunWithLooper
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.demomode.DemoModeController
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.plugins.DarkIconDispatcher
+import com.android.systemui.plugins.statusbar.StatusBarStateController
+import com.android.systemui.statusbar.NotificationListener
+import com.android.systemui.statusbar.NotificationMediaManager
+import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator
+import com.android.systemui.statusbar.notification.collection.provider.SectionStyleProvider
+import com.android.systemui.statusbar.notification.icon.ui.viewmodel.NotificationIconContainerAlwaysOnDisplayViewModel
+import com.android.systemui.statusbar.notification.icon.ui.viewmodel.NotificationIconContainerShelfViewModel
+import com.android.systemui.statusbar.notification.icon.ui.viewmodel.NotificationIconContainerStatusBarViewModel
+import com.android.systemui.statusbar.phone.DozeParameters
+import com.android.systemui.statusbar.phone.KeyguardBypassController
+import com.android.systemui.statusbar.phone.NotificationIconContainer
+import com.android.systemui.statusbar.phone.ScreenOffAnimationController
+import com.android.systemui.statusbar.window.StatusBarWindowController
+import com.android.systemui.util.mockito.whenever
+import com.android.wm.shell.bubbles.Bubbles
+import java.util.Optional
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mock
+import org.mockito.Mockito.verify
+import org.mockito.MockitoAnnotations
+
+@SmallTest
+@RunWith(AndroidTestingRunner::class)
+@RunWithLooper(setAsMainLooper = true)
+class NotificationIconAreaControllerViewBinderWrapperImplTest : SysuiTestCase() {
+    @Mock private lateinit var notifListener: NotificationListener
+    @Mock private lateinit var statusBarStateController: StatusBarStateController
+    @Mock private lateinit var wakeUpCoordinator: NotificationWakeUpCoordinator
+    @Mock private lateinit var keyguardBypassController: KeyguardBypassController
+    @Mock private lateinit var notifMediaManager: NotificationMediaManager
+    @Mock private lateinit var dozeParams: DozeParameters
+    @Mock private lateinit var sectionStyleProvider: SectionStyleProvider
+    @Mock private lateinit var darkIconDispatcher: DarkIconDispatcher
+    @Mock private lateinit var statusBarWindowController: StatusBarWindowController
+    @Mock private lateinit var screenOffAnimController: ScreenOffAnimationController
+    @Mock private lateinit var bubbles: Bubbles
+    @Mock private lateinit var demoModeController: DemoModeController
+    @Mock private lateinit var aodIcons: NotificationIconContainer
+    @Mock private lateinit var featureFlags: FeatureFlags
+
+    private val shelfViewModel = NotificationIconContainerShelfViewModel()
+    private val statusBarViewModel = NotificationIconContainerStatusBarViewModel()
+    private val aodViewModel = NotificationIconContainerAlwaysOnDisplayViewModel()
+
+    private lateinit var underTest: NotificationIconAreaControllerViewBinderWrapperImpl
+
+    @Before
+    fun setup() {
+        MockitoAnnotations.initMocks(this)
+        underTest =
+            NotificationIconAreaControllerViewBinderWrapperImpl(
+                mContext,
+                statusBarStateController,
+                wakeUpCoordinator,
+                keyguardBypassController,
+                notifMediaManager,
+                notifListener,
+                dozeParams,
+                sectionStyleProvider,
+                Optional.of(bubbles),
+                demoModeController,
+                darkIconDispatcher,
+                featureFlags,
+                statusBarWindowController,
+                screenOffAnimController,
+                shelfViewModel,
+                statusBarViewModel,
+                aodViewModel,
+            )
+    }
+
+    @Test
+    fun testNotificationIcons_settingHideIcons() {
+        underTest.settingsListener.onStatusBarIconsBehaviorChanged(true)
+        assertFalse(underTest.shouldShowLowPriorityIcons())
+    }
+
+    @Test
+    fun testNotificationIcons_settingShowIcons() {
+        underTest.settingsListener.onStatusBarIconsBehaviorChanged(false)
+        assertTrue(underTest.shouldShowLowPriorityIcons())
+    }
+
+    @Test
+    fun testAppearResetsTranslation() {
+        underTest.setupAodIcons(aodIcons)
+        whenever(dozeParams.shouldControlScreenOff()).thenReturn(false)
+        underTest.appearAodIcons()
+        verify(aodIcons).translationY = 0f
+        verify(aodIcons).alpha = 1.0f
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowControllerTest.kt
index 764005b8..0cc0b98 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowControllerTest.kt
@@ -17,6 +17,10 @@
 
 package com.android.systemui.statusbar.notification.row
 
+import android.app.Notification
+import android.net.Uri
+import android.os.UserHandle
+import android.os.UserHandle.USER_ALL
 import android.testing.AndroidTestingRunner
 import android.testing.TestableLooper
 import androidx.test.filters.SmallTest
@@ -29,13 +33,17 @@
 import com.android.systemui.plugins.FalsingManager
 import com.android.systemui.plugins.PluginManager
 import com.android.systemui.plugins.statusbar.StatusBarStateController
+import com.android.systemui.statusbar.SbnBuilder
 import com.android.systemui.statusbar.SmartReplyController
+import com.android.systemui.statusbar.notification.collection.NotificationEntry
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder
 import com.android.systemui.statusbar.notification.collection.provider.NotificationDismissibilityProvider
 import com.android.systemui.statusbar.notification.collection.render.FakeNodeController
 import com.android.systemui.statusbar.notification.collection.render.GroupExpansionManager
 import com.android.systemui.statusbar.notification.collection.render.GroupMembershipManager
 import com.android.systemui.statusbar.notification.logging.NotificationLogger
 import com.android.systemui.statusbar.notification.people.PeopleNotificationIdentifier
+import com.android.systemui.statusbar.notification.row.ExpandableNotificationRowController.BUBBLES_SETTING_URI
 import com.android.systemui.statusbar.notification.stack.NotificationChildrenContainer
 import com.android.systemui.statusbar.notification.stack.NotificationChildrenContainerLogger
 import com.android.systemui.statusbar.notification.stack.NotificationListContainer
@@ -46,9 +54,9 @@
 import com.android.systemui.util.mockito.any
 import com.android.systemui.util.mockito.eq
 import com.android.systemui.util.mockito.mock
+import com.android.systemui.util.mockito.withArgCaptor
 import com.android.systemui.util.time.SystemClock
 import com.android.systemui.wmshell.BubblesManager
-import java.util.Optional
 import junit.framework.Assert
 import org.junit.After
 import org.junit.Before
@@ -56,9 +64,11 @@
 import org.junit.runner.RunWith
 import org.mockito.Mockito
 import org.mockito.Mockito.anyBoolean
+import org.mockito.Mockito.mock
 import org.mockito.Mockito.never
 import org.mockito.Mockito.verify
 import org.mockito.Mockito.`when` as whenever
+import java.util.Optional
 
 @SmallTest
 @RunWith(AndroidTestingRunner::class)
@@ -94,10 +104,10 @@
     private val featureFlags: FeatureFlags = mock()
     private val peopleNotificationIdentifier: PeopleNotificationIdentifier = mock()
     private val bubblesManager: BubblesManager = mock()
+    private val settingsController: NotificationSettingsController = mock()
     private val dragController: ExpandableNotificationRowDragController = mock()
     private val dismissibilityProvider: NotificationDismissibilityProvider = mock()
     private val statusBarService: IStatusBarService = mock()
-
     private lateinit var controller: ExpandableNotificationRowController
 
     @Before
@@ -134,11 +144,16 @@
                 featureFlags,
                 peopleNotificationIdentifier,
                 Optional.of(bubblesManager),
+                settingsController,
                 dragController,
                 dismissibilityProvider,
                 statusBarService
             )
         whenever(view.childrenContainer).thenReturn(childrenContainer)
+
+        val notification = Notification.Builder(mContext).build()
+        val sbn = SbnBuilder().setNotification(notification).build()
+        whenever(view.entry).thenReturn(NotificationEntryBuilder().setSbn(sbn).build())
     }
 
     @After
@@ -206,4 +221,74 @@
         verify(view).removeChildNotification(eq(childView))
         verify(listContainer).notifyGroupChildRemoved(eq(childView), eq(childrenContainer))
     }
+
+    @Test
+    fun registerSettingsListener_forBubbles() {
+        controller.init(mock(NotificationEntry::class.java))
+        val viewStateObserver = withArgCaptor {
+            verify(view).addOnAttachStateChangeListener(capture());
+        }
+        viewStateObserver.onViewAttachedToWindow(view);
+        verify(settingsController).addCallback(any(), any());
+    }
+
+    @Test
+    fun unregisterSettingsListener_forBubbles() {
+        controller.init(mock(NotificationEntry::class.java))
+        val viewStateObserver = withArgCaptor {
+            verify(view).addOnAttachStateChangeListener(capture());
+        }
+        viewStateObserver.onViewDetachedFromWindow(view);
+        verify(settingsController).removeCallback(any(), any());
+    }
+
+    @Test
+    fun settingsListener_invalidUri() {
+        controller.mSettingsListener.onSettingChanged(Uri.EMPTY, view.entry.sbn.userId, "1")
+
+        verify(view, never()).getPrivateLayout()
+    }
+
+    @Test
+    fun settingsListener_invalidUserId() {
+        controller.mSettingsListener.onSettingChanged(BUBBLES_SETTING_URI, -1000, "1")
+        controller.mSettingsListener.onSettingChanged(BUBBLES_SETTING_URI, -1000, null)
+
+        verify(view, never()).getPrivateLayout()
+    }
+
+    @Test
+    fun settingsListener_validUserId() {
+        val childView: NotificationContentView = mock()
+        whenever(view.privateLayout).thenReturn(childView)
+
+        controller.mSettingsListener.onSettingChanged(
+                BUBBLES_SETTING_URI, view.entry.sbn.userId, "1")
+        verify(childView).setBubblesEnabledForUser(true)
+
+        controller.mSettingsListener.onSettingChanged(
+                BUBBLES_SETTING_URI, view.entry.sbn.userId, "9")
+        verify(childView).setBubblesEnabledForUser(false)
+    }
+
+    @Test
+    fun settingsListener_userAll() {
+        val childView: NotificationContentView = mock()
+        whenever(view.privateLayout).thenReturn(childView)
+
+        val notification = Notification.Builder(mContext).build()
+        val sbn = SbnBuilder().setNotification(notification)
+                .setUser(UserHandle.of(USER_ALL))
+                .build()
+        whenever(view.entry).thenReturn(NotificationEntryBuilder()
+                .setSbn(sbn)
+                .setUser(UserHandle.of(USER_ALL))
+                .build())
+
+        controller.mSettingsListener.onSettingChanged(BUBBLES_SETTING_URI, 9, "1")
+        verify(childView).setBubblesEnabledForUser(true)
+
+        controller.mSettingsListener.onSettingChanged(BUBBLES_SETTING_URI, 1, "0")
+        verify(childView).setBubblesEnabledForUser(false)
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.kt
index 0b90ebe..c4baa69 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.kt
@@ -250,6 +250,9 @@
             .thenReturn(actionListMarginTarget)
         view.setContainingNotification(mockContainingNotification)
 
+        // Given: controller says bubbles are enabled for the user
+        view.setBubblesEnabledForUser(true);
+
         // When: call NotificationContentView.setExpandedChild() to set the expandedChild
         view.expandedChild = mockExpandedChild
 
@@ -305,6 +308,12 @@
         // NotificationEntry, which should show bubble button
         view.onNotificationUpdated(createMockNotificationEntry(true))
 
+        // Then: no bubble yet
+        assertEquals(notificationContentMargin, getMarginBottom(actionListMarginTarget))
+
+        // Given: controller says bubbles are enabled for the user
+        view.setBubblesEnabledForUser(true);
+
         // Then: bottom margin of actionListMarginTarget should not change, still be 20
         assertEquals(0, getMarginBottom(actionListMarginTarget))
     }
@@ -405,7 +414,6 @@
             val userMock: UserHandle = mock()
             whenever(this.sbn).thenReturn(sbnMock)
             whenever(sbnMock.user).thenReturn(userMock)
-            doReturn(showButton).whenever(view).shouldShowBubbleButton(this)
         }
 
     private fun createLinearLayoutWithBottomMargin(bottomMargin: Int): LinearLayout {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfoTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfoTest.java
index 90adabf..596e9a2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfoTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfoTest.java
@@ -62,6 +62,7 @@
 import android.graphics.drawable.Icon;
 import android.os.Handler;
 import android.os.UserHandle;
+import android.os.UserManager;
 import android.service.notification.StatusBarNotification;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.AndroidTestingRunner;
@@ -132,6 +133,8 @@
     @Mock
     private PackageManager mMockPackageManager;
     @Mock
+    private UserManager mUserManager;
+    @Mock
     private OnUserInteractionCallback mOnUserInteractionCallback;
     @Mock
     private BubblesManager mBubblesManager;
@@ -238,6 +241,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -262,6 +266,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -314,6 +319,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -339,6 +345,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -363,6 +370,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -398,6 +406,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -423,6 +432,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -452,6 +462,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -476,6 +487,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -504,6 +516,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -532,6 +545,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -563,6 +577,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -600,6 +615,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -628,6 +644,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -663,6 +680,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -691,6 +709,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -735,6 +754,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -778,6 +798,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -822,6 +843,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -860,6 +882,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -896,6 +919,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -936,6 +960,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -967,6 +992,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -996,6 +1022,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -1033,6 +1060,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -1069,6 +1097,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -1104,6 +1133,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -1143,6 +1173,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -1173,6 +1204,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -1198,6 +1230,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -1219,11 +1252,13 @@
 
     @Test
     public void testSelectPriorityRequestsPinPeopleTile() {
+        when(mUserManager.isSameProfileGroup(anyInt(), anyInt())).thenReturn(true);
         //WHEN channel is default importance
         mNotificationChannel.setImportantConversation(false);
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -1250,10 +1285,45 @@
     }
 
     @Test
+    public void testSelectPriorityRequestsPinPeopleTile_noMultiuser() {
+        when(mUserManager.isSameProfileGroup(anyInt(), anyInt())).thenReturn(false);
+        //WHEN channel is default importance
+        mNotificationChannel.setImportantConversation(false);
+        mNotificationInfo.bindNotification(
+                mShortcutManager,
+                mMockPackageManager,
+                mUserManager,
+                mPeopleSpaceWidgetManager,
+                mMockINotificationManager,
+                mOnUserInteractionCallback,
+                TEST_PACKAGE_NAME,
+                mNotificationChannel,
+                mEntry,
+                mBubbleMetadata,
+                null,
+                mIconFactory,
+                mContext,
+                true,
+                mTestHandler,
+                mTestHandler, null, Optional.of(mBubblesManager),
+                mShadeController);
+
+        // WHEN user clicks "priority"
+        mNotificationInfo.setSelectedAction(NotificationConversationInfo.ACTION_FAVORITE);
+
+        // and then done
+        mNotificationInfo.findViewById(R.id.done).performClick();
+
+        // No widget prompt; on a secondary user
+        verify(mPeopleSpaceWidgetManager, never()).requestPinAppWidget(any(), any());
+    }
+
+    @Test
     public void testSelectDefaultDoesNotRequestPinPeopleTile() {
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
@@ -1288,6 +1358,7 @@
         mNotificationInfo.bindNotification(
                 mShortcutManager,
                 mMockPackageManager,
+                mUserManager,
                 mPeopleSpaceWidgetManager,
                 mMockINotificationManager,
                 mOnUserInteractionCallback,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
index 3cefc99..705d52b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
@@ -52,6 +52,7 @@
 import android.graphics.Color;
 import android.os.Binder;
 import android.os.Handler;
+import android.os.UserManager;
 import android.provider.Settings;
 import android.service.notification.StatusBarNotification;
 import android.testing.AndroidTestingRunner;
@@ -137,6 +138,8 @@
     @Mock private HeadsUpManagerPhone mHeadsUpManagerPhone;
     @Mock private ActivityStarter mActivityStarter;
 
+    @Mock private UserManager mUserManager;
+
     @Before
     public void setUp() {
         mTestableLooper = TestableLooper.get(this);
@@ -147,7 +150,7 @@
 
         mGutsManager = new NotificationGutsManager(mContext, mHandler, mHandler,
                 mAccessibilityManager,
-                mHighPriorityProvider, mINotificationManager,
+                mHighPriorityProvider, mINotificationManager, mUserManager,
                 mPeopleSpaceWidgetManager, mLauncherApps, mShortcutManager,
                 mChannelEditorDialogController, mContextTracker, mAssistantFeedbackController,
                 Optional.of(mBubblesManager), new UiEventLoggerFake(), mOnUserInteractionCallback,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationSettingsControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationSettingsControllerTest.kt
new file mode 100644
index 0000000..614995b
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationSettingsControllerTest.kt
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.row
+
+import android.app.ActivityManager
+import android.database.ContentObserver
+import android.net.Uri
+import android.os.Handler
+import android.provider.Settings.Secure
+import android.testing.AndroidTestingRunner
+import android.testing.TestableLooper
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.dump.DumpManager
+import com.android.systemui.settings.UserTracker
+import com.android.systemui.statusbar.notification.row.NotificationSettingsController.Listener
+import com.android.systemui.util.mockito.any
+import com.android.systemui.util.mockito.capture
+import com.android.systemui.util.mockito.eq
+import com.android.systemui.util.mockito.mock
+import com.android.systemui.util.mockito.whenever
+import com.android.systemui.util.settings.SecureSettings
+import org.junit.After
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentCaptor
+import org.mockito.ArgumentMatchers
+import org.mockito.ArgumentMatchers.anyInt
+import org.mockito.ArgumentMatchers.anyString
+import org.mockito.Captor
+import org.mockito.Mock
+import org.mockito.Mockito
+import org.mockito.Mockito.anyBoolean
+import org.mockito.Mockito.never
+import org.mockito.Mockito.verify
+import org.mockito.MockitoAnnotations
+
+@SmallTest
+@RunWith(AndroidTestingRunner::class)
+@TestableLooper.RunWithLooper
+class NotificationSettingsControllerTest : SysuiTestCase() {
+
+    val setting1: String = Secure.NOTIFICATION_BUBBLES
+    val setting2: String = Secure.ACCESSIBILITY_ENABLED
+    val settingUri1: Uri = Secure.getUriFor(setting1)
+    val settingUri2: Uri = Secure.getUriFor(setting2)
+
+    @Mock
+    private lateinit var userTracker: UserTracker
+    private lateinit var mainHandler: Handler
+    private lateinit var backgroundHandler: Handler
+    private lateinit var testableLooper: TestableLooper
+    @Mock
+    private lateinit var secureSettings: SecureSettings
+    @Mock
+    private lateinit var dumpManager: DumpManager
+
+    @Captor
+    private lateinit var userTrackerCallbackCaptor: ArgumentCaptor<UserTracker.Callback>
+    @Captor
+    private lateinit var settingsObserverCaptor: ArgumentCaptor<ContentObserver>
+
+    private lateinit var controller: NotificationSettingsController
+
+    @Before
+    fun setUp() {
+        MockitoAnnotations.initMocks(this)
+        testableLooper = TestableLooper.get(this)
+        mainHandler = Handler(testableLooper.looper)
+        backgroundHandler = Handler(testableLooper.looper)
+        allowTestableLooperAsMainThread()
+        controller =
+                NotificationSettingsController(
+                        userTracker,
+                        mainHandler,
+                        backgroundHandler,
+                        secureSettings,
+                        dumpManager
+                )
+    }
+
+    @After
+    fun tearDown() {
+        disallowTestableLooperAsMainThread()
+    }
+
+    @Test
+    fun creationRegistersCallbacks() {
+        verify(userTracker).addCallback(any(), any())
+        verify(dumpManager).registerNormalDumpable(anyString(), eq(controller))
+    }
+    @Test
+    fun updateContentObserverRegistration_onUserChange_noSettingsListeners() {
+        verify(userTracker).addCallback(capture(userTrackerCallbackCaptor), any())
+        val userCallback = userTrackerCallbackCaptor.value
+        val userId = 9
+
+        // When: User is changed
+        userCallback.onUserChanged(userId, context)
+
+        // Validate: Nothing to do, since we aren't monitoring settings
+        verify(secureSettings, never()).unregisterContentObserver(any())
+        verify(secureSettings, never()).registerContentObserverForUser(
+                any(Uri::class.java), anyBoolean(), any(), anyInt())
+    }
+    @Test
+    fun updateContentObserverRegistration_onUserChange_withSettingsListeners() {
+        // When: someone is listening to a setting
+        controller.addCallback(settingUri1,
+                Mockito.mock(Listener::class.java))
+
+        verify(userTracker).addCallback(capture(userTrackerCallbackCaptor), any())
+        val userCallback = userTrackerCallbackCaptor.value
+        val userId = 9
+
+        // Then: User is changed
+        userCallback.onUserChanged(userId, context)
+
+        // Validate: The tracker is unregistered and re-registered with the new user
+        verify(secureSettings).unregisterContentObserver(any())
+        verify(secureSettings).registerContentObserverForUser(
+                eq(settingUri1), eq(false), any(), eq(userId))
+    }
+
+    @Test
+    fun addCallback_onlyFirstForUriRegistersObserver() {
+        controller.addCallback(settingUri1,
+                Mockito.mock(Listener::class.java))
+        verify(secureSettings).registerContentObserverForUser(
+                eq(settingUri1), eq(false), any(), eq(ActivityManager.getCurrentUser()))
+
+        controller.addCallback(settingUri1,
+                Mockito.mock(Listener::class.java))
+        verify(secureSettings).registerContentObserverForUser(
+                any(Uri::class.java), anyBoolean(), any(), anyInt())
+    }
+
+    @Test
+    fun addCallback_secondUriRegistersObserver() {
+        controller.addCallback(settingUri1,
+                Mockito.mock(Listener::class.java))
+        verify(secureSettings).registerContentObserverForUser(
+                eq(settingUri1), eq(false), any(), eq(ActivityManager.getCurrentUser()))
+
+        controller.addCallback(settingUri2,
+                Mockito.mock(Listener::class.java))
+        verify(secureSettings).registerContentObserverForUser(
+                eq(settingUri2), eq(false), any(), eq(ActivityManager.getCurrentUser()))
+        verify(secureSettings).registerContentObserverForUser(
+                eq(settingUri1), anyBoolean(), any(), anyInt())
+    }
+
+    @Test
+    fun removeCallback_lastUnregistersObserver() {
+        val listenerSetting1 : Listener = mock()
+        val listenerSetting2 : Listener = mock()
+        controller.addCallback(settingUri1, listenerSetting1)
+        verify(secureSettings).registerContentObserverForUser(
+                eq(settingUri1), eq(false), any(), eq(ActivityManager.getCurrentUser()))
+
+        controller.addCallback(settingUri2, listenerSetting2)
+        verify(secureSettings).registerContentObserverForUser(
+                eq(settingUri2), anyBoolean(), any(), anyInt())
+
+        controller.removeCallback(settingUri2, listenerSetting2)
+        verify(secureSettings, never()).unregisterContentObserver(any())
+
+        controller.removeCallback(settingUri1, listenerSetting1)
+        verify(secureSettings).unregisterContentObserver(any())
+    }
+
+    @Test
+    fun addCallback_updatesCurrentValue() {
+        whenever(secureSettings.getStringForUser(
+                setting1, ActivityManager.getCurrentUser())).thenReturn("9")
+        whenever(secureSettings.getStringForUser(
+                setting2, ActivityManager.getCurrentUser())).thenReturn("5")
+
+        val listenerSetting1a : Listener = mock()
+        val listenerSetting1b : Listener = mock()
+        val listenerSetting2 : Listener = mock()
+
+        controller.addCallback(settingUri1, listenerSetting1a)
+        controller.addCallback(settingUri1, listenerSetting1b)
+        controller.addCallback(settingUri2, listenerSetting2)
+
+        testableLooper.processAllMessages()
+
+        verify(listenerSetting1a).onSettingChanged(
+                settingUri1, ActivityManager.getCurrentUser(), "9")
+        verify(listenerSetting1b).onSettingChanged(
+                settingUri1, ActivityManager.getCurrentUser(), "9")
+        verify(listenerSetting2).onSettingChanged(
+                settingUri2, ActivityManager.getCurrentUser(), "5")
+    }
+
+    @Test
+    fun removeCallback_noMoreUpdates() {
+        whenever(secureSettings.getStringForUser(
+                setting1, ActivityManager.getCurrentUser())).thenReturn("9")
+
+        val listenerSetting1a : Listener = mock()
+        val listenerSetting1b : Listener = mock()
+
+        // First, register
+        controller.addCallback(settingUri1, listenerSetting1a)
+        controller.addCallback(settingUri1, listenerSetting1b)
+        testableLooper.processAllMessages()
+
+        verify(secureSettings).registerContentObserverForUser(
+                any(Uri::class.java), anyBoolean(), capture(settingsObserverCaptor), anyInt())
+        verify(listenerSetting1a).onSettingChanged(
+                settingUri1, ActivityManager.getCurrentUser(), "9")
+        verify(listenerSetting1b).onSettingChanged(
+                settingUri1, ActivityManager.getCurrentUser(), "9")
+        Mockito.clearInvocations(listenerSetting1b)
+        Mockito.clearInvocations(listenerSetting1a)
+
+        // Remove one of them
+        controller.removeCallback(settingUri1, listenerSetting1a)
+
+        // On update, only remaining listener should get the callback
+        settingsObserverCaptor.value.onChange(false, settingUri1)
+        testableLooper.processAllMessages()
+
+        verify(listenerSetting1a, never()).onSettingChanged(
+                settingUri1, ActivityManager.getCurrentUser(), "9")
+        verify(listenerSetting1b).onSettingChanged(
+                settingUri1, ActivityManager.getCurrentUser(), "9")
+    }
+
+}
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithmTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithmTest.kt
index 987861d..77c9b8b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithmTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithmTest.kt
@@ -1,6 +1,7 @@
 package com.android.systemui.statusbar.notification.stack
 
 import android.annotation.DimenRes
+import android.content.pm.PackageManager
 import android.widget.FrameLayout
 import androidx.test.filters.SmallTest
 import com.android.keyguard.BouncerPanelExpansionCalculator.aboutToShowBouncerProgress
@@ -21,6 +22,7 @@
 import junit.framework.Assert.assertEquals
 import junit.framework.Assert.assertFalse
 import junit.framework.Assert.assertTrue
+import org.junit.Assume
 import org.junit.Before
 import org.junit.Rule
 import org.junit.Test
@@ -66,6 +68,8 @@
 
     @Before
     fun setUp() {
+        Assume.assumeFalse(isTv())
+
         whenever(notificationShelf.viewState).thenReturn(ExpandableViewState())
         whenever(notificationRow.viewState).thenReturn(ExpandableViewState())
         ambientState.isSmallScreen = true
@@ -73,6 +77,10 @@
         hostView.addView(notificationRow)
     }
 
+    private fun isTv(): Boolean {
+        return context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
+    }
+
     @Test
     fun resetViewStates_defaultHun_yTranslationIsInset() {
         whenever(notificationRow.isPinned).thenReturn(true)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacksTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacksTest.java
index 8545b89..3ad3c15 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacksTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacksTest.java
@@ -18,6 +18,8 @@
 
 import static android.view.Display.DEFAULT_DISPLAY;
 
+import static com.android.systemui.flags.Flags.ONE_WAY_HAPTICS_API_MIGRATION;
+
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.reset;
@@ -29,8 +31,10 @@
 import android.app.StatusBarManager;
 import android.os.PowerManager;
 import android.os.UserHandle;
+import android.os.VibrationEffect;
 import android.os.Vibrator;
 import android.testing.AndroidTestingRunner;
+import android.view.HapticFeedbackConstants;
 import android.view.WindowInsets;
 
 import androidx.test.filters.SmallTest;
@@ -42,6 +46,7 @@
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.assist.AssistManager;
+import com.android.systemui.flags.FakeFeatureFlags;
 import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.qs.QSHost;
@@ -98,6 +103,7 @@
     @Mock private UserTracker mUserTracker;
     @Mock private QSHost mQSHost;
     @Mock private ActivityStarter mActivityStarter;
+    private final FakeFeatureFlags mFeatureFlags = new FakeFeatureFlags();
 
     CentralSurfacesCommandQueueCallbacks mSbcqCallbacks;
 
@@ -134,7 +140,8 @@
                 mCameraLauncherLazy,
                 mUserTracker,
                 mQSHost,
-                mActivityStarter);
+                mActivityStarter,
+                mFeatureFlags);
 
         when(mUserTracker.getUserHandle()).thenReturn(
                 UserHandle.of(ActivityManager.getCurrentUser()));
@@ -241,4 +248,24 @@
 
         verifyZeroInteractions(mSystemBarAttributesListener);
     }
+
+    @Test
+    public void vibrateOnNavigationKeyDown_oneWayHapticsDisabled_usesVibrate() {
+        mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, false);
+
+        mSbcqCallbacks.vibrateOnNavigationKeyDown();
+
+        verify(mVibratorHelper).vibrate(VibrationEffect.EFFECT_TICK);
+    }
+
+    @Test
+    public void vibrateOnNavigationKeyDown_oneWayHapticsEnabled_usesPerformHapticFeedback() {
+        mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, true);
+
+        mSbcqCallbacks.vibrateOnNavigationKeyDown();
+
+        verify(mShadeViewController).performHapticFeedback(
+                HapticFeedbackConstants.GESTURE_START
+        );
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java
index 61da901..39b2948 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesImplTest.java
@@ -115,6 +115,7 @@
 import com.android.systemui.keyguard.ScreenLifecycle;
 import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.keyguard.ui.viewmodel.LightRevealScrimViewModel;
+import com.android.systemui.log.LogBuffer;
 import com.android.systemui.navigationbar.NavigationBarController;
 import com.android.systemui.notetask.NoteTaskController;
 import com.android.systemui.plugins.ActivityStarter;
@@ -441,6 +442,7 @@
         mShadeController = spy(new ShadeControllerImpl(
                 mCommandQueue,
                 mMainExecutor,
+                mock(LogBuffer.class),
                 mKeyguardStateController,
                 mStatusBarStateController,
                 mStatusBarKeyguardViewManager,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ConfigurationControllerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ConfigurationControllerImplTest.kt
index 6155e3c..56d2397 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ConfigurationControllerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ConfigurationControllerImplTest.kt
@@ -212,13 +212,13 @@
     @Test
     fun localeListChanged_listenerNotified() {
         val config = mContext.resources.configuration
-        config.locales = LocaleList(Locale.CANADA, Locale.GERMANY)
+        config.setLocales(LocaleList(Locale.CANADA, Locale.GERMANY))
         mConfigurationController.onConfigurationChanged(config)
 
         val listener = createAndAddListener()
 
         // WHEN the locales are updated
-        config.locales = LocaleList(Locale.FRANCE, Locale.JAPAN, Locale.CHINESE)
+        config.setLocales(LocaleList(Locale.FRANCE, Locale.JAPAN, Locale.CHINESE))
         mConfigurationController.onConfigurationChanged(config)
 
         // THEN the listener is notified
@@ -274,6 +274,23 @@
     }
 
     @Test
+    fun orientationUpdated_listenerNotified() {
+        val config = mContext.resources.configuration
+        config.orientation = Configuration.ORIENTATION_LANDSCAPE
+        mConfigurationController.onConfigurationChanged(config)
+
+        val listener = createAndAddListener()
+
+        // WHEN the orientation is updated
+        config.orientation = Configuration.ORIENTATION_PORTRAIT
+        mConfigurationController.onConfigurationChanged(config)
+
+        // THEN the listener is notified
+        assertThat(listener.orientationChanged).isTrue()
+    }
+
+
+    @Test
     fun multipleUpdates_listenerNotifiedOfAll() {
         val config = mContext.resources.configuration
         config.densityDpi = 14
@@ -325,6 +342,7 @@
         var themeChanged = false
         var localeListChanged = false
         var layoutDirectionChanged = false
+        var orientationChanged = false
 
         override fun onConfigChanged(newConfig: Configuration?) {
             changedConfig = newConfig
@@ -350,6 +368,9 @@
         override fun onLayoutDirectionChanged(isLayoutRtl: Boolean) {
             layoutDirectionChanged = true
         }
+        override fun onOrientationChanged(orientation: Int) {
+            orientationChanged = true
+        }
 
         fun assertNoMethodsCalled() {
             assertThat(densityOrFontScaleChanged).isFalse()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
index 2f1e372..ec6286b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
@@ -75,6 +75,7 @@
     private HeadsUpManagerPhone mHeadsUpManager;
     private View mOperatorNameView;
     private StatusBarStateController mStatusbarStateController;
+    private PhoneStatusBarTransitions mPhoneStatusBarTransitions;
     private KeyguardBypassController mBypassController;
     private NotificationWakeUpCoordinator mWakeUpCoordinator;
     private KeyguardStateController mKeyguardStateController;
@@ -95,6 +96,7 @@
         mHeadsUpManager = mock(HeadsUpManagerPhone.class);
         mOperatorNameView = new View(mContext);
         mStatusbarStateController = mock(StatusBarStateController.class);
+        mPhoneStatusBarTransitions = mock(PhoneStatusBarTransitions.class);
         mBypassController = mock(KeyguardBypassController.class);
         mWakeUpCoordinator = mock(NotificationWakeUpCoordinator.class);
         mKeyguardStateController = mock(KeyguardStateController.class);
@@ -105,6 +107,7 @@
                 mock(NotificationIconAreaController.class),
                 mHeadsUpManager,
                 mStatusbarStateController,
+                mPhoneStatusBarTransitions,
                 mBypassController,
                 mWakeUpCoordinator,
                 mDarkIconDispatcher,
@@ -188,6 +191,7 @@
                 mock(NotificationIconAreaController.class),
                 mHeadsUpManager,
                 mStatusbarStateController,
+                mPhoneStatusBarTransitions,
                 mBypassController,
                 mWakeUpCoordinator,
                 mDarkIconDispatcher,
@@ -283,4 +287,18 @@
                 /* delta = */ 0.001
         );
     }
+
+    @Test
+    public void onHeadsUpStateChanged_true_transitionsNotified() {
+        mHeadsUpAppearanceController.onHeadsUpStateChanged(mEntry, true);
+
+        verify(mPhoneStatusBarTransitions).onHeadsUpStateChanged(true);
+    }
+
+    @Test
+    public void onHeadsUpStateChanged_false_transitionsNotified() {
+        mHeadsUpAppearanceController.onHeadsUpStateChanged(mEntry, false);
+
+        verify(mPhoneStatusBarTransitions).onHeadsUpStateChanged(false);
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
index 72522ca..bb20d18 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
@@ -39,7 +39,6 @@
 import com.android.systemui.statusbar.AlertingNotificationManagerTest;
 import com.android.systemui.statusbar.NotificationShadeWindowController;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
 import com.android.systemui.statusbar.notification.collection.provider.VisualStabilityProvider;
 import com.android.systemui.statusbar.notification.collection.render.GroupMembershipManager;
 import com.android.systemui.statusbar.policy.AccessibilityManagerWrapper;
@@ -62,8 +61,6 @@
 public class HeadsUpManagerPhoneTest extends AlertingNotificationManagerTest {
     @Rule public MockitoRule rule = MockitoJUnit.rule();
 
-    private HeadsUpManagerPhone mHeadsUpManager;
-
     private final HeadsUpManagerLogger mHeadsUpManagerLogger = new HeadsUpManagerLogger(
             logcatLogBuffer());
     @Mock private GroupMembershipManager mGroupManager;
@@ -108,25 +105,8 @@
         }
     }
 
-    @Override
-    protected AlertingNotificationManager createAlertingNotificationManager() {
-        return mHeadsUpManager;
-    }
-
-    @Before
-    @Override
-    public void setUp() {
-        AccessibilityManagerWrapper accessibilityMgr =
-                mDependency.injectMockDependency(AccessibilityManagerWrapper.class);
-        when(accessibilityMgr.getRecommendedTimeoutMillis(anyInt(), anyInt()))
-                .thenReturn(TEST_AUTO_DISMISS_TIME);
-        when(mVSProvider.isReorderingAllowed()).thenReturn(true);
-        mDependency.injectMockDependency(NotificationShadeWindowController.class);
-        mContext.getOrCreateTestableResources().addOverride(
-                R.integer.ambient_notification_extension_time, 500);
-
-        super.setUp();
-        mHeadsUpManager = new TestableHeadsUpManagerPhone(
+    private HeadsUpManagerPhone createHeadsUpManagerPhone() {
+        return new TestableHeadsUpManagerPhone(
                 mContext,
                 mHeadsUpManagerLogger,
                 mGroupManager,
@@ -141,6 +121,26 @@
         );
     }
 
+    @Override
+    protected AlertingNotificationManager createAlertingNotificationManager() {
+        return createHeadsUpManagerPhone();
+    }
+
+    @Before
+    @Override
+    public void setUp() {
+        final AccessibilityManagerWrapper accessibilityMgr =
+                mDependency.injectMockDependency(AccessibilityManagerWrapper.class);
+        when(accessibilityMgr.getRecommendedTimeoutMillis(anyInt(), anyInt()))
+                .thenReturn(TEST_AUTO_DISMISS_TIME);
+        when(mVSProvider.isReorderingAllowed()).thenReturn(true);
+        mDependency.injectMockDependency(NotificationShadeWindowController.class);
+        mContext.getOrCreateTestableResources().addOverride(
+                R.integer.ambient_notification_extension_time, 500);
+
+        super.setUp();
+    }
+
     @After
     @Override
     public void tearDown() {
@@ -149,63 +149,67 @@
 
     @Test
     public void testSnooze() {
-        mHeadsUpManager.showNotification(mEntry);
+        final HeadsUpManagerPhone hmp = createHeadsUpManagerPhone();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
 
-        mHeadsUpManager.snooze();
+        hmp.showNotification(entry);
+        hmp.snooze();
 
-        assertTrue(mHeadsUpManager.isSnoozed(mEntry.getSbn().getPackageName()));
+        assertTrue(hmp.isSnoozed(entry.getSbn().getPackageName()));
     }
 
     @Test
     public void testSwipedOutNotification() {
-        mHeadsUpManager.showNotification(mEntry);
-        mHeadsUpManager.addSwipedOutNotification(mEntry.getKey());
+        final HeadsUpManagerPhone hmp = createHeadsUpManagerPhone();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
+
+        hmp.showNotification(entry);
+        hmp.addSwipedOutNotification(entry.getKey());
 
         // Remove should succeed because the notification is swiped out
-        mHeadsUpManager.removeNotification(mEntry.getKey(), false /* releaseImmediately */);
+        final boolean removedImmediately = hmp.removeNotification(entry.getKey(),
+                /* releaseImmediately = */ false);
 
-        assertFalse(mHeadsUpManager.isAlerting(mEntry.getKey()));
+        assertTrue(removedImmediately);
+        assertFalse(hmp.isAlerting(entry.getKey()));
     }
 
     @Test
     public void testCanRemoveImmediately_swipedOut() {
-        mHeadsUpManager.showNotification(mEntry);
-        mHeadsUpManager.addSwipedOutNotification(mEntry.getKey());
+        final HeadsUpManagerPhone hmp = createHeadsUpManagerPhone();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
+
+        hmp.showNotification(entry);
+        hmp.addSwipedOutNotification(entry.getKey());
 
         // Notification is swiped so it can be immediately removed.
-        assertTrue(mHeadsUpManager.canRemoveImmediately(mEntry.getKey()));
+        assertTrue(hmp.canRemoveImmediately(entry.getKey()));
     }
 
     @Ignore("b/141538055")
     @Test
     public void testCanRemoveImmediately_notTopEntry() {
-        NotificationEntry laterEntry = new NotificationEntryBuilder()
-                .setSbn(createNewNotification(1))
-                .build();
+        final HeadsUpManagerPhone hmp = createHeadsUpManagerPhone();
+        final NotificationEntry earlierEntry = createEntry(/* id = */ 0);
+        final NotificationEntry laterEntry = createEntry(/* id = */ 1);
         laterEntry.setRow(mRow);
-        mHeadsUpManager.showNotification(mEntry);
-        mHeadsUpManager.showNotification(laterEntry);
+
+        hmp.showNotification(earlierEntry);
+        hmp.showNotification(laterEntry);
 
         // Notification is "behind" a higher priority notification so we can remove it immediately.
-        assertTrue(mHeadsUpManager.canRemoveImmediately(mEntry.getKey()));
+        assertTrue(hmp.canRemoveImmediately(earlierEntry.getKey()));
     }
 
     @Test
     public void testExtendHeadsUp() {
-        mHeadsUpManager.showNotification(mEntry);
-        Runnable pastNormalTimeRunnable =
-                () -> mLivesPastNormalTime = mHeadsUpManager.isAlerting(mEntry.getKey());
-        mTestHandler.postDelayed(pastNormalTimeRunnable,
-                TEST_AUTO_DISMISS_TIME + mHeadsUpManager.mExtensionTime / 2);
-        mTestHandler.postDelayed(mTestTimeoutRunnable, TEST_TIMEOUT_TIME);
+        final HeadsUpManagerPhone hmp = createHeadsUpManagerPhone();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
 
-        mHeadsUpManager.extendHeadsUp();
+        hmp.showNotification(entry);
+        hmp.extendHeadsUp();
 
-        // Wait for normal time runnable and extended remove runnable and process them on arrival.
-        TestableLooper.get(this).processMessages(2);
-
-        assertFalse("Test timed out", mTimedOut);
-        assertTrue("Pulse was not extended", mLivesPastNormalTime);
-        assertFalse(mHeadsUpManager.isAlerting(mEntry.getKey()));
+        final int pastNormalTimeMillis = TEST_AUTO_DISMISS_TIME + hmp.mExtensionTime / 2;
+        verifyAlertingAtTime(hmp, entry, true, pastNormalTimeMillis, "normal time");
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImplTest.java
similarity index 94%
rename from packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerTest.java
rename to packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImplTest.java
index 8e1dcf0..1b8cfd4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImplTest.java
@@ -48,7 +48,7 @@
 @SmallTest
 @RunWith(AndroidTestingRunner.class)
 @TestableLooper.RunWithLooper
-public class NotificationIconAreaControllerTest extends SysuiTestCase {
+public class LegacyNotificationIconAreaControllerImplTest extends SysuiTestCase {
 
     @Mock
     private NotificationListener mListener;
@@ -70,7 +70,7 @@
     StatusBarWindowController mStatusBarWindowController;
     @Mock
     ScreenOffAnimationController mScreenOffAnimationController;
-    private NotificationIconAreaController mController;
+    private LegacyNotificationIconAreaControllerImpl mController;
     @Mock
     private Bubbles mBubbles;
     @Mock private DemoModeController mDemoModeController;
@@ -82,7 +82,7 @@
     @Before
     public void setup() {
         MockitoAnnotations.initMocks(this);
-        mController = new NotificationIconAreaController(
+        mController = new LegacyNotificationIconAreaControllerImpl(
                 mContext,
                 mStatusBarStateController,
                 mWakeUpCoordinator,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarTransitionsTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarTransitionsTest.kt
new file mode 100644
index 0000000..4af1b24
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarTransitionsTest.kt
@@ -0,0 +1,237 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.testing.TestableLooper
+import android.view.View
+import androidx.test.filters.SmallTest
+import com.android.systemui.R
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.statusbar.phone.BarTransitions.MODE_LIGHTS_OUT
+import com.android.systemui.statusbar.phone.BarTransitions.MODE_LIGHTS_OUT_TRANSPARENT
+import com.android.systemui.statusbar.phone.BarTransitions.MODE_OPAQUE
+import com.android.systemui.statusbar.phone.BarTransitions.MODE_SEMI_TRANSPARENT
+import com.android.systemui.statusbar.phone.BarTransitions.MODE_TRANSLUCENT
+import com.android.systemui.statusbar.phone.BarTransitions.MODE_TRANSPARENT
+import com.android.systemui.util.mockito.argumentCaptor
+import com.android.systemui.util.mockito.mock
+import com.android.systemui.util.mockito.whenever
+import com.google.common.truth.Truth.assertThat
+import org.junit.Before
+import org.junit.Test
+import org.mockito.Mockito.reset
+import org.mockito.Mockito.verify
+
+@SmallTest
+@TestableLooper.RunWithLooper(setAsMainLooper = true)
+class PhoneStatusBarTransitionsTest : SysuiTestCase() {
+
+    // PhoneStatusBarView does a lot of non-standard things when inflating, so just use mocks.
+    private val batteryView = mock<View>()
+    private val statusIcons = mock<View>()
+    private val startIcons = mock<View>()
+    private val statusBarView =
+        mock<PhoneStatusBarView>().apply {
+            whenever(this.context).thenReturn(mContext)
+            whenever(this.findViewById<View>(R.id.battery)).thenReturn(batteryView)
+            whenever(this.findViewById<View>(R.id.statusIcons)).thenReturn(statusIcons)
+            whenever(this.findViewById<View>(R.id.status_bar_start_side_except_heads_up))
+                .thenReturn(startIcons)
+        }
+    private val backgroundView = mock<View>().apply { whenever(this.context).thenReturn(mContext) }
+
+    private val underTest: PhoneStatusBarTransitions by lazy {
+        PhoneStatusBarTransitions(statusBarView, backgroundView).also {
+            // The views' alphas will be set when PhoneStatusBarTransitions is created and we want
+            // to ignore those in the tests, so clear those verifications here.
+            reset(batteryView)
+            reset(statusIcons)
+            reset(startIcons)
+        }
+    }
+
+    @Before
+    fun setUp() {
+        context.orCreateTestableResources.addOverride(
+            R.dimen.status_bar_icon_drawing_alpha,
+            RESOURCE_ALPHA,
+        )
+    }
+
+    @Test
+    fun transitionTo_lightsOutMode_batteryTranslucent() {
+        underTest.transitionTo(/* mode= */ MODE_LIGHTS_OUT, /* animate= */ false)
+
+        val alpha = batteryView.capturedAlpha()
+        assertThat(alpha).isGreaterThan(0)
+        assertThat(alpha).isLessThan(1)
+    }
+
+    @Test
+    fun transitionTo_lightsOutMode_statusIconsHidden() {
+        underTest.transitionTo(/* mode= */ MODE_LIGHTS_OUT, /* animate= */ false)
+
+        assertThat(statusIcons.capturedAlpha()).isEqualTo(0)
+    }
+
+    @Test
+    fun transitionTo_lightsOutMode_startIconsHidden() {
+        underTest.transitionTo(/* mode= */ MODE_LIGHTS_OUT, /* animate= */ false)
+
+        assertThat(startIcons.capturedAlpha()).isEqualTo(0)
+    }
+
+    @Test
+    fun transitionTo_lightsOutTransparentMode_batteryTranslucent() {
+        underTest.transitionTo(/* mode= */ MODE_LIGHTS_OUT_TRANSPARENT, /* animate= */ false)
+
+        val alpha = batteryView.capturedAlpha()
+        assertThat(alpha).isGreaterThan(0)
+        assertThat(alpha).isLessThan(1)
+    }
+
+    @Test
+    fun transitionTo_lightsOutTransparentMode_statusIconsHidden() {
+        underTest.transitionTo(/* mode= */ MODE_LIGHTS_OUT_TRANSPARENT, /* animate= */ false)
+
+        assertThat(statusIcons.capturedAlpha()).isEqualTo(0)
+    }
+
+    @Test
+    fun transitionTo_lightsOutTransparentMode_startIconsHidden() {
+        underTest.transitionTo(/* mode= */ MODE_LIGHTS_OUT_TRANSPARENT, /* animate= */ false)
+
+        assertThat(startIcons.capturedAlpha()).isEqualTo(0)
+    }
+
+    @Test
+    fun transitionTo_translucentMode_batteryIconShown() {
+        underTest.transitionTo(/* mode= */ MODE_TRANSLUCENT, /* animate= */ false)
+
+        assertThat(batteryView.capturedAlpha()).isEqualTo(1)
+    }
+
+    @Test
+    fun transitionTo_semiTransparentMode_statusIconsShown() {
+        underTest.transitionTo(/* mode= */ MODE_SEMI_TRANSPARENT, /* animate= */ false)
+
+        assertThat(statusIcons.capturedAlpha()).isEqualTo(1)
+    }
+
+    @Test
+    fun transitionTo_transparentMode_startIconsShown() {
+        // Transparent is the default, so we need to switch to a different mode first
+        underTest.transitionTo(/* mode= */ MODE_OPAQUE, /* animate= */ false)
+        reset(startIcons)
+
+        underTest.transitionTo(/* mode= */ MODE_TRANSPARENT, /* animate= */ false)
+
+        assertThat(startIcons.capturedAlpha()).isEqualTo(1)
+    }
+
+    @Test
+    fun transitionTo_opaqueMode_batteryIconUsesResourceAlpha() {
+        underTest.transitionTo(/* mode= */ MODE_OPAQUE, /* animate= */ false)
+
+        assertThat(batteryView.capturedAlpha()).isEqualTo(RESOURCE_ALPHA)
+    }
+
+    @Test
+    fun transitionTo_opaqueMode_statusIconsUseResourceAlpha() {
+        underTest.transitionTo(/* mode= */ MODE_OPAQUE, /* animate= */ false)
+
+        assertThat(statusIcons.capturedAlpha()).isEqualTo(RESOURCE_ALPHA)
+    }
+
+    @Test
+    fun transitionTo_opaqueMode_startIconsUseResourceAlpha() {
+        underTest.transitionTo(/* mode= */ MODE_OPAQUE, /* animate= */ false)
+
+        assertThat(startIcons.capturedAlpha()).isEqualTo(RESOURCE_ALPHA)
+    }
+
+    @Test
+    fun onHeadsUpStateChanged_true_semiTransparentMode_startIconsShown() {
+        underTest.transitionTo(/* mode= */ MODE_SEMI_TRANSPARENT, /* animate= */ false)
+        reset(startIcons)
+
+        underTest.onHeadsUpStateChanged(true)
+
+        assertThat(startIcons.capturedAlpha()).isEqualTo(1)
+    }
+
+    @Test
+    fun onHeadsUpStateChanged_true_opaqueMode_startIconsUseResourceAlpha() {
+        underTest.transitionTo(/* mode= */ MODE_OPAQUE, /* animate= */ false)
+        reset(startIcons)
+
+        underTest.onHeadsUpStateChanged(true)
+
+        assertThat(startIcons.capturedAlpha()).isEqualTo(RESOURCE_ALPHA)
+    }
+
+    /** Regression test for b/291173113. */
+    @Test
+    fun onHeadsUpStateChanged_true_lightsOutMode_startIconsUseResourceAlpha() {
+        underTest.transitionTo(/* mode= */ MODE_LIGHTS_OUT, /* animate= */ false)
+        reset(startIcons)
+
+        underTest.onHeadsUpStateChanged(true)
+
+        assertThat(startIcons.capturedAlpha()).isEqualTo(RESOURCE_ALPHA)
+    }
+
+    @Test
+    fun onHeadsUpStateChanged_false_semiTransparentMode_startIconsShown() {
+        underTest.transitionTo(/* mode= */ MODE_SEMI_TRANSPARENT, /* animate= */ false)
+        reset(startIcons)
+
+        underTest.onHeadsUpStateChanged(false)
+
+        assertThat(startIcons.capturedAlpha()).isEqualTo(1)
+    }
+
+    @Test
+    fun onHeadsUpStateChanged_false_opaqueMode_startIconsUseResourceAlpha() {
+        underTest.transitionTo(/* mode= */ MODE_OPAQUE, /* animate= */ false)
+        reset(startIcons)
+
+        underTest.onHeadsUpStateChanged(false)
+
+        assertThat(startIcons.capturedAlpha()).isEqualTo(RESOURCE_ALPHA)
+    }
+
+    @Test
+    fun onHeadsUpStateChanged_false_lightsOutMode_startIconsHidden() {
+        underTest.transitionTo(/* mode= */ MODE_LIGHTS_OUT, /* animate= */ false)
+        reset(startIcons)
+
+        underTest.onHeadsUpStateChanged(false)
+
+        assertThat(startIcons.capturedAlpha()).isEqualTo(0)
+    }
+
+    private fun View.capturedAlpha(): Float {
+        val captor = argumentCaptor<Float>()
+        verify(this).alpha = captor.capture()
+        return captor.value
+    }
+
+    private companion object {
+        const val RESOURCE_ALPHA = 0.34f
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt
index 2e92bb9..0b31523 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt
@@ -27,7 +27,7 @@
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.flags.FeatureFlags
 import com.android.systemui.flags.Flags
-import com.android.systemui.scene.domain.interactor.SceneInteractor
+import com.android.systemui.scene.ui.view.WindowRootView
 import com.android.systemui.shade.ShadeControllerImpl
 import com.android.systemui.shade.ShadeLogger
 import com.android.systemui.shade.ShadeViewController
@@ -77,7 +77,7 @@
     @Mock
     private lateinit var shadeControllerImpl: ShadeControllerImpl
     @Mock
-    private lateinit var sceneInteractor: Provider<SceneInteractor>
+    private lateinit var windowRootView: Provider<WindowRootView>
     @Mock
     private lateinit var shadeLogger: ShadeLogger
     @Mock
@@ -203,7 +203,7 @@
             centralSurfacesImpl,
             shadeControllerImpl,
             shadeViewController,
-            sceneInteractor,
+            windowRootView,
             shadeLogger,
             viewUtil,
             configurationController,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarContentInsetsProviderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarContentInsetsProviderTest.kt
index 1759fb7..210c5ab 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarContentInsetsProviderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarContentInsetsProviderTest.kt
@@ -463,10 +463,10 @@
         val provider = StatusBarContentInsetsProvider(contextMock, configurationController,
             mock(DumpManager::class.java))
 
-        configuration.windowConfiguration.maxBounds = Rect(0, 0, 1080, 2160)
+        configuration.windowConfiguration.setMaxBounds(Rect(0, 0, 1080, 2160))
         val firstDisplayInsets = provider.getStatusBarContentAreaForRotation(ROTATION_NONE)
 
-        configuration.windowConfiguration.maxBounds = Rect(0, 0, 800, 600)
+        configuration.windowConfiguration.setMaxBounds(Rect(0, 0, 800, 600))
 
         // WHEN: get insets on the second display
         val secondDisplayInsets = provider.getStatusBarContentAreaForRotation(ROTATION_NONE)
@@ -482,14 +482,14 @@
         val provider = StatusBarContentInsetsProvider(contextMock, configurationController,
             mock(DumpManager::class.java))
 
-        configuration.windowConfiguration.maxBounds = Rect(0, 0, 1080, 2160)
+        configuration.windowConfiguration.setMaxBounds(Rect(0, 0, 1080, 2160))
         val firstDisplayInsetsFirstCall = provider
             .getStatusBarContentAreaForRotation(ROTATION_NONE)
 
-        configuration.windowConfiguration.maxBounds = Rect(0, 0, 800, 600)
+        configuration.windowConfiguration.setMaxBounds(Rect(0, 0, 800, 600))
         provider.getStatusBarContentAreaForRotation(ROTATION_NONE)
 
-        configuration.windowConfiguration.maxBounds = Rect(0, 0, 1080, 2160)
+        configuration.windowConfiguration.setMaxBounds(Rect(0, 0, 1080, 2160))
 
         // WHEN: get insets on the first display again
         val firstDisplayInsetsSecondCall = provider
@@ -577,4 +577,4 @@
                 " expected=$expected actual=$actual",
                 expected.equals(actual))
     }
-}
\ No newline at end of file
+}
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 ed9cf3f..0da7360 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
@@ -35,6 +35,8 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import static kotlinx.coroutines.test.TestCoroutineDispatchersKt.StandardTestDispatcher;
+
 import android.service.trust.TrustAgentService;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
@@ -73,6 +75,8 @@
 import com.android.systemui.dreams.DreamOverlayStateController;
 import com.android.systemui.flags.FeatureFlags;
 import com.android.systemui.flags.Flags;
+import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor;
+import com.android.systemui.keyguard.domain.interactor.WindowManagerLockscreenVisibilityInteractor;
 import com.android.systemui.navigationbar.NavigationModeController;
 import com.android.systemui.navigationbar.TaskbarDelegate;
 import com.android.systemui.plugins.ActivityStarter;
@@ -201,7 +205,10 @@
                         mBouncerView,
                         mAlternateBouncerInteractor,
                         mUdfpsOverlayInteractor,
-                        mActivityStarter) {
+                        mActivityStarter,
+                        mock(KeyguardTransitionInteractor.class),
+                        StandardTestDispatcher(null, null),
+                        () -> mock(WindowManagerLockscreenVisibilityInteractor.class)) {
                     @Override
                     public ViewRootImpl getViewRootImpl() {
                         return mViewRootImpl;
@@ -701,7 +708,10 @@
                         mBouncerView,
                         mAlternateBouncerInteractor,
                         mUdfpsOverlayInteractor,
-                        mActivityStarter) {
+                        mActivityStarter,
+                        mock(KeyguardTransitionInteractor.class),
+                        StandardTestDispatcher(null, null),
+                        () -> mock(WindowManagerLockscreenVisibilityInteractor.class)) {
                     @Override
                     public ViewRootImpl getViewRootImpl() {
                         return mViewRootImpl;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
index 9c52788..34c4ac1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
@@ -32,7 +32,6 @@
 import androidx.test.filters.SmallTest;
 
 import com.android.internal.logging.testing.FakeMetricsLogger;
-import com.android.systemui.ForegroundServiceNotificationListener;
 import com.android.systemui.InitController;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.ActivityStarter;
@@ -94,7 +93,6 @@
         mDependency.injectTestDependency(ShadeController.class, mShadeController);
         mDependency.injectMockDependency(NotificationRemoteInputManager.Callback.class);
         mDependency.injectMockDependency(NotificationShadeWindowController.class);
-        mDependency.injectMockDependency(ForegroundServiceNotificationListener.class);
 
         NotificationShadeWindowView notificationShadeWindowView =
                 mock(NotificationShadeWindowView.class);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
index 823155b..b8f2cab 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
@@ -81,7 +81,7 @@
 import com.android.systemui.util.time.FakeSystemClock;
 
 import org.junit.Before;
-import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
@@ -136,8 +136,8 @@
     private StatusBarWindowStateController mStatusBarWindowStateController;
     @Mock
     private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
-    @ClassRule
-    public static AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
+    @Rule
+    public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
 
     private List<StatusBarWindowStateListener> mStatusBarWindowStateListeners = new ArrayList<>();
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt
index 6306a36..50ee6a3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt
@@ -55,6 +55,8 @@
     override val networkName =
         MutableStateFlow<NetworkNameModel>(NetworkNameModel.Default("default"))
 
+    override val isAllowedDuringAirplaneMode = MutableStateFlow(false)
+
     fun setDataEnabled(enabled: Boolean) {
         _dataEnabled.value = enabled
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepositoryTest.kt
index 441186a..a251c28 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepositoryTest.kt
@@ -20,6 +20,7 @@
 import android.testing.AndroidTestingRunner
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.log.table.TableLogBuffer
 import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState
 import com.android.systemui.statusbar.pipeline.mobile.data.model.NetworkNameModel
@@ -319,6 +320,14 @@
             job.cancel()
         }
 
+    @Test
+    fun isAllowedDuringAirplaneMode_alwaysTrue() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.isAllowedDuringAirplaneMode)
+
+            assertThat(latest).isTrue()
+        }
+
     private companion object {
         const val SUB_ID = 123
         const val NET_ID = 456
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepositoryTest.kt
index b701fbd..3dd2eaf 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepositoryTest.kt
@@ -22,6 +22,7 @@
 import android.telephony.TelephonyManager
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.log.table.TableLogBuffer
 import com.android.systemui.log.table.TableLogBufferFactory
 import com.android.systemui.statusbar.pipeline.mobile.data.model.NetworkNameModel
@@ -84,7 +85,11 @@
     @Before
     fun setUp() {
         mobileRepo = FakeMobileConnectionRepository(SUB_ID, tableLogBuffer)
-        carrierMergedRepo = FakeMobileConnectionRepository(SUB_ID, tableLogBuffer)
+        carrierMergedRepo =
+            FakeMobileConnectionRepository(SUB_ID, tableLogBuffer).apply {
+                // Mimicks the real carrier merged repository
+                this.isAllowedDuringAirplaneMode.value = true
+            }
 
         whenever(
                 mobileFactory.build(
@@ -300,6 +305,24 @@
         }
 
     @Test
+    fun isAllowedDuringAirplaneMode_updatesWhenCarrierMergedUpdates() =
+        testScope.runTest {
+            initializeRepo(startingIsCarrierMerged = false)
+
+            val latest by collectLastValue(underTest.isAllowedDuringAirplaneMode)
+
+            assertThat(latest).isFalse()
+
+            underTest.setIsCarrierMerged(true)
+
+            assertThat(latest).isTrue()
+
+            underTest.setIsCarrierMerged(false)
+
+            assertThat(latest).isFalse()
+        }
+
+    @Test
     fun factory_reusesLogBuffersForSameConnection() =
         testScope.runTest {
             val realLoggerFactory =
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt
index cf832b4..1ff737b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt
@@ -53,6 +53,7 @@
 import androidx.test.filters.SmallTest
 import com.android.settingslib.mobile.MobileMappings
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.log.table.TableLogBuffer
 import com.android.systemui.statusbar.pipeline.mobile.data.MobileInputLogger
 import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState
@@ -812,6 +813,14 @@
             job.cancel()
         }
 
+    @Test
+    fun isAllowedDuringAirplaneMode_alwaysFalse() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.isAllowedDuringAirplaneMode)
+
+            assertThat(latest).isFalse()
+        }
+
     private inline fun <reified T> getTelephonyCallbackForType(): T {
         return MobileTelephonyHelpers.getTelephonyCallbackForType(telephonyManager)
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconInteractor.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconInteractor.kt
index c4e4193..8d1da69 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconInteractor.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconInteractor.kt
@@ -77,6 +77,8 @@
 
     override val isForceHidden = MutableStateFlow(false)
 
+    override val isAllowedDuringAirplaneMode = MutableStateFlow(false)
+
     fun setIsEmergencyOnly(emergency: Boolean) {
         _isEmergencyOnly.value = emergency
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt
index c276865..58d3804 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt
@@ -23,6 +23,7 @@
 import com.android.settingslib.mobile.MobileIconCarrierIdOverridesImpl
 import com.android.settingslib.mobile.TelephonyIcons
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
 import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState
 import com.android.systemui.statusbar.pipeline.mobile.data.model.NetworkNameModel
 import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.CarrierMergedNetworkType
@@ -473,6 +474,18 @@
             job.cancel()
         }
 
+    @Test
+    fun isAllowedDuringAirplaneMode_matchesRepo() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.isAllowedDuringAirplaneMode)
+
+            connectionRepository.isAllowedDuringAirplaneMode.value = true
+            assertThat(latest).isTrue()
+
+            connectionRepository.isAllowedDuringAirplaneMode.value = false
+            assertThat(latest).isFalse()
+        }
+
     private fun createInteractor(
         overrides: MobileIconCarrierIdOverrides = MobileIconCarrierIdOverridesImpl()
     ) =
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModelTest.kt
index b5ab29d..72feec7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModelTest.kt
@@ -116,12 +116,13 @@
         }
 
     @Test
-    fun isVisible_airplane_false() =
+    fun isVisible_airplaneAndNotAllowed_false() =
         testScope.runTest {
             var latest: Boolean? = null
             val job = underTest.isVisible.onEach { latest = it }.launchIn(this)
 
             airplaneModeRepository.setIsAirplaneMode(true)
+            interactor.isAllowedDuringAirplaneMode.value = false
             interactor.isForceHidden.value = false
 
             assertThat(latest).isFalse()
@@ -129,6 +130,22 @@
             job.cancel()
         }
 
+    /** Regression test for b/291993542. */
+    @Test
+    fun isVisible_airplaneButAllowed_true() =
+        testScope.runTest {
+            var latest: Boolean? = null
+            val job = underTest.isVisible.onEach { latest = it }.launchIn(this)
+
+            airplaneModeRepository.setIsAirplaneMode(true)
+            interactor.isAllowedDuringAirplaneMode.value = true
+            interactor.isForceHidden.value = false
+
+            assertThat(latest).isTrue()
+
+            job.cancel()
+        }
+
     @Test
     fun isVisible_forceHidden_false() =
         testScope.runTest {
@@ -157,7 +174,7 @@
             airplaneModeRepository.setIsAirplaneMode(true)
             assertThat(latest).isFalse()
 
-            airplaneModeRepository.setIsAirplaneMode(false)
+            interactor.isAllowedDuringAirplaneMode.value = true
             assertThat(latest).isTrue()
 
             interactor.isForceHidden.value = true
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/FakeWifiRepository.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/FakeWifiRepository.kt
index 1bf431b..4f7bb72 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/FakeWifiRepository.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/FakeWifiRepository.kt
@@ -17,7 +17,7 @@
 package com.android.systemui.statusbar.pipeline.wifi.data.repository
 
 import com.android.systemui.statusbar.pipeline.shared.data.model.DataActivityModel
-import com.android.systemui.statusbar.pipeline.wifi.data.repository.prod.WifiRepositoryImpl.Companion.ACTIVITY_DEFAULT
+import com.android.systemui.statusbar.pipeline.wifi.data.repository.prod.WifiRepositoryHelper.ACTIVITY_DEFAULT
 import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiNetworkModel
 import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.StateFlow
@@ -34,6 +34,8 @@
         MutableStateFlow(WifiNetworkModel.Inactive)
     override val wifiNetwork: StateFlow<WifiNetworkModel> = _wifiNetwork
 
+    override val secondaryNetworks = MutableStateFlow<List<WifiNetworkModel>>(emptyList())
+
     private val _wifiActivity = MutableStateFlow(ACTIVITY_DEFAULT)
     override val wifiActivity: StateFlow<DataActivityModel> = _wifiActivity
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt
index fef042b..bea1154 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt
@@ -489,6 +489,26 @@
         }
 
     @Test
+    fun wifiNetwork_neverHasHotspot() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiInfo =
+                mock<WifiInfo>().apply {
+                    whenever(this.ssid).thenReturn(SSID)
+                    whenever(this.isPrimary).thenReturn(true)
+                }
+            val network = mock<Network>().apply { whenever(this.getNetId()).thenReturn(NETWORK_ID) }
+
+            getNetworkCallback()
+                .onCapabilitiesChanged(network, createWifiNetworkCapabilities(wifiInfo))
+
+            assertThat(latest is WifiNetworkModel.Active).isTrue()
+            assertThat((latest as WifiNetworkModel.Active).hotspotDeviceType)
+                .isEqualTo(WifiNetworkModel.HotspotDeviceType.NONE)
+        }
+
+    @Test
     fun wifiNetwork_isCarrierMerged_flowHasCarrierMerged() =
         testScope.runTest {
             val latest by collectLastValue(underTest.wifiNetwork)
@@ -984,6 +1004,27 @@
         }
 
     @Test
+    fun secondaryNetworks_alwaysEmpty() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.secondaryNetworks)
+            collectLastValue(underTest.wifiNetwork)
+
+            // Even WHEN we do have non-primary wifi info
+            val wifiInfo =
+                mock<WifiInfo>().apply {
+                    whenever(this.ssid).thenReturn(SSID)
+                    whenever(this.isPrimary).thenReturn(false)
+                }
+            val network = mock<Network>().apply { whenever(this.getNetId()).thenReturn(NETWORK_ID) }
+
+            getNetworkCallback()
+                .onCapabilitiesChanged(network, createWifiNetworkCapabilities(wifiInfo))
+
+            // THEN the secondary networks list is empty because this repo doesn't support it
+            assertThat(latest).isEmpty()
+        }
+
+    @Test
     fun isWifiConnectedWithValidSsid_inactiveNetwork_false() =
         testScope.runTest {
             collectLastValue(underTest.wifiNetwork)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryViaTrackerLibTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryViaTrackerLibTest.kt
index 7002cbb..662e36a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryViaTrackerLibTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryViaTrackerLibTest.kt
@@ -18,13 +18,18 @@
 
 import android.net.wifi.WifiManager
 import android.net.wifi.WifiManager.UNKNOWN_SSID
+import android.net.wifi.sharedconnectivity.app.NetworkProviderInfo
+import android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID
 import android.testing.TestableLooper
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.flags.FakeFeatureFlags
+import com.android.systemui.flags.Flags
 import com.android.systemui.log.LogBuffer
 import com.android.systemui.log.table.TableLogBuffer
 import com.android.systemui.statusbar.connectivity.WifiPickerTrackerFactory
+import com.android.systemui.statusbar.pipeline.shared.data.model.DataActivityModel
 import com.android.systemui.statusbar.pipeline.wifi.data.repository.prod.WifiRepositoryImpl.Companion.WIFI_NETWORK_DEFAULT
 import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiNetworkModel
 import com.android.systemui.util.concurrency.FakeExecutor
@@ -34,8 +39,13 @@
 import com.android.systemui.util.mockito.mock
 import com.android.systemui.util.mockito.whenever
 import com.android.systemui.util.time.FakeSystemClock
+import com.android.wifitrackerlib.HotspotNetworkEntry
+import com.android.wifitrackerlib.HotspotNetworkEntry.DeviceType
 import com.android.wifitrackerlib.MergedCarrierEntry
 import com.android.wifitrackerlib.WifiEntry
+import com.android.wifitrackerlib.WifiEntry.WIFI_LEVEL_MAX
+import com.android.wifitrackerlib.WifiEntry.WIFI_LEVEL_MIN
+import com.android.wifitrackerlib.WifiEntry.WIFI_LEVEL_UNREACHABLE
 import com.android.wifitrackerlib.WifiPickerTracker
 import com.google.common.truth.Truth.assertThat
 import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -45,6 +55,7 @@
 import kotlinx.coroutines.test.runTest
 import org.junit.Before
 import org.junit.Test
+import org.mockito.Mockito.verify
 
 /**
  * Note: Most of these tests are duplicates of [WifiRepositoryImplTest] tests.
@@ -57,10 +68,25 @@
 @TestableLooper.RunWithLooper(setAsMainLooper = true)
 class WifiRepositoryViaTrackerLibTest : SysuiTestCase() {
 
-    private lateinit var underTest: WifiRepositoryViaTrackerLib
+    // Using lazy means that the class will only be constructed once it's fetched. Because the
+    // repository internally sets some values on construction, we need to set up some test
+    // parameters (like feature flags) *before* construction. Using lazy allows us to do that setup
+    // inside each test case without needing to manually recreate the repository.
+    private val underTest: WifiRepositoryViaTrackerLib by lazy {
+        WifiRepositoryViaTrackerLib(
+            featureFlags,
+            testScope.backgroundScope,
+            executor,
+            wifiPickerTrackerFactory,
+            wifiManager,
+            logger,
+            tableLogger,
+        )
+    }
 
     private val executor = FakeExecutor(FakeSystemClock())
     private val logger = LogBuffer("name", maxSize = 100, logcatEchoTracker = mock())
+    private val featureFlags = FakeFeatureFlags()
     private val tableLogger = mock<TableLogBuffer>()
     private val wifiManager =
         mock<WifiManager>().apply { whenever(this.maxSignalLevel).thenReturn(10) }
@@ -74,12 +100,22 @@
 
     @Before
     fun setUp() {
+        featureFlags.set(Flags.INSTANT_TETHER, false)
+        featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, false)
         whenever(wifiPickerTrackerFactory.create(any(), capture(callbackCaptor)))
             .thenReturn(wifiPickerTracker)
-        underTest = createRepo()
     }
 
     @Test
+    fun wifiPickerTrackerCreation_scansDisabled() =
+        testScope.runTest {
+            collectLastValue(underTest.wifiNetwork)
+            testScope.runCurrent()
+
+            verify(wifiPickerTracker).disableScanning()
+        }
+
+    @Test
     fun isWifiEnabled_enabled_true() =
         testScope.runTest {
             val latest by collectLastValue(underTest.isWifiEnabled)
@@ -238,7 +274,7 @@
                 mock<WifiEntry>().apply {
                     whenever(this.isPrimaryNetwork).thenReturn(true)
                     whenever(this.level).thenReturn(3)
-                    whenever(this.ssid).thenReturn(SSID)
+                    whenever(this.title).thenReturn(TITLE)
                 }
             whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
             getCallback().onWifiEntriesChanged()
@@ -246,7 +282,240 @@
             assertThat(latest is WifiNetworkModel.Active).isTrue()
             val latestActive = latest as WifiNetworkModel.Active
             assertThat(latestActive.level).isEqualTo(3)
-            assertThat(latestActive.ssid).isEqualTo(SSID)
+            assertThat(latestActive.ssid).isEqualTo(TITLE)
+        }
+
+    @Test
+    fun accessPointInfo_alwaysFalse() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry =
+                mock<WifiEntry>().apply {
+                    whenever(this.isPrimaryNetwork).thenReturn(true)
+                    whenever(this.level).thenReturn(3)
+                    whenever(this.title).thenReturn(TITLE)
+                }
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest is WifiNetworkModel.Active).isTrue()
+            val latestActive = latest as WifiNetworkModel.Active
+            assertThat(latestActive.isPasspointAccessPoint).isFalse()
+            assertThat(latestActive.isOnlineSignUpForPasspointAccessPoint).isFalse()
+            assertThat(latestActive.passpointProviderFriendlyName).isNull()
+        }
+
+    @Test
+    fun wifiNetwork_unreachableLevel_inactiveNetwork() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry =
+                mock<WifiEntry>().apply {
+                    whenever(this.isPrimaryNetwork).thenReturn(true)
+                    whenever(this.level).thenReturn(WIFI_LEVEL_UNREACHABLE)
+                }
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).isEqualTo(WifiNetworkModel.Inactive)
+        }
+
+    @Test
+    fun wifiNetwork_levelTooHigh_inactiveNetwork() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry =
+                mock<WifiEntry>().apply {
+                    whenever(this.isPrimaryNetwork).thenReturn(true)
+                    whenever(this.level).thenReturn(WIFI_LEVEL_MAX + 1)
+                }
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).isEqualTo(WifiNetworkModel.Inactive)
+        }
+
+    @Test
+    fun wifiNetwork_levelTooLow_inactiveNetwork() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry =
+                mock<WifiEntry>().apply {
+                    whenever(this.isPrimaryNetwork).thenReturn(true)
+                    whenever(this.level).thenReturn(WIFI_LEVEL_MIN - 1)
+                }
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).isEqualTo(WifiNetworkModel.Inactive)
+        }
+
+    @Test
+    fun wifiNetwork_levelIsMax_activeNetworkWithMaxLevel() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry =
+                mock<WifiEntry>().apply {
+                    whenever(this.isPrimaryNetwork).thenReturn(true)
+                    whenever(this.level).thenReturn(WIFI_LEVEL_MAX)
+                }
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).isInstanceOf(WifiNetworkModel.Active::class.java)
+            assertThat((latest as WifiNetworkModel.Active).level).isEqualTo(WIFI_LEVEL_MAX)
+        }
+
+    @Test
+    fun wifiNetwork_levelIsMin_activeNetworkWithMinLevel() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry =
+                mock<WifiEntry>().apply {
+                    whenever(this.isPrimaryNetwork).thenReturn(true)
+                    whenever(this.level).thenReturn(WIFI_LEVEL_MIN)
+                }
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).isInstanceOf(WifiNetworkModel.Active::class.java)
+            assertThat((latest as WifiNetworkModel.Active).level).isEqualTo(WIFI_LEVEL_MIN)
+        }
+
+    @Test
+    fun wifiNetwork_notHotspot_none() =
+        testScope.runTest {
+            featureFlags.set(Flags.INSTANT_TETHER, true)
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry =
+                mock<WifiEntry>().apply { whenever(this.isPrimaryNetwork).thenReturn(true) }
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat((latest as WifiNetworkModel.Active).hotspotDeviceType)
+                .isEqualTo(WifiNetworkModel.HotspotDeviceType.NONE)
+        }
+
+    @Test
+    fun wifiNetwork_hotspot_unknown() =
+        testScope.runTest {
+            featureFlags.set(Flags.INSTANT_TETHER, true)
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry = createHotspotWithType(NetworkProviderInfo.DEVICE_TYPE_UNKNOWN)
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat((latest as WifiNetworkModel.Active).hotspotDeviceType)
+                .isEqualTo(WifiNetworkModel.HotspotDeviceType.UNKNOWN)
+        }
+
+    @Test
+    fun wifiNetwork_hotspot_phone() =
+        testScope.runTest {
+            featureFlags.set(Flags.INSTANT_TETHER, true)
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry = createHotspotWithType(NetworkProviderInfo.DEVICE_TYPE_PHONE)
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat((latest as WifiNetworkModel.Active).hotspotDeviceType)
+                .isEqualTo(WifiNetworkModel.HotspotDeviceType.PHONE)
+        }
+
+    @Test
+    fun wifiNetwork_hotspot_tablet() =
+        testScope.runTest {
+            featureFlags.set(Flags.INSTANT_TETHER, true)
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry = createHotspotWithType(NetworkProviderInfo.DEVICE_TYPE_TABLET)
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat((latest as WifiNetworkModel.Active).hotspotDeviceType)
+                .isEqualTo(WifiNetworkModel.HotspotDeviceType.TABLET)
+        }
+
+    @Test
+    fun wifiNetwork_hotspot_laptop() =
+        testScope.runTest {
+            featureFlags.set(Flags.INSTANT_TETHER, true)
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry = createHotspotWithType(NetworkProviderInfo.DEVICE_TYPE_LAPTOP)
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat((latest as WifiNetworkModel.Active).hotspotDeviceType)
+                .isEqualTo(WifiNetworkModel.HotspotDeviceType.LAPTOP)
+        }
+
+    @Test
+    fun wifiNetwork_hotspot_watch() =
+        testScope.runTest {
+            featureFlags.set(Flags.INSTANT_TETHER, true)
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry = createHotspotWithType(NetworkProviderInfo.DEVICE_TYPE_WATCH)
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat((latest as WifiNetworkModel.Active).hotspotDeviceType)
+                .isEqualTo(WifiNetworkModel.HotspotDeviceType.WATCH)
+        }
+
+    @Test
+    fun wifiNetwork_hotspot_auto() =
+        testScope.runTest {
+            featureFlags.set(Flags.INSTANT_TETHER, true)
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry = createHotspotWithType(NetworkProviderInfo.DEVICE_TYPE_AUTO)
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat((latest as WifiNetworkModel.Active).hotspotDeviceType)
+                .isEqualTo(WifiNetworkModel.HotspotDeviceType.AUTO)
+        }
+
+    @Test
+    fun wifiNetwork_hotspot_invalid() =
+        testScope.runTest {
+            featureFlags.set(Flags.INSTANT_TETHER, true)
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry = createHotspotWithType(1234)
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            assertThat((latest as WifiNetworkModel.Active).hotspotDeviceType)
+                .isEqualTo(WifiNetworkModel.HotspotDeviceType.INVALID)
+        }
+
+    @Test
+    fun wifiNetwork_hotspot_flagOff_valueNotUsed() =
+        testScope.runTest {
+            // WHEN the flag is off
+            featureFlags.set(Flags.INSTANT_TETHER, false)
+
+            val latest by collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry = createHotspotWithType(NetworkProviderInfo.DEVICE_TYPE_WATCH)
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+
+            // THEN NONE is always used, even if the wifi entry does have a hotspot device type
+            assertThat((latest as WifiNetworkModel.Active).hotspotDeviceType)
+                .isEqualTo(WifiNetworkModel.HotspotDeviceType.NONE)
         }
 
     @Test
@@ -258,6 +527,7 @@
                 mock<MergedCarrierEntry>().apply {
                     whenever(this.isPrimaryNetwork).thenReturn(true)
                     whenever(this.level).thenReturn(3)
+                    whenever(this.subscriptionId).thenReturn(567)
                 }
             whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
             getCallback().onWifiEntriesChanged()
@@ -265,7 +535,7 @@
             assertThat(latest is WifiNetworkModel.CarrierMerged).isTrue()
             val latestMerged = latest as WifiNetworkModel.CarrierMerged
             assertThat(latestMerged.level).isEqualTo(3)
-            // numberOfLevels = maxSignalLevel + 1
+            assertThat(latestMerged.subscriptionId).isEqualTo(567)
         }
 
     @Test
@@ -288,30 +558,23 @@
             assertThat(latestMerged.numberOfLevels).isEqualTo(6)
         }
 
-    /* TODO(b/292534484): Re-enable this test once WifiTrackerLib gives us the subscription ID.
     @Test
     fun wifiNetwork_carrierMergedButInvalidSubId_flowHasInvalid() =
         testScope.runTest {
             val latest by collectLastValue(underTest.wifiNetwork)
 
-            val wifiInfo =
-                mock<WifiInfo>().apply {
-                    whenever(this.isPrimary).thenReturn(true)
-                    whenever(this.isCarrierMerged).thenReturn(true)
+            val wifiEntry =
+                mock<MergedCarrierEntry>().apply {
+                    whenever(this.isPrimaryNetwork).thenReturn(true)
                     whenever(this.subscriptionId).thenReturn(INVALID_SUBSCRIPTION_ID)
                 }
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
 
-            getNetworkCallback()
-                .onCapabilitiesChanged(
-                    NETWORK,
-                    createWifiNetworkCapabilities(wifiInfo),
-                )
+            getCallback().onWifiEntriesChanged()
 
             assertThat(latest).isInstanceOf(WifiNetworkModel.Invalid::class.java)
         }
 
-     */
-
     @Test
     fun wifiNetwork_notValidated_networkNotValidated() =
         testScope.runTest {
@@ -382,7 +645,7 @@
                 mock<WifiEntry>().apply {
                     whenever(this.isPrimaryNetwork).thenReturn(true)
                     whenever(this.level).thenReturn(3)
-                    whenever(this.ssid).thenReturn("AB")
+                    whenever(this.title).thenReturn("AB")
                 }
             whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
             getCallback().onWifiEntriesChanged()
@@ -397,7 +660,7 @@
                 mock<WifiEntry>().apply {
                     whenever(this.isPrimaryNetwork).thenReturn(true)
                     whenever(this.level).thenReturn(4)
-                    whenever(this.ssid).thenReturn("CD")
+                    whenever(this.title).thenReturn("CD")
                 }
             whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(newWifiEntry)
             getCallback().onWifiEntriesChanged()
@@ -430,12 +693,12 @@
             val wifiEntry =
                 mock<WifiEntry>().apply {
                     whenever(this.isPrimaryNetwork).thenReturn(true)
-                    whenever(this.ssid).thenReturn(SSID)
+                    whenever(this.title).thenReturn(TITLE)
                 }
             whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
             getCallback().onWifiEntriesChanged()
 
-            assertThat((latest as WifiNetworkModel.Active).ssid).isEqualTo(SSID)
+            assertThat((latest as WifiNetworkModel.Active).ssid).isEqualTo(TITLE)
 
             // WHEN we lose our current network
             whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(null)
@@ -480,7 +743,7 @@
                 mock<WifiEntry>().apply {
                     whenever(this.isPrimaryNetwork).thenReturn(true)
                     whenever(this.level).thenReturn(1)
-                    whenever(this.ssid).thenReturn(SSID)
+                    whenever(this.title).thenReturn(TITLE)
                 }
             whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
             getCallback().onWifiEntriesChanged()
@@ -488,7 +751,7 @@
             assertThat(latest1 is WifiNetworkModel.Active).isTrue()
             val latest1Active = latest1 as WifiNetworkModel.Active
             assertThat(latest1Active.level).isEqualTo(1)
-            assertThat(latest1Active.ssid).isEqualTo(SSID)
+            assertThat(latest1Active.ssid).isEqualTo(TITLE)
 
             // WHEN we add a second subscriber after having already emitted a value
             val latest2 by collectLastValue(underTest.wifiNetwork)
@@ -497,7 +760,198 @@
             assertThat(latest2 is WifiNetworkModel.Active).isTrue()
             val latest2Active = latest2 as WifiNetworkModel.Active
             assertThat(latest2Active.level).isEqualTo(1)
-            assertThat(latest2Active.ssid).isEqualTo(SSID)
+            assertThat(latest2Active.ssid).isEqualTo(TITLE)
+        }
+
+    @Test
+    fun secondaryNetworks_activeEntriesEmpty_isEmpty() =
+        testScope.runTest {
+            featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, true)
+            val latest by collectLastValue(underTest.secondaryNetworks)
+
+            whenever(wifiPickerTracker.activeWifiEntries).thenReturn(listOf())
+
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).isEmpty()
+        }
+
+    @Test
+    fun secondaryNetworks_oneActiveEntry_hasOne() =
+        testScope.runTest {
+            featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, true)
+            val latest by collectLastValue(underTest.secondaryNetworks)
+
+            val wifiEntry = mock<WifiEntry>()
+            whenever(wifiPickerTracker.activeWifiEntries).thenReturn(listOf(wifiEntry))
+
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).hasSize(1)
+        }
+
+    @Test
+    fun secondaryNetworks_multipleActiveEntries_hasMultiple() =
+        testScope.runTest {
+            featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, true)
+            val latest by collectLastValue(underTest.secondaryNetworks)
+
+            val wifiEntry1 = mock<WifiEntry>()
+            val wifiEntry2 = mock<WifiEntry>()
+            whenever(wifiPickerTracker.activeWifiEntries).thenReturn(listOf(wifiEntry1, wifiEntry2))
+
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).hasSize(2)
+        }
+
+    @Test
+    fun secondaryNetworks_mapsToInactive() =
+        testScope.runTest {
+            featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, true)
+            val latest by collectLastValue(underTest.secondaryNetworks)
+
+            val inactiveEntry =
+                mock<WifiEntry>().apply { whenever(this.level).thenReturn(WIFI_LEVEL_UNREACHABLE) }
+            whenever(wifiPickerTracker.activeWifiEntries).thenReturn(listOf(inactiveEntry))
+
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).hasSize(1)
+            assertThat(latest!![0]).isInstanceOf(WifiNetworkModel.Inactive::class.java)
+        }
+
+    @Test
+    fun secondaryNetworks_mapsToActive() =
+        testScope.runTest {
+            featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, true)
+            val latest by collectLastValue(underTest.secondaryNetworks)
+
+            val activeEntry = mock<WifiEntry>().apply { whenever(this.level).thenReturn(2) }
+            whenever(wifiPickerTracker.activeWifiEntries).thenReturn(listOf(activeEntry))
+
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).hasSize(1)
+            assertThat(latest!![0]).isInstanceOf(WifiNetworkModel.Active::class.java)
+            assertThat((latest!![0] as WifiNetworkModel.Active).level).isEqualTo(2)
+        }
+
+    @Test
+    fun secondaryNetworks_mapsToCarrierMerged() =
+        testScope.runTest {
+            featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, true)
+            val latest by collectLastValue(underTest.secondaryNetworks)
+
+            val carrierMergedEntry =
+                mock<MergedCarrierEntry>().apply { whenever(this.level).thenReturn(3) }
+            whenever(wifiPickerTracker.activeWifiEntries).thenReturn(listOf(carrierMergedEntry))
+
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).hasSize(1)
+            assertThat(latest!![0]).isInstanceOf(WifiNetworkModel.CarrierMerged::class.java)
+            assertThat((latest!![0] as WifiNetworkModel.CarrierMerged).level).isEqualTo(3)
+        }
+
+    @Test
+    fun secondaryNetworks_mapsMultipleInOrder() =
+        testScope.runTest {
+            featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, true)
+            val latest by collectLastValue(underTest.secondaryNetworks)
+
+            val activeEntry = mock<WifiEntry>().apply { whenever(this.level).thenReturn(2) }
+            val carrierMergedEntry =
+                mock<MergedCarrierEntry>().apply { whenever(this.level).thenReturn(3) }
+            whenever(wifiPickerTracker.activeWifiEntries)
+                .thenReturn(listOf(activeEntry, carrierMergedEntry))
+
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest!![0]).isInstanceOf(WifiNetworkModel.Active::class.java)
+            assertThat((latest!![0] as WifiNetworkModel.Active).level).isEqualTo(2)
+            assertThat(latest!![1]).isInstanceOf(WifiNetworkModel.CarrierMerged::class.java)
+            assertThat((latest!![1] as WifiNetworkModel.CarrierMerged).level).isEqualTo(3)
+        }
+
+    @Test
+    fun secondaryNetworks_filtersOutConnectedEntry() =
+        testScope.runTest {
+            featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, true)
+            val latest by collectLastValue(underTest.secondaryNetworks)
+
+            val connectedEntry = mock<WifiEntry>().apply { whenever(this.level).thenReturn(1) }
+            val secondaryEntry1 = mock<WifiEntry>().apply { whenever(this.level).thenReturn(2) }
+            val secondaryEntry2 = mock<WifiEntry>().apply { whenever(this.level).thenReturn(3) }
+            // WHEN the active list has both a primary and secondary networks
+            whenever(wifiPickerTracker.activeWifiEntries)
+                .thenReturn(listOf(connectedEntry, secondaryEntry1, secondaryEntry2))
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(connectedEntry)
+
+            getCallback().onWifiEntriesChanged()
+
+            // THEN only the secondary networks are included
+            assertThat(latest).hasSize(2)
+            assertThat((latest!![0] as WifiNetworkModel.Active).level).isEqualTo(2)
+            assertThat((latest!![1] as WifiNetworkModel.Active).level).isEqualTo(3)
+        }
+
+    @Test
+    fun secondaryNetworks_noConnectedEntry_hasAllActiveEntries() =
+        testScope.runTest {
+            featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, true)
+            val latest by collectLastValue(underTest.secondaryNetworks)
+
+            val secondaryEntry1 = mock<WifiEntry>().apply { whenever(this.level).thenReturn(2) }
+            val secondaryEntry2 = mock<WifiEntry>().apply { whenever(this.level).thenReturn(3) }
+            whenever(wifiPickerTracker.activeWifiEntries)
+                .thenReturn(listOf(secondaryEntry1, secondaryEntry2))
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(null)
+
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).hasSize(2)
+            assertThat((latest!![0] as WifiNetworkModel.Active).level).isEqualTo(2)
+            assertThat((latest!![1] as WifiNetworkModel.Active).level).isEqualTo(3)
+        }
+
+    @Test
+    fun secondaryNetworks_filtersOutPrimaryNetwork() =
+        testScope.runTest {
+            featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, true)
+            val latest by collectLastValue(underTest.secondaryNetworks)
+
+            val primaryEntry =
+                mock<WifiEntry>().apply {
+                    whenever(this.isPrimaryNetwork).thenReturn(true)
+                    whenever(this.level).thenReturn(1)
+                }
+            val secondaryEntry1 = mock<WifiEntry>().apply { whenever(this.level).thenReturn(2) }
+            val secondaryEntry2 = mock<WifiEntry>().apply { whenever(this.level).thenReturn(3) }
+            // WHEN the active list has both a primary and secondary networks
+            whenever(wifiPickerTracker.activeWifiEntries)
+                .thenReturn(listOf(secondaryEntry1, primaryEntry, secondaryEntry2))
+
+            getCallback().onWifiEntriesChanged()
+
+            // THEN only the secondary networks are included
+            assertThat(latest).hasSize(2)
+            assertThat((latest!![0] as WifiNetworkModel.Active).level).isEqualTo(2)
+            assertThat((latest!![1] as WifiNetworkModel.Active).level).isEqualTo(3)
+        }
+
+    @Test
+    fun secondaryNetworks_flagOff_noNetworks() =
+        testScope.runTest {
+            featureFlags.set(Flags.WIFI_SECONDARY_NETWORKS, false)
+            val latest by collectLastValue(underTest.secondaryNetworks)
+
+            val wifiEntry = mock<WifiEntry>()
+            whenever(wifiPickerTracker.activeWifiEntries).thenReturn(listOf(wifiEntry))
+
+            getCallback().onWifiEntriesChanged()
+
+            assertThat(latest).isEmpty()
         }
 
     @Test
@@ -541,40 +995,15 @@
             assertThat(underTest.isWifiConnectedWithValidSsid()).isFalse()
         }
 
-    /* TODO(b/292534484): Re-enable this test once WifiTrackerLib gives us the subscription ID.
-       @Test
-       fun isWifiConnectedWithValidSsid_invalidNetwork_false() =
-       testScope.runTest {
-           collectLastValue(underTest.wifiNetwork)
-
-           val wifiInfo =
-               mock<WifiInfo>().apply {
-                   whenever(this.isPrimary).thenReturn(true)
-                   whenever(this.isCarrierMerged).thenReturn(true)
-                   whenever(this.subscriptionId).thenReturn(INVALID_SUBSCRIPTION_ID)
-               }
-
-           getNetworkCallback()
-               .onCapabilitiesChanged(
-                   NETWORK,
-                   createWifiNetworkCapabilities(wifiInfo),
-               )
-           testScope.runCurrent()
-
-           assertThat(underTest.isWifiConnectedWithValidSsid()).isFalse()
-       }
-
-    */
-
     @Test
-    fun isWifiConnectedWithValidSsid_activeNetwork_nullSsid_false() =
+    fun isWifiConnectedWithValidSsid_invalidNetwork_false() =
         testScope.runTest {
             collectLastValue(underTest.wifiNetwork)
 
             val wifiEntry =
-                mock<WifiEntry>().apply {
+                mock<MergedCarrierEntry>().apply {
                     whenever(this.isPrimaryNetwork).thenReturn(true)
-                    whenever(this.ssid).thenReturn(null)
+                    whenever(this.subscriptionId).thenReturn(INVALID_SUBSCRIPTION_ID)
                 }
             whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
             getCallback().onWifiEntriesChanged()
@@ -584,14 +1013,14 @@
         }
 
     @Test
-    fun isWifiConnectedWithValidSsid_activeNetwork_unknownSsid_false() =
+    fun isWifiConnectedWithValidSsid_activeNetwork_nullTitle_false() =
         testScope.runTest {
             collectLastValue(underTest.wifiNetwork)
 
             val wifiEntry =
                 mock<WifiEntry>().apply {
                     whenever(this.isPrimaryNetwork).thenReturn(true)
-                    whenever(this.ssid).thenReturn(UNKNOWN_SSID)
+                    whenever(this.title).thenReturn(null)
                 }
             whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
             getCallback().onWifiEntriesChanged()
@@ -601,14 +1030,31 @@
         }
 
     @Test
-    fun isWifiConnectedWithValidSsid_activeNetwork_validSsid_true() =
+    fun isWifiConnectedWithValidSsid_activeNetwork_unknownTitle_false() =
         testScope.runTest {
             collectLastValue(underTest.wifiNetwork)
 
             val wifiEntry =
                 mock<WifiEntry>().apply {
                     whenever(this.isPrimaryNetwork).thenReturn(true)
-                    whenever(this.ssid).thenReturn("fakeSsid")
+                    whenever(this.title).thenReturn(UNKNOWN_SSID)
+                }
+            whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
+            getCallback().onWifiEntriesChanged()
+            testScope.runCurrent()
+
+            assertThat(underTest.isWifiConnectedWithValidSsid()).isFalse()
+        }
+
+    @Test
+    fun isWifiConnectedWithValidSsid_activeNetwork_validTitle_true() =
+        testScope.runTest {
+            collectLastValue(underTest.wifiNetwork)
+
+            val wifiEntry =
+                mock<WifiEntry>().apply {
+                    whenever(this.isPrimaryNetwork).thenReturn(true)
+                    whenever(this.title).thenReturn("fakeSsid")
                 }
             whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
             getCallback().onWifiEntriesChanged()
@@ -626,7 +1072,7 @@
             val wifiEntry =
                 mock<WifiEntry>().apply {
                     whenever(this.isPrimaryNetwork).thenReturn(true)
-                    whenever(this.ssid).thenReturn("fakeSsid")
+                    whenever(this.title).thenReturn("fakeSsid")
                 }
             whenever(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntry)
             getCallback().onWifiEntriesChanged()
@@ -643,23 +1089,74 @@
             assertThat(underTest.isWifiConnectedWithValidSsid()).isFalse()
         }
 
+    @Test
+    fun wifiActivity_callbackGivesNone_activityFlowHasNone() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.wifiActivity)
+
+            getTrafficStateCallback()
+                .onStateChanged(WifiManager.TrafficStateCallback.DATA_ACTIVITY_NONE)
+
+            assertThat(latest)
+                .isEqualTo(DataActivityModel(hasActivityIn = false, hasActivityOut = false))
+        }
+
+    @Test
+    fun wifiActivity_callbackGivesIn_activityFlowHasIn() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.wifiActivity)
+
+            getTrafficStateCallback()
+                .onStateChanged(WifiManager.TrafficStateCallback.DATA_ACTIVITY_IN)
+
+            assertThat(latest)
+                .isEqualTo(DataActivityModel(hasActivityIn = true, hasActivityOut = false))
+        }
+
+    @Test
+    fun wifiActivity_callbackGivesOut_activityFlowHasOut() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.wifiActivity)
+
+            getTrafficStateCallback()
+                .onStateChanged(WifiManager.TrafficStateCallback.DATA_ACTIVITY_OUT)
+
+            assertThat(latest)
+                .isEqualTo(DataActivityModel(hasActivityIn = false, hasActivityOut = true))
+        }
+
+    @Test
+    fun wifiActivity_callbackGivesInout_activityFlowHasInAndOut() =
+        testScope.runTest {
+            val latest by collectLastValue(underTest.wifiActivity)
+
+            getTrafficStateCallback()
+                .onStateChanged(WifiManager.TrafficStateCallback.DATA_ACTIVITY_INOUT)
+
+            assertThat(latest)
+                .isEqualTo(DataActivityModel(hasActivityIn = true, hasActivityOut = true))
+        }
+
     private fun getCallback(): WifiPickerTracker.WifiPickerTrackerCallback {
         testScope.runCurrent()
         return callbackCaptor.value
     }
 
-    private fun createRepo(): WifiRepositoryViaTrackerLib {
-        return WifiRepositoryViaTrackerLib(
-            testScope.backgroundScope,
-            executor,
-            wifiPickerTrackerFactory,
-            wifiManager,
-            logger,
-            tableLogger,
-        )
+    private fun getTrafficStateCallback(): WifiManager.TrafficStateCallback {
+        testScope.runCurrent()
+        val callbackCaptor = argumentCaptor<WifiManager.TrafficStateCallback>()
+        verify(wifiManager).registerTrafficStateCallback(any(), callbackCaptor.capture())
+        return callbackCaptor.value!!
+    }
+
+    private fun createHotspotWithType(@DeviceType type: Int): HotspotNetworkEntry {
+        return mock<HotspotNetworkEntry>().apply {
+            whenever(this.isPrimaryNetwork).thenReturn(true)
+            whenever(this.deviceType).thenReturn(type)
+        }
     }
 
     private companion object {
-        const val SSID = "AB"
+        const val TITLE = "AB"
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/shared/model/WifiNetworkModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/shared/model/WifiNetworkModelTest.kt
index 4e0c309..ba035be 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/shared/model/WifiNetworkModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/shared/model/WifiNetworkModelTest.kt
@@ -136,7 +136,8 @@
                 networkId = 5,
                 isValidated = true,
                 level = 3,
-                ssid = "Test SSID"
+                ssid = "Test SSID",
+                hotspotDeviceType = WifiNetworkModel.HotspotDeviceType.LAPTOP,
             )
 
         activeNetwork.logDiffs(prevVal = WifiNetworkModel.Inactive, logger)
@@ -146,6 +147,7 @@
         assertThat(logger.changes).contains(Pair(COL_VALIDATED, "true"))
         assertThat(logger.changes).contains(Pair(COL_LEVEL, "3"))
         assertThat(logger.changes).contains(Pair(COL_SSID, "Test SSID"))
+        assertThat(logger.changes).contains(Pair(COL_HOTSPOT, "LAPTOP"))
     }
     @Test
     fun logDiffs_activeToInactive_resetsAllActiveFields() {
@@ -165,6 +167,7 @@
         assertThat(logger.changes).contains(Pair(COL_VALIDATED, "false"))
         assertThat(logger.changes).contains(Pair(COL_LEVEL, LEVEL_DEFAULT.toString()))
         assertThat(logger.changes).contains(Pair(COL_SSID, "null"))
+        assertThat(logger.changes).contains(Pair(COL_HOTSPOT, "null"))
     }
 
     @Test
@@ -175,7 +178,8 @@
                 networkId = 5,
                 isValidated = true,
                 level = 3,
-                ssid = "Test SSID"
+                ssid = "Test SSID",
+                hotspotDeviceType = WifiNetworkModel.HotspotDeviceType.AUTO,
             )
         val prevVal =
             WifiNetworkModel.CarrierMerged(
@@ -191,6 +195,7 @@
         assertThat(logger.changes).contains(Pair(COL_VALIDATED, "true"))
         assertThat(logger.changes).contains(Pair(COL_LEVEL, "3"))
         assertThat(logger.changes).contains(Pair(COL_SSID, "Test SSID"))
+        assertThat(logger.changes).contains(Pair(COL_HOTSPOT, "AUTO"))
     }
     @Test
     fun logDiffs_activeToCarrierMerged_logsAllFields() {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BatteryControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BatteryControllerTest.java
index c886f9b..cdeb592 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BatteryControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BatteryControllerTest.java
@@ -29,6 +29,9 @@
 import static org.mockito.Mockito.when;
 
 import android.content.Intent;
+import android.hardware.usb.UsbManager;
+import android.hardware.usb.UsbPort;
+import android.hardware.usb.UsbPortStatus;
 import android.os.BatteryManager;
 import android.os.Handler;
 import android.os.PowerManager;
@@ -56,6 +59,9 @@
 import org.mockito.MockitoAnnotations;
 import org.mockito.MockitoSession;
 
+import java.util.ArrayList;
+import java.util.List;
+
 @SmallTest
 @RunWith(AndroidTestingRunner.class)
 @TestableLooper.RunWithLooper
@@ -65,8 +71,10 @@
     @Mock private BroadcastDispatcher mBroadcastDispatcher;
     @Mock private DemoModeController mDemoModeController;
     @Mock private View mView;
+    @Mock private UsbPort mUsbPort;
+    @Mock private UsbManager mUsbManager;
+    @Mock private UsbPortStatus mUsbPortStatus;
     private BatteryControllerImpl mBatteryController;
-
     private MockitoSession mMockitoSession;
 
     @Before
@@ -255,4 +263,38 @@
 
         Assert.assertFalse(mBatteryController.isBatteryDefender());
     }
+
+    @Test
+    public void complianceChanged_complianceIncompatible_outputsTrue() {
+        mContext.addMockSystemService(UsbManager.class, mUsbManager);
+        setupIncompatibleCharging();
+        Intent intent = new Intent(UsbManager.ACTION_USB_PORT_COMPLIANCE_CHANGED);
+
+        mBatteryController.onReceive(getContext(), intent);
+
+        Assert.assertTrue(mBatteryController.isIncompatibleCharging());
+    }
+
+    @Test
+    public void complianceChanged_emptyComplianceWarnings_outputsFalse() {
+        mContext.addMockSystemService(UsbManager.class, mUsbManager);
+        setupIncompatibleCharging();
+        when(mUsbPortStatus.getComplianceWarnings()).thenReturn(new int[1]);
+        Intent intent = new Intent(UsbManager.ACTION_USB_PORT_COMPLIANCE_CHANGED);
+
+        mBatteryController.onReceive(getContext(), intent);
+
+        Assert.assertFalse(mBatteryController.isIncompatibleCharging());
+    }
+
+    private void setupIncompatibleCharging() {
+        final List<UsbPort> usbPorts = new ArrayList<>();
+        usbPorts.add(mUsbPort);
+        when(mUsbManager.getPorts()).thenReturn(usbPorts);
+        when(mUsbPort.getStatus()).thenReturn(mUsbPortStatus);
+        when(mUsbPort.supportsComplianceWarnings()).thenReturn(true);
+        when(mUsbPortStatus.isConnected()).thenReturn(true);
+        when(mUsbPortStatus.getComplianceWarnings())
+                .thenReturn(new int[]{UsbPortStatus.COMPLIANCE_WARNING_OTHER});
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/HeadsUpManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/HeadsUpManagerTest.java
index 14edf3d..e5bbead 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/HeadsUpManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/HeadsUpManagerTest.java
@@ -16,6 +16,8 @@
 
 package com.android.systemui.statusbar.policy;
 
+import static android.app.Notification.FLAG_FSI_REQUESTED_BUT_DENIED;
+
 import static com.android.systemui.dump.LogBufferHelperKt.logcatLogBuffer;
 
 import static com.google.common.truth.Truth.assertThat;
@@ -40,7 +42,6 @@
 import android.content.Context;
 import android.content.Intent;
 import android.os.Handler;
-import android.service.notification.StatusBarNotification;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
@@ -48,6 +49,7 @@
 
 import com.android.internal.logging.UiEventLogger;
 import com.android.internal.logging.testing.UiEventLoggerFake;
+import com.android.systemui.R;
 import com.android.systemui.statusbar.AlertingNotificationManager;
 import com.android.systemui.statusbar.AlertingNotificationManagerTest;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
@@ -63,16 +65,11 @@
 @RunWith(AndroidTestingRunner.class)
 @TestableLooper.RunWithLooper
 public class HeadsUpManagerTest extends AlertingNotificationManagerTest {
-    private static final int TEST_A11Y_AUTO_DISMISS_TIME = 600;
-    private static final int TEST_A11Y_TIMEOUT_TIME = 5_000;
+    private static final int TEST_TOUCH_ACCEPTANCE_TIME = 200;
+    private static final int TEST_A11Y_AUTO_DISMISS_TIME = 1_000;
+    private static final int TEST_A11Y_TIMEOUT_TIME = 3_000;
 
-    private HeadsUpManager mHeadsUpManager;
-    private boolean mLivesPastNormalTime;
     private UiEventLoggerFake mUiEventLoggerFake = new UiEventLoggerFake();
-    @Mock private HeadsUpManager.HeadsUpEntry mAlertEntry;
-    @Mock private NotificationEntry mEntry;
-    @Mock private StatusBarNotification mSbn;
-    @Mock private Notification mNotification;
     private final HeadsUpManagerLogger mLogger = spy(new HeadsUpManagerLogger(logcatLogBuffer()));
     @Mock private AccessibilityManagerWrapper mAccessibilityMgr;
 
@@ -83,27 +80,81 @@
                 AccessibilityManagerWrapper accessibilityManagerWrapper,
                 UiEventLogger uiEventLogger) {
             super(context, logger, handler, accessibilityManagerWrapper, uiEventLogger);
+            mTouchAcceptanceDelay = TEST_TOUCH_ACCEPTANCE_TIME;
             mMinimumDisplayTime = TEST_MINIMUM_DISPLAY_TIME;
-            mStickyDisplayTime = TEST_STICKY_DISPLAY_TIME;
             mAutoDismissNotificationDecay = TEST_AUTO_DISMISS_TIME;
+            mStickyDisplayTime = TEST_STICKY_AUTO_DISMISS_TIME;
         }
     }
 
+    private HeadsUpManager createHeadsUpManager() {
+        return new TestableHeadsUpManager(mContext, mLogger, mTestHandler, mAccessibilityMgr,
+                mUiEventLoggerFake);
+    }
+
     @Override
     protected AlertingNotificationManager createAlertingNotificationManager() {
-        return mHeadsUpManager;
+        return createHeadsUpManager();
     }
 
+    private NotificationEntry createStickyEntry(int id) {
+        final Notification notif = new Notification.Builder(mContext, "")
+                .setSmallIcon(R.drawable.ic_person)
+                .setFullScreenIntent(mock(PendingIntent.class), /* highPriority */ true)
+                .build();
+        return createEntry(id, notif);
+    }
+
+    private NotificationEntry createStickyForSomeTimeEntry(int id) {
+        final Notification notif = new Notification.Builder(mContext, "")
+                .setSmallIcon(R.drawable.ic_person)
+                .setFlag(FLAG_FSI_REQUESTED_BUT_DENIED, true)
+                .build();
+        return createEntry(id, notif);
+    }
+
+    private PendingIntent createFullScreenIntent() {
+        return PendingIntent.getActivity(
+                getContext(), 0, new Intent(getContext(), this.getClass()),
+                PendingIntent.FLAG_MUTABLE_UNAUDITED);
+    }
+
+    private NotificationEntry createFullScreenIntentEntry(int id) {
+        final Notification notif = new Notification.Builder(mContext, "")
+                .setSmallIcon(R.drawable.ic_person)
+                .setFullScreenIntent(createFullScreenIntent(), /* highPriority */ true)
+                .build();
+        return createEntry(id, notif);
+    }
+
+
+    private void useAccessibilityTimeout(boolean use) {
+        if (use) {
+            doReturn(TEST_A11Y_AUTO_DISMISS_TIME).when(mAccessibilityMgr)
+                    .getRecommendedTimeoutMillis(anyInt(), anyInt());
+        } else {
+            when(mAccessibilityMgr.getRecommendedTimeoutMillis(anyInt(), anyInt())).then(
+                    i -> i.getArgument(0));
+        }
+    }
+
+
     @Before
     @Override
     public void setUp() {
         initMocks(this);
-        when(mEntry.getSbn()).thenReturn(mSbn);
-        when(mEntry.getKey()).thenReturn("entryKey");
-        when(mSbn.getNotification()).thenReturn(mNotification);
         super.setUp();
-        mHeadsUpManager = new TestableHeadsUpManager(mContext, mLogger, mTestHandler,
-                mAccessibilityMgr, mUiEventLoggerFake);
+
+        assertThat(TEST_MINIMUM_DISPLAY_TIME).isLessThan(TEST_AUTO_DISMISS_TIME);
+        assertThat(TEST_AUTO_DISMISS_TIME).isLessThan(TEST_STICKY_AUTO_DISMISS_TIME);
+        assertThat(TEST_STICKY_AUTO_DISMISS_TIME).isLessThan(TEST_A11Y_AUTO_DISMISS_TIME);
+
+        assertThat(TEST_TOUCH_ACCEPTANCE_TIME + TEST_AUTO_DISMISS_TIME).isLessThan(
+                TEST_TIMEOUT_TIME);
+        assertThat(TEST_TOUCH_ACCEPTANCE_TIME + TEST_STICKY_AUTO_DISMISS_TIME).isLessThan(
+                TEST_TIMEOUT_TIME);
+        assertThat(TEST_TOUCH_ACCEPTANCE_TIME + TEST_A11Y_AUTO_DISMISS_TIME).isLessThan(
+                TEST_A11Y_TIMEOUT_TIME);
     }
 
     @After
@@ -114,193 +165,327 @@
 
     @Test
     public void testHunRemovedLogging() {
-        mAlertEntry.mEntry = mEntry;
-        mHeadsUpManager.onAlertEntryRemoved(mAlertEntry);
-        verify(mLogger, times(1)).logNotificationActuallyRemoved(eq(mEntry));
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry notifEntry = createEntry(/* id = */ 0);
+        final HeadsUpManager.HeadsUpEntry headsUpEntry = mock(HeadsUpManager.HeadsUpEntry.class);
+        headsUpEntry.mEntry = notifEntry;
+
+        hum.onAlertEntryRemoved(headsUpEntry);
+
+        verify(mLogger, times(1)).logNotificationActuallyRemoved(eq(notifEntry));
     }
 
     @Test
     public void testShouldHeadsUpBecomePinned_hasFSI_notUnpinned_true() {
-        // Set up NotifEntry with FSI
-        NotificationEntry notifEntry = new NotificationEntryBuilder()
-                .setSbn(createNewNotification(/* id= */ 0))
-                .build();
-        notifEntry.getSbn().getNotification().fullScreenIntent = PendingIntent.getActivity(
-                getContext(), 0, new Intent(getContext(), this.getClass()),
-                PendingIntent.FLAG_MUTABLE_UNAUDITED);
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry notifEntry = createFullScreenIntentEntry(/* id = */ 0);
 
         // Add notifEntry to ANM mAlertEntries map and make it NOT unpinned
-        mHeadsUpManager.showNotification(notifEntry);
-        HeadsUpManager.HeadsUpEntry headsUpEntry =
-                mHeadsUpManager.getHeadsUpEntry(notifEntry.getKey());
+        hum.showNotification(notifEntry);
+
+        final HeadsUpManager.HeadsUpEntry headsUpEntry = hum.getHeadsUpEntry(notifEntry.getKey());
         headsUpEntry.wasUnpinned = false;
 
-        assertTrue(mHeadsUpManager.shouldHeadsUpBecomePinned(notifEntry));
+        assertTrue(hum.shouldHeadsUpBecomePinned(notifEntry));
     }
 
     @Test
     public void testShouldHeadsUpBecomePinned_wasUnpinned_false() {
-        // Set up NotifEntry with FSI
-        NotificationEntry notifEntry = new NotificationEntryBuilder()
-                .setSbn(createNewNotification(/* id= */ 0))
-                .build();
-        notifEntry.getSbn().getNotification().fullScreenIntent = PendingIntent.getActivity(
-                getContext(), 0, new Intent(getContext(), this.getClass()),
-                PendingIntent.FLAG_MUTABLE_UNAUDITED);
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry notifEntry = createFullScreenIntentEntry(/* id = */ 0);
 
         // Add notifEntry to ANM mAlertEntries map and make it unpinned
-        mHeadsUpManager.showNotification(notifEntry);
-        HeadsUpManager.HeadsUpEntry headsUpEntry =
-                mHeadsUpManager.getHeadsUpEntry(notifEntry.getKey());
+        hum.showNotification(notifEntry);
+
+        final HeadsUpManager.HeadsUpEntry headsUpEntry = hum.getHeadsUpEntry(notifEntry.getKey());
         headsUpEntry.wasUnpinned = true;
 
-        assertFalse(mHeadsUpManager.shouldHeadsUpBecomePinned(notifEntry));
+        assertFalse(hum.shouldHeadsUpBecomePinned(notifEntry));
     }
 
     @Test
     public void testShouldHeadsUpBecomePinned_noFSI_false() {
-        // Set up NotifEntry with no FSI
-        NotificationEntry notifEntry = new NotificationEntryBuilder()
-                .setSbn(createNewNotification(/* id= */ 0))
-                .build();
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
 
-        assertFalse(mHeadsUpManager.shouldHeadsUpBecomePinned(notifEntry));
+        assertFalse(hum.shouldHeadsUpBecomePinned(entry));
     }
 
+
+    @Test
+    public void testShowNotification_autoDismissesIncludingTouchAcceptanceDelay() {
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
+        useAccessibilityTimeout(false);
+
+        hum.showNotification(entry);
+
+        final int pastJustAutoDismissMillis =
+                TEST_TOUCH_ACCEPTANCE_TIME / 2 + TEST_AUTO_DISMISS_TIME;
+        verifyAlertingAtTime(hum, entry, true, pastJustAutoDismissMillis, "just auto dismiss");
+    }
+
+
+    @Test
+    public void testShowNotification_autoDismissesWithDefaultTimeout() {
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
+        useAccessibilityTimeout(false);
+
+        hum.showNotification(entry);
+
+        final int pastDefaultTimeoutMillis = TEST_TOUCH_ACCEPTANCE_TIME
+                + (TEST_AUTO_DISMISS_TIME + TEST_A11Y_AUTO_DISMISS_TIME) / 2;
+        verifyAlertingAtTime(hum, entry, false, pastDefaultTimeoutMillis, "default timeout");
+    }
+
+
+    @Test
+    public void testShowNotification_stickyForSomeTime_autoDismissesWithStickyTimeout() {
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry entry = createStickyForSomeTimeEntry(/* id = */ 0);
+        useAccessibilityTimeout(false);
+
+        hum.showNotification(entry);
+
+        final int pastDefaultTimeoutMillis = TEST_TOUCH_ACCEPTANCE_TIME
+                + (TEST_AUTO_DISMISS_TIME + TEST_STICKY_AUTO_DISMISS_TIME) / 2;
+        verifyAlertingAtTime(hum, entry, true, pastDefaultTimeoutMillis, "default timeout");
+    }
+
+
+    @Test
+    public void testShowNotification_sticky_neverAutoDismisses() {
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry entry = createStickyEntry(/* id = */ 0);
+        useAccessibilityTimeout(false);
+
+        hum.showNotification(entry);
+
+        final int pastLongestAutoDismissMillis =
+                TEST_TOUCH_ACCEPTANCE_TIME + 2 * TEST_A11Y_AUTO_DISMISS_TIME;
+        final Boolean[] wasAlerting = {null};
+        final Runnable checkAlerting =
+                () -> wasAlerting[0] = hum.isAlerting(entry.getKey());
+        mTestHandler.postDelayed(checkAlerting, pastLongestAutoDismissMillis);
+        TestableLooper.get(this).processMessages(1);
+
+        assertTrue("Should still be alerting past longest auto-dismiss", wasAlerting[0]);
+        assertTrue("Should still be alerting after processing",
+                hum.isAlerting(entry.getKey()));
+    }
+
+
     @Test
     public void testShowNotification_autoDismissesWithAccessibilityTimeout() {
-        doReturn(TEST_A11Y_AUTO_DISMISS_TIME).when(mAccessibilityMgr)
-                .getRecommendedTimeoutMillis(anyInt(), anyInt());
-        mHeadsUpManager.showNotification(mEntry);
-        Runnable pastNormalTimeRunnable =
-                () -> mLivesPastNormalTime = mHeadsUpManager.isAlerting(mEntry.getKey());
-        mTestHandler.postDelayed(pastNormalTimeRunnable,
-                        (TEST_A11Y_AUTO_DISMISS_TIME + TEST_AUTO_DISMISS_TIME) / 2);
-        mTestHandler.postDelayed(mTestTimeoutRunnable, TEST_A11Y_TIMEOUT_TIME);
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
+        useAccessibilityTimeout(true);
 
-        TestableLooper.get(this).processMessages(2);
+        hum.showNotification(entry);
 
-        assertFalse("Test timed out", mTimedOut);
-        assertTrue("Heads up should live long enough", mLivesPastNormalTime);
-        assertFalse(mHeadsUpManager.isAlerting(mEntry.getKey()));
+        final int pastDefaultTimeoutMillis = TEST_TOUCH_ACCEPTANCE_TIME
+                + (TEST_AUTO_DISMISS_TIME + TEST_A11Y_AUTO_DISMISS_TIME) / 2;
+        verifyAlertingAtTime(hum, entry, true, pastDefaultTimeoutMillis, "default timeout");
+    }
+
+
+    @Test
+    public void testShowNotification_stickyForSomeTime_autoDismissesWithAccessibilityTimeout() {
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry entry = createStickyForSomeTimeEntry(/* id = */ 0);
+        useAccessibilityTimeout(true);
+
+        hum.showNotification(entry);
+
+        final int pastStickyTimeoutMillis = TEST_TOUCH_ACCEPTANCE_TIME
+                + (TEST_STICKY_AUTO_DISMISS_TIME + TEST_A11Y_AUTO_DISMISS_TIME) / 2;
+        verifyAlertingAtTime(hum, entry, true, pastStickyTimeoutMillis, "sticky timeout");
+    }
+
+
+    @Test
+    public void testRemoveNotification_beforeMinimumDisplayTime() {
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
+        useAccessibilityTimeout(false);
+
+        hum.showNotification(entry);
+
+        // Try to remove but defer, since the notification has not been shown long enough.
+        final boolean removedImmediately = hum.removeNotification(
+                entry.getKey(), false /* releaseImmediately */);
+
+        assertFalse("HUN should not be removed before minimum display time", removedImmediately);
+        assertTrue("HUN should still be alerting before minimum display time",
+                hum.isAlerting(entry.getKey()));
+
+        final int pastMinimumDisplayTimeMillis =
+                (TEST_MINIMUM_DISPLAY_TIME + TEST_AUTO_DISMISS_TIME) / 2;
+        verifyAlertingAtTime(hum, entry, false, pastMinimumDisplayTimeMillis,
+                "minimum display time");
+    }
+
+
+    @Test
+    public void testRemoveNotification_afterMinimumDisplayTime() {
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
+        useAccessibilityTimeout(false);
+
+        hum.showNotification(entry);
+
+        // After the minimum display time:
+        // 1. Check whether the notification is still alerting.
+        // 2. Try to remove it and check whether the remove succeeded.
+        // 3. Check whether it is still alerting after trying to remove it.
+        final Boolean[] livedPastMinimumDisplayTime = {null};
+        final Boolean[] removedAfterMinimumDisplayTime = {null};
+        final Boolean[] livedPastRemoveAfterMinimumDisplayTime = {null};
+        final Runnable pastMinimumDisplayTimeRunnable = () -> {
+            livedPastMinimumDisplayTime[0] = hum.isAlerting(entry.getKey());
+            removedAfterMinimumDisplayTime[0] = hum.removeNotification(
+                    entry.getKey(), /* releaseImmediately = */ false);
+            livedPastRemoveAfterMinimumDisplayTime[0] = hum.isAlerting(entry.getKey());
+        };
+        final int pastMinimumDisplayTimeMillis =
+                (TEST_MINIMUM_DISPLAY_TIME + TEST_AUTO_DISMISS_TIME) / 2;
+        mTestHandler.postDelayed(pastMinimumDisplayTimeRunnable, pastMinimumDisplayTimeMillis);
+        // Wait until the minimum display time has passed before attempting removal.
+        TestableLooper.get(this).processMessages(1);
+
+        assertTrue("HUN should live past minimum display time",
+                livedPastMinimumDisplayTime[0]);
+        assertTrue("HUN should be removed immediately past minimum display time",
+                removedAfterMinimumDisplayTime[0]);
+        assertFalse("HUN should not live after being removed past minimum display time",
+                livedPastRemoveAfterMinimumDisplayTime[0]);
+        assertFalse(hum.isAlerting(entry.getKey()));
+    }
+
+
+    @Test
+    public void testRemoveNotification_releaseImmediately() {
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry entry = createEntry(/* id = */ 0);
+
+        hum.showNotification(entry);
+
+        // Remove forcibly with releaseImmediately = true.
+        final boolean removedImmediately = hum.removeNotification(
+                entry.getKey(), /* releaseImmediately = */ true);
+
+        assertTrue(removedImmediately);
+        assertFalse(hum.isAlerting(entry.getKey()));
     }
 
 
     @Test
     public void testIsSticky_rowPinnedAndExpanded_true() {
-        NotificationEntry notifEntry = new NotificationEntryBuilder()
-                .setSbn(createNewNotification(/* id= */ 0))
-                .build();
-
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry notifEntry = createEntry(/* id = */ 0);
         when(mRow.isPinned()).thenReturn(true);
         notifEntry.setRow(mRow);
 
-        mHeadsUpManager.showNotification(notifEntry);
+        hum.showNotification(notifEntry);
 
-        HeadsUpManager.HeadsUpEntry headsUpEntry =
-                mHeadsUpManager.getHeadsUpEntry(notifEntry.getKey());
+        final HeadsUpManager.HeadsUpEntry headsUpEntry = hum.getHeadsUpEntry(notifEntry.getKey());
         headsUpEntry.setExpanded(true);
 
-        assertTrue(mHeadsUpManager.isSticky(notifEntry.getKey()));
+        assertTrue(hum.isSticky(notifEntry.getKey()));
     }
 
     @Test
     public void testIsSticky_remoteInputActive_true() {
-        NotificationEntry notifEntry = new NotificationEntryBuilder()
-                .setSbn(createNewNotification(/* id= */ 0))
-                .build();
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry notifEntry = createEntry(/* id = */ 0);
 
-        mHeadsUpManager.showNotification(notifEntry);
+        hum.showNotification(notifEntry);
 
-        HeadsUpManager.HeadsUpEntry headsUpEntry =
-                mHeadsUpManager.getHeadsUpEntry(notifEntry.getKey());
-
+        final HeadsUpManager.HeadsUpEntry headsUpEntry = hum.getHeadsUpEntry(notifEntry.getKey());
         headsUpEntry.remoteInputActive = true;
 
-        assertTrue(mHeadsUpManager.isSticky(notifEntry.getKey()));
+        assertTrue(hum.isSticky(notifEntry.getKey()));
     }
 
     @Test
     public void testIsSticky_hasFullScreenIntent_true() {
-        NotificationEntry notifEntry = new NotificationEntryBuilder()
-                .setSbn(createNewNotification(/* id= */ 0))
-                .build();
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry notifEntry = createFullScreenIntentEntry(/* id = */ 0);
 
-        mHeadsUpManager.showNotification(notifEntry);
+        hum.showNotification(notifEntry);
 
-        HeadsUpManager.HeadsUpEntry headsUpEntry =
-                mHeadsUpManager.getHeadsUpEntry(notifEntry.getKey());
-
-        notifEntry.getSbn().getNotification().fullScreenIntent = PendingIntent.getActivity(
-                getContext(), 0, new Intent(getContext(), this.getClass()),
-                PendingIntent.FLAG_MUTABLE_UNAUDITED);
-
-        assertTrue(mHeadsUpManager.isSticky(notifEntry.getKey()));
+        assertTrue(hum.isSticky(notifEntry.getKey()));
     }
 
+
     @Test
-    public void testIsSticky_stickyAndNotDemoted_true() {
-        NotificationEntry alertEntry = new NotificationEntryBuilder()
-                .setSbn(createStickySbn(0))
-                .build();
+    public void testIsSticky_stickyForSomeTime_false() {
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry entry = createStickyForSomeTimeEntry(/* id = */ 0);
 
-        mHeadsUpManager.showNotification(alertEntry);
+        hum.showNotification(entry);
 
-        assertTrue(mHeadsUpManager.isSticky(alertEntry.getKey()));
+        assertFalse(hum.isSticky(entry.getKey()));
     }
 
+
     @Test
     public void testIsSticky_false() {
-        NotificationEntry notifEntry = new NotificationEntryBuilder()
-                .setSbn(createNewNotification(/* id= */ 0))
-                .build();
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry notifEntry = createEntry(/* id = */ 0);
 
-        mHeadsUpManager.showNotification(notifEntry);
+        hum.showNotification(notifEntry);
 
-        HeadsUpManager.HeadsUpEntry headsUpEntry =
-                mHeadsUpManager.getHeadsUpEntry(notifEntry.getKey());
+        final HeadsUpManager.HeadsUpEntry headsUpEntry = hum.getHeadsUpEntry(notifEntry.getKey());
         headsUpEntry.setExpanded(false);
         headsUpEntry.remoteInputActive = false;
 
-        assertFalse(mHeadsUpManager.isSticky(notifEntry.getKey()));
+        assertFalse(hum.isSticky(notifEntry.getKey()));
     }
 
     @Test
     public void testCompareTo_withNullEntries() {
-        NotificationEntry alertEntry = new NotificationEntryBuilder().setTag("alert").build();
-        mHeadsUpManager.showNotification(alertEntry);
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry alertEntry = new NotificationEntryBuilder().setTag("alert").build();
 
-        assertThat(mHeadsUpManager.compare(alertEntry, null)).isLessThan(0);
-        assertThat(mHeadsUpManager.compare(null, alertEntry)).isGreaterThan(0);
-        assertThat(mHeadsUpManager.compare(null, null)).isEqualTo(0);
+        hum.showNotification(alertEntry);
+
+        assertThat(hum.compare(alertEntry, null)).isLessThan(0);
+        assertThat(hum.compare(null, alertEntry)).isGreaterThan(0);
+        assertThat(hum.compare(null, null)).isEqualTo(0);
     }
 
     @Test
     public void testCompareTo_withNonAlertEntries() {
-        NotificationEntry nonAlertEntry1 = new NotificationEntryBuilder().setTag("nae1").build();
-        NotificationEntry nonAlertEntry2 = new NotificationEntryBuilder().setTag("nae2").build();
-        NotificationEntry alertEntry = new NotificationEntryBuilder().setTag("alert").build();
-        mHeadsUpManager.showNotification(alertEntry);
+        final HeadsUpManager hum = createHeadsUpManager();
 
-        assertThat(mHeadsUpManager.compare(alertEntry, nonAlertEntry1)).isLessThan(0);
-        assertThat(mHeadsUpManager.compare(nonAlertEntry1, alertEntry)).isGreaterThan(0);
-        assertThat(mHeadsUpManager.compare(nonAlertEntry1, nonAlertEntry2)).isEqualTo(0);
+        final NotificationEntry nonAlertEntry1 = new NotificationEntryBuilder().setTag(
+                "nae1").build();
+        final NotificationEntry nonAlertEntry2 = new NotificationEntryBuilder().setTag(
+                "nae2").build();
+        final NotificationEntry alertEntry = new NotificationEntryBuilder().setTag("alert").build();
+        hum.showNotification(alertEntry);
+
+        assertThat(hum.compare(alertEntry, nonAlertEntry1)).isLessThan(0);
+        assertThat(hum.compare(nonAlertEntry1, alertEntry)).isGreaterThan(0);
+        assertThat(hum.compare(nonAlertEntry1, nonAlertEntry2)).isEqualTo(0);
     }
 
     @Test
     public void testAlertEntryCompareTo_ongoingCallLessThanActiveRemoteInput() {
-        HeadsUpManager.HeadsUpEntry ongoingCall = mHeadsUpManager.new HeadsUpEntry();
+        final HeadsUpManager hum = createHeadsUpManager();
+
+        final HeadsUpManager.HeadsUpEntry ongoingCall = hum.new HeadsUpEntry();
         ongoingCall.setEntry(new NotificationEntryBuilder()
-                .setSbn(createNewSbn(0,
+                .setSbn(createSbn(/* id = */ 0,
                         new Notification.Builder(mContext, "")
                                 .setCategory(Notification.CATEGORY_CALL)
                                 .setOngoing(true)))
                 .build());
 
-        HeadsUpManager.HeadsUpEntry activeRemoteInput = mHeadsUpManager.new HeadsUpEntry();
-        activeRemoteInput.setEntry(new NotificationEntryBuilder()
-                .setSbn(createNewNotification(1))
-                .build());
+        final HeadsUpManager.HeadsUpEntry activeRemoteInput = hum.new HeadsUpEntry();
+        activeRemoteInput.setEntry(createEntry(/* id = */ 1));
         activeRemoteInput.remoteInputActive = true;
 
         assertThat(ongoingCall.compareTo(activeRemoteInput)).isLessThan(0);
@@ -309,20 +494,20 @@
 
     @Test
     public void testAlertEntryCompareTo_incomingCallLessThanActiveRemoteInput() {
-        HeadsUpManager.HeadsUpEntry incomingCall = mHeadsUpManager.new HeadsUpEntry();
-        Person person = new Person.Builder().setName("person").build();
-        PendingIntent intent = mock(PendingIntent.class);
+        final HeadsUpManager hum = createHeadsUpManager();
+
+        final HeadsUpManager.HeadsUpEntry incomingCall = hum.new HeadsUpEntry();
+        final Person person = new Person.Builder().setName("person").build();
+        final PendingIntent intent = mock(PendingIntent.class);
         incomingCall.setEntry(new NotificationEntryBuilder()
-                .setSbn(createNewSbn(0,
+                .setSbn(createSbn(/* id = */ 0,
                         new Notification.Builder(mContext, "")
                                 .setStyle(Notification.CallStyle
                                         .forIncomingCall(person, intent, intent))))
                 .build());
 
-        HeadsUpManager.HeadsUpEntry activeRemoteInput = mHeadsUpManager.new HeadsUpEntry();
-        activeRemoteInput.setEntry(new NotificationEntryBuilder()
-                .setSbn(createNewNotification(1))
-                .build());
+        final HeadsUpManager.HeadsUpEntry activeRemoteInput = hum.new HeadsUpEntry();
+        activeRemoteInput.setEntry(createEntry(/* id = */ 1));
         activeRemoteInput.remoteInputActive = true;
 
         assertThat(incomingCall.compareTo(activeRemoteInput)).isLessThan(0);
@@ -331,22 +516,18 @@
 
     @Test
     public void testPinEntry_logsPeek() {
-        // Needs full screen intent in order to be pinned
-        final PendingIntent fullScreenIntent = PendingIntent.getActivity(mContext, 0,
-                new Intent().setPackage(mContext.getPackageName()), PendingIntent.FLAG_MUTABLE);
+        final HeadsUpManager hum = createHeadsUpManager();
 
-        HeadsUpManager.HeadsUpEntry entryToPin = mHeadsUpManager.new HeadsUpEntry();
-        entryToPin.setEntry(new NotificationEntryBuilder()
-                .setSbn(createNewSbn(0,
-                        new Notification.Builder(mContext, "")
-                                .setFullScreenIntent(fullScreenIntent, true)))
-                .build());
+        // Needs full screen intent in order to be pinned
+        final HeadsUpManager.HeadsUpEntry entryToPin = hum.new HeadsUpEntry();
+        entryToPin.setEntry(createFullScreenIntentEntry(/* id = */ 0));
+
         // Note: the standard way to show a notification would be calling showNotification rather
         // than onAlertEntryAdded. However, in practice showNotification in effect adds
         // the notification and then updates it; in order to not log twice, the entry needs
         // to have a functional ExpandableNotificationRow that can keep track of whether it's
         // pinned or not (via isRowPinned()). That feels like a lot to pull in to test this one bit.
-        mHeadsUpManager.onAlertEntryAdded(entryToPin);
+        hum.onAlertEntryAdded(entryToPin);
 
         assertEquals(1, mUiEventLoggerFake.numLogs());
         assertEquals(HeadsUpManager.NotificationPeekEvent.NOTIFICATION_PEEK.getId(),
@@ -355,14 +536,15 @@
 
     @Test
     public void testSetUserActionMayIndirectlyRemove() {
-        NotificationEntry notifEntry = new NotificationEntryBuilder()
-                .setSbn(createNewNotification(/* id= */ 0))
-                .build();
+        final HeadsUpManager hum = createHeadsUpManager();
+        final NotificationEntry notifEntry = createEntry(/* id = */ 0);
 
-        mHeadsUpManager.showNotification(notifEntry);
-        assertFalse(mHeadsUpManager.canRemoveImmediately(notifEntry.getKey()));
+        hum.showNotification(notifEntry);
 
-        mHeadsUpManager.setUserActionMayIndirectlyRemove(notifEntry);
-        assertTrue(mHeadsUpManager.canRemoveImmediately(notifEntry.getKey()));
+        assertFalse(hum.canRemoveImmediately(notifEntry.getKey()));
+
+        hum.setUserActionMayIndirectlyRemove(notifEntry);
+
+        assertTrue(hum.canRemoveImmediately(notifEntry.getKey()));
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyguardStateControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyguardStateControllerTest.java
index 5cabcd4..cae892f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyguardStateControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyguardStateControllerTest.java
@@ -36,6 +36,7 @@
 import com.android.keyguard.logging.KeyguardUpdateMonitorLogger;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.dump.DumpManager;
+import com.android.systemui.flags.FeatureFlags;
 import com.android.systemui.keyguard.KeyguardUnlockAnimationController;
 
 import dagger.Lazy;
@@ -67,6 +68,8 @@
     private Lazy<KeyguardUnlockAnimationController> mKeyguardUnlockAnimationControllerLazy;
     @Mock
     private KeyguardUpdateMonitorLogger mLogger;
+    @Mock
+    private FeatureFlags mFeatureFlags;
 
     @Captor
     private ArgumentCaptor<KeyguardUpdateMonitorCallback> mUpdateCallbackCaptor;
@@ -80,7 +83,8 @@
                 mLockPatternUtils,
                 mKeyguardUnlockAnimationControllerLazy,
                 mLogger,
-                mDumpManager);
+                mDumpManager,
+                mFeatureFlags);
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
index ef39ff8..79feb41 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
@@ -82,7 +82,7 @@
 
 import org.junit.After;
 import org.junit.Before;
-import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
@@ -111,8 +111,8 @@
     private BlockingQueueIntentReceiver mReceiver;
     private final UiEventLoggerFake mUiEventLoggerFake = new UiEventLoggerFake();
 
-    @ClassRule
-    public static AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
+    @Rule
+    public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
 
     @Before
     public void setUp() throws Exception {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/VariableDateViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/VariableDateViewControllerTest.kt
index 871a48c..b78e839 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/VariableDateViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/VariableDateViewControllerTest.kt
@@ -19,11 +19,14 @@
 import android.os.Handler
 import android.testing.AndroidTestingRunner
 import android.testing.TestableLooper
+import android.view.View
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.broadcast.BroadcastDispatcher
+import com.android.systemui.shade.ShadeExpansionStateManager
 import com.android.systemui.util.mockito.any
 import com.android.systemui.util.mockito.capture
+import com.android.systemui.util.mockito.mock
 import com.android.systemui.util.time.FakeSystemClock
 import com.google.common.truth.Truth.assertThat
 import org.junit.Before
@@ -59,6 +62,7 @@
 
     private var lastText: String? = null
 
+    private lateinit var shadeExpansionStateManager: ShadeExpansionStateManager
     private lateinit var systemClock: FakeSystemClock
     private lateinit var testableLooper: TestableLooper
     private lateinit var testableHandler: Handler
@@ -76,6 +80,8 @@
         systemClock = FakeSystemClock()
         systemClock.setCurrentTimeMillis(TIME_STAMP)
 
+        shadeExpansionStateManager = ShadeExpansionStateManager()
+
         `when`(view.longerPattern).thenReturn(LONG_PATTERN)
         `when`(view.shorterPattern).thenReturn(SHORT_PATTERN)
         `when`(view.handler).thenReturn(testableHandler)
@@ -99,6 +105,8 @@
         controller = VariableDateViewController(
                 systemClock,
                 broadcastDispatcher,
+                shadeExpansionStateManager,
+                mock(),
                 testableHandler,
                 view
         )
@@ -121,7 +129,7 @@
 
     @Test
     fun testLotsOfSpaceUseLongText() {
-        onMeasureListenerCaptor.value.onMeasureAction(10000)
+        onMeasureListenerCaptor.value.onMeasureAction(10000, View.MeasureSpec.EXACTLY)
 
         testableLooper.processAllMessages()
         assertThat(lastText).isEqualTo(longText)
@@ -129,7 +137,7 @@
 
     @Test
     fun testSmallSpaceUseEmpty() {
-        onMeasureListenerCaptor.value.onMeasureAction(1)
+        onMeasureListenerCaptor.value.onMeasureAction(1, View.MeasureSpec.EXACTLY)
         testableLooper.processAllMessages()
 
         assertThat(lastText).isEmpty()
@@ -139,7 +147,7 @@
     fun testSpaceInBetweenUseShortText() {
         val average = ((getTextLength(longText) + getTextLength(shortText)) / 2).toInt()
 
-        onMeasureListenerCaptor.value.onMeasureAction(average)
+        onMeasureListenerCaptor.value.onMeasureAction(average, View.MeasureSpec.EXACTLY)
         testableLooper.processAllMessages()
 
         assertThat(lastText).isEqualTo(shortText)
@@ -147,10 +155,10 @@
 
     @Test
     fun testSwitchBackToLonger() {
-        onMeasureListenerCaptor.value.onMeasureAction(1)
+        onMeasureListenerCaptor.value.onMeasureAction(1, View.MeasureSpec.EXACTLY)
         testableLooper.processAllMessages()
 
-        onMeasureListenerCaptor.value.onMeasureAction(10000)
+        onMeasureListenerCaptor.value.onMeasureAction(10000, View.MeasureSpec.EXACTLY)
         testableLooper.processAllMessages()
 
         assertThat(lastText).isEqualTo(longText)
@@ -161,11 +169,41 @@
         `when`(view.freezeSwitching).thenReturn(true)
 
         val average = ((getTextLength(longText) + getTextLength(shortText)) / 2).toInt()
-        onMeasureListenerCaptor.value.onMeasureAction(average)
+        onMeasureListenerCaptor.value.onMeasureAction(average, View.MeasureSpec.EXACTLY)
         testableLooper.processAllMessages()
         assertThat(lastText).isEqualTo(longText)
 
-        onMeasureListenerCaptor.value.onMeasureAction(1)
+        onMeasureListenerCaptor.value.onMeasureAction(1, View.MeasureSpec.EXACTLY)
+        testableLooper.processAllMessages()
+        assertThat(lastText).isEqualTo(longText)
+    }
+
+    @Test
+    fun testQsExpansionTrue_ignoreAtMostMeasureRequests() {
+        shadeExpansionStateManager.onQsExpansionFractionChanged(0f)
+
+        onMeasureListenerCaptor.value.onMeasureAction(
+                getTextLength(shortText).toInt(),
+                View.MeasureSpec.EXACTLY
+            )
+        testableLooper.processAllMessages()
+
+        onMeasureListenerCaptor.value.onMeasureAction(10000, View.MeasureSpec.AT_MOST)
+        testableLooper.processAllMessages()
+        assertThat(lastText).isEqualTo(shortText)
+    }
+
+    @Test
+    fun testQsExpansionFalse_acceptAtMostMeasureRequests() {
+        shadeExpansionStateManager.onQsExpansionFractionChanged(1f)
+
+        onMeasureListenerCaptor.value.onMeasureAction(
+                getTextLength(shortText).toInt(),
+                View.MeasureSpec.EXACTLY
+        )
+        testableLooper.processAllMessages()
+
+        onMeasureListenerCaptor.value.onMeasureAction(10000, View.MeasureSpec.AT_MOST)
         testableLooper.processAllMessages()
         assertThat(lastText).isEqualTo(longText)
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/ListenerSetTest.kt b/packages/SystemUI/tests/src/com/android/systemui/util/ListenerSetTest.kt
index 2662da2..1404a4f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/ListenerSetTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/ListenerSetTest.kt
@@ -16,43 +16,128 @@
 
 package com.android.systemui.util
 
-import android.test.suitebuilder.annotation.SmallTest
-import androidx.test.runner.AndroidJUnit4
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
 import com.google.common.truth.Truth.assertThat
-import org.junit.Before
 import org.junit.Test
 import org.junit.runner.RunWith
 
 @SmallTest
 @RunWith(AndroidJUnit4::class)
-class ListenerSetTest : SysuiTestCase() {
+open class ListenerSetTest : SysuiTestCase() {
 
-    var runnableSet: ListenerSet<Runnable> = ListenerSet()
+    private val runnableSet: IListenerSet<Runnable> = makeRunnableListenerSet()
 
-    @Before
-    fun setup() {
-        runnableSet = ListenerSet()
-    }
+    open fun makeRunnableListenerSet(): IListenerSet<Runnable> = ListenerSet()
 
     @Test
     fun addIfAbsent_doesNotDoubleAdd() {
         // setup & preconditions
         val runnable1 = Runnable { }
         val runnable2 = Runnable { }
-        assertThat(runnableSet.toList()).isEmpty()
+        assertThat(runnableSet).isEmpty()
 
         // Test that an element can be added
         assertThat(runnableSet.addIfAbsent(runnable1)).isTrue()
-        assertThat(runnableSet.toList()).containsExactly(runnable1)
+        assertThat(runnableSet).containsExactly(runnable1)
 
         // Test that a second element can be added
         assertThat(runnableSet.addIfAbsent(runnable2)).isTrue()
-        assertThat(runnableSet.toList()).containsExactly(runnable1, runnable2)
+        assertThat(runnableSet).containsExactly(runnable1, runnable2)
 
         // Test that re-adding the first element does nothing and returns false
         assertThat(runnableSet.addIfAbsent(runnable1)).isFalse()
-        assertThat(runnableSet.toList()).containsExactly(runnable1, runnable2)
+        assertThat(runnableSet).containsExactly(runnable1, runnable2)
+    }
+
+    @Test
+    fun isEmpty_changes() {
+        val runnable = Runnable { }
+        assertThat(runnableSet).isEmpty()
+        assertThat(runnableSet.isEmpty()).isTrue()
+        assertThat(runnableSet.isNotEmpty()).isFalse()
+
+        assertThat(runnableSet.addIfAbsent(runnable)).isTrue()
+        assertThat(runnableSet).isNotEmpty()
+        assertThat(runnableSet.isEmpty()).isFalse()
+        assertThat(runnableSet.isNotEmpty()).isTrue()
+
+        assertThat(runnableSet.remove(runnable)).isTrue()
+        assertThat(runnableSet).isEmpty()
+        assertThat(runnableSet.isEmpty()).isTrue()
+        assertThat(runnableSet.isNotEmpty()).isFalse()
+    }
+
+    @Test
+    fun size_changes() {
+        assertThat(runnableSet).isEmpty()
+        assertThat(runnableSet.size).isEqualTo(0)
+
+        assertThat(runnableSet.addIfAbsent(Runnable { })).isTrue()
+        assertThat(runnableSet.size).isEqualTo(1)
+
+        assertThat(runnableSet.addIfAbsent(Runnable { })).isTrue()
+        assertThat(runnableSet.size).isEqualTo(2)
+    }
+
+    @Test
+    fun contains_worksAsExpected() {
+        val runnable1 = Runnable { }
+        val runnable2 = Runnable { }
+        assertThat(runnableSet).isEmpty()
+        assertThat(runnable1 in runnableSet).isFalse()
+        assertThat(runnable2 in runnableSet).isFalse()
+        assertThat(runnableSet).doesNotContain(runnable1)
+        assertThat(runnableSet).doesNotContain(runnable2)
+
+        assertThat(runnableSet.addIfAbsent(runnable1)).isTrue()
+        assertThat(runnable1 in runnableSet).isTrue()
+        assertThat(runnable2 in runnableSet).isFalse()
+        assertThat(runnableSet).contains(runnable1)
+        assertThat(runnableSet).doesNotContain(runnable2)
+
+        assertThat(runnableSet.addIfAbsent(runnable2)).isTrue()
+        assertThat(runnable1 in runnableSet).isTrue()
+        assertThat(runnable2 in runnableSet).isTrue()
+        assertThat(runnableSet).contains(runnable1)
+        assertThat(runnableSet).contains(runnable2)
+
+        assertThat(runnableSet.remove(runnable1)).isTrue()
+        assertThat(runnable1 in runnableSet).isFalse()
+        assertThat(runnable2 in runnableSet).isTrue()
+        assertThat(runnableSet).doesNotContain(runnable1)
+        assertThat(runnableSet).contains(runnable2)
+    }
+
+    @Test
+    fun containsAll_worksAsExpected() {
+        val runnable1 = Runnable { }
+        val runnable2 = Runnable { }
+
+        assertThat(runnableSet).isEmpty()
+        assertThat(runnableSet.containsAll(listOf())).isTrue()
+        assertThat(runnableSet.containsAll(listOf(runnable1))).isFalse()
+        assertThat(runnableSet.containsAll(listOf(runnable2))).isFalse()
+        assertThat(runnableSet.containsAll(listOf(runnable1, runnable2))).isFalse()
+
+        assertThat(runnableSet.addIfAbsent(runnable1)).isTrue()
+        assertThat(runnableSet.containsAll(listOf())).isTrue()
+        assertThat(runnableSet.containsAll(listOf(runnable1))).isTrue()
+        assertThat(runnableSet.containsAll(listOf(runnable2))).isFalse()
+        assertThat(runnableSet.containsAll(listOf(runnable1, runnable2))).isFalse()
+
+        assertThat(runnableSet.addIfAbsent(runnable2)).isTrue()
+        assertThat(runnableSet.containsAll(listOf())).isTrue()
+        assertThat(runnableSet.containsAll(listOf(runnable1))).isTrue()
+        assertThat(runnableSet.containsAll(listOf(runnable2))).isTrue()
+        assertThat(runnableSet.containsAll(listOf(runnable1, runnable2))).isTrue()
+
+        assertThat(runnableSet.remove(runnable1)).isTrue()
+        assertThat(runnableSet.containsAll(listOf())).isTrue()
+        assertThat(runnableSet.containsAll(listOf(runnable1))).isFalse()
+        assertThat(runnableSet.containsAll(listOf(runnable2))).isTrue()
+        assertThat(runnableSet.containsAll(listOf(runnable1, runnable2))).isFalse()
     }
 
     @Test
@@ -60,22 +145,22 @@
         // setup and preconditions
         val runnable1 = Runnable { }
         val runnable2 = Runnable { }
-        assertThat(runnableSet.toList()).isEmpty()
+        assertThat(runnableSet).isEmpty()
         runnableSet.addIfAbsent(runnable1)
         runnableSet.addIfAbsent(runnable2)
-        assertThat(runnableSet.toList()).containsExactly(runnable1, runnable2)
+        assertThat(runnableSet).containsExactly(runnable1, runnable2)
 
         // Test that removing the first runnable only removes that one runnable
         assertThat(runnableSet.remove(runnable1)).isTrue()
-        assertThat(runnableSet.toList()).containsExactly(runnable2)
+        assertThat(runnableSet).containsExactly(runnable2)
 
         // Test that removing a non-present runnable does not error
         assertThat(runnableSet.remove(runnable1)).isFalse()
-        assertThat(runnableSet.toList()).containsExactly(runnable2)
+        assertThat(runnableSet).containsExactly(runnable2)
 
         // Test that removing the other runnable succeeds
         assertThat(runnableSet.remove(runnable2)).isTrue()
-        assertThat(runnableSet.toList()).isEmpty()
+        assertThat(runnableSet).isEmpty()
     }
 
     @Test
@@ -92,17 +177,17 @@
         val runnable2 = Runnable {
             runnablesCalled.add(2)
         }
-        assertThat(runnableSet.toList()).isEmpty()
+        assertThat(runnableSet).isEmpty()
         runnableSet.addIfAbsent(runnable1)
         runnableSet.addIfAbsent(runnable2)
-        assertThat(runnableSet.toList()).containsExactly(runnable1, runnable2)
+        assertThat(runnableSet).containsExactly(runnable1, runnable2)
 
         // Test that both runnables are called and 1 was removed
         for (runnable in runnableSet) {
             runnable.run()
         }
         assertThat(runnablesCalled).containsExactly(1, 2)
-        assertThat(runnableSet.toList()).containsExactly(runnable2)
+        assertThat(runnableSet).containsExactly(runnable2)
     }
 
     @Test
@@ -120,16 +205,16 @@
         val runnable2 = Runnable {
             runnablesCalled.add(2)
         }
-        assertThat(runnableSet.toList()).isEmpty()
+        assertThat(runnableSet).isEmpty()
         runnableSet.addIfAbsent(runnable1)
         runnableSet.addIfAbsent(runnable2)
-        assertThat(runnableSet.toList()).containsExactly(runnable1, runnable2)
+        assertThat(runnableSet).containsExactly(runnable1, runnable2)
 
         // Test that both original runnables are called and 99 was added but not called
         for (runnable in runnableSet) {
             runnable.run()
         }
         assertThat(runnablesCalled).containsExactly(1, 2)
-        assertThat(runnableSet.toList()).containsExactly(runnable1, runnable2, runnable99)
+        assertThat(runnableSet).containsExactly(runnable1, runnable2, runnable99)
     }
 }
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/NamedListenerSetTest.kt b/packages/SystemUI/tests/src/com/android/systemui/util/NamedListenerSetTest.kt
new file mode 100644
index 0000000..c89e317
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/NamedListenerSetTest.kt
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class NamedListenerSetTest : ListenerSetTest() {
+    override fun makeRunnableListenerSet(): IListenerSet<Runnable> = NamedListenerSet()
+
+    private val runnableSet = NamedListenerSet(NamedRunnable::name)
+
+    class NamedRunnable(val name: String, private val block: () -> Unit = {}) : Runnable {
+        override fun run() = block()
+    }
+
+    @Test
+    fun addIfAbsent_addsMultipleWithSameName_onlyIfInstanceIsAbsent() {
+        // setup & preconditions
+        val runnable1 = NamedRunnable("A")
+        val runnable2 = NamedRunnable("A")
+        assertThat(runnableSet).isEmpty()
+
+        // Test that an element can be added
+        assertThat(runnableSet.addIfAbsent(runnable1)).isTrue()
+        assertThat(runnableSet).containsExactly(runnable1)
+
+        // Test that a second element can be added, even with the same name
+        assertThat(runnableSet.addIfAbsent(runnable2)).isTrue()
+        assertThat(runnableSet).containsExactly(runnable1, runnable2)
+
+        // Test that re-adding the first element does nothing and returns false
+        assertThat(runnableSet.addIfAbsent(runnable1)).isFalse()
+        assertThat(runnableSet).containsExactly(runnable1, runnable2)
+    }
+
+    @Test
+    fun forEachNamed_includesCorrectNames() {
+        val runnable1 = NamedRunnable("A")
+        val runnable2 = NamedRunnable("X")
+        val runnable3 = NamedRunnable("X")
+        assertThat(runnableSet).isEmpty()
+
+        assertThat(runnableSet.addIfAbsent(runnable1)).isTrue()
+        assertThat(runnableSet.toNamedPairs())
+            .containsExactly(
+                "A" to runnable1,
+            )
+
+        assertThat(runnableSet.addIfAbsent(runnable2)).isTrue()
+        assertThat(runnableSet.toNamedPairs())
+            .containsExactly(
+                "A" to runnable1,
+                "X" to runnable2,
+            )
+
+        assertThat(runnableSet.addIfAbsent(runnable3)).isTrue()
+        assertThat(runnableSet.toNamedPairs())
+            .containsExactly(
+                "A" to runnable1,
+                "X" to runnable2,
+                "X" to runnable3,
+            )
+
+        assertThat(runnableSet.remove(runnable1)).isTrue()
+        assertThat(runnableSet.toNamedPairs())
+            .containsExactly(
+                "X" to runnable2,
+                "X" to runnable3,
+            )
+
+        assertThat(runnableSet.remove(runnable2)).isTrue()
+        assertThat(runnableSet.toNamedPairs())
+            .containsExactly(
+                "X" to runnable3,
+            )
+    }
+
+    /**
+     * This private method uses [NamedListenerSet.forEachNamed] to produce a list of pairs in order
+     * to validate that method.
+     */
+    private fun <T : Any> NamedListenerSet<T>.toNamedPairs() =
+        sequence { forEachNamed { name, listener -> yield(name to listener) } }.toList()
+}
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 462fd0a..69d7586 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogControllerImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogControllerImplTest.java
@@ -104,8 +104,6 @@
     private UserTracker mUserTracker;
     @Mock
     private DumpManager mDumpManager;
-    @Mock
-    private Handler mHandler;
 
 
     @Before
@@ -130,7 +128,7 @@
                 mBroadcastDispatcher, mRingerModeTracker, mThreadFactory, mAudioManager,
                 mNotificationManager, mVibrator, mIAudioService, mAccessibilityManager,
                 mPackageManager, mWakefullnessLifcycle, mKeyguardManager,
-                mActivityManager, mUserTracker, mDumpManager, mHandler, mCallback);
+                mActivityManager, mUserTracker, mDumpManager, mCallback);
         mVolumeController.setEnableDialogs(true, true);
     }
 
@@ -245,12 +243,11 @@
                 ActivityManager activityManager,
                 UserTracker userTracker,
                 DumpManager dumpManager,
-                Handler mainHandler,
                 C callback) {
             super(context, broadcastDispatcher, ringerModeTracker, theadFactory, audioManager,
                     notificationManager, optionalVibrator, iAudioService, accessibilityManager,
                     packageManager, wakefulnessLifecycle, keyguardManager,
-                    activityManager, userTracker, dumpManager, mainHandler);
+                    activityManager, userTracker, dumpManager);
             mCallbacks = callback;
 
             ArgumentCaptor<WakefulnessLifecycle.Observer> observerCaptor =
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
index fa18e57..5f0011b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
@@ -31,6 +31,7 @@
 
 import static org.junit.Assume.assumeNotNull;
 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.reset;
@@ -38,7 +39,6 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.animation.AnimatorTestRule;
 import android.app.KeyguardManager;
 import android.content.res.Configuration;
 import android.media.AudioManager;
@@ -85,14 +85,14 @@
 @RunWith(AndroidTestingRunner.class)
 @TestableLooper.RunWithLooper
 public class VolumeDialogImplTest extends SysuiTestCase {
-    private static final AnimatorTestRule sAnimatorTestRule = new AnimatorTestRule();
-
     VolumeDialogImpl mDialog;
     View mActiveRinger;
     View mDrawerContainer;
     View mDrawerVibrate;
     View mDrawerMute;
     View mDrawerNormal;
+    CaptionsToggleImageButton mODICaptionsIcon;
+
     private TestableLooper mTestableLooper;
     private ConfigurationController mConfigurationController;
     private int mOriginalOrientation;
@@ -177,9 +177,14 @@
         mActiveRinger = mDialog.getDialogView().findViewById(
                 R.id.volume_new_ringer_active_icon_container);
         mDrawerContainer = mDialog.getDialogView().findViewById(R.id.volume_drawer_container);
-        mDrawerVibrate = mDrawerContainer.findViewById(R.id.volume_drawer_vibrate);
-        mDrawerMute = mDrawerContainer.findViewById(R.id.volume_drawer_mute);
-        mDrawerNormal = mDrawerContainer.findViewById(R.id.volume_drawer_normal);
+
+        // Drawer is not always available, e.g. on TVs
+        if (mDrawerContainer != null) {
+            mDrawerVibrate = mDrawerContainer.findViewById(R.id.volume_drawer_vibrate);
+            mDrawerMute = mDrawerContainer.findViewById(R.id.volume_drawer_mute);
+            mDrawerNormal = mDrawerContainer.findViewById(R.id.volume_drawer_normal);
+        }
+        mODICaptionsIcon = mDialog.getDialogView().findViewById(R.id.odi_captions_icon);
 
         Prefs.putInt(mContext,
                 Prefs.Key.SEEN_RINGER_GUIDANCE_COUNT,
@@ -188,6 +193,10 @@
         Prefs.putBoolean(mContext, Prefs.Key.HAS_SEEN_ODI_CAPTIONS_TOOLTIP, false);
     }
 
+    private void assumeHasDrawer() {
+        assumeNotNull("Layout does not contain drawer", mDrawerContainer);
+    }
+
     private State createShellState() {
         State state = new VolumeDialogController.State();
         for (int i = AudioManager.STREAM_VOICE_CALL; i <= AudioManager.STREAM_ACCESSIBILITY; i++) {
@@ -359,6 +368,8 @@
 
     @Test
     public void testSelectVibrateFromDrawer() {
+        assumeHasDrawer();
+
         mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, false);
         final State initialUnsetState = new State();
         initialUnsetState.ringerModeInternal = AudioManager.RINGER_MODE_NORMAL;
@@ -374,6 +385,8 @@
 
     @Test
     public void testSelectVibrateFromDrawer_OnewayAPI_On() {
+        assumeHasDrawer();
+
         mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, true);
         final State initialUnsetState = new State();
         initialUnsetState.ringerModeInternal = RINGER_MODE_NORMAL;
@@ -389,6 +402,8 @@
 
     @Test
     public void testSelectMuteFromDrawer() {
+        assumeHasDrawer();
+
         mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, false);
         final State initialUnsetState = new State();
         initialUnsetState.ringerModeInternal = AudioManager.RINGER_MODE_NORMAL;
@@ -404,6 +419,8 @@
 
     @Test
     public void testSelectMuteFromDrawer_OnewayAPI_On() {
+        assumeHasDrawer();
+
         mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, true);
         final State initialUnsetState = new State();
         initialUnsetState.ringerModeInternal = RINGER_MODE_NORMAL;
@@ -419,6 +436,8 @@
 
     @Test
     public void testSelectNormalFromDrawer() {
+        assumeHasDrawer();
+
         mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, false);
         final State initialUnsetState = new State();
         initialUnsetState.ringerModeInternal = AudioManager.RINGER_MODE_VIBRATE;
@@ -434,6 +453,8 @@
 
     @Test
     public void testSelectNormalFromDrawer_OnewayAPI_On() {
+        assumeHasDrawer();
+
         mFeatureFlags.set(ONE_WAY_HAPTICS_API_MIGRATION, true);
         final State initialUnsetState = new State();
         initialUnsetState.ringerModeInternal = AudioManager.RINGER_MODE_VIBRATE;
@@ -688,6 +709,28 @@
         assertRingerContainerDescribesItsState(RINGER_MODE_VIBRATE, RingerDrawerState.CLOSE);
     }
 
+    @Test
+    public void testOnCaptionEnabledStateChanged_checkBeforeSwitchTrue_setCaptionsEnabledState() {
+        ArgumentCaptor<VolumeDialogController.Callbacks> controllerCallbackCapture =
+                ArgumentCaptor.forClass(VolumeDialogController.Callbacks.class);
+        verify(mVolumeDialogController).addCallback(controllerCallbackCapture.capture(), any());
+        VolumeDialogController.Callbacks callbacks = controllerCallbackCapture.getValue();
+
+        callbacks.onCaptionEnabledStateChanged(true, true);
+        verify(mVolumeDialogController).setCaptionsEnabledState(eq(false));
+    }
+
+    @Test
+    public void testOnCaptionEnabledStateChanged_checkBeforeSwitchFalse_getCaptionsEnabledTrue() {
+        ArgumentCaptor<VolumeDialogController.Callbacks> controllerCallbackCapture =
+                ArgumentCaptor.forClass(VolumeDialogController.Callbacks.class);
+        verify(mVolumeDialogController).addCallback(controllerCallbackCapture.capture(), any());
+        VolumeDialogController.Callbacks callbacks = controllerCallbackCapture.getValue();
+
+        callbacks.onCaptionEnabledStateChanged(true, false);
+        assertTrue(mODICaptionsIcon.getCaptionsEnabled());
+    }
+
     /**
      * The content description should include ringer state, and the correct one.
      */
@@ -727,7 +770,6 @@
     public void teardown() {
         cleanUp(mDialog);
         setOrientation(mOriginalOrientation);
-        sAnimatorTestRule.advanceTimeBy(mLongestHideShowAnimationDuration);
         mTestableLooper.moveTimeForward(mLongestHideShowAnimationDuration);
         mTestableLooper.processAllMessages();
         reset(mPostureController);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/wallpapers/WallpaperLocalColorExtractorTest.java b/packages/SystemUI/tests/src/com/android/systemui/wallpapers/WallpaperLocalColorExtractorTest.java
index fc5f782..1125d41 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/wallpapers/WallpaperLocalColorExtractorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/wallpapers/WallpaperLocalColorExtractorTest.java
@@ -109,6 +109,7 @@
 
         WallpaperLocalColorExtractor colorExtractor = new WallpaperLocalColorExtractor(
                 mBackgroundExecutor,
+                new Object(),
                 new WallpaperLocalColorExtractor.WallpaperLocalColorExtractorCallback() {
                     @Override
                     public void onColorsProcessed(List<RectF> regions,
diff --git a/packages/SystemUI/tests/utils/src/android/animation/AnimatorTestRule.java b/packages/SystemUI/tests/utils/src/android/animation/AnimatorTestRule.java
index 19c68e8..41dbc14 100644
--- a/packages/SystemUI/tests/utils/src/android/animation/AnimatorTestRule.java
+++ b/packages/SystemUI/tests/utils/src/android/animation/AnimatorTestRule.java
@@ -49,7 +49,7 @@
  * public class SampleAnimatorTest {
  *
  *     {@literal @}Rule
- *     public AnimatorTestRule sAnimatorTestRule = new AnimatorTestRule();
+ *     public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
  *
  *     {@literal @}UiThreadTest
  *     {@literal @}Test
@@ -58,7 +58,7 @@
  *         animator.setDuration(1000L);
  *         assertThat(animator.getAnimatedValue(), is(0));
  *         animator.start();
- *         sAnimatorTestRule.advanceTimeBy(500L);
+ *         mAnimatorTestRule.advanceTimeBy(500L);
  *         assertThat(animator.getAnimatedValue(), is(500));
  *     }
  * }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/authentication/data/repository/FakeAuthenticationRepository.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/authentication/data/repository/FakeAuthenticationRepository.kt
index c2e1ac7..7c98df6 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/authentication/data/repository/FakeAuthenticationRepository.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/authentication/data/repository/FakeAuthenticationRepository.kt
@@ -20,7 +20,8 @@
 import com.android.internal.widget.LockPatternView
 import com.android.internal.widget.LockscreenCredential
 import com.android.keyguard.KeyguardSecurityModel.SecurityMode
-import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel
+import com.android.systemui.authentication.shared.model.AuthenticationPatternCoordinate
 import com.android.systemui.authentication.shared.model.AuthenticationResultModel
 import com.android.systemui.authentication.shared.model.AuthenticationThrottlingModel
 import kotlinx.coroutines.flow.MutableStateFlow
@@ -47,7 +48,7 @@
 
     private val _authenticationMethod =
         MutableStateFlow<AuthenticationMethodModel>(DEFAULT_AUTHENTICATION_METHOD)
-    val authenticationMethod: StateFlow<AuthenticationMethodModel> =
+    override val authenticationMethod: StateFlow<AuthenticationMethodModel> =
         _authenticationMethod.asStateFlow()
 
     private var isLockscreenEnabled = true
@@ -154,13 +155,13 @@
         val DEFAULT_AUTHENTICATION_METHOD = AuthenticationMethodModel.Pin
         val PATTERN =
             listOf(
-                AuthenticationMethodModel.Pattern.PatternCoordinate(2, 0),
-                AuthenticationMethodModel.Pattern.PatternCoordinate(2, 1),
-                AuthenticationMethodModel.Pattern.PatternCoordinate(2, 2),
-                AuthenticationMethodModel.Pattern.PatternCoordinate(1, 1),
-                AuthenticationMethodModel.Pattern.PatternCoordinate(0, 0),
-                AuthenticationMethodModel.Pattern.PatternCoordinate(0, 1),
-                AuthenticationMethodModel.Pattern.PatternCoordinate(0, 2),
+                AuthenticationPatternCoordinate(2, 0),
+                AuthenticationPatternCoordinate(2, 1),
+                AuthenticationPatternCoordinate(2, 2),
+                AuthenticationPatternCoordinate(1, 1),
+                AuthenticationPatternCoordinate(0, 0),
+                AuthenticationPatternCoordinate(0, 1),
+                AuthenticationPatternCoordinate(0, 2),
             )
         const val MAX_FAILED_AUTH_TRIES_BEFORE_THROTTLING = 5
         const val THROTTLE_DURATION_MS = 30000
@@ -172,7 +173,6 @@
                 is AuthenticationMethodModel.Pin -> SecurityMode.PIN
                 is AuthenticationMethodModel.Password -> SecurityMode.Password
                 is AuthenticationMethodModel.Pattern -> SecurityMode.Pattern
-                is AuthenticationMethodModel.Swipe,
                 is AuthenticationMethodModel.None -> SecurityMode.None
             }
         }
@@ -208,8 +208,7 @@
             }
         }
 
-        private fun List<AuthenticationMethodModel.Pattern.PatternCoordinate>.toCells():
-            List<LockPatternView.Cell> {
+        private fun List<AuthenticationPatternCoordinate>.toCells(): List<LockPatternView.Cell> {
             return map { coordinate -> LockPatternView.Cell.of(coordinate.y, coordinate.x) }
         }
     }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/communal/data/repository/FakeCommunalWidgetRepository.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/communal/data/repository/FakeCommunalWidgetRepository.kt
new file mode 100644
index 0000000..1a8c583
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/communal/data/repository/FakeCommunalWidgetRepository.kt
@@ -0,0 +1,15 @@
+package com.android.systemui.communal.data.repository
+
+import com.android.systemui.communal.shared.CommunalAppWidgetInfo
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+
+/** Fake implementation of [CommunalWidgetRepository] */
+class FakeCommunalWidgetRepository : CommunalWidgetRepository {
+    private val _stopwatchAppWidgetInfo = MutableStateFlow<CommunalAppWidgetInfo?>(null)
+    override val stopwatchAppWidgetInfo: Flow<CommunalAppWidgetInfo?> = _stopwatchAppWidgetInfo
+
+    fun setStopwatchAppWidgetInfo(appWidgetInfo: CommunalAppWidgetInfo) {
+        _stopwatchAppWidgetInfo.value = appWidgetInfo
+    }
+}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/flags/FakeFeatureFlags.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/flags/FakeFeatureFlags.kt
index 36fa7e6..013dbb4 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/flags/FakeFeatureFlags.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/flags/FakeFeatureFlags.kt
@@ -19,45 +19,45 @@
 import java.io.PrintWriter
 
 class FakeFeatureFlags : FeatureFlags {
-    private val booleanFlags = mutableMapOf<Int, Boolean>()
-    private val stringFlags = mutableMapOf<Int, String>()
-    private val intFlags = mutableMapOf<Int, Int>()
-    private val knownFlagNames = mutableMapOf<Int, String>()
-    private val flagListeners = mutableMapOf<Int, MutableSet<FlagListenable.Listener>>()
-    private val listenerFlagIds = mutableMapOf<FlagListenable.Listener, MutableSet<Int>>()
+    private val booleanFlags = mutableMapOf<String, Boolean>()
+    private val stringFlags = mutableMapOf<String, String>()
+    private val intFlags = mutableMapOf<String, Int>()
+    private val knownFlagNames = mutableMapOf<String, String>()
+    private val flagListeners = mutableMapOf<String, MutableSet<FlagListenable.Listener>>()
+    private val listenerflagNames = mutableMapOf<FlagListenable.Listener, MutableSet<String>>()
 
     init {
         FlagsFactory.knownFlags.forEach { entry: Map.Entry<String, Flag<*>> ->
-            knownFlagNames[entry.value.id] = entry.key
+            knownFlagNames[entry.value.name] = entry.key
         }
     }
 
     fun set(flag: BooleanFlag, value: Boolean) {
-        if (booleanFlags.put(flag.id, value)?.let { value != it } != false) {
+        if (booleanFlags.put(flag.name, value)?.let { value != it } != false) {
             notifyFlagChanged(flag)
         }
     }
 
     fun set(flag: ResourceBooleanFlag, value: Boolean) {
-        if (booleanFlags.put(flag.id, value)?.let { value != it } != false) {
+        if (booleanFlags.put(flag.name, value)?.let { value != it } != false) {
             notifyFlagChanged(flag)
         }
     }
 
     fun set(flag: SysPropBooleanFlag, value: Boolean) {
-        if (booleanFlags.put(flag.id, value)?.let { value != it } != false) {
+        if (booleanFlags.put(flag.name, value)?.let { value != it } != false) {
             notifyFlagChanged(flag)
         }
     }
 
     fun set(flag: StringFlag, value: String) {
-        if (stringFlags.put(flag.id, value)?.let { value != it } == null) {
+        if (stringFlags.put(flag.name, value)?.let { value != it } == null) {
             notifyFlagChanged(flag)
         }
     }
 
     fun set(flag: ResourceStringFlag, value: String) {
-        if (stringFlags.put(flag.id, value)?.let { value != it } == null) {
+        if (stringFlags.put(flag.name, value)?.let { value != it } == null) {
             notifyFlagChanged(flag)
         }
     }
@@ -73,7 +73,7 @@
      *  and the flag value *does* matter, you'll notice when the flag is flipped and tests
      *  start failing.
      */
-    fun setDefault(flag: BooleanFlag) = booleanFlags.putIfAbsent(flag.id, flag.default)
+    fun setDefault(flag: BooleanFlag) = booleanFlags.putIfAbsent(flag.name, flag.default)
 
     /**
      * Set the given flag's default value if no other value has been set.
@@ -86,10 +86,10 @@
      *  and the flag value *does* matter, you'll notice when the flag is flipped and tests
      *  start failing.
      */
-    fun setDefault(flag: SysPropBooleanFlag) = booleanFlags.putIfAbsent(flag.id, flag.default)
+    fun setDefault(flag: SysPropBooleanFlag) = booleanFlags.putIfAbsent(flag.name, flag.default)
 
     private fun notifyFlagChanged(flag: Flag<*>) {
-        flagListeners[flag.id]?.let { listeners ->
+        flagListeners[flag.name]?.let { listeners ->
             listeners.forEach { listener ->
                 listener.onFlagChanged(
                     object : FlagListenable.FlagEvent {
@@ -101,30 +101,30 @@
         }
     }
 
-    override fun isEnabled(flag: UnreleasedFlag): Boolean = requireBooleanValue(flag.id)
+    override fun isEnabled(flag: UnreleasedFlag): Boolean = requireBooleanValue(flag.name)
 
-    override fun isEnabled(flag: ReleasedFlag): Boolean = requireBooleanValue(flag.id)
+    override fun isEnabled(flag: ReleasedFlag): Boolean = requireBooleanValue(flag.name)
 
-    override fun isEnabled(flag: ResourceBooleanFlag): Boolean = requireBooleanValue(flag.id)
+    override fun isEnabled(flag: ResourceBooleanFlag): Boolean = requireBooleanValue(flag.name)
 
-    override fun isEnabled(flag: SysPropBooleanFlag): Boolean = requireBooleanValue(flag.id)
+    override fun isEnabled(flag: SysPropBooleanFlag): Boolean = requireBooleanValue(flag.name)
 
-    override fun getString(flag: StringFlag): String = requireStringValue(flag.id)
+    override fun getString(flag: StringFlag): String = requireStringValue(flag.name)
 
-    override fun getString(flag: ResourceStringFlag): String = requireStringValue(flag.id)
+    override fun getString(flag: ResourceStringFlag): String = requireStringValue(flag.name)
 
-    override fun getInt(flag: IntFlag): Int = requireIntValue(flag.id)
+    override fun getInt(flag: IntFlag): Int = requireIntValue(flag.name)
 
-    override fun getInt(flag: ResourceIntFlag): Int = requireIntValue(flag.id)
+    override fun getInt(flag: ResourceIntFlag): Int = requireIntValue(flag.name)
 
     override fun addListener(flag: Flag<*>, listener: FlagListenable.Listener) {
-        flagListeners.getOrPut(flag.id) { mutableSetOf() }.add(listener)
-        listenerFlagIds.getOrPut(listener) { mutableSetOf() }.add(flag.id)
+        flagListeners.getOrPut(flag.name) { mutableSetOf() }.add(listener)
+        listenerflagNames.getOrPut(listener) { mutableSetOf() }.add(flag.name)
     }
 
     override fun removeListener(listener: FlagListenable.Listener) {
-        listenerFlagIds.remove(listener)?.let {
-                flagIds -> flagIds.forEach {
+        listenerflagNames.remove(listener)?.let {
+                flagNames -> flagNames.forEach {
                         id -> flagListeners[id]?.remove(listener)
                 }
         }
@@ -134,22 +134,22 @@
         // no-op
     }
 
-    private fun flagName(flagId: Int): String {
-        return knownFlagNames[flagId] ?: "UNKNOWN(id=$flagId)"
+    private fun flagName(flagName: String): String {
+        return knownFlagNames[flagName] ?: "UNKNOWN($flagName)"
     }
 
-    private fun requireBooleanValue(flagId: Int): Boolean {
-        return booleanFlags[flagId]
-            ?: error("Flag ${flagName(flagId)} was accessed as boolean but not specified.")
+    private fun requireBooleanValue(flagName: String): Boolean {
+        return booleanFlags[flagName]
+            ?: error("Flag ${flagName(flagName)} was accessed as boolean but not specified.")
     }
 
-    private fun requireStringValue(flagId: Int): String {
-        return stringFlags[flagId]
-            ?: error("Flag ${flagName(flagId)} was accessed as string but not specified.")
+    private fun requireStringValue(flagName: String): String {
+        return stringFlags[flagName]
+            ?: error("Flag ${flagName(flagName)} was accessed as string but not specified.")
     }
 
-    private fun requireIntValue(flagId: Int): Int {
-        return intFlags[flagId]
-            ?: error("Flag ${flagName(flagId)} was accessed as int but not specified.")
+    private fun requireIntValue(flagName: String): Int {
+        return intFlags[flagName]
+            ?: error("Flag ${flagName(flagName)} was accessed as int but not specified.")
     }
 }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/FakeBiometricSettingsRepository.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/FakeBiometricSettingsRepository.kt
index 8c98aea..e91e955 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/FakeBiometricSettingsRepository.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/FakeBiometricSettingsRepository.kt
@@ -22,32 +22,24 @@
 import kotlinx.coroutines.flow.Flow
 import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.StateFlow
-import kotlinx.coroutines.flow.asStateFlow
 import kotlinx.coroutines.flow.map
 
 class FakeBiometricSettingsRepository : BiometricSettingsRepository {
+    private val _isFingerprintEnrolledAndEnabled = MutableStateFlow(false)
+    override val isFingerprintEnrolledAndEnabled: StateFlow<Boolean>
+        get() = _isFingerprintEnrolledAndEnabled
 
-    private val _isFingerprintEnrolled = MutableStateFlow<Boolean>(false)
-    override val isFingerprintEnrolled: StateFlow<Boolean> = _isFingerprintEnrolled.asStateFlow()
+    private val _isFingerprintAuthCurrentlyAllowed = MutableStateFlow(false)
+    override val isFingerprintAuthCurrentlyAllowed: StateFlow<Boolean>
+        get() = _isFingerprintAuthCurrentlyAllowed
 
-    private val _isFaceEnrolled = MutableStateFlow(false)
-    override val isFaceEnrolled: Flow<Boolean>
-        get() = _isFaceEnrolled
+    private val _isFaceAuthEnrolledAndEnabled = MutableStateFlow(false)
+    override val isFaceAuthEnrolledAndEnabled: Flow<Boolean>
+        get() = _isFaceAuthEnrolledAndEnabled
 
-    private val _isFaceAuthEnabled = MutableStateFlow(false)
-    override val isFaceAuthenticationEnabled: Flow<Boolean>
-        get() = _isFaceAuthEnabled
-
-    private val _isStrongBiometricAllowed = MutableStateFlow(false)
-    override val isStrongBiometricAllowed = _isStrongBiometricAllowed.asStateFlow()
-
-    private val _isNonStrongBiometricAllowed = MutableStateFlow(false)
-    override val isNonStrongBiometricAllowed: StateFlow<Boolean>
-        get() = _isNonStrongBiometricAllowed
-
-    private val _isFingerprintEnabledByDevicePolicy = MutableStateFlow(false)
-    override val isFingerprintEnabledByDevicePolicy =
-        _isFingerprintEnabledByDevicePolicy.asStateFlow()
+    private val _isFaceAuthCurrentlyAllowed = MutableStateFlow(false)
+    override val isFaceAuthCurrentlyAllowed: Flow<Boolean>
+        get() = _isFaceAuthCurrentlyAllowed
 
     private val _isFaceAuthSupportedInCurrentPosture = MutableStateFlow(false)
     override val isFaceAuthSupportedInCurrentPosture: Flow<Boolean>
@@ -59,34 +51,33 @@
     private val _authFlags = MutableStateFlow(AuthenticationFlags(0, 0))
     override val authenticationFlags: Flow<AuthenticationFlags>
         get() = _authFlags
-    fun setFingerprintEnrolled(isFingerprintEnrolled: Boolean) {
-        _isFingerprintEnrolled.value = isFingerprintEnrolled
-    }
-
-    fun setStrongBiometricAllowed(isStrongBiometricAllowed: Boolean) {
-        _isStrongBiometricAllowed.value = isStrongBiometricAllowed
-    }
-
-    fun setFingerprintEnabledByDevicePolicy(isFingerprintEnabledByDevicePolicy: Boolean) {
-        _isFingerprintEnabledByDevicePolicy.value = isFingerprintEnabledByDevicePolicy
-    }
 
     fun setAuthenticationFlags(value: AuthenticationFlags) {
         _authFlags.value = value
     }
 
-    fun setFaceEnrolled(isFaceEnrolled: Boolean) {
-        _isFaceEnrolled.value = isFaceEnrolled
+    fun setIsFingerprintAuthEnrolledAndEnabled(value: Boolean) {
+        _isFingerprintEnrolledAndEnabled.value = value
+        _isFingerprintAuthCurrentlyAllowed.value = _isFingerprintAuthCurrentlyAllowed.value && value
+    }
+
+    fun setIsFingerprintAuthCurrentlyAllowed(value: Boolean) {
+        _isFingerprintAuthCurrentlyAllowed.value = value
+    }
+
+    fun setIsFaceAuthEnrolledAndEnabled(value: Boolean) {
+        _isFaceAuthEnrolledAndEnabled.value = value
+        _isFaceAuthCurrentlyAllowed.value = _isFaceAuthCurrentlyAllowed.value && value
+    }
+
+    fun setIsFaceAuthCurrentlyAllowed(value: Boolean) {
+        _isFaceAuthCurrentlyAllowed.value = value
     }
 
     fun setIsFaceAuthSupportedInCurrentPosture(value: Boolean) {
         _isFaceAuthSupportedInCurrentPosture.value = value
     }
 
-    fun setIsFaceAuthEnabled(enabled: Boolean) {
-        _isFaceAuthEnabled.value = enabled
-    }
-
     fun setIsUserInLockdown(value: Boolean) {
         if (value) {
             setAuthenticationFlags(
@@ -105,12 +96,4 @@
             )
         }
     }
-
-    fun setIsNonStrongBiometricAllowed(value: Boolean) {
-        _isNonStrongBiometricAllowed.value = value
-    }
-
-    fun setIsStrongBiometricAllowed(value: Boolean) {
-        _isStrongBiometricAllowed.value = value
-    }
 }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/FakeKeyguardRepository.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/FakeKeyguardRepository.kt
index 15ce055..faebcaa 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/FakeKeyguardRepository.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/FakeKeyguardRepository.kt
@@ -146,7 +146,6 @@
         _animateBottomAreaDozingTransitions.tryEmit(animate)
     }
 
-
     @Deprecated("Deprecated as part of b/278057014")
     override fun setBottomAreaAlpha(alpha: Float) {
         _bottomAreaAlpha.value = alpha
@@ -257,8 +256,11 @@
         goingToFullShade: Boolean,
         occlusionTransitionRunning: Boolean
     ) {
-        _keyguardRootViewVisibility.value = KeyguardRootViewVisibilityState(
-            statusBarState, goingToFullShade, occlusionTransitionRunning
-        )
+        _keyguardRootViewVisibility.value =
+            KeyguardRootViewVisibilityState(
+                statusBarState,
+                goingToFullShade,
+                occlusionTransitionRunning
+            )
     }
 }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/FakeKeyguardSurfaceBehindRepository.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/FakeKeyguardSurfaceBehindRepository.kt
new file mode 100644
index 0000000..823f29a
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/data/repository/FakeKeyguardSurfaceBehindRepository.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.keyguard.data.repository
+
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+class FakeKeyguardSurfaceBehindRepository : KeyguardSurfaceBehindRepository {
+    private val _isAnimatingSurface = MutableStateFlow(false)
+    override val isAnimatingSurface = _isAnimatingSurface.asStateFlow()
+
+    override fun setAnimatingSurface(animating: Boolean) {
+        _isAnimatingSurface.value = animating
+    }
+}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractorFactory.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractorFactory.kt
index 312ade5..23faaf3 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractorFactory.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/domain/interactor/KeyguardTransitionInteractorFactory.kt
@@ -18,6 +18,8 @@
 
 import com.android.systemui.keyguard.data.repository.FakeKeyguardTransitionRepository
 import com.android.systemui.keyguard.data.repository.KeyguardTransitionRepository
+import com.android.systemui.util.mockito.mock
+import dagger.Lazy
 import kotlinx.coroutines.CoroutineScope
 
 /**
@@ -30,18 +32,36 @@
     fun create(
         scope: CoroutineScope,
         repository: KeyguardTransitionRepository = FakeKeyguardTransitionRepository(),
+        keyguardInteractor: KeyguardInteractor =
+            KeyguardInteractorFactory.create().keyguardInteractor,
+        fromLockscreenTransitionInteractor: Lazy<FromLockscreenTransitionInteractor> = Lazy {
+            mock<FromLockscreenTransitionInteractor>()
+        },
+        fromPrimaryBouncerTransitionInteractor: Lazy<FromPrimaryBouncerTransitionInteractor> =
+            Lazy {
+                mock<FromPrimaryBouncerTransitionInteractor>()
+            },
     ): WithDependencies {
         return WithDependencies(
             repository = repository,
+            keyguardInteractor = keyguardInteractor,
+            fromLockscreenTransitionInteractor = fromLockscreenTransitionInteractor,
+            fromPrimaryBouncerTransitionInteractor = fromPrimaryBouncerTransitionInteractor,
             KeyguardTransitionInteractor(
                 scope = scope,
                 repository = repository,
+                keyguardInteractor = { keyguardInteractor },
+                fromLockscreenTransitionInteractor = fromLockscreenTransitionInteractor,
+                fromPrimaryBouncerTransitionInteractor = fromPrimaryBouncerTransitionInteractor,
             )
         )
     }
 
     data class WithDependencies(
         val repository: KeyguardTransitionRepository,
+        val keyguardInteractor: KeyguardInteractor,
+        val fromLockscreenTransitionInteractor: Lazy<FromLockscreenTransitionInteractor>,
+        val fromPrimaryBouncerTransitionInteractor: Lazy<FromPrimaryBouncerTransitionInteractor>,
         val keyguardTransitionInteractor: KeyguardTransitionInteractor,
     )
 }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/scene/SceneTestUtils.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/scene/SceneTestUtils.kt
index 6cffb66..f0e1111 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/scene/SceneTestUtils.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/scene/SceneTestUtils.kt
@@ -18,9 +18,11 @@
 
 import android.content.pm.UserInfo
 import com.android.systemui.SysuiTestCase
+import com.android.systemui.authentication.data.model.AuthenticationMethodModel as DataLayerAuthenticationMethodModel
 import com.android.systemui.authentication.data.repository.AuthenticationRepository
 import com.android.systemui.authentication.data.repository.FakeAuthenticationRepository
 import com.android.systemui.authentication.domain.interactor.AuthenticationInteractor
+import com.android.systemui.authentication.domain.model.AuthenticationMethodModel as DomainLayerAuthenticationMethodModel
 import com.android.systemui.bouncer.data.repository.BouncerRepository
 import com.android.systemui.bouncer.data.repository.FakeKeyguardBouncerRepository
 import com.android.systemui.bouncer.domain.interactor.BouncerInteractor
@@ -32,14 +34,11 @@
 import com.android.systemui.keyguard.data.repository.FakeKeyguardRepository
 import com.android.systemui.keyguard.data.repository.KeyguardRepository
 import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor
-import com.android.systemui.keyguard.domain.interactor.LockscreenSceneInteractor
 import com.android.systemui.keyguard.shared.model.WakeSleepReason
 import com.android.systemui.keyguard.shared.model.WakefulnessModel
 import com.android.systemui.keyguard.shared.model.WakefulnessState
 import com.android.systemui.scene.data.repository.SceneContainerRepository
 import com.android.systemui.scene.domain.interactor.SceneInteractor
-import com.android.systemui.scene.shared.model.RemoteUserInput
-import com.android.systemui.scene.shared.model.RemoteUserInputAction
 import com.android.systemui.scene.shared.model.SceneContainerConfig
 import com.android.systemui.scene.shared.model.SceneKey
 import com.android.systemui.user.data.repository.FakeUserRepository
@@ -98,7 +97,7 @@
     fun fakeSceneContainerRepository(
         containerConfig: SceneContainerConfig = fakeSceneContainerConfig(),
     ): SceneContainerRepository {
-        return SceneContainerRepository(containerConfig)
+        return SceneContainerRepository(applicationScope(), containerConfig)
     }
 
     fun fakeSceneKeys(): List<SceneKey> {
@@ -124,6 +123,7 @@
         repository: SceneContainerRepository = fakeSceneContainerRepository()
     ): SceneInteractor {
         return SceneInteractor(
+            applicationScope = applicationScope(),
             repository = repository,
             logger = mock(),
         )
@@ -135,6 +135,7 @@
 
     fun authenticationInteractor(
         repository: AuthenticationRepository,
+        sceneInteractor: SceneInteractor = sceneInteractor(),
     ): AuthenticationInteractor {
         return AuthenticationInteractor(
             applicationScope = applicationScope(),
@@ -142,6 +143,7 @@
             backgroundDispatcher = testDispatcher,
             userRepository = userRepository,
             keyguardRepository = keyguardRepository,
+            sceneInteractor = sceneInteractor,
             clock = mock { whenever(elapsedRealtime()).thenAnswer { testScope.currentTime } }
         )
     }
@@ -176,23 +178,14 @@
 
     fun bouncerViewModel(
         bouncerInteractor: BouncerInteractor,
+        authenticationInteractor: AuthenticationInteractor,
     ): BouncerViewModel {
         return BouncerViewModel(
             applicationContext = context,
             applicationScope = applicationScope(),
-            interactor = bouncerInteractor,
-            featureFlags = featureFlags,
-        )
-    }
-
-    fun lockScreenSceneInteractor(
-        authenticationInteractor: AuthenticationInteractor,
-        bouncerInteractor: BouncerInteractor,
-    ): LockscreenSceneInteractor {
-        return LockscreenSceneInteractor(
-            applicationScope = applicationScope(),
-            authenticationInteractor = authenticationInteractor,
             bouncerInteractor = bouncerInteractor,
+            authenticationInteractor = authenticationInteractor,
+            featureFlags = featureFlags,
         )
     }
 
@@ -201,13 +194,17 @@
     }
 
     companion object {
-        val REMOTE_INPUT_DOWN_GESTURE =
-            listOf(
-                RemoteUserInput(10f, 10f, RemoteUserInputAction.DOWN),
-                RemoteUserInput(10f, 20f, RemoteUserInputAction.MOVE),
-                RemoteUserInput(10f, 30f, RemoteUserInputAction.MOVE),
-                RemoteUserInput(10f, 40f, RemoteUserInputAction.MOVE),
-                RemoteUserInput(10f, 40f, RemoteUserInputAction.UP),
-            )
+        fun DomainLayerAuthenticationMethodModel.toDataLayer(): DataLayerAuthenticationMethodModel {
+            return when (this) {
+                DomainLayerAuthenticationMethodModel.None -> DataLayerAuthenticationMethodModel.None
+                DomainLayerAuthenticationMethodModel.Swipe ->
+                    DataLayerAuthenticationMethodModel.None
+                DomainLayerAuthenticationMethodModel.Pin -> DataLayerAuthenticationMethodModel.Pin
+                DomainLayerAuthenticationMethodModel.Password ->
+                    DataLayerAuthenticationMethodModel.Password
+                DomainLayerAuthenticationMethodModel.Pattern ->
+                    DataLayerAuthenticationMethodModel.Pattern
+            }
+        }
     }
 }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/settings/FakeDisplayTracker.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/settings/FakeDisplayTracker.kt
index 1403cea..3fd11a1 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/settings/FakeDisplayTracker.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/settings/FakeDisplayTracker.kt
@@ -26,7 +26,7 @@
     override var defaultDisplayId: Int = Display.DEFAULT_DISPLAY
     override var allDisplays: Array<Display> = displayManager.displays
 
-    private val displayCallbacks: MutableList<DisplayTracker.Callback> = ArrayList()
+    val displayCallbacks: MutableList<DisplayTracker.Callback> = ArrayList()
     private val brightnessCallbacks: MutableList<DisplayTracker.Callback> = ArrayList()
     override fun addDisplayChangeCallback(callback: DisplayTracker.Callback, executor: Executor) {
         displayCallbacks.add(callback)
@@ -43,12 +43,12 @@
         brightnessCallbacks.remove(callback)
     }
 
-    fun setDefaultDisplay(displayId: Int) {
-        defaultDisplayId = displayId
+    override fun getDisplay(displayId: Int): Display {
+        return allDisplays.filter { display -> display.displayId == displayId }[0]
     }
 
-    fun setDisplays(displays: Array<Display>) {
-        allDisplays = displays
+    fun setDefaultDisplay(displayId: Int) {
+        defaultDisplayId = displayId
     }
 
     fun triggerOnDisplayAdded(displayId: Int) {
diff --git a/services/Android.bp b/services/Android.bp
index 53dc068..9264172 100644
--- a/services/Android.bp
+++ b/services/Android.bp
@@ -115,7 +115,6 @@
         ":services.profcollect-sources",
         ":services.restrictions-sources",
         ":services.searchui-sources",
-        ":services.selectiontoolbar-sources",
         ":services.smartspace-sources",
         ":services.soundtrigger-sources",
         ":services.systemcaptions-sources",
@@ -174,7 +173,6 @@
         "services.profcollect",
         "services.restrictions",
         "services.searchui",
-        "services.selectiontoolbar",
         "services.smartspace",
         "services.soundtrigger",
         "services.systemcaptions",
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 9b9593b..8060d5a 100644
--- a/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java
@@ -637,7 +637,7 @@
             MotionEvent event, MotionEvent rawEvent, int policyFlags) {
         switch (event.getActionMasked()) {
             case ACTION_DOWN:
-                // We should have already received ACTION_DOWN. Ignore.
+                handleActionDownStateTouchExploring(event, rawEvent, policyFlags);
                 break;
             case ACTION_POINTER_DOWN:
                 handleActionPointerDown(event, rawEvent, policyFlags);
@@ -843,6 +843,15 @@
         }
     }
 
+    private void handleActionDownStateTouchExploring(
+            MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+        // This is an interrupted and continued touch exploration. Maintain the consistency of the
+        // event stream.
+        mSendTouchExplorationEndDelayed.cancel();
+        mSendTouchInteractionEndDelayed.cancel();
+        sendTouchExplorationGestureStartAndHoverEnterIfNeeded(policyFlags);
+    }
+
     /**
      * Handles move events while touch exploring. this is also where we drag or delegate based on
      * the number of fingers moving on the screen.
@@ -1100,12 +1109,15 @@
     }
 
     /**
-     * Sends the enter events if needed. Such events are hover enter and touch explore
-     * gesture start.
+     * Sends the enter events if needed. Such events are hover enter and touch explore gesture
+     * start.
      *
      * @param policyFlags The policy flags associated with the event.
      */
     private void sendTouchExplorationGestureStartAndHoverEnterIfNeeded(int policyFlags) {
+        if (!mState.isTouchExploring()) {
+            mDispatcher.sendAccessibilityEvent(TYPE_TOUCH_EXPLORATION_GESTURE_START);
+        }
         MotionEvent event = mState.getLastInjectedHoverEvent();
         if (event != null && event.getActionMasked() == ACTION_HOVER_EXIT) {
             final int pointerIdBits = event.getPointerIdBits();
@@ -1118,7 +1130,6 @@
         }
     }
 
-
     /**
      * Determines whether a two pointer gesture is a dragging one.
      *
diff --git a/services/autofill/java/com/android/server/autofill/Session.java b/services/autofill/java/com/android/server/autofill/Session.java
index 37abe1b..1827a5b 100644
--- a/services/autofill/java/com/android/server/autofill/Session.java
+++ b/services/autofill/java/com/android/server/autofill/Session.java
@@ -54,8 +54,8 @@
 import static com.android.server.autofill.FillRequestEventLogger.TRIGGER_REASON_SERVED_FROM_CACHED_RESPONSE;
 import static com.android.server.autofill.FillResponseEventLogger.AVAILABLE_COUNT_WHEN_FILL_REQUEST_FAILED_OR_TIMEOUT;
 import static com.android.server.autofill.FillResponseEventLogger.DETECTION_PREFER_AUTOFILL_PROVIDER;
-import static com.android.server.autofill.FillResponseEventLogger.DETECTION_PREFER_UNKNOWN;
 import static com.android.server.autofill.FillResponseEventLogger.DETECTION_PREFER_PCC;
+import static com.android.server.autofill.FillResponseEventLogger.DETECTION_PREFER_UNKNOWN;
 import static com.android.server.autofill.FillResponseEventLogger.HAVE_SAVE_TRIGGER_ID;
 import static com.android.server.autofill.FillResponseEventLogger.RESPONSE_STATUS_FAILURE;
 import static com.android.server.autofill.FillResponseEventLogger.RESPONSE_STATUS_SESSION_DESTROYED;
@@ -135,6 +135,7 @@
 import android.service.autofill.CompositeUserData;
 import android.service.autofill.Dataset;
 import android.service.autofill.Dataset.DatasetEligibleReason;
+import android.service.autofill.Field;
 import android.service.autofill.FieldClassification;
 import android.service.autofill.FieldClassification.Match;
 import android.service.autofill.FieldClassificationUserData;
@@ -190,6 +191,7 @@
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
@@ -1539,6 +1541,17 @@
                 return;
             }
 
+            if (mSessionFlags.mShowingSaveUi) {
+                // Even though the session has not yet been destroyed at this point, after the
+                // saveUi gets closed, the session will be destroyed and AutofillManager will reset
+                // its state. Processing the fill request will result in a great chance of corrupt
+                // state in Autofill.
+                Slog.w(TAG, "Call to Session#onFillRequestSuccess() rejected - session: "
+                        + id + " is showing saveUi");
+                mFillResponseEventLogger.maybeSetResponseStatus(RESPONSE_STATUS_SESSION_DESTROYED);
+                mFillResponseEventLogger.logAndEndEvent();
+                return;
+            }
 
             requestLog = mRequestLogs.get(requestId);
             if (requestLog != null) {
@@ -1817,11 +1830,11 @@
      */
     private static class DatasetComputationContainer {
         // List of all autofill ids that have a corresponding datasets
-        Set<AutofillId> mAutofillIds = new ArraySet<>();
+        Set<AutofillId> mAutofillIds = new LinkedHashSet<>();
         // Set of datasets. Kept separately, to be able to be used directly for composing
         // FillResponse.
         Set<Dataset> mDatasets = new LinkedHashSet<>();
-        ArrayMap<AutofillId, Set<Dataset>> mAutofillIdToDatasetMap = new ArrayMap<>();
+        Map<AutofillId, Set<Dataset>> mAutofillIdToDatasetMap = new LinkedHashMap<>();
 
         public String toString() {
             final StringBuilder builder = new StringBuilder("DatasetComputationContainer[");
@@ -1859,7 +1872,7 @@
                 // for now to keep safe. TODO(b/266379948): Revisit this logic.
 
                 Set<Dataset> datasets = c2.mAutofillIdToDatasetMap.get(id);
-                Set<Dataset> copyDatasets = new ArraySet<>(datasets);
+                Set<Dataset> copyDatasets = new LinkedHashSet<>(datasets);
                 c1.mAutofillIds.add(id);
                 c1.mAutofillIdToDatasetMap.put(id, copyDatasets);
                 c1.mDatasets.addAll(copyDatasets);
@@ -1875,6 +1888,13 @@
         }
     }
 
+    /**
+     * Computes datasets that are eligible to be shown based on provider detections.
+     * Datasets are populated in the provided container for them to be later merged with the
+     * PCC eligible datasets based on preference strategy.
+     * @param response
+     * @param container
+     */
     private void computeDatasetsForProviderAndUpdateContainer(
             FillResponse response, DatasetComputationContainer container) {
         @DatasetEligibleReason int globalPickReason = PICK_REASON_UNKNOWN;
@@ -1886,9 +1906,9 @@
         }
         List<Dataset> datasets = response.getDatasets();
         if (datasets == null) return;
-        ArrayMap<AutofillId, Set<Dataset>> autofillIdToDatasetMap = new ArrayMap<>();
+        Map<AutofillId, Set<Dataset>> autofillIdToDatasetMap = new LinkedHashMap<>();
         Set<Dataset> eligibleDatasets = new LinkedHashSet<>();
-        Set<AutofillId> eligibleAutofillIds = new ArraySet<>();
+        Set<AutofillId> eligibleAutofillIds = new LinkedHashSet<>();
         for (Dataset dataset : response.getDatasets()) {
             if (dataset.getFieldIds() == null || dataset.getFieldIds().isEmpty()) continue;
             @DatasetEligibleReason int pickReason = globalPickReason;
@@ -1964,7 +1984,7 @@
                 eligibleAutofillIds.add(id);
                 Set<Dataset> datasetForIds = autofillIdToDatasetMap.get(id);
                 if (datasetForIds == null) {
-                    datasetForIds = new ArraySet<>();
+                    datasetForIds = new LinkedHashSet<>();
                 }
                 datasetForIds.add(dataset);
                 autofillIdToDatasetMap.put(id, datasetForIds);
@@ -1975,23 +1995,30 @@
         container.mAutofillIds = eligibleAutofillIds;
     }
 
+    /**
+     * Computes datasets that are eligible to be shown based on PCC detections.
+     * Datasets are populated in the provided container for them to be later merged with the
+     * provider eligible datasets based on preference strategy.
+     * @param response
+     * @param container
+     */
     private void computeDatasetsForPccAndUpdateContainer(
             FillResponse response, DatasetComputationContainer container) {
         List<Dataset> datasets = response.getDatasets();
         if (datasets == null) return;
 
         synchronized (mLock) {
-            ArrayMap<String, Set<AutofillId>> hintsToAutofillIdMap =
+            Map<String, Set<AutofillId>> hintsToAutofillIdMap =
                     mClassificationState.mHintsToAutofillIdMap;
 
             // TODO(266379948): Handle group hints too.
-            ArrayMap<String, Set<AutofillId>> groupHintsToAutofillIdMap =
+            Map<String, Set<AutofillId>> groupHintsToAutofillIdMap =
                     mClassificationState.mGroupHintsToAutofillIdMap;
 
-            ArrayMap<AutofillId, Set<Dataset>> map = new ArrayMap<>();
+            Map<AutofillId, Set<Dataset>> map = new LinkedHashMap<>();
 
             Set<Dataset> eligibleDatasets = new LinkedHashSet<>();
-            Set<AutofillId> eligibleAutofillIds = new ArraySet<>();
+            Set<AutofillId> eligibleAutofillIds = new LinkedHashSet<>();
 
             for (int i = 0; i < datasets.size(); i++) {
 
@@ -2007,13 +2034,35 @@
                 ArrayList<InlinePresentation> fieldInlinePresentations = new ArrayList<>();
                 ArrayList<InlinePresentation> fieldInlineTooltipPresentations = new ArrayList<>();
                 ArrayList<Dataset.DatasetFieldFilter> fieldFilters = new ArrayList<>();
-                Set<AutofillId> datasetAutofillIds = new ArraySet<>();
+                Set<AutofillId> datasetAutofillIds = new LinkedHashSet<>();
+
+                boolean isDatasetAvailable = false;
+                Set<AutofillId> additionalDatasetAutofillIds = new LinkedHashSet<>();
+                Set<AutofillId> additionalEligibleAutofillIds = new LinkedHashSet<>();
 
                 for (int j = 0; j < dataset.getAutofillDatatypes().size(); j++) {
                     if (dataset.getAutofillDatatypes().get(j) == null) {
+                        // TODO : revisit pickReason logic
                         if (dataset.getFieldIds() != null && dataset.getFieldIds().get(j) != null) {
                             pickReason = PICK_REASON_PCC_DETECTION_PREFERRED_WITH_PROVIDER;
                         }
+                        // Check if the autofill id at this index is detected by PCC.
+                        // If not, add that id here, otherwise, we can have duplicates when later
+                        // merging with provider datasets.
+                        // Howover, this doesn't make datasetAvailable for PCC on its own.
+                        // For that, there has to be a datatype detected by PCC, and the dataset
+                        // for that datatype provided by the provider.
+                        AutofillId autofillId = dataset.getFieldIds().get(j);
+                        if (!mClassificationState.mClassificationCombinedHintsMap
+                                .containsKey(autofillId)) {
+                            additionalEligibleAutofillIds.add(autofillId);
+                            additionalDatasetAutofillIds.add(autofillId);
+                            // For each of the field, copy over values.
+                            copyFieldsFromDataset(dataset, j, autofillId, fieldIds, fieldValues,
+                                    fieldPresentations, fieldDialogPresentations,
+                                    fieldInlinePresentations, fieldInlineTooltipPresentations,
+                                    fieldFilters);
+                        }
                         continue;
                     }
                     String hint = dataset.getAutofillDatatypes().get(j);
@@ -2021,22 +2070,18 @@
                     if (hintsToAutofillIdMap.containsKey(hint)) {
                         ArrayList<AutofillId> tempIds =
                                 new ArrayList<>(hintsToAutofillIdMap.get(hint));
-
+                        if (tempIds.isEmpty()) {
+                            continue;
+                        }
+                        isDatasetAvailable = true;
                         for (AutofillId autofillId : tempIds) {
                             eligibleAutofillIds.add(autofillId);
                             datasetAutofillIds.add(autofillId);
                             // For each of the field, copy over values.
-                            fieldIds.add(autofillId);
-                            fieldValues.add(dataset.getFieldValues().get(j));
-                            //  TODO(b/266379948): might need to make it more efficient by not
-                            //  copying over value if it didn't exist. This would require creating
-                            //  a getter for the presentations arraylist.
-                            fieldPresentations.add(dataset.getFieldPresentation(j));
-                            fieldDialogPresentations.add(dataset.getFieldDialogPresentation(j));
-                            fieldInlinePresentations.add(dataset.getFieldInlinePresentation(j));
-                            fieldInlineTooltipPresentations.add(
-                                    dataset.getFieldInlineTooltipPresentation(j));
-                            fieldFilters.add(dataset.getFilter(j));
+                            copyFieldsFromDataset(dataset, j, autofillId, fieldIds, fieldValues,
+                                    fieldPresentations, fieldDialogPresentations,
+                                    fieldInlinePresentations, fieldInlineTooltipPresentations,
+                                    fieldFilters);
                         }
                     }
                     // TODO(b/266379948):  handle the case:
@@ -2045,34 +2090,38 @@
                     // TODO(b/266379948):  also handle the case where there could be more types in
                     // the dataset, provided by the provider, however, they aren't applicable.
                 }
-                Dataset newDataset =
-                        new Dataset(
-                                fieldIds,
-                                fieldValues,
-                                fieldPresentations,
-                                fieldDialogPresentations,
-                                fieldInlinePresentations,
-                                fieldInlineTooltipPresentations,
-                                fieldFilters,
-                                new ArrayList<>(),
-                                dataset.getFieldContent(),
-                                null,
-                                null,
-                                null,
-                                null,
-                                dataset.getId(),
-                                dataset.getAuthentication());
-                newDataset.setEligibleReasonReason(pickReason);
-                eligibleDatasets.add(newDataset);
-                Set<Dataset> newDatasets;
-                for (AutofillId autofillId : datasetAutofillIds) {
-                    if (map.containsKey(autofillId)) {
-                        newDatasets = map.get(autofillId);
-                    } else {
-                        newDatasets = new ArraySet<>();
+                if (isDatasetAvailable) {
+                    datasetAutofillIds.addAll(additionalDatasetAutofillIds);
+                    eligibleAutofillIds.addAll(additionalEligibleAutofillIds);
+                    Dataset newDataset =
+                            new Dataset(
+                                    fieldIds,
+                                    fieldValues,
+                                    fieldPresentations,
+                                    fieldDialogPresentations,
+                                    fieldInlinePresentations,
+                                    fieldInlineTooltipPresentations,
+                                    fieldFilters,
+                                    new ArrayList<>(),
+                                    dataset.getFieldContent(),
+                                    null,
+                                    null,
+                                    null,
+                                    null,
+                                    dataset.getId(),
+                                    dataset.getAuthentication());
+                    newDataset.setEligibleReasonReason(pickReason);
+                    eligibleDatasets.add(newDataset);
+                    Set<Dataset> newDatasets;
+                    for (AutofillId autofillId : datasetAutofillIds) {
+                        if (map.containsKey(autofillId)) {
+                            newDatasets = map.get(autofillId);
+                        } else {
+                            newDatasets = new LinkedHashSet<>();
+                        }
+                        newDatasets.add(newDataset);
+                        map.put(autofillId, newDatasets);
                     }
-                    newDatasets.add(newDataset);
-                    map.put(autofillId, newDatasets);
                 }
             }
             container.mAutofillIds = eligibleAutofillIds;
@@ -2081,6 +2130,31 @@
         }
     }
 
+    private void copyFieldsFromDataset(
+            Dataset dataset,
+            int index,
+            AutofillId autofillId,
+            ArrayList<AutofillId> fieldIds,
+            ArrayList<AutofillValue> fieldValues,
+            ArrayList<RemoteViews> fieldPresentations,
+            ArrayList<RemoteViews> fieldDialogPresentations,
+            ArrayList<InlinePresentation> fieldInlinePresentations,
+            ArrayList<InlinePresentation> fieldInlineTooltipPresentations,
+            ArrayList<Dataset.DatasetFieldFilter> fieldFilters) {
+        // copy over values
+        fieldIds.add(autofillId);
+        fieldValues.add(dataset.getFieldValues().get(index));
+        //  TODO(b/266379948): might need to make it more efficient by not
+        //  copying over value if it didn't exist. This would require creating
+        //  a getter for the presentations arraylist.
+        fieldPresentations.add(dataset.getFieldPresentation(index));
+        fieldDialogPresentations.add(dataset.getFieldDialogPresentation(index));
+        fieldInlinePresentations.add(dataset.getFieldInlinePresentation(index));
+        fieldInlineTooltipPresentations.add(
+                dataset.getFieldInlineTooltipPresentation(index));
+        fieldFilters.add(dataset.getFilter(index));
+    }
+
     @GuardedBy("mLock")
     private void processNullResponseOrFallbackLocked(int requestId, int flags) {
         if (!mSessionFlags.mClientSuggestionsEnabled) {
@@ -2649,10 +2723,7 @@
                     if (sDebug) Slog.d(TAG,  "Updating client state from auth dataset");
                     mClientState = newClientState;
                 }
-                Dataset dataset = (Dataset) result;
-                FillResponse temp = new FillResponse.Builder().addDataset(dataset).build();
-                temp = getEffectiveFillResponse(temp);
-                dataset = temp.getDatasets().get(0);
+                Dataset dataset = getEffectiveDatasetForAuthentication((Dataset) result);
                 final Dataset oldDataset = authenticatedResponse.getDatasets().get(datasetIdx);
                 if (!isAuthResultDatasetEphemeral(oldDataset, data)) {
                     authenticatedResponse.getDatasets().set(datasetIdx, dataset);
@@ -2678,6 +2749,39 @@
         }
     }
 
+    Dataset getEffectiveDatasetForAuthentication(Dataset authenticatedDataset) {
+        FillResponse response = new FillResponse.Builder().addDataset(authenticatedDataset).build();
+        response = getEffectiveFillResponse(response);
+        if (DBG) {
+            Slog.d(TAG, "DBG: authenticated effective response: " + response);
+        }
+        if (response == null || response.getDatasets().size() == 0) {
+            Log.wtf(TAG, "No datasets in fill response on authentication. response = "
+                    + (response == null ? "null" : response.toString()));
+            return authenticatedDataset;
+        }
+        List<Dataset> datasets = response.getDatasets();
+        Dataset result = response.getDatasets().get(0);
+        if (datasets.size() > 1) {
+            Dataset.Builder builder = new Dataset.Builder();
+            for (Dataset dataset : datasets) {
+                if (!dataset.getFieldIds().isEmpty()) {
+                    for (int i = 0; i < dataset.getFieldIds().size(); i++) {
+                        builder.setField(dataset.getFieldIds().get(i),
+                                new Field.Builder().setValue(dataset.getFieldValues().get(i))
+                                        .build());
+                    }
+                }
+            }
+            result = builder.setId(authenticatedDataset.getId()).build();
+        }
+
+        if (DBG) {
+            Slog.d(TAG, "DBG: authenticated effective dataset after auth: " + result);
+        }
+        return result;
+    }
+
     /**
      * Returns whether the dataset returned from the authentication result is ephemeral or not.
      * See {@link AutofillManager#EXTRA_AUTHENTICATION_RESULT_EPHEMERAL_DATASET} for more
@@ -4204,7 +4308,15 @@
                     // We don't send an empty response to IME so that it doesn't cause UI flicker
                     // on the IME side if it arrives before the input view is finished on the IME.
                     mInlineSessionController.resetInlineFillUiLocked();
-                    mCurrentViewId = null;
+
+                    if ((viewState.getState() &
+                            ViewState.STATE_PENDING_CREATE_INLINE_REQUEST) != 0) {
+                        // View was exited before Inline Request sent back, do not set it to
+                        // null yet to let onHandleAssistData finish processing
+                    } else {
+                        mCurrentViewId = null;
+                    }
+
 
                     mPresentationStatsEventLogger.maybeSetNoPresentationEventReason(
                                 NOT_SHOWN_REASON_VIEW_FOCUS_CHANGED);
diff --git a/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java b/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java
index 631b453..fd45d24 100644
--- a/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java
+++ b/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java
@@ -281,9 +281,9 @@
         final long timestamp = System.currentTimeMillis();
 
         final AssociationInfo association = new AssociationInfo(id, userId, packageName,
-                macAddress, displayName, deviceProfile, associatedDevice, selfManaged,
-                /* notifyOnDeviceNearby */ false, /* revoked */ false, timestamp, Long.MAX_VALUE,
-                /* systemDataSyncFlags */ 0);
+                /* tag */ null, macAddress, displayName, deviceProfile, associatedDevice,
+                selfManaged, /* notifyOnDeviceNearby */ false, /* revoked */ false,
+                timestamp, Long.MAX_VALUE, /* systemDataSyncFlags */ 0);
 
         if (deviceProfile != null) {
             // If the "Device Profile" is specified, make the companion application a holder of the
diff --git a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
index c5501f1..996c68b 100644
--- a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
+++ b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
@@ -668,7 +668,6 @@
             addOnAssociationsChangedListener_enforcePermission();
 
             enforceCallerIsSystemOrCanInteractWithUserId(getContext(), userId);
-
             mListeners.register(listener, userId);
         }
 
@@ -1015,6 +1014,29 @@
         }
 
         @Override
+        public void setAssociationTag(int associationId, String tag) {
+            AssociationInfo association = getAssociationWithCallerChecks(associationId);
+            association = AssociationInfo.builder(association).setTag(tag).build();
+            mAssociationStore.updateAssociation(association);
+        }
+
+        @Override
+        public void clearAssociationTag(int associationId) {
+            setAssociationTag(associationId, null);
+        }
+
+        @Override
+        public byte[] getBackupPayload(int userId) {
+            // TODO(b/286124853): back up CDM data
+            return new byte[0];
+        }
+
+        @Override
+        public void applyRestoredPayload(byte[] payload, int userId) {
+            // TODO(b/286124853): restore CDM data
+        }
+
+        @Override
         public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
                 String[] args, ShellCallback callback, ResultReceiver resultReceiver)
                 throws RemoteException {
diff --git a/services/companion/java/com/android/server/companion/PersistentDataStore.java b/services/companion/java/com/android/server/companion/PersistentDataStore.java
index 54798f4..b4b9379 100644
--- a/services/companion/java/com/android/server/companion/PersistentDataStore.java
+++ b/services/companion/java/com/android/server/companion/PersistentDataStore.java
@@ -171,6 +171,7 @@
     private static final String XML_TAG_ASSOCIATION = "association";
     private static final String XML_TAG_PREVIOUSLY_USED_IDS = "previously-used-ids";
     private static final String XML_TAG_PACKAGE = "package";
+    private static final String XML_TAG_TAG = "tag";
     private static final String XML_TAG_ID = "id";
 
     private static final String XML_ATTR_PERSISTENCE_VERSION = "persistence-version";
@@ -421,6 +422,7 @@
         requireStartOfTag(parser, XML_TAG_ASSOCIATION);
 
         final String appPackage = readStringAttribute(parser, XML_ATTR_PACKAGE);
+        final String tag = readStringAttribute(parser, XML_TAG_TAG);
         final String deviceAddress = readStringAttribute(parser, LEGACY_XML_ATTR_DEVICE);
 
         if (appPackage == null || deviceAddress == null) return;
@@ -429,7 +431,7 @@
         final boolean notify = readBooleanAttribute(parser, XML_ATTR_NOTIFY_DEVICE_NEARBY);
         final long timeApproved = readLongAttribute(parser, XML_ATTR_TIME_APPROVED, 0L);
 
-        out.add(new AssociationInfo(associationId, userId, appPackage,
+        out.add(new AssociationInfo(associationId, userId, appPackage, tag,
                 MacAddress.fromString(deviceAddress), null, profile, null,
                 /* managedByCompanionApp */ false, notify, /* revoked */ false, timeApproved,
                 Long.MAX_VALUE, /* systemDataSyncFlags */ 0));
@@ -456,6 +458,7 @@
         final int associationId = readIntAttribute(parser, XML_ATTR_ID);
         final String profile = readStringAttribute(parser, XML_ATTR_PROFILE);
         final String appPackage = readStringAttribute(parser, XML_ATTR_PACKAGE);
+        final String tag = readStringAttribute(parser, XML_TAG_TAG);
         final MacAddress macAddress = stringToMacAddress(
                 readStringAttribute(parser, XML_ATTR_MAC_ADDRESS));
         final String displayName = readStringAttribute(parser, XML_ATTR_DISPLAY_NAME);
@@ -469,7 +472,7 @@
                 XML_ATTR_SYSTEM_DATA_SYNC_FLAGS, 0);
 
         final AssociationInfo associationInfo = createAssociationInfoNoThrow(associationId, userId,
-                appPackage, macAddress, displayName, profile, selfManaged, notify, revoked,
+                appPackage, tag, macAddress, displayName, profile, selfManaged, notify, revoked,
                 timeApproved, lastTimeConnected, systemDataSyncFlags);
         if (associationInfo != null) {
             out.add(associationInfo);
@@ -518,6 +521,7 @@
         writeIntAttribute(serializer, XML_ATTR_ID, a.getId());
         writeStringAttribute(serializer, XML_ATTR_PROFILE, a.getDeviceProfile());
         writeStringAttribute(serializer, XML_ATTR_PACKAGE, a.getPackageName());
+        writeStringAttribute(serializer, XML_TAG_TAG, a.getTag());
         writeStringAttribute(serializer, XML_ATTR_MAC_ADDRESS, a.getDeviceMacAddressAsString());
         writeStringAttribute(serializer, XML_ATTR_DISPLAY_NAME, a.getDisplayName());
         writeBooleanAttribute(serializer, XML_ATTR_SELF_MANAGED, a.isSelfManaged());
@@ -565,17 +569,17 @@
     }
 
     private static AssociationInfo createAssociationInfoNoThrow(int associationId,
-            @UserIdInt int userId, @NonNull String appPackage, @Nullable MacAddress macAddress,
-            @Nullable CharSequence displayName, @Nullable String profile, boolean selfManaged,
-            boolean notify, boolean revoked, long timeApproved, long lastTimeConnected,
-            int systemDataSyncFlags) {
+            @UserIdInt int userId, @NonNull String appPackage, @Nullable String tag,
+            @Nullable MacAddress macAddress, @Nullable CharSequence displayName,
+            @Nullable String profile, boolean selfManaged, boolean notify, boolean revoked,
+            long timeApproved, long lastTimeConnected, int systemDataSyncFlags) {
         AssociationInfo associationInfo = null;
         try {
             // We do not persist AssociatedDevice, which means that AssociationInfo retrieved from
             // datastore is not guaranteed to be identical to the one from initial association.
-            associationInfo = new AssociationInfo(associationId, userId, appPackage, macAddress,
-                    displayName, profile, null, selfManaged, notify, revoked,
-                    timeApproved, lastTimeConnected, systemDataSyncFlags);
+            associationInfo = new AssociationInfo(associationId, userId, appPackage, tag,
+                    macAddress, displayName, profile, null, selfManaged, notify,
+                    revoked, timeApproved, lastTimeConnected, systemDataSyncFlags);
         } catch (Exception e) {
             if (DEBUG) Log.w(TAG, "Could not create AssociationInfo", e);
         }
diff --git a/services/companion/java/com/android/server/companion/presence/CompanionDevicePresenceMonitor.java b/services/companion/java/com/android/server/companion/presence/CompanionDevicePresenceMonitor.java
index f45a1c4..8fea078 100644
--- a/services/companion/java/com/android/server/companion/presence/CompanionDevicePresenceMonitor.java
+++ b/services/companion/java/com/android/server/companion/presence/CompanionDevicePresenceMonitor.java
@@ -281,43 +281,30 @@
             case DEVICE_EVENT_BLE_APPEARED:
             case DEVICE_EVENT_BT_CONNECTED:
             case DEVICE_EVENT_SELF_MANAGED_APPEARED:
-                final boolean alreadyPresent = isDevicePresent(associationId);
                 final boolean added = presentDevicesForSource.add(associationId);
+
                 if (!added) {
                     Slog.w(TAG, "Association with id "
                             + associationId + " is ALREADY reported as "
                             + "present by this source, event=" + event);
-                    return;
                 }
-                // For backward compatibility, do not send the onDeviceAppeared() callback
-                // if it already reported BLE device status.
-                if (event == DEVICE_EVENT_BT_CONNECTED && alreadyPresent) {
-                    Slog.i(TAG, "Ignore sending onDeviceAppeared callback, "
-                            + "device id (" + associationId + ") already present.");
-                } else {
-                    mCallback.onDeviceAppeared(associationId);
-                }
+
+                mCallback.onDeviceAppeared(associationId);
 
                 break;
             case DEVICE_EVENT_BLE_DISAPPEARED:
             case DEVICE_EVENT_BT_DISCONNECTED:
             case DEVICE_EVENT_SELF_MANAGED_DISAPPEARED:
                 final boolean removed = presentDevicesForSource.remove(associationId);
+
                 if (!removed) {
-                    Log.w(TAG, "Association with id " + associationId + " was NOT reported "
+                    Slog.w(TAG, "Association with id " + associationId + " was NOT reported "
                             + "as present by this source, event= " + event);
 
                     return;
                 }
-                final boolean stillPresent = isDevicePresent(associationId);
-                // For backward compatibility, do not send the onDeviceDisappeared()
-                // callback when ble scan still presenting.
-                if (stillPresent) {
-                    Slog.i(TAG, "Ignore sending onDeviceDisappeared callback, "
-                            + "device id (" + associationId + ") is still present.");
-                } else {
-                    mCallback.onDeviceDisappeared(associationId);
-                }
+
+                mCallback.onDeviceDisappeared(associationId);
 
                 break;
             default:
diff --git a/services/companion/java/com/android/server/companion/virtual/TEST_MAPPING b/services/companion/java/com/android/server/companion/virtual/TEST_MAPPING
index d862a54..253ef43 100644
--- a/services/companion/java/com/android/server/companion/virtual/TEST_MAPPING
+++ b/services/companion/java/com/android/server/companion/virtual/TEST_MAPPING
@@ -33,16 +33,27 @@
       ]
     },
     {
-      "name": "CtsVirtualDevicesTestCases",
+      "name": "CtsHardwareTestCases",
       "options": [
         {
           "include-filter": "android.hardware.input.cts.tests"
         },
         {
-          "exclude-annotation": "androidx.test.filters.FlakyTest"
+          "exclude-annotation": "android.platform.test.annotations.FlakyTest"
         }
       ],
       "file_patterns": ["Virtual[^/]*\\.java"]
+    },
+    {
+      "name": "CtsAccessibilityServiceTestCases",
+      "options": [
+        {
+          "include-filter": "android.accessibilityservice.cts.AccessibilityDisplayProxyTest"
+        },
+        {
+          "exclude-annotation": "android.support.test.filters.FlakyTest"
+        }
+      ]
     }
   ]
 }
diff --git a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java
index 402fbb8..d1be5a9 100644
--- a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java
+++ b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java
@@ -43,6 +43,7 @@
 import android.companion.virtual.audio.IAudioRoutingCallback;
 import android.companion.virtual.sensor.VirtualSensor;
 import android.companion.virtual.sensor.VirtualSensorEvent;
+import android.content.AttributionSource;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
@@ -106,9 +107,7 @@
     private static final String TAG = "VirtualDeviceImpl";
 
     private static final int DEFAULT_VIRTUAL_DISPLAY_FLAGS =
-            DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC
-                    | DisplayManager.VIRTUAL_DISPLAY_FLAG_ROTATES_WITH_CONTENT
-                    | DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY
+            DisplayManager.VIRTUAL_DISPLAY_FLAG_TOUCH_FEEDBACK_DISABLED
                     | DisplayManager.VIRTUAL_DISPLAY_FLAG_DESTROY_CONTENT_ON_REMOVAL
                     | DisplayManager.VIRTUAL_DISPLAY_FLAG_SUPPORTS_TOUCH
                     | DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_FOCUS;
@@ -127,6 +126,7 @@
     private final VirtualDeviceManagerService mService;
     private final PendingTrampolineCallback mPendingTrampolineCallback;
     private final int mOwnerUid;
+    private final String mOwnerPackageName;
     private int mDeviceId;
     private @Nullable String mPersistentDeviceId;
     // Thou shall not hold the mVirtualDeviceLock over the mInputController calls.
@@ -198,7 +198,7 @@
             AssociationInfo associationInfo,
             VirtualDeviceManagerService service,
             IBinder token,
-            int ownerUid,
+            AttributionSource attributionSource,
             int deviceId,
             CameraAccessController cameraAccessController,
             PendingTrampolineCallback pendingTrampolineCallback,
@@ -211,7 +211,7 @@
                 associationInfo,
                 service,
                 token,
-                ownerUid,
+                attributionSource,
                 deviceId,
                 /* inputController= */ null,
                 cameraAccessController,
@@ -229,7 +229,7 @@
             AssociationInfo associationInfo,
             VirtualDeviceManagerService service,
             IBinder token,
-            int ownerUid,
+            AttributionSource attributionSource,
             int deviceId,
             InputController inputController,
             CameraAccessController cameraAccessController,
@@ -240,7 +240,8 @@
             VirtualDeviceParams params,
             DisplayManagerGlobal displayManager) {
         super(PermissionEnforcer.fromContext(context));
-        UserHandle ownerUserHandle = UserHandle.getUserHandleForUid(ownerUid);
+        mOwnerPackageName = attributionSource.getPackageName();
+        UserHandle ownerUserHandle = UserHandle.getUserHandleForUid(attributionSource.getUid());
         mContext = context.createContextAsUser(ownerUserHandle, 0);
         mAssociationInfo = associationInfo;
         mPersistentDeviceId = PERSISTENT_ID_PREFIX_CDM_ASSOCIATION + associationInfo.getId();
@@ -249,7 +250,7 @@
         mActivityListener = activityListener;
         mSoundEffectListener = soundEffectListener;
         mRunningAppsChangedCallback = runningAppsChangedCallback;
-        mOwnerUid = ownerUid;
+        mOwnerUid = attributionSource.getUid();
         mDeviceId = deviceId;
         mAppToken = token;
         mParams = params;
@@ -773,7 +774,9 @@
         fout.println("  VirtualDevice: ");
         fout.println("    mDeviceId: " + mDeviceId);
         fout.println("    mAssociationId: " + mAssociationInfo.getId());
-        fout.println("    mParams: " + mParams);
+        fout.println("    mOwnerPackageName: " + mOwnerPackageName);
+        fout.println("    mParams: ");
+        mParams.dump(fout, "        ");
         fout.println("    mVirtualDisplayIds: ");
         synchronized (mVirtualDeviceLock) {
             for (int i = 0; i < mVirtualDisplays.size(); i++) {
diff --git a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java
index 77508a8..e558498 100644
--- a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java
+++ b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java
@@ -35,6 +35,7 @@
 import android.companion.virtual.VirtualDeviceManager;
 import android.companion.virtual.VirtualDeviceParams;
 import android.companion.virtual.sensor.VirtualSensor;
+import android.content.AttributionSource;
 import android.content.Context;
 import android.content.Intent;
 import android.hardware.display.IVirtualDisplayCallback;
@@ -314,13 +315,15 @@
         @Override // Binder call
         public IVirtualDevice createVirtualDevice(
                 IBinder token,
-                String packageName,
+                AttributionSource attributionSource,
                 int associationId,
                 @NonNull VirtualDeviceParams params,
                 @NonNull IVirtualDeviceActivityListener activityListener,
                 @NonNull IVirtualDeviceSoundEffectListener soundEffectListener) {
             createVirtualDevice_enforcePermission();
+            attributionSource.enforceCallingUid();
             final int callingUid = getCallingUid();
+            final String packageName = attributionSource.getPackageName();
             if (!PermissionUtils.validateCallingPackageName(getContext(), packageName)) {
                 throw new SecurityException(
                         "Package name " + packageName + " does not belong to calling uid "
@@ -340,10 +343,9 @@
             final int deviceId = sNextUniqueIndex.getAndIncrement();
             final Consumer<ArraySet<Integer>> runningAppsChangedCallback =
                     runningUids -> notifyRunningAppsChanged(deviceId, runningUids);
-            VirtualDeviceImpl virtualDevice = new VirtualDeviceImpl(getContext(),
-                    associationInfo, VirtualDeviceManagerService.this, token, callingUid,
-                    deviceId, cameraAccessController,
-                    mPendingTrampolineCallback, activityListener,
+            VirtualDeviceImpl virtualDevice = new VirtualDeviceImpl(getContext(), associationInfo,
+                    VirtualDeviceManagerService.this, token, attributionSource, deviceId,
+                    cameraAccessController, mPendingTrampolineCallback, activityListener,
                     soundEffectListener, runningAppsChangedCallback, params);
             synchronized (mVirtualDeviceManagerLock) {
                 if (mVirtualDevices.size() == 0) {
diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
index 315972c..f594170 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
@@ -1225,15 +1225,13 @@
         public ContentCaptureOptions getOptions(@UserIdInt int userId,
                 @NonNull String packageName) {
             boolean isContentCaptureReceiverEnabled;
-            boolean isContentProtectionReceiverEnabled;
+            boolean isContentProtectionReceiverEnabled =
+                    isContentProtectionReceiverEnabled(userId, packageName);
             ArraySet<ComponentName> whitelistedComponents = null;
 
             synchronized (mGlobalWhitelistStateLock) {
                 isContentCaptureReceiverEnabled =
                         isContentCaptureReceiverEnabled(userId, packageName);
-                isContentProtectionReceiverEnabled =
-                        isContentProtectionReceiverEnabled(userId, packageName);
-
                 if (!isContentCaptureReceiverEnabled) {
                     // Full package is not allowlisted: check individual components next
                     whitelistedComponents = getWhitelistedComponents(userId, packageName);
diff --git a/services/core/Android.bp b/services/core/Android.bp
index 9f263c8..66a77a3 100644
--- a/services/core/Android.bp
+++ b/services/core/Android.bp
@@ -98,7 +98,10 @@
 
 java_library_static {
     name: "services.core.unboosted",
-    defaults: ["platform_service_defaults"],
+    defaults: [
+        "platform_service_defaults",
+        "android.hardware.power-java_static",
+    ],
     srcs: [
         ":android.hardware.biometrics.face-V3-java-source",
         ":android.hardware.tv.hdmi.connection-V1-java-source",
@@ -152,7 +155,7 @@
         "android.hardware.boot-V1.0-java", // HIDL
         "android.hardware.boot-V1.1-java", // HIDL
         "android.hardware.boot-V1.2-java", // HIDL
-        "android.hardware.boot-V1-java",   // AIDL
+        "android.hardware.boot-V1-java", // AIDL
         "android.hardware.broadcastradio-V2.0-java", // HIDL
         "android.hardware.broadcastradio-V1-java", // AIDL
         "android.hardware.health-V1.0-java", // HIDL
@@ -176,7 +179,6 @@
         "android.hardware.ir-V1-java",
         "android.hardware.rebootescrow-V1-java",
         "android.hardware.power.stats-V2-java",
-        "android.hardware.power-V4-java",
         "android.hidl.manager-V1.2-java",
         "cbor-java",
         "icu4j_calendar_astronomer",
@@ -188,6 +190,8 @@
         "securebox",
         "apache-commons-math",
         "power_optimization_flags_lib",
+        "notification_flags_lib",
+        "pm_flags_lib",
     ],
     javac_shard_size: 50,
     javacflags: [
diff --git a/services/core/java/android/content/pm/PackageManagerInternal.java b/services/core/java/android/content/pm/PackageManagerInternal.java
index 846283c..557e4ac 100644
--- a/services/core/java/android/content/pm/PackageManagerInternal.java
+++ b/services/core/java/android/content/pm/PackageManagerInternal.java
@@ -1369,6 +1369,13 @@
     public abstract void setPackageStoppedState(@NonNull String packageName, boolean stopped,
             @UserIdInt int userId);
 
+    /**
+     * Tells PackageManager when a component (except BroadcastReceivers) of the package is used
+     * and the package should get out of stopped state and be enabled.
+     */
+    public abstract void notifyComponentUsed(@NonNull String packageName,
+            @UserIdInt int userId, @NonNull String recentCallingPackage, @NonNull String debugInfo);
+
     /** @deprecated For legacy shell command only. */
     @Deprecated
     public abstract void legacyDumpProfiles(@NonNull String packageName,
@@ -1396,4 +1403,10 @@
      */
     public abstract int[] getDistractingPackageRestrictionsAsUser(
             @NonNull String[] packageNames, int userId);
+
+    /**
+     * Checks if package is quarantined for a specific user.
+     */
+    public abstract boolean isPackageQuarantined(@NonNull String packageName,
+            @UserIdInt int userId);
 }
diff --git a/services/core/java/com/android/server/EventLogTags.logtags b/services/core/java/com/android/server/EventLogTags.logtags
index b67e627..d47a399 100644
--- a/services/core/java/com/android/server/EventLogTags.logtags
+++ b/services/core/java/com/android/server/EventLogTags.logtags
@@ -81,7 +81,7 @@
 # when a notification has been clicked
 27520 notification_clicked (key|3),(lifespan|1),(freshness|1),(exposure|1),(rank|1),(count|1)
 # when a notification action button has been clicked
-27521 notification_action_clicked (key|3),(action_index|1),(lifespan|1),(freshness|1),(exposure|1),(rank|1),(count|1)
+27521 notification_action_clicked (key|3),(piIdentifier|3),(pendingIntent|3),(action_index|1),(lifespan|1),(freshness|1),(exposure|1),(rank|1),(count|1)
 # when a notification has been canceled
 27530 notification_canceled (key|3),(reason|1),(lifespan|1),(freshness|1),(exposure|1),(rank|1),(count|1),(listener|3)
 # replaces 27510 with a row per notification
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index 830d55a..7fb9580 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -1289,6 +1289,16 @@
         return mVold.supportsBlockCheckpoint();
     }
 
+    private void prepareUserStorageForMoveInternal(String fromVolumeUuid, String toVolumeUuid,
+            List<UserInfo> users) throws Exception {
+
+        final int flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
+        for (UserInfo user : users) {
+            prepareUserStorageInternal(fromVolumeUuid, user.id, user.serialNumber, flags);
+            prepareUserStorageInternal(toVolumeUuid, user.id, user.serialNumber, flags);
+        }
+    }
+
     @Override
     public void onAwakeStateChanged(boolean isAwake) {
         // Ignored
@@ -2912,6 +2922,7 @@
 
         final VolumeInfo from;
         final VolumeInfo to;
+        final List<UserInfo> users;
 
         synchronized (mLock) {
             if (Objects.equals(mPrimaryStorageUuid, volumeUuid)) {
@@ -2925,7 +2936,7 @@
             mMoveTargetUuid = volumeUuid;
 
             // We need all the users unlocked to move their primary storage
-            final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
+            users = mContext.getSystemService(UserManager.class).getUsers();
             for (UserInfo user : users) {
                 if (StorageManager.isFileEncrypted() && !isUserKeyUnlocked(user.id)) {
                     Slog.w(TAG, "Failing move due to locked user " + user.id);
@@ -2961,6 +2972,19 @@
             }
         }
 
+        // Prepare the storage before move, this is required to unlock adoptable storage (as the
+        // keys are tied to prepare user data step) & also is required for the destination files to
+        // end up with the correct SELinux labels and encryption policies for directories
+        try {
+            prepareUserStorageForMoveInternal(mPrimaryStorageUuid, volumeUuid, users);
+        } catch (Exception e) {
+            Slog.w(TAG, "Failing move due to failure on prepare user data", e);
+            synchronized (mLock) {
+                onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
+            }
+            return;
+        }
+
         try {
             mVold.moveStorage(from.id, to.id, new IVoldTaskListener.Stub() {
                 @Override
@@ -4904,5 +4928,16 @@
             mCloudProviderChangeListeners.add(listener);
             mHandler.obtainMessage(H_CLOUD_MEDIA_PROVIDER_CHANGED, listener).sendToTarget();
         }
+
+        @Override
+        public void prepareUserStorageForMove(String fromVolumeUuid, String toVolumeUuid,
+                List<UserInfo> users) {
+            try {
+                prepareUserStorageForMoveInternal(fromVolumeUuid, toVolumeUuid, users);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
+
     }
 }
diff --git a/services/core/java/com/android/server/TEST_MAPPING b/services/core/java/com/android/server/TEST_MAPPING
index 41cca49..03022b0 100644
--- a/services/core/java/com/android/server/TEST_MAPPING
+++ b/services/core/java/com/android/server/TEST_MAPPING
@@ -1,7 +1,13 @@
 {
     "presubmit": [
         {
-            "name": "CtsLocationFineTestCases"
+            "name": "CtsLocationFineTestCases",
+            "options": [
+                {
+                    // TODO: Wait for test to deflake - b/293934372
+                    "exclude-filter":"android.location.cts.fine.ScanningSettingsTest"
+                }
+             ]
         },
         {
             "name": "CtsLocationCoarseTestCases"
diff --git a/services/core/java/com/android/server/accounts/AccountManagerService.java b/services/core/java/com/android/server/accounts/AccountManagerService.java
index d398260..330742a 100644
--- a/services/core/java/com/android/server/accounts/AccountManagerService.java
+++ b/services/core/java/com/android/server/accounts/AccountManagerService.java
@@ -5309,11 +5309,12 @@
             if (Log.isLoggable(TAG, Log.VERBOSE)) {
                 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
             }
-            int flags = Context.BIND_AUTO_CREATE;
+            long flags = Context.BIND_FILTER_OUT_QUARANTINED_COMPONENTS | Context.BIND_AUTO_CREATE;
             if (mAuthenticatorCache.getBindInstantServiceAllowed(mAccounts.userId)) {
                 flags |= Context.BIND_ALLOW_INSTANT;
             }
-            if (!mContext.bindServiceAsUser(intent, this, flags, UserHandle.of(mAccounts.userId))) {
+            if (!mContext.bindServiceAsUser(intent, this, Context.BindServiceFlags.of(flags),
+                    UserHandle.of(mAccounts.userId))) {
                 Log.w(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
                 // Perform unbind as per documentation at Context.bindServiceAsUser
                 mContext.unbindService(this);
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index da2588b..93fe0c9 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -2501,12 +2501,12 @@
                         FGS_STOP_REASON_STOP_FOREGROUND,
                         FGS_TYPE_POLICY_CHECK_UNKNOWN);
 
-                // foregroundServiceType is used in logFGSStateChangeLocked(), so we can't clear it
-                // earlier.
-                r.foregroundServiceType = 0;
                 synchronized (mFGSLogger) {
                     mFGSLogger.logForegroundServiceStop(r.appInfo.uid, r);
                 }
+                // foregroundServiceType is used in logFGSStateChangeLocked(), so we can't clear it
+                // earlier.
+                r.foregroundServiceType = 0;
                 r.mFgsNotificationWasDeferred = false;
                 signalForegroundServiceObserversLocked(r);
                 resetFgsRestrictionLocked(r);
@@ -3601,6 +3601,8 @@
                 || (flags & Context.BIND_EXTERNAL_SERVICE_LONG) != 0;
         final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
         final boolean inSharedIsolatedProcess = (flags & Context.BIND_SHARED_ISOLATED_PROCESS) != 0;
+        final boolean filterOutQuarantined =
+                (flags & Context.BIND_FILTER_OUT_QUARANTINED_COMPONENTS) != 0;
 
         ProcessRecord attributedApp = null;
         if (sdkSandboxClientAppUid > 0) {
@@ -3610,7 +3612,7 @@
                 isSdkSandboxService, sdkSandboxClientAppUid, sdkSandboxClientAppPackage,
                 resolvedType, callingPackage, callingPid, callingUid, userId, true, callerFg,
                 isBindExternal, allowInstant, null /* fgsDelegateOptions */,
-                inSharedIsolatedProcess);
+                inSharedIsolatedProcess, filterOutQuarantined);
         if (res == null) {
             return 0;
         }
@@ -4119,6 +4121,20 @@
             boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
             boolean allowInstant, ForegroundServiceDelegationOptions fgsDelegateOptions,
             boolean inSharedIsolatedProcess) {
+        return retrieveServiceLocked(service, instanceName, isSdkSandboxService,
+                sdkSandboxClientAppUid, sdkSandboxClientAppPackage, resolvedType, callingPackage,
+                callingPid, callingUid, userId, createIfNeeded, callingFromFg, isBindExternal,
+                allowInstant, fgsDelegateOptions, inSharedIsolatedProcess,
+                false /* filterOutQuarantined */);
+    }
+
+    private ServiceLookupResult retrieveServiceLocked(Intent service,
+            String instanceName, boolean isSdkSandboxService, int sdkSandboxClientAppUid,
+            String sdkSandboxClientAppPackage, String resolvedType,
+            String callingPackage, int callingPid, int callingUid, int userId,
+            boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
+            boolean allowInstant, ForegroundServiceDelegationOptions fgsDelegateOptions,
+            boolean inSharedIsolatedProcess, boolean filterOutQuarantined) {
         if (isSdkSandboxService && instanceName == null) {
             throw new IllegalArgumentException("No instanceName provided for sdk sandbox process");
         }
@@ -4235,11 +4251,14 @@
 
         if (r == null) {
             try {
-                int flags = ActivityManagerService.STOCK_PM_FLAGS
+                long flags = ActivityManagerService.STOCK_PM_FLAGS
                         | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
                 if (allowInstant) {
                     flags |= PackageManager.MATCH_INSTANT;
                 }
+                if (filterOutQuarantined) {
+                    flags |= PackageManager.FILTER_OUT_QUARANTINED_COMPONENTS;
+                }
                 // TODO: come back and remove this assumption to triage all services
                 ResolveInfo rInfo = mAm.getPackageManagerInternal().resolveService(service,
                         resolvedType, flags, userId, callingUid);
@@ -5069,7 +5088,7 @@
             boolean whileRestarting, boolean permissionsReviewRequired, boolean packageFrozen,
             boolean enqueueOomAdj)
             throws TransactionTooLargeException {
-        if (r.app != null && r.app.getThread() != null) {
+        if (r.app != null && r.app.isThreadReady()) {
             sendServiceArgsLocked(r, execInFg, false);
             return null;
         }
@@ -5116,10 +5135,9 @@
                     r.packageName, r.userId, UsageEvents.Event.APP_COMPONENT_USED);
         }
 
-        // Service is now being launched, its package can't be stopped.
         try {
-            mAm.mPackageManagerInt.setPackageStoppedState(
-                    r.packageName, false, r.userId);
+            mAm.mPackageManagerInt.notifyComponentUsed(
+                    r.packageName, r.userId, r.mRecentCallingPackage, r.toString());
         } catch (IllegalArgumentException e) {
             Slog.w(TAG, "Failed trying to unstop package "
                     + r.packageName + ": " + e);
@@ -5141,7 +5159,7 @@
                 final IApplicationThread thread = app.getThread();
                 final int pid = app.getPid();
                 final UidRecord uidRecord = app.getUidRecord();
-                if (thread != null) {
+                if (app.isThreadReady()) {
                     try {
                         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
                             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
@@ -5173,7 +5191,7 @@
                     final int pid = app.getPid();
                     final UidRecord uidRecord = app.getUidRecord();
                     r.isolationHostProc = app;
-                    if (thread != null) {
+                    if (app.isThreadReady()) {
                         try {
                             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
                                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
@@ -5573,7 +5591,7 @@
 
         boolean oomAdjusted = false;
         // Tell the service that it has been unbound.
-        if (r.app != null && r.app.getThread() != null) {
+        if (r.app != null && r.app.isThreadReady()) {
             for (int i = r.bindings.size() - 1; i >= 0; i--) {
                 IntentBindRecord ibr = r.bindings.valueAt(i);
                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
@@ -5715,7 +5733,7 @@
             mAm.mBatteryStatsService.noteServiceStopLaunch(r.appInfo.uid, r.name.getPackageName(),
                     r.name.getClassName());
             stopServiceAndUpdateAllowlistManagerLocked(r);
-            if (r.app.getThread() != null) {
+            if (r.app.isThreadReady()) {
                 // Bump the process to the top of LRU list
                 mAm.updateLruProcessLocked(r.app, false, null);
                 updateServiceForegroundLocked(r.app.mServices, false);
@@ -5879,7 +5897,7 @@
         if (!c.serviceDead) {
             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
                     + ": shouldUnbind=" + b.intent.hasBound);
-            if (s.app != null && s.app.getThread() != null && b.intent.apps.size() == 0
+            if (s.app != null && s.app.isThreadReady() && b.intent.apps.size() == 0
                     && b.intent.hasBound) {
                 try {
                     bumpServiceExecutingLocked(s, false, "unbind", OOM_ADJ_REASON_UNBIND_SERVICE);
@@ -6381,7 +6399,7 @@
                     sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
                             sr.getLastStartId(), baseIntent, null, 0, null, null,
                             ActivityManager.PROCESS_STATE_UNKNOWN));
-                    if (sr.app != null && sr.app.getThread() != null) {
+                    if (sr.app != null && sr.app.isThreadReady()) {
                         // We always run in the foreground, since this is called as
                         // part of the "remove task" UI operation.
                         try {
diff --git a/services/core/java/com/android/server/am/ActivityManagerConstants.java b/services/core/java/com/android/server/am/ActivityManagerConstants.java
index 3fd7d7e..c20f0aa 100644
--- a/services/core/java/com/android/server/am/ActivityManagerConstants.java
+++ b/services/core/java/com/android/server/am/ActivityManagerConstants.java
@@ -1032,7 +1032,7 @@
     private static final String KEY_ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION =
             "enable_wait_for_finish_attach_application";
 
-    private static final boolean DEFAULT_ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION = false;
+    private static final boolean DEFAULT_ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION = true;
 
     /** @see #KEY_ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION */
     public volatile boolean mEnableWaitForFinishAttachApplication =
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index c1f2f67..c4816fb 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -58,6 +58,7 @@
 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_PERSISTENT;
 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_SYSTEM;
 import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
+import static android.content.pm.PackageManager.FILTER_OUT_QUARANTINED_COMPONENTS;
 import static android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES;
 import static android.content.pm.PackageManager.MATCH_ALL;
 import static android.content.pm.PackageManager.MATCH_ANY_USER;
@@ -3095,6 +3096,22 @@
         }
     }
 
+    /**
+     * Enforces that the uid of the caller matches the uid of the package.
+     *
+     * @param packageName the name of the package to match uid against.
+     * @param callingUid the uid of the caller.
+     * @throws SecurityException if the calling uid doesn't match uid of the package.
+     */
+    private void enforceCallingPackage(String packageName, int callingUid) {
+        final int userId = UserHandle.getUserId(callingUid);
+        final int packageUid = getPackageManagerInternal().getPackageUid(packageName,
+                /*flags=*/ 0, userId);
+        if (packageUid != callingUid) {
+            throw new SecurityException(packageName + " does not belong to uid " + callingUid);
+        }
+    }
+
     @Override
     public void setPackageScreenCompatMode(String packageName, int mode) {
         mActivityTaskManager.setPackageScreenCompatMode(packageName, mode);
@@ -7393,6 +7410,9 @@
             case BugreportParams.BUGREPORT_MODE_WIFI:
                 type = "bugreportwifi";
                 break;
+            case BugreportParams.BUGREPORT_MODE_ONBOARDING:
+                type = "bugreportonboarding";
+                break;
             default:
                 throw new IllegalArgumentException(
                     "Provided bugreport type is not correct, value: "
@@ -13704,13 +13724,16 @@
     // A backup agent has just come up
     @Override
     public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) {
+        final int callingUid = Binder.getCallingUid();
+        enforceCallingPackage(agentPackageName, callingUid);
+
         // Resolve the target user id and enforce permissions.
-        userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
+        userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid,
                 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null);
         if (DEBUG_BACKUP) {
             Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent
                     + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId
-                    + " callingUid = " + Binder.getCallingUid() + " uid = " + Process.myUid());
+                    + " callingUid = " + callingUid + " uid = " + Process.myUid());
         }
 
         synchronized(this) {
@@ -14199,7 +14222,8 @@
     private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
             int callingUid, int[] users, int[] broadcastAllowList) {
         // TODO: come back and remove this assumption to triage all broadcasts
-        int pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING;
+        long pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING
+                | FILTER_OUT_QUARANTINED_COMPONENTS;
 
         List<ResolveInfo> receivers = null;
         HashSet<ComponentName> singleUserReceivers = null;
@@ -14827,6 +14851,16 @@
 
                             mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended,
                                     userIdExtra);
+
+                            final boolean quarantined = intent.getBooleanExtra(
+                                    Intent.EXTRA_QUARANTINED, false);
+                            if (suspended && quarantined && packageNames != null) {
+                                for (int i = 0; i < packageNames.length; i++) {
+                                    forceStopPackageLocked(packageNames[i], -1, false, true, true,
+                                            false, false, userId, "suspended");
+                                }
+                            }
+
                             break;
                     }
                     break;
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index c0ac1f8..d3bfc9a 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -764,37 +764,37 @@
                     out.println(
                             "Error: Activity not started, unable to "
                                     + "resolve " + intent.toString());
-                    break;
+                    return 1;
                 case ActivityManager.START_CLASS_NOT_FOUND:
                     out.println(NO_CLASS_ERROR_CODE);
                     out.println("Error: Activity class " +
                             intent.getComponent().toShortString()
                             + " does not exist.");
-                    break;
+                    return 1;
                 case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
                     out.println(
                             "Error: Activity not started, you requested to "
                                     + "both forward and receive its result");
-                    break;
+                    return 1;
                 case ActivityManager.START_PERMISSION_DENIED:
                     out.println(
                             "Error: Activity not started, you do not "
                                     + "have permission to access it.");
-                    break;
+                    return 1;
                 case ActivityManager.START_NOT_VOICE_COMPATIBLE:
                     out.println(
                             "Error: Activity not started, voice control not allowed for: "
                                     + intent);
-                    break;
+                    return 1;
                 case ActivityManager.START_NOT_CURRENT_USER_ACTIVITY:
                     out.println(
                             "Error: Not allowed to start background user activity"
                                     + " that shouldn't be displayed for all users.");
-                    break;
+                    return 1;
                 default:
                     out.println(
                             "Error: Activity not started, unknown error code " + res);
-                    break;
+                    return 1;
             }
             out.flush();
             if (mWaitOption && launched) {
diff --git a/services/core/java/com/android/server/am/ComponentAliasResolver.java b/services/core/java/com/android/server/am/ComponentAliasResolver.java
index 6e93ce4..3fa6102 100644
--- a/services/core/java/com/android/server/am/ComponentAliasResolver.java
+++ b/services/core/java/com/android/server/am/ComponentAliasResolver.java
@@ -457,7 +457,7 @@
     @Nullable
     public Resolution<ResolveInfo> resolveReceiver(@NonNull Intent intent,
             @NonNull ResolveInfo receiver, @Nullable String resolvedType,
-            int packageFlags, int userId, int callingUid, boolean forSend) {
+            long packageFlags, int userId, int callingUid, boolean forSend) {
         // Resolve this alias.
         final Resolution<ComponentName> resolution = resolveComponentAlias(() ->
                 receiver.activityInfo.getComponentName());
diff --git a/services/core/java/com/android/server/am/ContentProviderHelper.java b/services/core/java/com/android/server/am/ContentProviderHelper.java
index e26ee9c..4cc147f 100644
--- a/services/core/java/com/android/server/am/ContentProviderHelper.java
+++ b/services/core/java/com/android/server/am/ContentProviderHelper.java
@@ -505,12 +505,12 @@
                                     cpr.appInfo.packageName, userId, Event.APP_COMPONENT_USED);
                         }
 
-                        // Content provider is now in use, its package can't be stopped.
                         try {
                             checkTime(startTime,
                                     "getContentProviderImpl: before set stopped state");
-                            mService.mPackageManagerInt.setPackageStoppedState(
-                                    cpr.appInfo.packageName, false, userId);
+                            mService.mPackageManagerInt.notifyComponentUsed(
+                                    cpr.appInfo.packageName, userId, callingPackage,
+                                    cpr.toString());
                             checkTime(startTime, "getContentProviderImpl: after set stopped state");
                         } catch (IllegalArgumentException e) {
                             Slog.w(TAG, "Failed trying to unstop package "
diff --git a/services/core/java/com/android/server/am/CoreSettingsObserver.java b/services/core/java/com/android/server/am/CoreSettingsObserver.java
index 9fdb833..e84fed7 100644
--- a/services/core/java/com/android/server/am/CoreSettingsObserver.java
+++ b/services/core/java/com/android/server/am/CoreSettingsObserver.java
@@ -30,6 +30,7 @@
 
 import com.android.internal.R;
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
 
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -163,6 +164,12 @@
                 WidgetFlags.MAGNIFIER_ASPECT_RATIO_DEFAULT));
 
         sDeviceConfigEntries.add(new DeviceConfigEntry<Boolean>(
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.REMOTEVIEWS_ADAPTER_CONVERSION,
+                SystemUiDeviceConfigFlags.KEY_REMOTEVIEWS_ADAPTER_CONVERSION, boolean.class,
+                SystemUiDeviceConfigFlags.REMOTEVIEWS_ADAPTER_CONVERSION_DEFAULT));
+
+        sDeviceConfigEntries.add(new DeviceConfigEntry<Boolean>(
                 TextFlags.NAMESPACE, TextFlags.ENABLE_NEW_CONTEXT_MENU,
                 TextFlags.KEY_ENABLE_NEW_CONTEXT_MENU, boolean.class,
                 TextFlags.ENABLE_NEW_CONTEXT_MENU_DEFAULT));
diff --git a/services/core/java/com/android/server/am/ForegroundServiceTypeLoggerModule.java b/services/core/java/com/android/server/am/ForegroundServiceTypeLoggerModule.java
index 786e1cc..f6859d1 100644
--- a/services/core/java/com/android/server/am/ForegroundServiceTypeLoggerModule.java
+++ b/services/core/java/com/android/server/am/ForegroundServiceTypeLoggerModule.java
@@ -141,6 +141,10 @@
         // grab the appropriate types
         final IntArray apiTypes =
                 convertFgsTypeToApiTypes(record.foregroundServiceType);
+        if (apiTypes.size() == 0) {
+            Slog.w(TAG, "Foreground service start for UID: "
+                    + uid + " does not have any types");
+        }
         // now we need to iterate through the types
         // and insert the new record as needed
         final IntArray apiTypesFound = new IntArray();
@@ -201,6 +205,9 @@
         // and also clean up the start calls stack by UID
         final IntArray apiTypes = convertFgsTypeToApiTypes(record.foregroundServiceType);
         final UidState uidState = mUids.get(uid);
+        if (apiTypes.size() == 0) {
+            Slog.w(TAG, "FGS stop call for: " + uid + " has no types!");
+        }
         if (uidState == null) {
             Slog.w(TAG, "FGS stop call being logged with no start call for UID for UID "
                     + uid
@@ -460,16 +467,17 @@
     public void logFgsApiEvent(ServiceRecord r, int fgsState,
             @FgsApiState int apiState,
             @ForegroundServiceApiType int apiType, long timestamp) {
-        long apiDurationBeforeFgsStart = r.createRealTime - timestamp;
-        long apiDurationAfterFgsEnd = timestamp - r.mFgsExitTime;
+        long apiDurationBeforeFgsStart = 0;
+        long apiDurationAfterFgsEnd = 0;
         UidState uidState = mUids.get(r.appInfo.uid);
-        if (uidState != null) {
-            if (uidState.mFirstFgsTimeStamp.contains(apiType)) {
-                apiDurationBeforeFgsStart = uidState.mFirstFgsTimeStamp.get(apiType) - timestamp;
-            }
-            if (uidState.mLastFgsTimeStamp.contains(apiType)) {
-                apiDurationAfterFgsEnd = timestamp - uidState.mLastFgsTimeStamp.get(apiType);
-            }
+        if (uidState == null) {
+            return;
+        }
+        if (uidState.mFirstFgsTimeStamp.contains(apiType)) {
+            apiDurationBeforeFgsStart = uidState.mFirstFgsTimeStamp.get(apiType) - timestamp;
+        }
+        if (uidState.mLastFgsTimeStamp.contains(apiType)) {
+            apiDurationAfterFgsEnd = timestamp - uidState.mLastFgsTimeStamp.get(apiType);
         }
         final int[] apiTypes = new int[1];
         apiTypes[0] = apiType;
@@ -525,10 +533,11 @@
             @ForegroundServiceApiType int apiType, long timestamp) {
         long apiDurationAfterFgsEnd = 0;
         UidState uidState = mUids.get(uid);
-        if (uidState != null) {
-            if (uidState.mLastFgsTimeStamp.contains(apiType)) {
-                apiDurationAfterFgsEnd = timestamp - uidState.mLastFgsTimeStamp.get(apiType);
-            }
+        if (uidState == null) {
+            return;
+        }
+        if (uidState.mLastFgsTimeStamp.contains(apiType)) {
+            apiDurationAfterFgsEnd = timestamp - uidState.mLastFgsTimeStamp.get(apiType);
         }
         final int[] apiTypes = new int[1];
         apiTypes[0] = apiType;
diff --git a/services/core/java/com/android/server/am/ProcessRecord.java b/services/core/java/com/android/server/am/ProcessRecord.java
index 7037fec..e2edd8a 100644
--- a/services/core/java/com/android/server/am/ProcessRecord.java
+++ b/services/core/java/com/android/server/am/ProcessRecord.java
@@ -774,6 +774,11 @@
     }
 
     @GuardedBy("mService")
+    boolean isThreadReady() {
+        return mThread != null && !mPendingFinishAttach;
+    }
+
+    @GuardedBy("mService")
     long getStartSeq() {
         return mStartSeq;
     }
diff --git a/services/core/java/com/android/server/am/ServiceRecord.java b/services/core/java/com/android/server/am/ServiceRecord.java
index f7bbc8b..70a1c91 100644
--- a/services/core/java/com/android/server/am/ServiceRecord.java
+++ b/services/core/java/com/android/server/am/ServiceRecord.java
@@ -286,6 +286,12 @@
                 + ")");
     }
 
+    private String getFgsInfoForWtf() {
+        return " cmp: " + this.getComponentName().toShortString()
+                + " sdk: " + this.appInfo.targetSdkVersion
+                ;
+    }
+
     void maybeLogFgsLogicChange() {
         final int origWiu = reasonOr(mAllowWhileInUsePermissionInFgsReasonNoBinding,
                 mAllowWIUInBindService);
@@ -311,7 +317,8 @@
                 + " OS:" // Orig-start
                 + changeMessage(mAllowStartForegroundNoBinding, mAllowStartInBindService)
                 + " NS:" // New-start
-                + changeMessage(mAllowStartForegroundNoBinding, mAllowStartByBindings);
+                + changeMessage(mAllowStartForegroundNoBinding, mAllowStartByBindings)
+                + getFgsInfoForWtf();
         Slog.wtf(TAG_SERVICE, message);
     }
 
@@ -1524,7 +1531,11 @@
         sb.append("ServiceRecord{")
             .append(Integer.toHexString(System.identityHashCode(this)))
             .append(" u").append(userId)
-            .append(' ').append(shortInstanceName).append('}');
+            .append(' ').append(shortInstanceName);
+        if (mRecentCallingPackage != null) {
+            sb.append(" c:").append(mRecentCallingPackage);
+        }
+        sb.append('}');
         return stringName = sb.toString();
     }
 
diff --git a/services/core/java/com/android/server/am/TEST_MAPPING b/services/core/java/com/android/server/am/TEST_MAPPING
index 0af9b2b..575db01 100644
--- a/services/core/java/com/android/server/am/TEST_MAPPING
+++ b/services/core/java/com/android/server/am/TEST_MAPPING
@@ -88,11 +88,14 @@
       "file_patterns": ["Battery[^/]*\\.java", "MeasuredEnergy[^/]*\\.java"],
       "name": "FrameworksServicesTests",
       "options": [
-        { "include-filter": "com.android.server.am.BatteryStatsServiceTest" },
-        { "include-filter": "com.android.server.power.stats.BatteryStatsTests" }
+        { "include-filter": "com.android.server.am.BatteryStatsServiceTest" }
       ]
     },
     {
+      "file_patterns": ["Battery[^/]*\\.java", "MeasuredEnergy[^/]*\\.java"],
+      "name": "PowerStatsTests"
+    },
+    {
       "file_patterns": ["Broadcast.*"],
       "name": "FrameworksMockingServicesTests",
       "options": [
@@ -111,27 +114,14 @@
       ]
     },
     {
-      "name": "CtsUsageStatsTestCases",
+      "name": "CtsBRSTestCases",
       "file_patterns": [
         "ActivityManagerService\\.java",
         "BroadcastQueue\\.java"
       ],
       "options": [
-        {
-          "include-filter": "android.app.usage.cts.BroadcastResponseStatsTest"
-        },
-        {
-          "exclude-annotation": "androidx.test.filters.FlakyTest"
-        },
-        {
-          "exclude-annotation": "android.platform.test.annotations.FlakyTest"
-        },
-        {
-          "exclude-annotation": "androidx.test.filters.MediumTest"
-        },
-        {
-          "exclude-annotation": "androidx.test.filters.LargeTest"
-        }
+        { "exclude-annotation": "androidx.test.filters.FlakyTest" },
+        { "exclude-annotation": "org.junit.Ignore" }
       ]
     }
   ],
diff --git a/services/core/java/com/android/server/app/GameManagerService.java b/services/core/java/com/android/server/app/GameManagerService.java
index 80d14a2..81397b4 100644
--- a/services/core/java/com/android/server/app/GameManagerService.java
+++ b/services/core/java/com/android/server/app/GameManagerService.java
@@ -129,8 +129,6 @@
     private static final String EVENT_ON_USER_SWITCHING = "ON_USER_SWITCHING";
     private static final String EVENT_ON_USER_STOPPING = "ON_USER_STOPPING";
 
-    private static final boolean DEBUG = false;
-
     static final int WRITE_SETTINGS = 1;
     static final int REMOVE_SETTINGS = 2;
     static final int POPULATE_GAME_MODE_SETTINGS = 3;
@@ -407,6 +405,7 @@
         @Override
         public void onPropertiesChanged(Properties properties) {
             final String[] packageNames = properties.getKeyset().toArray(new String[0]);
+            Slog.v(TAG, "Device config changed for packages: " + Arrays.toString(packageNames));
             updateConfigsForUser(ActivityManager.getCurrentUser(), true /*checkGamePackage*/,
                     packageNames);
         }
@@ -1861,15 +1860,11 @@
                     final GamePackageConfiguration config =
                             new GamePackageConfiguration(mPackageManager, packageName, userId);
                     if (config.isActive()) {
-                        if (DEBUG) {
-                            Slog.i(TAG, "Adding config: " + config.toString());
-                        }
+                        Slog.v(TAG, "Adding config: " + config.toString());
                         mConfigs.put(packageName, config);
                     } else {
-                        if (DEBUG) {
-                            Slog.w(TAG, "Inactive package config for "
+                        Slog.v(TAG, "Inactive package config for "
                                     + config.getPackageName() + ":" + config.toString());
-                        }
                         mConfigs.remove(packageName);
                     }
                 }
diff --git a/services/core/java/com/android/server/apphibernation/AppHibernationService.java b/services/core/java/com/android/server/apphibernation/AppHibernationService.java
index 86da39b..a17b3d5 100644
--- a/services/core/java/com/android/server/apphibernation/AppHibernationService.java
+++ b/services/core/java/com/android/server/apphibernation/AppHibernationService.java
@@ -97,7 +97,7 @@
  */
 public final class AppHibernationService extends SystemService {
     private static final String TAG = "AppHibernationService";
-    private static final int PACKAGE_MATCH_FLAGS =
+    private static final long PACKAGE_MATCH_FLAGS =
             PackageManager.MATCH_DIRECT_BOOT_AWARE
                     | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
                     | PackageManager.MATCH_UNINSTALLED_PACKAGES
diff --git a/services/core/java/com/android/server/audio/AudioDeviceBroker.java b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
index af8aa916..d89171d 100644
--- a/services/core/java/com/android/server/audio/AudioDeviceBroker.java
+++ b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
@@ -435,7 +435,7 @@
         // LE Audio it stays the same and we must trigger the proper stream volume alignment, if
         // LE Audio communication device is activated after the audio system has already switched to
         // MODE_IN_CALL mode.
-        if (isBluetoothLeAudioRequested()) {
+        if (isBluetoothLeAudioRequested() && device != null) {
             final int streamType = mAudioService.getBluetoothContextualVolumeStream();
             final int leAudioVolIndex = getVssVolumeForDevice(streamType, device.getInternalType());
             final int leAudioMaxVolIndex = getMaxVssVolumeForStream(streamType);
diff --git a/services/core/java/com/android/server/audio/AudioDeviceInventory.java b/services/core/java/com/android/server/audio/AudioDeviceInventory.java
index 5a92cb4..13e3fc7 100644
--- a/services/core/java/com/android/server/audio/AudioDeviceInventory.java
+++ b/services/core/java/com/android/server/audio/AudioDeviceInventory.java
@@ -2070,12 +2070,18 @@
     @GuardedBy("mDevicesLock")
     private void makeLeAudioDeviceAvailable(
             AudioDeviceBroker.BtDeviceInfo btInfo, int streamType, String eventSource) {
-        final String address = btInfo.mDevice.getAddress();
-        final String name = BtHelper.getName(btInfo.mDevice);
         final int volumeIndex = btInfo.mVolume == -1 ? -1 : btInfo.mVolume * 10;
         final int device = btInfo.mAudioSystemDevice;
 
         if (device != AudioSystem.DEVICE_NONE) {
+            final String address = btInfo.mDevice.getAddress();
+            String name = BtHelper.getName(btInfo.mDevice);
+
+            // The BT Stack does not provide a name for LE Broadcast devices
+            if (device == AudioSystem.DEVICE_OUT_BLE_BROADCAST && name.equals("")) {
+                name = "Broadcast";
+            }
+
             /* Audio Policy sees Le Audio similar to A2DP. Let's make sure
              * AUDIO_POLICY_FORCE_NO_BT_A2DP is not set
              */
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index 76c4cfe..3f50dfd3 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -10742,6 +10742,27 @@
 
     @Override
     @android.annotation.EnforcePermission(MODIFY_AUDIO_SETTINGS_PRIVILEGED)
+    public boolean isCsdAsAFeatureAvailable() {
+        super.isCsdAsAFeatureAvailable_enforcePermission();
+        return mSoundDoseHelper.isCsdAsAFeatureAvailable();
+    }
+
+    @Override
+    @android.annotation.EnforcePermission(MODIFY_AUDIO_SETTINGS_PRIVILEGED)
+    public boolean isCsdAsAFeatureEnabled() {
+        super.isCsdAsAFeatureEnabled_enforcePermission();
+        return mSoundDoseHelper.isCsdAsAFeatureEnabled();
+    }
+
+    @Override
+    @android.annotation.EnforcePermission(MODIFY_AUDIO_SETTINGS_PRIVILEGED)
+    public void setCsdAsAFeatureEnabled(boolean csdToggleValue) {
+        super.setCsdAsAFeatureEnabled_enforcePermission();
+        mSoundDoseHelper.setCsdAsAFeatureEnabled(csdToggleValue);
+    }
+
+    @Override
+    @android.annotation.EnforcePermission(MODIFY_AUDIO_SETTINGS_PRIVILEGED)
     public void setBluetoothAudioDeviceCategory(@NonNull String address, boolean isBle,
             @AudioDeviceCategory int btAudioDeviceCategory) {
         super.setBluetoothAudioDeviceCategory_enforcePermission();
diff --git a/services/core/java/com/android/server/audio/SoundDoseHelper.java b/services/core/java/com/android/server/audio/SoundDoseHelper.java
index 851c5c3..95b6c2c 100644
--- a/services/core/java/com/android/server/audio/SoundDoseHelper.java
+++ b/services/core/java/com/android/server/audio/SoundDoseHelper.java
@@ -37,13 +37,11 @@
 import android.media.ISoundDoseCallback;
 import android.media.SoundDoseRecord;
 import android.os.Binder;
-import android.os.HandlerExecutor;
 import android.os.Message;
 import android.os.RemoteException;
 import android.os.SystemClock;
 import android.os.SystemProperties;
 import android.os.UserHandle;
-import android.provider.DeviceConfig;
 import android.provider.Settings;
 import android.text.TextUtils;
 import android.util.Log;
@@ -143,8 +141,6 @@
 
     private static final int SAFE_MEDIA_VOLUME_UNINITIALIZED = -1;
 
-    private static final String FEATURE_FLAG_ENABLE_CSD = "enable_csd";
-
     private final EventLogger mLogger = new EventLogger(AudioService.LOG_NB_EVENTS_SOUND_DOSE,
             "CSD updates");
 
@@ -193,7 +189,15 @@
 
     private final AtomicBoolean mEnableCsd = new AtomicBoolean(false);
 
-    private ArrayList<ISoundDose.AudioDeviceCategory> mCachedAudioDeviceCategories =
+    private final Object mCsdAsAFeatureLock = new Object();
+
+    @GuardedBy("mCsdAsAFeatureLock")
+    private boolean mIsCsdAsAFeatureAvailable = false;
+
+    @GuardedBy("mCsdAsAFeatureLock")
+    private boolean mIsCsdAsAFeatureEnabled = false;
+
+    private final ArrayList<ISoundDose.AudioDeviceCategory> mCachedAudioDeviceCategories =
             new ArrayList<>();
 
     private final Object mCsdStateLock = new Object();
@@ -315,10 +319,6 @@
 
         mAlarmManager = (AlarmManager) mContext.getSystemService(
                 Context.ALARM_SERVICE);
-
-        DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_MEDIA,
-                new HandlerExecutor(mAudioHandler),
-                p -> updateCsdEnabled("onPropertiesChanged"));
     }
 
     void initSafeVolumes() {
@@ -334,9 +334,8 @@
                 SAFE_MEDIA_VOLUME_UNINITIALIZED);
         mSafeMediaVolumeDevices.append(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
                 SAFE_MEDIA_VOLUME_UNINITIALIZED);
-        // TODO(b/278265907): enable A2DP when we can distinguish A2DP headsets
-        // mSafeMediaVolumeDevices.append(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
-        //        SAFE_MEDIA_VOLUME_UNINITIALIZED);
+        mSafeMediaVolumeDevices.append(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
+                SAFE_MEDIA_VOLUME_UNINITIALIZED);
     }
 
     float getOutputRs2UpperBound() {
@@ -494,6 +493,38 @@
         return false;
     }
 
+    boolean isCsdAsAFeatureAvailable() {
+        synchronized (mCsdAsAFeatureLock) {
+            return mIsCsdAsAFeatureAvailable;
+        }
+    }
+
+    boolean isCsdAsAFeatureEnabled() {
+        synchronized (mCsdAsAFeatureLock) {
+            return mIsCsdAsAFeatureEnabled;
+        }
+    }
+
+    void setCsdAsAFeatureEnabled(boolean csdAsAFeatureEnabled) {
+        boolean doUpdate;
+        synchronized (mCsdAsAFeatureLock) {
+            doUpdate = mIsCsdAsAFeatureEnabled != csdAsAFeatureEnabled && mIsCsdAsAFeatureAvailable;
+            mIsCsdAsAFeatureEnabled = csdAsAFeatureEnabled;
+            final long callingIdentity = Binder.clearCallingIdentity();
+            try {
+                mSettings.putSecureIntForUser(mAudioService.getContentResolver(),
+                        Settings.Secure.AUDIO_SAFE_CSD_AS_A_FEATURE_ENABLED,
+                        mIsCsdAsAFeatureEnabled ? 1 : 0, UserHandle.USER_CURRENT);
+            } finally {
+                Binder.restoreCallingIdentity(callingIdentity);
+            }
+        }
+
+        if (doUpdate) {
+            updateCsdEnabled("setCsdAsAFeatureEnabled");
+        }
+    }
+
     void setAudioDeviceCategory(String address, int internalAudioType, boolean isHeadphone) {
         if (!mEnableCsd.get()) {
             return;
@@ -864,6 +895,13 @@
             Log.e(TAG, "Exception while forcing the internal MEL computation", e);
         }
 
+        synchronized (mCsdAsAFeatureLock) {
+            mIsCsdAsAFeatureEnabled = mSettings.getSecureIntForUser(
+                    mAudioService.getContentResolver(),
+                    Settings.Secure.AUDIO_SAFE_CSD_AS_A_FEATURE_ENABLED, 0,
+                    UserHandle.USER_CURRENT) != 0;
+        }
+
         synchronized (mCsdStateLock) {
             if (mGlobalTimeOffsetInSecs == GLOBAL_TIME_OFFSET_UNINITIALIZED) {
                 mGlobalTimeOffsetInSecs = System.currentTimeMillis() / 1000L;
@@ -908,18 +946,23 @@
 
     @GuardedBy("mSafeMediaVolumeStateLock")
     private void updateSafeMediaVolume_l(String caller) {
-        boolean safeMediaVolumeEnabled =
-                SystemProperties.getBoolean(SYSTEM_PROPERTY_SAFEMEDIA_FORCE, false)
-                        || (mContext.getResources().getBoolean(
-                        com.android.internal.R.bool.config_safe_media_volume_enabled)
-                        && !mEnableCsd.get());
         boolean safeMediaVolumeBypass =
-                SystemProperties.getBoolean(SYSTEM_PROPERTY_SAFEMEDIA_BYPASS, false);
+                SystemProperties.getBoolean(SYSTEM_PROPERTY_SAFEMEDIA_BYPASS, false)
+                        || mEnableCsd.get();
+        boolean safeMediaVolumeForce = SystemProperties.getBoolean(SYSTEM_PROPERTY_SAFEMEDIA_FORCE,
+                false);
+        // we are using the MCC overlaid legacy flag used for the safe volume enablement
+        // to determine whether the MCC enforces any safe hearing standard.
+        boolean mccEnforcedSafeMediaVolume = mContext.getResources().getBoolean(
+                com.android.internal.R.bool.config_safe_media_volume_enabled);
+
+        boolean safeVolumeEnabled =
+                (mccEnforcedSafeMediaVolume || safeMediaVolumeForce) && !safeMediaVolumeBypass;
 
         // The persisted state is either "disabled" or "active": this is the state applied
         // next time we boot and cannot be "inactive"
         int persistedState;
-        if (safeMediaVolumeEnabled && !safeMediaVolumeBypass) {
+        if (safeVolumeEnabled) {
             persistedState = SAFE_MEDIA_VOLUME_ACTIVE;
             // The state can already be "inactive" here if the user has forced it before
             // the 30 seconds timeout for forced configuration. In this case we don't reset
@@ -946,22 +989,28 @@
     }
 
     private void updateCsdEnabled(String caller) {
-        boolean newEnableCsd = SystemProperties.getBoolean(SYSTEM_PROPERTY_SAFEMEDIA_CSD_FORCE,
-                false);
-        if (!newEnableCsd) {
-            final String featureFlagEnableCsdValue = DeviceConfig.getProperty(
-                    DeviceConfig.NAMESPACE_MEDIA,
-                    FEATURE_FLAG_ENABLE_CSD);
-            if (featureFlagEnableCsdValue != null) {
-                newEnableCsd = Boolean.parseBoolean(featureFlagEnableCsdValue);
+        boolean csdForce = SystemProperties.getBoolean(SYSTEM_PROPERTY_SAFEMEDIA_CSD_FORCE, false);
+        // we are using the MCC overlaid legacy flag used for the safe volume enablement
+        // to determine whether the MCC enforces any safe hearing standard.
+        boolean mccEnforcedSafeMedia = mContext.getResources().getBoolean(
+                com.android.internal.R.bool.config_safe_media_volume_enabled);
+        boolean csdEnable = mContext.getResources().getBoolean(
+                R.bool.config_safe_sound_dosage_enabled);
+        boolean newEnabledCsd = (mccEnforcedSafeMedia && csdEnable) || csdForce;
+
+        synchronized (mCsdAsAFeatureLock) {
+            if (!mccEnforcedSafeMedia && csdEnable) {
+                mIsCsdAsAFeatureAvailable = true;
+                newEnabledCsd = mIsCsdAsAFeatureEnabled || csdForce;
+                Log.v(TAG, caller + ": CSD as a feature is not enforced and enabled: "
+                        + newEnabledCsd);
             } else {
-                newEnableCsd = mContext.getResources().getBoolean(
-                        R.bool.config_safe_sound_dosage_enabled);
+                mIsCsdAsAFeatureAvailable = false;
             }
         }
 
-        if (mEnableCsd.compareAndSet(!newEnableCsd, newEnableCsd)) {
-            Log.i(TAG, caller + ": enable CSD " + newEnableCsd);
+        if (mEnableCsd.compareAndSet(!newEnabledCsd, newEnabledCsd)) {
+            Log.i(TAG, caller + ": enabled CSD " + newEnabledCsd);
             initCsd();
 
             synchronized (mSafeMediaVolumeStateLock) {
diff --git a/services/core/java/com/android/server/backup/SystemBackupAgent.java b/services/core/java/com/android/server/backup/SystemBackupAgent.java
index b5d5cbe..de4979a 100644
--- a/services/core/java/com/android/server/backup/SystemBackupAgent.java
+++ b/services/core/java/com/android/server/backup/SystemBackupAgent.java
@@ -61,6 +61,7 @@
     private static final String PEOPLE_HELPER = "people";
     private static final String APP_LOCALES_HELPER = "app_locales";
     private static final String APP_GENDER_HELPER = "app_gender";
+    private static final String COMPANION_HELPER = "companion";
 
     // These paths must match what the WallpaperManagerService uses.  The leaf *_FILENAME
     // are also used in the full-backup file format, so must not change unless steps are
@@ -95,7 +96,8 @@
                     PERMISSION_HELPER,
                     NOTIFICATION_HELPER,
                     SYNC_SETTINGS_HELPER,
-                    APP_LOCALES_HELPER);
+                    APP_LOCALES_HELPER,
+                    COMPANION_HELPER);
 
     /** Helpers that are enabled for full, non-system users. */
     private static final Set<String> sEligibleHelpersForNonSystemUser =
@@ -132,6 +134,7 @@
         addHelperIfEligibleForUser(APP_LOCALES_HELPER, new AppSpecificLocalesBackupHelper(mUserId));
         addHelperIfEligibleForUser(APP_GENDER_HELPER,
                 new AppGrammaticalGenderBackupHelper(mUserId));
+        addHelperIfEligibleForUser(COMPANION_HELPER, new CompanionBackupHelper(mUserId));
     }
 
     @Override
diff --git a/services/core/java/com/android/server/biometrics/AuthSession.java b/services/core/java/com/android/server/biometrics/AuthSession.java
index cb5e7f1..2ae3118 100644
--- a/services/core/java/com/android/server/biometrics/AuthSession.java
+++ b/services/core/java/com/android/server/biometrics/AuthSession.java
@@ -150,6 +150,10 @@
     // Timestamp when hardware authentication occurred
     private long mAuthenticatedTimeMs;
 
+    @NonNull
+    private final OperationContextExt mOperationContext;
+
+
     AuthSession(@NonNull Context context,
             @NonNull BiometricContext biometricContext,
             @NonNull IStatusBarService statusBarService,
@@ -215,6 +219,7 @@
         mFingerprintSensorProperties = fingerprintSensorProperties;
         mCancelled = false;
         mBiometricFrameworkStatsLogger = logger;
+        mOperationContext = new OperationContextExt(true /* isBP */);
 
         try {
             mClientReceiver.asBinder().linkToDeath(this, 0 /* flags */);
@@ -581,6 +586,8 @@
         } else {
             Slog.d(TAG, "delaying fingerprint sensor start");
         }
+
+        mBiometricContext.updateContext(mOperationContext, isCrypto());
     }
 
     // call once anytime after onDialogAnimatedIn() to indicate it's appropriate to start the
@@ -743,12 +750,12 @@
                         + ", Client: " + BiometricsProtoEnums.CLIENT_BIOMETRIC_PROMPT
                         + ", RequireConfirmation: " + mPreAuthInfo.confirmationRequested
                         + ", State: " + FrameworkStatsLog.BIOMETRIC_AUTHENTICATED__STATE__CONFIRMED
-                        + ", Latency: " + latency);
+                        + ", Latency: " + latency
+                        + ", SessionId: " + mOperationContext.getId());
             }
 
             mBiometricFrameworkStatsLogger.authenticate(
-                    mBiometricContext.updateContext(new OperationContextExt(true /* isBP */),
-                            isCrypto()),
+                    mOperationContext,
                     statsModality(),
                     BiometricsProtoEnums.ACTION_UNKNOWN,
                     BiometricsProtoEnums.CLIENT_BIOMETRIC_PROMPT,
@@ -780,13 +787,13 @@
                         + ", Client: " + BiometricsProtoEnums.CLIENT_BIOMETRIC_PROMPT
                         + ", Reason: " + reason
                         + ", Error: " + error
-                        + ", Latency: " + latency);
+                        + ", Latency: " + latency
+                        + ", SessionId: " + mOperationContext.getId());
             }
             // Auth canceled
             if (error != 0) {
                 mBiometricFrameworkStatsLogger.error(
-                        mBiometricContext.updateContext(new OperationContextExt(true /* isBP */),
-                                isCrypto()),
+                        mOperationContext,
                         statsModality(),
                         BiometricsProtoEnums.ACTION_AUTHENTICATE,
                         BiometricsProtoEnums.CLIENT_BIOMETRIC_PROMPT,
diff --git a/services/core/java/com/android/server/biometrics/AuthenticationStats.java b/services/core/java/com/android/server/biometrics/AuthenticationStats.java
new file mode 100644
index 0000000..e109cc8
--- /dev/null
+++ b/services/core/java/com/android/server/biometrics/AuthenticationStats.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.biometrics;
+
+/**
+ * Utility class for on-device biometric authentication data, including total authentication,
+ * rejections, and the number of sent enrollment notifications.
+ */
+public class AuthenticationStats {
+
+    private static final float FRR_NOT_ENOUGH_ATTEMPTS = -1.0f;
+
+    private final int mUserId;
+    private int mTotalAttempts;
+    private int mRejectedAttempts;
+    private int mEnrollmentNotifications;
+    private final int mModality;
+
+    public AuthenticationStats(final int userId, int totalAttempts, int rejectedAttempts,
+            int enrollmentNotifications, final int modality) {
+        mUserId = userId;
+        mTotalAttempts = totalAttempts;
+        mRejectedAttempts = rejectedAttempts;
+        mEnrollmentNotifications = enrollmentNotifications;
+        mModality = modality;
+    }
+
+    public AuthenticationStats(final int userId, final int modality) {
+        mUserId = userId;
+        mTotalAttempts = 0;
+        mRejectedAttempts = 0;
+        mEnrollmentNotifications = 0;
+        mModality = modality;
+    }
+
+    public int getUserId() {
+        return mUserId;
+    }
+
+    public int getTotalAttempts() {
+        return mTotalAttempts;
+    }
+
+    public int getRejectedAttempts() {
+        return mRejectedAttempts;
+    }
+
+    public int getEnrollmentNotifications() {
+        return mEnrollmentNotifications;
+    }
+
+    public int getModality() {
+        return mModality;
+    }
+
+    /** Calculate FRR. */
+    public float getFrr() {
+        if (mTotalAttempts > 0) {
+            return mRejectedAttempts / (float) mTotalAttempts;
+        } else {
+            return FRR_NOT_ENOUGH_ATTEMPTS;
+        }
+    }
+
+    /** Update total authentication attempts and rejections. */
+    public void authenticate(boolean authenticated) {
+        if (!authenticated) {
+            mRejectedAttempts++;
+        }
+        mTotalAttempts++;
+    }
+
+    /** Reset total authentication attempts and rejections. */
+    public void resetData() {
+        mTotalAttempts = 0;
+        mRejectedAttempts = 0;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+
+        if (!(obj instanceof AuthenticationStats)) {
+            return false;
+        }
+
+        AuthenticationStats target = (AuthenticationStats) obj;
+        return this.getUserId() == target.getUserId()
+                && this.getTotalAttempts()
+                == target.getTotalAttempts()
+                && this.getRejectedAttempts()
+                == target.getRejectedAttempts()
+                && this.getEnrollmentNotifications()
+                == target.getEnrollmentNotifications()
+                && this.getModality() == target.getModality();
+    }
+
+    @Override
+    public int hashCode() {
+        return String.format("userId: %d, totalAttempts: %d, rejectedAttempts: %d, "
+                + "enrollmentNotifications: %d, modality: %d", mUserId, mTotalAttempts,
+                mRejectedAttempts, mEnrollmentNotifications, mModality).hashCode();
+    }
+}
diff --git a/services/core/java/com/android/server/biometrics/AuthenticationStatsCollector.java b/services/core/java/com/android/server/biometrics/AuthenticationStatsCollector.java
new file mode 100644
index 0000000..97e5c6f
--- /dev/null
+++ b/services/core/java/com/android/server/biometrics/AuthenticationStatsCollector.java
@@ -0,0 +1,192 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.biometrics;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageManager;
+import android.hardware.face.FaceManager;
+import android.hardware.fingerprint.FingerprintManager;
+import android.os.UserHandle;
+
+import com.android.internal.R;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.biometrics.sensors.BiometricNotification;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Calculate and collect on-device False Rejection Rates (FRR).
+ * FRR = All [given biometric modality] unlock failures / all [given biometric modality] unlock
+ * attempts.
+ */
+public class AuthenticationStatsCollector {
+
+    private static final String TAG = "AuthenticationStatsCollector";
+
+    // The minimum number of attempts that will calculate the FRR and trigger the notification.
+    private static final int MINIMUM_ATTEMPTS = 500;
+    // Upload the data every 50 attempts (average number of daily authentications).
+    private static final int AUTHENTICATION_UPLOAD_INTERVAL = 50;
+    // The maximum number of eligible biometric enrollment notification can be sent.
+    private static final int MAXIMUM_ENROLLMENT_NOTIFICATIONS = 2;
+
+    @NonNull private final Context mContext;
+
+    private final float mThreshold;
+    private final int mModality;
+
+    @NonNull private final Map<Integer, AuthenticationStats> mUserAuthenticationStatsMap;
+
+    // TODO(b/295582896): Find a way to make this NonNull
+    @Nullable private AuthenticationStatsPersister mAuthenticationStatsPersister;
+    @NonNull private BiometricNotification mBiometricNotification;
+
+    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(@NonNull Context context, @NonNull Intent intent) {
+            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
+            if (userId != UserHandle.USER_NULL
+                    && intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
+                onUserRemoved(userId);
+            }
+        }
+    };
+
+    public AuthenticationStatsCollector(@NonNull Context context, int modality,
+            @NonNull BiometricNotification biometricNotification) {
+        mContext = context;
+        mThreshold = context.getResources()
+                .getFraction(R.fraction.config_biometricNotificationFrrThreshold, 1, 1);
+        mUserAuthenticationStatsMap = new HashMap<>();
+        mModality = modality;
+        mBiometricNotification = biometricNotification;
+
+        context.registerReceiver(mBroadcastReceiver, new IntentFilter(Intent.ACTION_USER_REMOVED));
+    }
+
+    private void initializeUserAuthenticationStatsMap() {
+        mAuthenticationStatsPersister = new AuthenticationStatsPersister(mContext);
+        for (AuthenticationStats stats : mAuthenticationStatsPersister.getAllFrrStats(mModality)) {
+            mUserAuthenticationStatsMap.put(stats.getUserId(), stats);
+        }
+    }
+
+    /** Update total authentication and rejected attempts. */
+    public void authenticate(int userId, boolean authenticated) {
+        // SharedPreference is not ready when starting system server, initialize
+        // mUserAuthenticationStatsMap in authentication to ensure SharedPreference
+        // is ready for application use.
+        if (mUserAuthenticationStatsMap.isEmpty()) {
+            initializeUserAuthenticationStatsMap();
+        }
+        // Check if this is a new user.
+        if (!mUserAuthenticationStatsMap.containsKey(userId)) {
+            mUserAuthenticationStatsMap.put(userId, new AuthenticationStats(userId, mModality));
+        }
+
+        AuthenticationStats authenticationStats = mUserAuthenticationStatsMap.get(userId);
+
+        authenticationStats.authenticate(authenticated);
+
+        persistDataIfNeeded(userId);
+        sendNotificationIfNeeded(userId);
+    }
+
+    /** Check if a notification should be sent after a calculation cycle. */
+    private void sendNotificationIfNeeded(int userId) {
+        AuthenticationStats authenticationStats = mUserAuthenticationStatsMap.get(userId);
+        if (authenticationStats.getTotalAttempts() < MINIMUM_ATTEMPTS) {
+            return;
+        }
+
+        // Don't send notification if FRR below the threshold.
+        if (authenticationStats.getEnrollmentNotifications() >= MAXIMUM_ENROLLMENT_NOTIFICATIONS
+                || authenticationStats.getFrr() < mThreshold) {
+            authenticationStats.resetData();
+            return;
+        }
+
+        authenticationStats.resetData();
+
+        final PackageManager packageManager = mContext.getPackageManager();
+
+        // Don't send notification to single-modality devices.
+        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)
+                || !packageManager.hasSystemFeature(PackageManager.FEATURE_FACE)) {
+            return;
+        }
+
+        final FaceManager faceManager = mContext.getSystemService(FaceManager.class);
+        final boolean hasEnrolledFace = faceManager.hasEnrolledTemplates(userId);
+
+        final FingerprintManager fingerprintManager = mContext
+                .getSystemService(FingerprintManager.class);
+        final boolean hasEnrolledFingerprint = fingerprintManager.hasEnrolledTemplates(userId);
+
+        // Don't send notification when both face and fingerprint are enrolled.
+        if (hasEnrolledFace && hasEnrolledFingerprint) {
+            return;
+        }
+        if (hasEnrolledFace && !hasEnrolledFingerprint) {
+            mBiometricNotification.sendFpEnrollNotification(mContext);
+        } else if (!hasEnrolledFace && hasEnrolledFingerprint) {
+            mBiometricNotification.sendFaceEnrollNotification(mContext);
+        }
+    }
+
+    private void persistDataIfNeeded(int userId) {
+        AuthenticationStats authenticationStats = mUserAuthenticationStatsMap.get(userId);
+        if (authenticationStats.getTotalAttempts() % AUTHENTICATION_UPLOAD_INTERVAL == 0) {
+            mAuthenticationStatsPersister.persistFrrStats(authenticationStats.getUserId(),
+                    authenticationStats.getTotalAttempts(),
+                    authenticationStats.getRejectedAttempts(),
+                    authenticationStats.getEnrollmentNotifications(),
+                    authenticationStats.getModality());
+        }
+    }
+
+    private void onUserRemoved(final int userId) {
+        if (mAuthenticationStatsPersister == null) {
+            initializeUserAuthenticationStatsMap();
+        }
+        mUserAuthenticationStatsMap.remove(userId);
+        mAuthenticationStatsPersister.removeFrrStats(userId);
+    }
+
+    /**
+     * Only being used in tests. Callers should not make any changes to the returned
+     * authentication stats.
+     *
+     * @return AuthenticationStats of the user, or null if the stats doesn't exist.
+     */
+    @Nullable
+    @VisibleForTesting
+    AuthenticationStats getAuthenticationStatsForUser(int userId) {
+        return mUserAuthenticationStatsMap.getOrDefault(userId, null);
+    }
+
+    @VisibleForTesting
+    void setAuthenticationStatsForUser(int userId, AuthenticationStats authenticationStats) {
+        mUserAuthenticationStatsMap.put(userId, authenticationStats);
+    }
+}
diff --git a/services/core/java/com/android/server/biometrics/AuthenticationStatsPersister.java b/services/core/java/com/android/server/biometrics/AuthenticationStatsPersister.java
new file mode 100644
index 0000000..21e93a8
--- /dev/null
+++ b/services/core/java/com/android/server/biometrics/AuthenticationStatsPersister.java
@@ -0,0 +1,215 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.biometrics;
+
+import android.annotation.NonNull;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.hardware.biometrics.BiometricsProtoEnums;
+import android.os.Environment;
+import android.util.Slog;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Persists and retrieves stats for Biometric Authentication.
+ * Authentication stats include userId, total attempts, rejected attempts,
+ * and the number of sent enrollment notifications.
+ * Data are stored in SharedPreferences in a form of a set of JSON objects,
+ * where it's one element per user.
+ */
+public class AuthenticationStatsPersister {
+
+    private static final String TAG = "AuthenticationStatsPersister";
+    private static final String FILE_NAME = "authentication_stats";
+    private static final String USER_ID = "user_id";
+    private static final String FACE_ATTEMPTS = "face_attempts";
+    private static final String FACE_REJECTIONS = "face_rejections";
+    private static final String FINGERPRINT_ATTEMPTS = "fingerprint_attempts";
+    private static final String FINGERPRINT_REJECTIONS = "fingerprint_rejections";
+    private static final String ENROLLMENT_NOTIFICATIONS = "enrollment_notifications";
+    private static final String KEY = "frr_stats";
+
+    @NonNull private final SharedPreferences mSharedPreferences;
+
+    AuthenticationStatsPersister(@NonNull Context context) {
+        // The package info in the context isn't initialized in the way it is for normal apps,
+        // so the standard, name-based context.getSharedPreferences doesn't work. Instead, we
+        // build the path manually below using the same policy that appears in ContextImpl.
+        final File prefsFile = new File(Environment.getDataSystemDeDirectory(), FILE_NAME);
+        mSharedPreferences = context.getSharedPreferences(prefsFile, Context.MODE_PRIVATE);
+    }
+
+    /**
+     * Get all frr data from SharedPreference.
+     */
+    public List<AuthenticationStats> getAllFrrStats(int modality) {
+        List<AuthenticationStats> authenticationStatsList = new ArrayList<>();
+        for (String frrStats : readFrrStats()) {
+            try {
+                JSONObject frrStatsJson = new JSONObject(frrStats);
+                if (modality == BiometricsProtoEnums.MODALITY_FACE) {
+                    authenticationStatsList.add(new AuthenticationStats(
+                            getIntValue(frrStatsJson, USER_ID, -1 /* defaultValue */),
+                            getIntValue(frrStatsJson, FACE_ATTEMPTS),
+                            getIntValue(frrStatsJson, FACE_REJECTIONS),
+                            getIntValue(frrStatsJson, ENROLLMENT_NOTIFICATIONS),
+                            modality));
+                } else if (modality == BiometricsProtoEnums.MODALITY_FINGERPRINT) {
+                    authenticationStatsList.add(new AuthenticationStats(
+                            getIntValue(frrStatsJson, USER_ID, -1 /* defaultValue */),
+                            getIntValue(frrStatsJson, FINGERPRINT_ATTEMPTS),
+                            getIntValue(frrStatsJson, FINGERPRINT_REJECTIONS),
+                            getIntValue(frrStatsJson, ENROLLMENT_NOTIFICATIONS),
+                            modality));
+                }
+            } catch (JSONException e) {
+                Slog.w(TAG, String.format("Unable to resolve authentication stats JSON: %s",
+                        frrStats));
+            }
+        }
+        return authenticationStatsList;
+    }
+
+    /**
+     * Remove frr data for a specific user.
+     */
+    public void removeFrrStats(int userId) {
+        try {
+            // Copy into a new HashSet to allow modification.
+            Set<String> frrStatsSet = new HashSet<>(readFrrStats());
+
+            // Remove the old authentication stat for the user if it exists.
+            for (Iterator<String> iterator = frrStatsSet.iterator(); iterator.hasNext();) {
+                String frrStats = iterator.next();
+                JSONObject frrStatJson = new JSONObject(frrStats);
+                if (getValue(frrStatJson, USER_ID).equals(String.valueOf(userId))) {
+                    iterator.remove();
+                    break;
+                }
+            }
+
+            mSharedPreferences.edit().putStringSet(KEY, frrStatsSet).apply();
+        } catch (JSONException ignored) {
+        }
+    }
+
+    /**
+     * Persist frr data for a specific user.
+     */
+    public void persistFrrStats(int userId, int totalAttempts, int rejectedAttempts,
+            int enrollmentNotifications, int modality) {
+        try {
+            // Copy into a new HashSet to allow modification.
+            Set<String> frrStatsSet = new HashSet<>(readFrrStats());
+
+            // Remove the old authentication stat for the user if it exists.
+            JSONObject frrStatJson = null;
+            for (Iterator<String> iterator = frrStatsSet.iterator(); iterator.hasNext();) {
+                String frrStats = iterator.next();
+                frrStatJson = new JSONObject(frrStats);
+                if (getValue(frrStatJson, USER_ID).equals(String.valueOf(userId))) {
+                    iterator.remove();
+                    break;
+                }
+            }
+
+            // If there's existing frr stats in the file, we want to update the stats for the given
+            // modality and keep the stats for other modalities.
+            if (frrStatJson != null) {
+                frrStatsSet.add(buildFrrStats(frrStatJson, totalAttempts, rejectedAttempts,
+                        enrollmentNotifications, modality));
+            } else {
+                frrStatsSet.add(buildFrrStats(userId, totalAttempts, rejectedAttempts,
+                        enrollmentNotifications, modality));
+            }
+
+            mSharedPreferences.edit().putStringSet(KEY, frrStatsSet).apply();
+
+        } catch (JSONException e) {
+            Slog.e(TAG, "Unable to persist authentication stats");
+        }
+    }
+
+    private Set<String> readFrrStats() {
+        return mSharedPreferences.getStringSet(KEY, Set.of());
+    }
+
+    // Update frr stats for existing frrStats JSONObject and build the new string.
+    private String buildFrrStats(JSONObject frrStats, int totalAttempts, int rejectedAttempts,
+            int enrollmentNotifications, int modality) throws JSONException {
+        if (modality == BiometricsProtoEnums.MODALITY_FACE) {
+            return frrStats
+                    .put(FACE_ATTEMPTS, totalAttempts)
+                    .put(FACE_REJECTIONS, rejectedAttempts)
+                    .put(ENROLLMENT_NOTIFICATIONS, enrollmentNotifications)
+                    .toString();
+        } else if (modality == BiometricsProtoEnums.MODALITY_FINGERPRINT) {
+            return frrStats
+                    .put(FINGERPRINT_ATTEMPTS, totalAttempts)
+                    .put(FINGERPRINT_REJECTIONS, rejectedAttempts)
+                    .put(ENROLLMENT_NOTIFICATIONS, enrollmentNotifications)
+                    .toString();
+        } else {
+            return frrStats.toString();
+        }
+    }
+
+    // Build string for new user and new authentication stats.
+    private String buildFrrStats(int userId, int totalAttempts, int rejectedAttempts,
+            int enrollmentNotifications, int modality)
+            throws JSONException {
+        if (modality == BiometricsProtoEnums.MODALITY_FACE) {
+            return new JSONObject()
+                    .put(USER_ID, userId)
+                    .put(FACE_ATTEMPTS, totalAttempts)
+                    .put(FACE_REJECTIONS, rejectedAttempts)
+                    .put(ENROLLMENT_NOTIFICATIONS, enrollmentNotifications)
+                    .toString();
+        } else if (modality == BiometricsProtoEnums.MODALITY_FINGERPRINT) {
+            return new JSONObject()
+                    .put(USER_ID, userId)
+                    .put(FINGERPRINT_ATTEMPTS, totalAttempts)
+                    .put(FINGERPRINT_REJECTIONS, rejectedAttempts)
+                    .put(ENROLLMENT_NOTIFICATIONS, enrollmentNotifications)
+                    .toString();
+        } else {
+            return "";
+        }
+    }
+
+    private String getValue(JSONObject jsonObject, String key) throws JSONException {
+        return jsonObject.has(key) ? jsonObject.getString(key) : "";
+    }
+
+    private int getIntValue(JSONObject jsonObject, String key) throws JSONException {
+        return getIntValue(jsonObject, key, 0 /* defaultValue */);
+    }
+
+    private int getIntValue(JSONObject jsonObject, String key, int defaultValue)
+            throws JSONException {
+        return jsonObject.has(key) ? jsonObject.getInt(key) : defaultValue;
+    }
+}
diff --git a/services/core/java/com/android/server/biometrics/BiometricService.java b/services/core/java/com/android/server/biometrics/BiometricService.java
index 279aaf9..1898b80 100644
--- a/services/core/java/com/android/server/biometrics/BiometricService.java
+++ b/services/core/java/com/android/server/biometrics/BiometricService.java
@@ -1308,10 +1308,13 @@
                                 .getString(R.string.biometric_dialog_default_subtitle));
                     } else if (hasEligibleFingerprintSensor) {
                         promptInfo.setSubtitle(getContext()
-                                .getString(R.string.biometric_dialog_fingerprint_subtitle));
+                                .getString(R.string.fingerprint_dialog_default_subtitle));
                     } else if (hasEligibleFaceSensor) {
                         promptInfo.setSubtitle(getContext()
-                                .getString(R.string.biometric_dialog_face_subtitle));
+                                .getString(R.string.face_dialog_default_subtitle));
+                    } else {
+                        promptInfo.setSubtitle(getContext()
+                                .getString(R.string.screen_lock_dialog_default_subtitle));
                     }
                 }
 
diff --git a/services/core/java/com/android/server/biometrics/log/BiometricLogger.java b/services/core/java/com/android/server/biometrics/log/BiometricLogger.java
index c76a2e3..87037af 100644
--- a/services/core/java/com/android/server/biometrics/log/BiometricLogger.java
+++ b/services/core/java/com/android/server/biometrics/log/BiometricLogger.java
@@ -27,6 +27,7 @@
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.FrameworkStatsLog;
+import com.android.server.biometrics.AuthenticationStatsCollector;
 import com.android.server.biometrics.Utils;
 
 /**
@@ -41,6 +42,7 @@
     private final int mStatsAction;
     private final int mStatsClient;
     private final BiometricFrameworkStatsLogger mSink;
+    @NonNull private final AuthenticationStatsCollector mAuthenticationStatsCollector;
     @NonNull private final ALSProbe mALSProbe;
 
     private long mFirstAcquireTimeMs;
@@ -49,7 +51,8 @@
     /** Get a new logger with all unknown fields (for operations that do not require logs). */
     public static BiometricLogger ofUnknown(@NonNull Context context) {
         return new BiometricLogger(context, BiometricsProtoEnums.MODALITY_UNKNOWN,
-                BiometricsProtoEnums.ACTION_UNKNOWN, BiometricsProtoEnums.CLIENT_UNKNOWN);
+                BiometricsProtoEnums.ACTION_UNKNOWN, BiometricsProtoEnums.CLIENT_UNKNOWN,
+                null /* AuthenticationStatsCollector */);
     }
 
     /**
@@ -64,26 +67,32 @@
      * @param statsClient One of {@link BiometricsProtoEnums} CLIENT_* constants.
      */
     public BiometricLogger(
-            @NonNull Context context, int statsModality, int statsAction, int statsClient) {
+            @NonNull Context context, int statsModality, int statsAction, int statsClient,
+            AuthenticationStatsCollector authenticationStatsCollector) {
         this(statsModality, statsAction, statsClient,
                 BiometricFrameworkStatsLogger.getInstance(),
+                authenticationStatsCollector,
                 context.getSystemService(SensorManager.class));
     }
 
     @VisibleForTesting
     BiometricLogger(
             int statsModality, int statsAction, int statsClient,
-            BiometricFrameworkStatsLogger logSink, SensorManager sensorManager) {
+            BiometricFrameworkStatsLogger logSink,
+            @NonNull AuthenticationStatsCollector statsCollector,
+            SensorManager sensorManager) {
         mStatsModality = statsModality;
         mStatsAction = statsAction;
         mStatsClient = statsClient;
         mSink = logSink;
+        mAuthenticationStatsCollector = statsCollector;
         mALSProbe = new ALSProbe(sensorManager);
     }
 
     /** Creates a new logger with the action replaced with the new action. */
     public BiometricLogger swapAction(@NonNull Context context, int statsAction) {
-        return new BiometricLogger(context, mStatsModality, statsAction, mStatsClient);
+        return new BiometricLogger(context, mStatsModality, statsAction, mStatsClient,
+                null /* AuthenticationStatsCollector */);
     }
 
     /** Disable logging metrics and only log critical events, such as system health issues. */
@@ -192,10 +201,13 @@
     public void logOnAuthenticated(Context context, OperationContextExt operationContext,
             boolean authenticated, boolean requireConfirmation, int targetUserId,
             boolean isBiometricPrompt) {
+        // Do not log metrics when fingerprint enrollment reason is ENROLL_FIND_SENSOR
         if (!mShouldLogMetrics) {
             return;
         }
 
+        mAuthenticationStatsCollector.authenticate(targetUserId, authenticated);
+
         int authState = FrameworkStatsLog.BIOMETRIC_AUTHENTICATED__STATE__UNKNOWN;
         if (!authenticated) {
             authState = FrameworkStatsLog.BIOMETRIC_AUTHENTICATED__STATE__REJECTED;
diff --git a/services/core/java/com/android/server/biometrics/log/OperationContextExt.java b/services/core/java/com/android/server/biometrics/log/OperationContextExt.java
index 4a10e8e..f78ca43 100644
--- a/services/core/java/com/android/server/biometrics/log/OperationContextExt.java
+++ b/services/core/java/com/android/server/biometrics/log/OperationContextExt.java
@@ -103,8 +103,14 @@
      */
     @NonNull
     public OperationContext toAidlContext(@NonNull FingerprintAuthenticateOptions options) {
-        mAidlContext.authenticateReason = AuthenticateReason
-                .fingerprintAuthenticateReason(getAuthReason(options));
+        if (options.getVendorReason() != null) {
+            mAidlContext.authenticateReason = AuthenticateReason
+                    .vendorAuthenticateReason(options.getVendorReason());
+
+        } else {
+            mAidlContext.authenticateReason = AuthenticateReason
+                    .fingerprintAuthenticateReason(getAuthReason(options));
+        }
         mAidlContext.wakeReason = getWakeReason(options);
 
         return mAidlContext;
diff --git a/services/core/java/com/android/server/biometrics/sensors/BiometricNotification.java b/services/core/java/com/android/server/biometrics/sensors/BiometricNotification.java
new file mode 100644
index 0000000..90e1860
--- /dev/null
+++ b/services/core/java/com/android/server/biometrics/sensors/BiometricNotification.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.biometrics.sensors;
+
+import android.annotation.NonNull;
+import android.content.Context;
+
+/**
+ * Interface for biometrics to send notifications.
+ */
+public interface BiometricNotification {
+
+    /**
+     * Sends a face enrollment notification.
+     */
+    void sendFaceEnrollNotification(@NonNull Context context);
+
+    /**
+     * Sends a fingerprint enrollment notification.
+     */
+    void sendFpEnrollNotification(@NonNull Context context);
+}
diff --git a/services/core/java/com/android/server/biometrics/sensors/BiometricNotificationImpl.java b/services/core/java/com/android/server/biometrics/sensors/BiometricNotificationImpl.java
new file mode 100644
index 0000000..7b42046
--- /dev/null
+++ b/services/core/java/com/android/server/biometrics/sensors/BiometricNotificationImpl.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.biometrics.sensors;
+
+import android.annotation.NonNull;
+import android.content.Context;
+
+import com.android.server.biometrics.AuthenticationStatsCollector;
+
+/**
+ * Implementation to send biometric notifications for {@link AuthenticationStatsCollector}.
+ */
+public class BiometricNotificationImpl implements BiometricNotification {
+
+    @Override
+    public void sendFaceEnrollNotification(@NonNull Context context) {
+        BiometricNotificationUtils.showFaceEnrollNotification(context);
+    }
+
+    @Override
+    public void sendFpEnrollNotification(@NonNull Context context) {
+        BiometricNotificationUtils.showFingerprintEnrollNotification(context);
+    }
+}
diff --git a/services/core/java/com/android/server/biometrics/sensors/BiometricNotificationUtils.java b/services/core/java/com/android/server/biometrics/sensors/BiometricNotificationUtils.java
index f516a49..2ff695d 100644
--- a/services/core/java/com/android/server/biometrics/sensors/BiometricNotificationUtils.java
+++ b/services/core/java/com/android/server/biometrics/sensors/BiometricNotificationUtils.java
@@ -35,9 +35,22 @@
 public class BiometricNotificationUtils {
 
     private static final String TAG = "BiometricNotificationUtils";
-    private static final String RE_ENROLL_NOTIFICATION_TAG = "FaceService";
-    private static final String BAD_CALIBRATION_NOTIFICATION_TAG = "FingerprintService";
+    private static final String FACE_RE_ENROLL_NOTIFICATION_TAG = "FaceReEnroll";
+    private static final String FACE_ENROLL_NOTIFICATION_TAG = "FaceEnroll";
+    private static final String FINGERPRINT_ENROLL_NOTIFICATION_TAG = "FingerprintEnroll";
+    private static final String BAD_CALIBRATION_NOTIFICATION_TAG = "FingerprintBadCalibration";
     private static final String KEY_RE_ENROLL_FACE = "re_enroll_face_unlock";
+    private static final String FACE_SETTINGS_ACTION = "android.settings.FACE_SETTINGS";
+    private static final String FINGERPRINT_SETTINGS_ACTION =
+            "android.settings.FINGERPRINT_SETTINGS";
+    private static final String FACE_ENROLL_ACTION = "android.settings.FACE_ENROLL";
+    private static final String FINGERPRINT_ENROLL_ACTION = "android.settings.FINGERPRINT_ENROLL";
+    private static final String SETTINGS_PACKAGE = "com.android.settings";
+    private static final String FACE_ENROLL_CHANNEL = "FaceEnrollNotificationChannel";
+    private static final String FACE_RE_ENROLL_CHANNEL = "FaceReEnrollNotificationChannel";
+    private static final String FINGERPRINT_ENROLL_CHANNEL = "FingerprintEnrollNotificationChannel";
+    private static final String FINGERPRINT_BAD_CALIBRATION_CHANNEL =
+            "FingerprintBadCalibrationNotificationChannel";
     private static final int NOTIFICATION_ID = 1;
     private static final long NOTIFICATION_INTERVAL_MS = 24 * 60 * 60 * 1000;
     private static long sLastAlertTime = 0;
@@ -56,18 +69,67 @@
         final String content =
                 context.getString(R.string.face_recalibrate_notification_content);
 
-        final Intent intent = new Intent("android.settings.FACE_SETTINGS");
-        intent.setPackage("com.android.settings");
+        final Intent intent = new Intent(FACE_SETTINGS_ACTION);
+        intent.setPackage(SETTINGS_PACKAGE);
         intent.putExtra(KEY_RE_ENROLL_FACE, true);
 
         final PendingIntent pendingIntent = PendingIntent.getActivityAsUser(context,
                 0 /* requestCode */, intent, PendingIntent.FLAG_IMMUTABLE /* flags */,
                 null /* options */, UserHandle.CURRENT);
 
-        final String channelName = "FaceEnrollNotificationChannel";
+        showNotificationHelper(context, name, title, content, pendingIntent, FACE_RE_ENROLL_CHANNEL,
+                FACE_RE_ENROLL_NOTIFICATION_TAG, Notification.VISIBILITY_SECRET);
+    }
 
-        showNotificationHelper(context, name, title, content, pendingIntent, channelName,
-                RE_ENROLL_NOTIFICATION_TAG);
+    /**
+     * Shows a face enrollment notification.
+     */
+    public static void showFaceEnrollNotification(@NonNull Context context) {
+
+        final String name =
+                context.getString(R.string.device_unlock_notification_name);
+        final String title =
+                context.getString(R.string.alternative_unlock_setup_notification_title);
+        final String content =
+                context.getString(R.string.alternative_face_setup_notification_content);
+
+        final Intent intent = new Intent(FACE_ENROLL_ACTION);
+        intent.setPackage(SETTINGS_PACKAGE);
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        context.startActivity(intent);
+
+        final PendingIntent pendingIntent = PendingIntent.getActivityAsUser(context,
+                0 /* requestCode */, intent, PendingIntent.FLAG_IMMUTABLE /* flags */,
+                null /* options */, UserHandle.CURRENT);
+
+        showNotificationHelper(context, name, title, content, pendingIntent, FACE_ENROLL_CHANNEL,
+                FACE_ENROLL_NOTIFICATION_TAG, Notification.VISIBILITY_PUBLIC);
+    }
+
+    /**
+     * Shows a fingerprint enrollment notification.
+     */
+    public static void showFingerprintEnrollNotification(@NonNull Context context) {
+
+        final String name =
+                context.getString(R.string.device_unlock_notification_name);
+        final String title =
+                context.getString(R.string.alternative_unlock_setup_notification_title);
+        final String content =
+                context.getString(R.string.alternative_fp_setup_notification_content);
+
+        final Intent intent = new Intent(FINGERPRINT_ENROLL_ACTION);
+        intent.setPackage(SETTINGS_PACKAGE);
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        context.startActivity(intent);
+
+        final PendingIntent pendingIntent = PendingIntent.getActivityAsUser(context,
+                0 /* requestCode */, intent, PendingIntent.FLAG_IMMUTABLE /* flags */,
+                null /* options */, UserHandle.CURRENT);
+
+        showNotificationHelper(context, name, title, content, pendingIntent,
+                FINGERPRINT_ENROLL_CHANNEL, FINGERPRINT_ENROLL_NOTIFICATION_TAG,
+                Notification.VISIBILITY_PUBLIC);
     }
 
     /**
@@ -93,22 +155,21 @@
         final String content =
                 context.getString(R.string.fingerprint_recalibrate_notification_content);
 
-        final Intent intent = new Intent("android.settings.FINGERPRINT_SETTINGS");
-        intent.setPackage("com.android.settings");
+        final Intent intent = new Intent(FINGERPRINT_SETTINGS_ACTION);
+        intent.setPackage(SETTINGS_PACKAGE);
 
         final PendingIntent pendingIntent = PendingIntent.getActivityAsUser(context,
                 0 /* requestCode */, intent, PendingIntent.FLAG_IMMUTABLE /* flags */,
                 null /* options */, UserHandle.CURRENT);
 
-        final String channelName = "FingerprintBadCalibrationNotificationChannel";
-
-        showNotificationHelper(context, name, title, content, pendingIntent, channelName,
-                BAD_CALIBRATION_NOTIFICATION_TAG);
+        showNotificationHelper(context, name, title, content, pendingIntent,
+                FINGERPRINT_BAD_CALIBRATION_CHANNEL, BAD_CALIBRATION_NOTIFICATION_TAG,
+                Notification.VISIBILITY_SECRET);
     }
 
     private static void showNotificationHelper(Context context, String name, String title,
                 String content, PendingIntent pendingIntent, String channelName,
-                String notificationTag) {
+                String notificationTag, int visibility) {
         final NotificationManager notificationManager =
                 context.getSystemService(NotificationManager.class);
         final NotificationChannel channel = new NotificationChannel(channelName, name,
@@ -123,7 +184,7 @@
                 .setAutoCancel(true)
                 .setCategory(Notification.CATEGORY_SYSTEM)
                 .setContentIntent(pendingIntent)
-                .setVisibility(Notification.VISIBILITY_SECRET)
+                .setVisibility(visibility)
                 .build();
 
         notificationManager.createNotificationChannel(channel);
@@ -134,10 +195,30 @@
     /**
      * Cancels a face re-enrollment notification
      */
-    public static void cancelReEnrollNotification(@NonNull Context context) {
+    public static void cancelFaceReEnrollNotification(@NonNull Context context) {
         final NotificationManager notificationManager =
                 context.getSystemService(NotificationManager.class);
-        notificationManager.cancelAsUser(RE_ENROLL_NOTIFICATION_TAG, NOTIFICATION_ID,
+        notificationManager.cancelAsUser(FACE_RE_ENROLL_NOTIFICATION_TAG, NOTIFICATION_ID,
+                UserHandle.CURRENT);
+    }
+
+    /**
+     * Cancels a face enrollment notification
+     */
+    public static void cancelFaceEnrollNotification(@NonNull Context context) {
+        final NotificationManager notificationManager =
+                context.getSystemService(NotificationManager.class);
+        notificationManager.cancelAsUser(FACE_ENROLL_NOTIFICATION_TAG, NOTIFICATION_ID,
+                UserHandle.CURRENT);
+    }
+
+    /**
+     * Cancels a fingerprint enrollment notification
+     */
+    public static void cancelFingerprintEnrollNotification(@NonNull Context context) {
+        final NotificationManager notificationManager =
+                context.getSystemService(NotificationManager.class);
+        notificationManager.cancelAsUser(FINGERPRINT_ENROLL_NOTIFICATION_TAG, NOTIFICATION_ID,
                 UserHandle.CURRENT);
     }
 
diff --git a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClient.java b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClient.java
index 722c9af..f55cf05 100644
--- a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClient.java
+++ b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceEnrollClient.java
@@ -109,7 +109,8 @@
     public void start(@NonNull ClientMonitorCallback callback) {
         super.start(callback);
 
-        BiometricNotificationUtils.cancelReEnrollNotification(getContext());
+        BiometricNotificationUtils.cancelFaceEnrollNotification(getContext());
+        BiometricNotificationUtils.cancelFaceReEnrollNotification(getContext());
     }
 
     @NonNull
diff --git a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java
index 33ed63c..28f0a4d 100644
--- a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java
+++ b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceProvider.java
@@ -49,12 +49,14 @@
 import android.view.Surface;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.biometrics.AuthenticationStatsCollector;
 import com.android.server.biometrics.Utils;
 import com.android.server.biometrics.log.BiometricContext;
 import com.android.server.biometrics.log.BiometricLogger;
 import com.android.server.biometrics.sensors.AuthSessionCoordinator;
 import com.android.server.biometrics.sensors.AuthenticationClient;
 import com.android.server.biometrics.sensors.BaseClientMonitor;
+import com.android.server.biometrics.sensors.BiometricNotificationImpl;
 import com.android.server.biometrics.sensors.BiometricScheduler;
 import com.android.server.biometrics.sensors.BiometricStateCallback;
 import com.android.server.biometrics.sensors.ClientMonitorCallback;
@@ -112,6 +114,8 @@
     private final BiometricContext mBiometricContext;
     @NonNull
     private final AuthSessionCoordinator mAuthSessionCoordinator;
+    @NonNull
+    private final AuthenticationStatsCollector mAuthenticationStatsCollector;
     @Nullable
     private IFace mDaemon;
 
@@ -173,6 +177,9 @@
         mAuthSessionCoordinator = mBiometricContext.getAuthSessionCoordinator();
         mDaemon = daemon;
 
+        mAuthenticationStatsCollector = new AuthenticationStatsCollector(mContext,
+                BiometricsProtoEnums.MODALITY_FACE, new BiometricNotificationImpl());
+
         for (SensorProps prop : props) {
             final int sensorId = prop.commonProps.sensorId;
 
@@ -283,7 +290,8 @@
                     mContext, mFaceSensors.get(sensorId).getLazySession(), userId,
                     mContext.getOpPackageName(), sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN,
+                            mAuthenticationStatsCollector),
                     mBiometricContext,
                     mFaceSensors.get(sensorId).getAuthenticatorIds());
 
@@ -341,7 +349,8 @@
             final FaceInvalidationClient client = new FaceInvalidationClient(mContext,
                     mFaceSensors.get(sensorId).getLazySession(), userId, sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN,
+                            mAuthenticationStatsCollector),
                     mBiometricContext,
                     mFaceSensors.get(sensorId).getAuthenticatorIds(), callback);
             scheduleForSensor(sensorId, client);
@@ -372,7 +381,8 @@
                     mFaceSensors.get(sensorId).getLazySession(), token,
                     new ClientMonitorCallbackConverter(receiver), userId, opPackageName, sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN,
+                            mAuthenticationStatsCollector),
                     mBiometricContext);
             scheduleForSensor(sensorId, client);
         });
@@ -386,7 +396,8 @@
                     mFaceSensors.get(sensorId).getLazySession(), token, userId,
                     opPackageName, sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, challenge);
             scheduleForSensor(sensorId, client);
         });
@@ -407,7 +418,8 @@
                     opPackageName, id, FaceUtils.getInstance(sensorId), disabledFeatures,
                     ENROLL_TIMEOUT_SEC, previewSurface, sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_ENROLL,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, maxTemplatesPerUser, debugConsent);
             scheduleForSensor(sensorId, client, new ClientMonitorCompositeCallback(
                             mBiometricStateCallback, new ClientMonitorCallback() {
@@ -443,7 +455,8 @@
             final FaceDetectClient client = new FaceDetectClient(mContext,
                     mFaceSensors.get(sensorId).getLazySession(),
                     token, id, callback, options,
-                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient),
+                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, isStrongBiometric);
             scheduleForSensor(sensorId, client, mBiometricStateCallback);
         });
@@ -471,7 +484,8 @@
                     mContext, mFaceSensors.get(sensorId).getLazySession(), token, requestId,
                     callback, operationId, restricted, options, cookie,
                     false /* requireConfirmation */,
-                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient),
+                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, isStrongBiometric,
                     mUsageStats, mFaceSensors.get(sensorId).getLockoutCache(),
                     allowBackgroundAuthentication, Utils.getCurrentStrength(sensorId));
@@ -540,7 +554,8 @@
                     new ClientMonitorCallbackConverter(receiver), faceIds, userId,
                     opPackageName, FaceUtils.getInstance(sensorId), sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_REMOVE,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN,
+                            mAuthenticationStatsCollector),
                     mBiometricContext,
                     mFaceSensors.get(sensorId).getAuthenticatorIds());
             scheduleForSensor(sensorId, client, mBiometricStateCallback);
@@ -554,7 +569,8 @@
                     mContext, mFaceSensors.get(sensorId).getLazySession(), userId,
                     mContext.getOpPackageName(), sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, hardwareAuthToken,
                     mFaceSensors.get(sensorId).getLockoutCache(), mLockoutResetDispatcher,
                     Utils.getCurrentStrength(sensorId));
@@ -624,7 +640,8 @@
                             mFaceSensors.get(sensorId).getLazySession(), userId,
                             mContext.getOpPackageName(), sensorId,
                             createLogger(BiometricsProtoEnums.ACTION_ENUMERATE,
-                                    BiometricsProtoEnums.CLIENT_UNKNOWN),
+                                    BiometricsProtoEnums.CLIENT_UNKNOWN,
+                                    mAuthenticationStatsCollector),
                             mBiometricContext,
                             FaceUtils.getInstance(sensorId),
                             mFaceSensors.get(sensorId).getAuthenticatorIds());
@@ -636,9 +653,10 @@
         });
     }
 
-    private BiometricLogger createLogger(int statsAction, int statsClient) {
+    private BiometricLogger createLogger(int statsAction, int statsClient,
+            AuthenticationStatsCollector authenticationStatsCollector) {
         return new BiometricLogger(mContext, BiometricsProtoEnums.MODALITY_FACE,
-                statsAction, statsClient);
+                statsAction, statsClient, authenticationStatsCollector);
     }
 
     @Override
diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/Face10.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/Face10.java
index 1e33c96..8086261 100644
--- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/Face10.java
+++ b/services/core/java/com/android/server/biometrics/sensors/face/hidl/Face10.java
@@ -52,6 +52,7 @@
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.FrameworkStatsLog;
+import com.android.server.biometrics.AuthenticationStatsCollector;
 import com.android.server.biometrics.SensorServiceStateProto;
 import com.android.server.biometrics.SensorStateProto;
 import com.android.server.biometrics.UserStateProto;
@@ -61,7 +62,7 @@
 import com.android.server.biometrics.sensors.AcquisitionClient;
 import com.android.server.biometrics.sensors.AuthenticationConsumer;
 import com.android.server.biometrics.sensors.BaseClientMonitor;
-import com.android.server.biometrics.sensors.BiometricNotificationUtils;
+import com.android.server.biometrics.sensors.BiometricNotificationImpl;
 import com.android.server.biometrics.sensors.BiometricScheduler;
 import com.android.server.biometrics.sensors.BiometricStateCallback;
 import com.android.server.biometrics.sensors.ClientMonitorCallback;
@@ -124,6 +125,7 @@
     @Nullable private IBiometricsFace mDaemon;
     @NonNull private final HalResultController mHalResultController;
     @NonNull private final BiometricContext mBiometricContext;
+    @NonNull private final AuthenticationStatsCollector mAuthenticationStatsCollector;
     // for requests that do not use biometric prompt
     @NonNull private final AtomicLong mRequestCounter = new AtomicLong(0);
     private int mCurrentUserId = UserHandle.USER_NULL;
@@ -364,6 +366,9 @@
             mCurrentUserId = UserHandle.USER_NULL;
         });
 
+        mAuthenticationStatsCollector = new AuthenticationStatsCollector(mContext,
+                BiometricsProtoEnums.MODALITY_FACE, new BiometricNotificationImpl());
+
         try {
             ActivityManager.getService().registerUserSwitchObserver(mUserSwitchObserver, TAG);
         } catch (RemoteException e) {
@@ -554,7 +559,7 @@
                     mLazyDaemon, token, new ClientMonitorCallbackConverter(receiver), userId,
                     opPackageName, mSensorId,
                     createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext, sSystemClock.millis());
             mGeneratedChallengeCache = client;
             mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() {
@@ -586,7 +591,7 @@
             final FaceRevokeChallengeClient client = new FaceRevokeChallengeClient(mContext,
                     mLazyDaemon, token, userId, opPackageName, mSensorId,
                     createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext);
             mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() {
                 @Override
@@ -610,14 +615,12 @@
         mHandler.post(() -> {
             scheduleUpdateActiveUserWithoutHandler(userId);
 
-            BiometricNotificationUtils.cancelReEnrollNotification(mContext);
-
             final FaceEnrollClient client = new FaceEnrollClient(mContext, mLazyDaemon, token,
                     new ClientMonitorCallbackConverter(receiver), userId, hardwareAuthToken,
                     opPackageName, id, FaceUtils.getLegacyInstance(mSensorId), disabledFeatures,
                     ENROLL_TIMEOUT_SEC, previewSurface, mSensorId,
                     createLogger(BiometricsProtoEnums.ACTION_ENROLL,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext);
 
             mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() {
@@ -677,7 +680,8 @@
             final FaceAuthenticationClient client = new FaceAuthenticationClient(mContext,
                     mLazyDaemon, token, requestId, receiver, operationId, restricted,
                     options, cookie, false /* requireConfirmation */,
-                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient),
+                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, isStrongBiometric, mLockoutTracker,
                     mUsageStats, allowBackgroundAuthentication,
                     Utils.getCurrentStrength(mSensorId));
@@ -713,7 +717,7 @@
                     new ClientMonitorCallbackConverter(receiver), faceId, userId, opPackageName,
                     FaceUtils.getLegacyInstance(mSensorId), mSensorId,
                     createLogger(BiometricsProtoEnums.ACTION_REMOVE,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext, mAuthenticatorIds);
             mScheduler.scheduleClientMonitor(client, mBiometricStateCallback);
         });
@@ -731,7 +735,7 @@
                     opPackageName,
                     FaceUtils.getLegacyInstance(mSensorId), mSensorId,
                     createLogger(BiometricsProtoEnums.ACTION_REMOVE,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext, mAuthenticatorIds);
             mScheduler.scheduleClientMonitor(client, mBiometricStateCallback);
         });
@@ -750,7 +754,7 @@
             final FaceResetLockoutClient client = new FaceResetLockoutClient(mContext,
                     mLazyDaemon, userId, mContext.getOpPackageName(), mSensorId,
                     createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext, hardwareAuthToken);
             mScheduler.scheduleClientMonitor(client);
         });
@@ -821,7 +825,7 @@
             final FaceInternalCleanupClient client = new FaceInternalCleanupClient(mContext,
                     mLazyDaemon, userId, mContext.getOpPackageName(), mSensorId,
                     createLogger(BiometricsProtoEnums.ACTION_ENUMERATE,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext,
                     FaceUtils.getLegacyInstance(mSensorId), mAuthenticatorIds);
             mScheduler.scheduleClientMonitor(client, new ClientMonitorCompositeCallback(callback,
@@ -953,7 +957,7 @@
         final FaceUpdateActiveUserClient client = new FaceUpdateActiveUserClient(mContext,
                 mLazyDaemon, targetUserId, mContext.getOpPackageName(), mSensorId,
                 createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                        BiometricsProtoEnums.CLIENT_UNKNOWN),
+                        BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                 mBiometricContext, hasEnrolled, mAuthenticatorIds);
         mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() {
             @Override
@@ -968,9 +972,10 @@
         });
     }
 
-    private BiometricLogger createLogger(int statsAction, int statsClient) {
+    private BiometricLogger createLogger(int statsAction, int statsClient,
+            AuthenticationStatsCollector authenticationStatsCollector) {
         return new BiometricLogger(mContext, BiometricsProtoEnums.MODALITY_FACE,
-                statsAction, statsClient);
+                statsAction, statsClient, authenticationStatsCollector);
     }
 
     /**
diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceEnrollClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceEnrollClient.java
index 16d2f7a..27b9c79 100644
--- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceEnrollClient.java
+++ b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceEnrollClient.java
@@ -33,6 +33,7 @@
 import com.android.server.biometrics.Utils;
 import com.android.server.biometrics.log.BiometricContext;
 import com.android.server.biometrics.log.BiometricLogger;
+import com.android.server.biometrics.sensors.BiometricNotificationUtils;
 import com.android.server.biometrics.sensors.BiometricUtils;
 import com.android.server.biometrics.sensors.ClientMonitorCallback;
 import com.android.server.biometrics.sensors.ClientMonitorCallbackConverter;
@@ -71,6 +72,14 @@
                 .getIntArray(R.array.config_face_acquire_vendor_enroll_ignorelist);
     }
 
+    @Override
+    public void start(@NonNull ClientMonitorCallback callback) {
+        super.start(callback);
+
+        BiometricNotificationUtils.cancelFaceEnrollNotification(getContext());
+        BiometricNotificationUtils.cancelFaceReEnrollNotification(getContext());
+    }
+
     @NonNull
     @Override
     protected ClientMonitorCallback wrapCallbackForStart(@NonNull ClientMonitorCallback callback) {
diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClient.java
index f9e08d6..46ff6b4 100644
--- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClient.java
+++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintEnrollClient.java
@@ -104,6 +104,13 @@
         }
     }
 
+    @Override
+    public void start(@NonNull ClientMonitorCallback callback) {
+        super.start(callback);
+
+        BiometricNotificationUtils.cancelFingerprintEnrollNotification(getContext());
+    }
+
     @NonNull
     @Override
     protected ClientMonitorCallback wrapCallbackForStart(@NonNull ClientMonitorCallback callback) {
diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java
index 0421d78..5f4b894 100644
--- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java
+++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintProvider.java
@@ -57,12 +57,14 @@
 import android.util.proto.ProtoOutputStream;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.biometrics.AuthenticationStatsCollector;
 import com.android.server.biometrics.Utils;
 import com.android.server.biometrics.log.BiometricContext;
 import com.android.server.biometrics.log.BiometricLogger;
 import com.android.server.biometrics.sensors.AuthSessionCoordinator;
 import com.android.server.biometrics.sensors.AuthenticationClient;
 import com.android.server.biometrics.sensors.BaseClientMonitor;
+import com.android.server.biometrics.sensors.BiometricNotificationImpl;
 import com.android.server.biometrics.sensors.BiometricScheduler;
 import com.android.server.biometrics.sensors.BiometricStateCallback;
 import com.android.server.biometrics.sensors.ClientMonitorCallback;
@@ -122,6 +124,7 @@
     @Nullable private IUdfpsOverlayController mUdfpsOverlayController;
     @Nullable private ISidefpsController mSidefpsController;
     private AuthSessionCoordinator mAuthSessionCoordinator;
+    @NonNull private final AuthenticationStatsCollector mAuthenticationStatsCollector;
 
     private final class BiometricTaskStackListener extends TaskStackListener {
         @Override
@@ -181,6 +184,9 @@
         mAuthSessionCoordinator = mBiometricContext.getAuthSessionCoordinator();
         mDaemon = daemon;
 
+        mAuthenticationStatsCollector = new AuthenticationStatsCollector(mContext,
+                BiometricsProtoEnums.MODALITY_FINGERPRINT, new BiometricNotificationImpl());
+
         final List<SensorLocationInternal> workaroundLocations = getWorkaroundSensorProps(context);
 
         for (SensorProps prop : props) {
@@ -338,7 +344,8 @@
                             mFingerprintSensors.get(sensorId).getLazySession(), userId,
                             mContext.getOpPackageName(), sensorId,
                             createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                                    BiometricsProtoEnums.CLIENT_UNKNOWN),
+                                    BiometricsProtoEnums.CLIENT_UNKNOWN,
+                                    mAuthenticationStatsCollector),
                             mBiometricContext,
                             mFingerprintSensors.get(sensorId).getAuthenticatorIds());
             scheduleForSensor(sensorId, client);
@@ -363,7 +370,8 @@
                     mContext, mFingerprintSensors.get(sensorId).getLazySession(), userId,
                     mContext.getOpPackageName(), sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, hardwareAuthToken,
                     mFingerprintSensors.get(sensorId).getLockoutCache(), mLockoutResetDispatcher,
                     Utils.getCurrentStrength(sensorId));
@@ -380,7 +388,7 @@
                             mFingerprintSensors.get(sensorId).getLazySession(), token,
                             new ClientMonitorCallbackConverter(receiver), userId, opPackageName,
                             sensorId, createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                             mBiometricContext);
             scheduleForSensor(sensorId, client);
         });
@@ -395,7 +403,8 @@
                             mFingerprintSensors.get(sensorId).getLazySession(), token,
                             userId, opPackageName, sensorId,
                             createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                                    BiometricsProtoEnums.CLIENT_UNKNOWN),
+                                    BiometricsProtoEnums.CLIENT_UNKNOWN,
+                                    mAuthenticationStatsCollector),
                             mBiometricContext, challenge);
             scheduleForSensor(sensorId, client);
         });
@@ -415,7 +424,7 @@
                     new ClientMonitorCallbackConverter(receiver), userId, hardwareAuthToken,
                     opPackageName, FingerprintUtils.getInstance(sensorId), sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_ENROLL,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext,
                     mFingerprintSensors.get(sensorId).getSensorProperties(),
                     mUdfpsOverlayController, mSidefpsController,
@@ -455,7 +464,8 @@
             final FingerprintDetectClient client = new FingerprintDetectClient(mContext,
                     mFingerprintSensors.get(sensorId).getLazySession(), token, id, callback,
                     options,
-                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient),
+                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, mUdfpsOverlayController, isStrongBiometric);
             scheduleForSensor(sensorId, client, mBiometricStateCallback);
         });
@@ -477,7 +487,8 @@
                     mContext, mFingerprintSensors.get(sensorId).getLazySession(), token, requestId,
                     callback, operationId, restricted, options, cookie,
                     false /* requireConfirmation */,
-                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient),
+                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, isStrongBiometric,
                     mTaskStackListener, mFingerprintSensors.get(sensorId).getLockoutCache(),
                     mUdfpsOverlayController, mSidefpsController,
@@ -566,7 +577,8 @@
                     new ClientMonitorCallbackConverter(receiver), fingerprintIds, userId,
                     opPackageName, FingerprintUtils.getInstance(sensorId), sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_REMOVE,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN,
+                            mAuthenticationStatsCollector),
                     mBiometricContext,
                     mFingerprintSensors.get(sensorId).getAuthenticatorIds());
             scheduleForSensor(sensorId, client, mBiometricStateCallback);
@@ -588,7 +600,8 @@
                             mFingerprintSensors.get(sensorId).getLazySession(), userId,
                             mContext.getOpPackageName(), sensorId,
                             createLogger(BiometricsProtoEnums.ACTION_ENUMERATE,
-                                    BiometricsProtoEnums.CLIENT_UNKNOWN),
+                                    BiometricsProtoEnums.CLIENT_UNKNOWN,
+                                    mAuthenticationStatsCollector),
                             mBiometricContext,
                             FingerprintUtils.getInstance(sensorId),
                             mFingerprintSensors.get(sensorId).getAuthenticatorIds());
@@ -600,9 +613,10 @@
         });
     }
 
-    private BiometricLogger createLogger(int statsAction, int statsClient) {
+    private BiometricLogger createLogger(int statsAction, int statsClient,
+            AuthenticationStatsCollector authenticationStatsCollector) {
         return new BiometricLogger(mContext, BiometricsProtoEnums.MODALITY_FINGERPRINT,
-                statsAction, statsClient);
+                statsAction, statsClient, authenticationStatsCollector);
     }
 
     @Override
@@ -635,7 +649,8 @@
                     new FingerprintInvalidationClient(mContext,
                             mFingerprintSensors.get(sensorId).getLazySession(), userId, sensorId,
                             createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                                    BiometricsProtoEnums.CLIENT_UNKNOWN),
+                                    BiometricsProtoEnums.CLIENT_UNKNOWN,
+                                    mAuthenticationStatsCollector),
                             mBiometricContext,
                             mFingerprintSensors.get(sensorId).getAuthenticatorIds(), callback);
             scheduleForSensor(sensorId, client);
diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21.java
index 92b216d..d0b71fc 100644
--- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21.java
+++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21.java
@@ -52,6 +52,7 @@
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.FrameworkStatsLog;
+import com.android.server.biometrics.AuthenticationStatsCollector;
 import com.android.server.biometrics.SensorServiceStateProto;
 import com.android.server.biometrics.SensorStateProto;
 import com.android.server.biometrics.UserStateProto;
@@ -65,6 +66,7 @@
 import com.android.server.biometrics.sensors.AuthenticationClient;
 import com.android.server.biometrics.sensors.AuthenticationConsumer;
 import com.android.server.biometrics.sensors.BaseClientMonitor;
+import com.android.server.biometrics.sensors.BiometricNotificationImpl;
 import com.android.server.biometrics.sensors.BiometricScheduler;
 import com.android.server.biometrics.sensors.BiometricStateCallback;
 import com.android.server.biometrics.sensors.ClientMonitorCallback;
@@ -123,6 +125,7 @@
     @Nullable private IUdfpsOverlayController mUdfpsOverlayController;
     @Nullable private ISidefpsController mSidefpsController;
     @NonNull private final BiometricContext mBiometricContext;
+    @NonNull private final AuthenticationStatsCollector mAuthenticationStatsCollector;
     // for requests that do not use biometric prompt
     @NonNull private final AtomicLong mRequestCounter = new AtomicLong(0);
     private int mCurrentUserId = UserHandle.USER_NULL;
@@ -351,6 +354,9 @@
             mCurrentUserId = UserHandle.USER_NULL;
         });
 
+        mAuthenticationStatsCollector = new AuthenticationStatsCollector(mContext,
+                BiometricsProtoEnums.MODALITY_FINGERPRINT, new BiometricNotificationImpl());
+
         try {
             ActivityManager.getService().registerUserSwitchObserver(mUserSwitchObserver, TAG);
         } catch (RemoteException e) {
@@ -497,7 +503,8 @@
                 new FingerprintUpdateActiveUserClient(mContext, mLazyDaemon, targetUserId,
                         mContext.getOpPackageName(), mSensorProperties.sensorId,
                         createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                                BiometricsProtoEnums.CLIENT_UNKNOWN),
+                                BiometricsProtoEnums.CLIENT_UNKNOWN,
+                                mAuthenticationStatsCollector),
                         mBiometricContext,
                         this::getCurrentUser, hasEnrolled, mAuthenticatorIds, force);
         mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() {
@@ -544,7 +551,8 @@
             final FingerprintResetLockoutClient client = new FingerprintResetLockoutClient(mContext,
                     userId, mContext.getOpPackageName(), sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, mLockoutTracker);
             mScheduler.scheduleClientMonitor(client);
         });
@@ -559,7 +567,8 @@
                             new ClientMonitorCallbackConverter(receiver), userId, opPackageName,
                             mSensorProperties.sensorId,
                             createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                                    BiometricsProtoEnums.CLIENT_UNKNOWN),
+                                    BiometricsProtoEnums.CLIENT_UNKNOWN,
+                                    mAuthenticationStatsCollector),
                             mBiometricContext);
             mScheduler.scheduleClientMonitor(client);
         });
@@ -573,7 +582,8 @@
                     mContext, mLazyDaemon, token, userId, opPackageName,
                     mSensorProperties.sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_UNKNOWN,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN,
+                            mAuthenticationStatsCollector),
                     mBiometricContext);
             mScheduler.scheduleClientMonitor(client);
         });
@@ -594,7 +604,7 @@
                     FingerprintUtils.getLegacyInstance(mSensorId), ENROLL_TIMEOUT_SEC,
                     mSensorProperties.sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_ENROLL,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext, mUdfpsOverlayController, mSidefpsController, enrollReason);
             mScheduler.scheduleClientMonitor(client, new ClientMonitorCallback() {
                 @Override
@@ -639,7 +649,8 @@
             final boolean isStrongBiometric = Utils.isStrongBiometric(mSensorProperties.sensorId);
             final FingerprintDetectClient client = new FingerprintDetectClient(mContext,
                     mLazyDaemon, token, id, listener, options,
-                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient),
+                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, mUdfpsOverlayController, isStrongBiometric);
             mScheduler.scheduleClientMonitor(client, mBiometricStateCallback);
         });
@@ -660,7 +671,8 @@
             final FingerprintAuthenticationClient client = new FingerprintAuthenticationClient(
                     mContext, mLazyDaemon, token, requestId, listener, operationId,
                     restricted, options, cookie, false /* requireConfirmation */,
-                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient),
+                    createLogger(BiometricsProtoEnums.ACTION_AUTHENTICATE, statsClient,
+                            mAuthenticationStatsCollector),
                     mBiometricContext, isStrongBiometric,
                     mTaskStackListener, mLockoutTracker,
                     mUdfpsOverlayController, mSidefpsController,
@@ -706,7 +718,7 @@
                     userId, opPackageName, FingerprintUtils.getLegacyInstance(mSensorId),
                     mSensorProperties.sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_REMOVE,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext, mAuthenticatorIds);
             mScheduler.scheduleClientMonitor(client, mBiometricStateCallback);
         });
@@ -726,7 +738,7 @@
                     FingerprintUtils.getLegacyInstance(mSensorId),
                     mSensorProperties.sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_REMOVE,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext, mAuthenticatorIds);
             mScheduler.scheduleClientMonitor(client, mBiometricStateCallback);
         });
@@ -741,7 +753,7 @@
                     mContext, mLazyDaemon, userId, mContext.getOpPackageName(),
                     mSensorProperties.sensorId,
                     createLogger(BiometricsProtoEnums.ACTION_ENUMERATE,
-                            BiometricsProtoEnums.CLIENT_UNKNOWN),
+                            BiometricsProtoEnums.CLIENT_UNKNOWN, mAuthenticationStatsCollector),
                     mBiometricContext,
                     FingerprintUtils.getLegacyInstance(mSensorId), mAuthenticatorIds);
             mScheduler.scheduleClientMonitor(client, callback);
@@ -762,9 +774,10 @@
                 mBiometricStateCallback));
     }
 
-    private BiometricLogger createLogger(int statsAction, int statsClient) {
+    private BiometricLogger createLogger(int statsAction, int statsClient,
+            AuthenticationStatsCollector authenticationStatsCollector) {
         return new BiometricLogger(mContext, BiometricsProtoEnums.MODALITY_FINGERPRINT,
-                statsAction, statsClient);
+                statsAction, statsClient, authenticationStatsCollector);
     }
 
     @Override
diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintEnrollClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintEnrollClient.java
index 6fee84a..382e7e2 100644
--- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintEnrollClient.java
+++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintEnrollClient.java
@@ -81,6 +81,13 @@
         }
     }
 
+    @Override
+    public void start(@NonNull ClientMonitorCallback callback) {
+        super.start(callback);
+
+        BiometricNotificationUtils.cancelFingerprintEnrollNotification(getContext());
+    }
+
     @NonNull
     @Override
     protected ClientMonitorCallback wrapCallbackForStart(@NonNull ClientMonitorCallback callback) {
diff --git a/services/core/java/com/android/server/content/SyncManager.java b/services/core/java/com/android/server/content/SyncManager.java
index 3e31bd1..0aac7c2 100644
--- a/services/core/java/com/android/server/content/SyncManager.java
+++ b/services/core/java/com/android/server/content/SyncManager.java
@@ -220,8 +220,10 @@
     private static final int SYNC_OP_STATE_INVALID_SYNC_DISABLED = 5;
 
     /** Flags used when connecting to a sync adapter service */
-    private static final int SYNC_ADAPTER_CONNECTION_FLAGS = Context.BIND_AUTO_CREATE
-            | Context.BIND_NOT_FOREGROUND | Context.BIND_ALLOW_OOM_MANAGEMENT;
+    private static final Context.BindServiceFlags SYNC_ADAPTER_CONNECTION_FLAGS =
+            Context.BindServiceFlags.of(
+                    Context.BIND_FILTER_OUT_QUARANTINED_COMPONENTS | Context.BIND_AUTO_CREATE
+                            | Context.BIND_NOT_FOREGROUND | Context.BIND_ALLOW_OOM_MANAGEMENT);
 
     /** Singleton instance. */
     @GuardedBy("SyncManager.class")
diff --git a/services/core/java/com/android/server/display/DisplayBrightnessState.java b/services/core/java/com/android/server/display/DisplayBrightnessState.java
index da51569..1c1b69b 100644
--- a/services/core/java/com/android/server/display/DisplayBrightnessState.java
+++ b/services/core/java/com/android/server/display/DisplayBrightnessState.java
@@ -134,6 +134,13 @@
     }
 
     /**
+     * Helper methods to create builder
+     */
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    /**
      * A DisplayBrightnessState's builder class.
      */
     public static class Builder {
diff --git a/services/core/java/com/android/server/display/DisplayDevice.java b/services/core/java/com/android/server/display/DisplayDevice.java
index d57dc47..8642fb8 100644
--- a/services/core/java/com/android/server/display/DisplayDevice.java
+++ b/services/core/java/com/android/server/display/DisplayDevice.java
@@ -16,6 +16,9 @@
 
 package com.android.server.display;
 
+import static android.view.Surface.ROTATION_270;
+import static android.view.Surface.ROTATION_90;
+
 import android.annotation.Nullable;
 import android.content.Context;
 import android.graphics.Point;
@@ -132,12 +135,15 @@
     /**
      * Returns the default size of the surface associated with the display, or null if the surface
      * is not provided for layer mirroring by SurfaceFlinger. For non virtual displays, this will
-     * be the actual display device's size.
+     * be the actual display device's size, reflecting the current rotation.
      */
     @Nullable
     public Point getDisplaySurfaceDefaultSizeLocked() {
         DisplayDeviceInfo displayDeviceInfo = getDisplayDeviceInfoLocked();
-        return new Point(displayDeviceInfo.width, displayDeviceInfo.height);
+        final boolean isRotated = mCurrentOrientation == ROTATION_90
+                || mCurrentOrientation == ROTATION_270;
+        return isRotated ? new Point(displayDeviceInfo.height, displayDeviceInfo.width)
+                : new Point(displayDeviceInfo.width, displayDeviceInfo.height);
     }
 
     /**
@@ -358,7 +364,7 @@
         }
 
         boolean isRotated = (mCurrentOrientation == Surface.ROTATION_90
-                || mCurrentOrientation == Surface.ROTATION_270);
+                || mCurrentOrientation == ROTATION_270);
         DisplayDeviceInfo info = getDisplayDeviceInfoLocked();
         viewport.deviceWidth = isRotated ? info.height : info.width;
         viewport.deviceHeight = isRotated ? info.width : info.height;
diff --git a/services/core/java/com/android/server/display/DisplayDeviceConfig.java b/services/core/java/com/android/server/display/DisplayDeviceConfig.java
index e5965ef..01eceda 100644
--- a/services/core/java/com/android/server/display/DisplayDeviceConfig.java
+++ b/services/core/java/com/android/server/display/DisplayDeviceConfig.java
@@ -222,8 +222,14 @@
  *          <minimum>120</minimum>
  *          <maximum>120</maximum>
  *        </refreshRate>
- *        <thermalStatusLimit>light</thermalStatusLimit>
  *        <allowInLowPowerMode>false</allowInLowPowerMode>
+ *        <minimumHdrPercentOfScreen>0.6</minimumHdrPercentOfScreen>
+ *        <sdrHdrRatioMap>
+ *          <point>
+ *            <sdrNits>2.000</sdrNits>
+ *            <hdrRatio>4.000</hdrRatio>
+ *          </point>
+ *        </sdrHdrRatioMap>
  *      </highBrightnessMode>
  *
  *      <luxThrottling>
@@ -276,6 +282,10 @@
  *      <lightSensor>
  *        <type>android.sensor.light</type>
  *        <name>1234 Ambient Light Sensor</name>
+ *        <refreshRate>
+ *          <minimum>60</minimum>
+ *          <maximum>120</maximum>
+ *        </refreshRate>
  *      </lightSensor>
  *      <screenOffBrightnessSensor>
  *        <type>com.google.sensor.binned_brightness</type>
@@ -1568,37 +1578,40 @@
     public String toString() {
         return "DisplayDeviceConfig{"
                 + "mLoadedFrom=" + mLoadedFrom
-                + ", mBacklight=" + Arrays.toString(mBacklight)
+                + "\n"
+                + "mBacklight=" + Arrays.toString(mBacklight)
                 + ", mNits=" + Arrays.toString(mNits)
                 + ", mRawBacklight=" + Arrays.toString(mRawBacklight)
                 + ", mRawNits=" + Arrays.toString(mRawNits)
                 + ", mInterpolationType=" + mInterpolationType
-                + ", mBrightness=" + Arrays.toString(mBrightness)
-                + ", mBrightnessToBacklightSpline=" + mBrightnessToBacklightSpline
+                + "mBrightness=" + Arrays.toString(mBrightness)
+                + "\n"
+                + "mBrightnessToBacklightSpline=" + mBrightnessToBacklightSpline
                 + ", mBacklightToBrightnessSpline=" + mBacklightToBrightnessSpline
                 + ", mNitsToBacklightSpline=" + mNitsToBacklightSpline
                 + ", mBacklightMinimum=" + mBacklightMinimum
                 + ", mBacklightMaximum=" + mBacklightMaximum
                 + ", mBrightnessDefault=" + mBrightnessDefault
                 + ", mQuirks=" + mQuirks
-                + ", isHbmEnabled=" + mIsHighBrightnessModeEnabled
-                + ", mLuxThrottlingData=" + mLuxThrottlingData
+                + ", mIsHighBrightnessModeEnabled=" + mIsHighBrightnessModeEnabled
+                + "\n"
+                + "mLuxThrottlingData=" + mLuxThrottlingData
                 + ", mHbmData=" + mHbmData
                 + ", mSdrToHdrRatioSpline=" + mSdrToHdrRatioSpline
                 + ", mThermalBrightnessThrottlingDataMapByThrottlingId="
                 + mThermalBrightnessThrottlingDataMapByThrottlingId
                 + "\n"
-                + ", mBrightnessRampFastDecrease=" + mBrightnessRampFastDecrease
+                + "mBrightnessRampFastDecrease=" + mBrightnessRampFastDecrease
                 + ", mBrightnessRampFastIncrease=" + mBrightnessRampFastIncrease
                 + ", mBrightnessRampSlowDecrease=" + mBrightnessRampSlowDecrease
                 + ", mBrightnessRampSlowIncrease=" + mBrightnessRampSlowIncrease
                 + ", mBrightnessRampDecreaseMaxMillis=" + mBrightnessRampDecreaseMaxMillis
                 + ", mBrightnessRampIncreaseMaxMillis=" + mBrightnessRampIncreaseMaxMillis
                 + "\n"
-                + ", mAmbientHorizonLong=" + mAmbientHorizonLong
+                + "mAmbientHorizonLong=" + mAmbientHorizonLong
                 + ", mAmbientHorizonShort=" + mAmbientHorizonShort
                 + "\n"
-                + ", mScreenDarkeningMinThreshold=" + mScreenDarkeningMinThreshold
+                + "mScreenDarkeningMinThreshold=" + mScreenDarkeningMinThreshold
                 + ", mScreenDarkeningMinThresholdIdle=" + mScreenDarkeningMinThresholdIdle
                 + ", mScreenBrighteningMinThreshold=" + mScreenBrighteningMinThreshold
                 + ", mScreenBrighteningMinThresholdIdle=" + mScreenBrighteningMinThresholdIdle
@@ -1608,7 +1621,7 @@
                 + ", mAmbientLuxBrighteningMinThresholdIdle="
                 + mAmbientLuxBrighteningMinThresholdIdle
                 + "\n"
-                + ", mScreenBrighteningLevels=" + Arrays.toString(
+                + "mScreenBrighteningLevels=" + Arrays.toString(
                 mScreenBrighteningLevels)
                 + ", mScreenBrighteningPercentages=" + Arrays.toString(
                 mScreenBrighteningPercentages)
@@ -1625,7 +1638,7 @@
                 + ", mAmbientDarkeningPercentages=" + Arrays.toString(
                 mAmbientDarkeningPercentages)
                 + "\n"
-                + ", mAmbientBrighteningLevelsIdle=" + Arrays.toString(
+                + "mAmbientBrighteningLevelsIdle=" + Arrays.toString(
                 mAmbientBrighteningLevelsIdle)
                 + ", mAmbientBrighteningPercentagesIdle=" + Arrays.toString(
                 mAmbientBrighteningPercentagesIdle)
@@ -1642,7 +1655,7 @@
                 + ", mScreenDarkeningPercentagesIdle=" + Arrays.toString(
                 mScreenDarkeningPercentagesIdle)
                 + "\n"
-                + ", mAmbientLightSensor=" + mAmbientLightSensor
+                + "mAmbientLightSensor=" + mAmbientLightSensor
                 + ", mScreenOffBrightnessSensor=" + mScreenOffBrightnessSensor
                 + ", mProximitySensor=" + mProximitySensor
                 + ", mRefreshRateLimitations= " + Arrays.toString(mRefreshRateLimitations.toArray())
@@ -1656,7 +1669,7 @@
                 + ", mDdcAutoBrightnessAvailable= " + mDdcAutoBrightnessAvailable
                 + ", mAutoBrightnessAvailable= " + mAutoBrightnessAvailable
                 + "\n"
-                + ", mDefaultLowBlockingZoneRefreshRate= " + mDefaultLowBlockingZoneRefreshRate
+                + "mDefaultLowBlockingZoneRefreshRate= " + mDefaultLowBlockingZoneRefreshRate
                 + ", mDefaultHighBlockingZoneRefreshRate= " + mDefaultHighBlockingZoneRefreshRate
                 + ", mDefaultPeakRefreshRate= " + mDefaultPeakRefreshRate
                 + ", mDefaultRefreshRate= " + mDefaultRefreshRate
@@ -1665,7 +1678,7 @@
                 + ", mDefaultRefreshRateInHbmSunlight= " + mDefaultRefreshRateInHbmSunlight
                 + ", mRefreshRateThrottlingMap= " + mRefreshRateThrottlingMap
                 + "\n"
-                + ", mLowDisplayBrightnessThresholds= "
+                + "mLowDisplayBrightnessThresholds= "
                 + Arrays.toString(mLowDisplayBrightnessThresholds)
                 + ", mLowAmbientBrightnessThresholds= "
                 + Arrays.toString(mLowAmbientBrightnessThresholds)
@@ -1674,10 +1687,10 @@
                 + ", mHighAmbientBrightnessThresholds= "
                 + Arrays.toString(mHighAmbientBrightnessThresholds)
                 + "\n"
-                + ", mScreenOffBrightnessSensorValueToLux=" + Arrays.toString(
+                + "mScreenOffBrightnessSensorValueToLux=" + Arrays.toString(
                 mScreenOffBrightnessSensorValueToLux)
                 + "\n"
-                + ", mUsiVersion= " + mHostUsiVersion
+                + "mUsiVersion= " + mHostUsiVersion
                 + "}";
     }
 
@@ -2080,7 +2093,7 @@
 
     /** Loads the refresh rate profiles. */
     private void loadRefreshRateZoneProfiles(RefreshRateConfigs refreshRateConfigs) {
-        if (refreshRateConfigs == null) {
+        if (refreshRateConfigs == null || refreshRateConfigs.getRefreshRateZoneProfiles() == null) {
             return;
         }
         for (RefreshRateZone zone :
diff --git a/services/core/java/com/android/server/display/DisplayManagerService.java b/services/core/java/com/android/server/display/DisplayManagerService.java
index 19dffeb..fe445a6 100644
--- a/services/core/java/com/android/server/display/DisplayManagerService.java
+++ b/services/core/java/com/android/server/display/DisplayManagerService.java
@@ -39,6 +39,7 @@
 import static android.hardware.display.DisplayViewport.VIEWPORT_INTERNAL;
 import static android.hardware.display.DisplayViewport.VIEWPORT_VIRTUAL;
 import static android.hardware.display.HdrConversionMode.HDR_CONVERSION_UNSUPPORTED;
+import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL;
 import static android.os.Process.FIRST_APPLICATION_UID;
 import static android.os.Process.ROOT_UID;
 
@@ -593,7 +594,7 @@
         DisplayManagerGlobal.invalidateLocalDisplayInfoCaches();
 
         publishBinderService(Context.DISPLAY_SERVICE, new BinderService(),
-                true /*allowIsolated*/);
+                true /*allowIsolated*/, DUMP_FLAG_PRIORITY_CRITICAL);
         publishLocalService(DisplayManagerInternal.class, new LocalService());
     }
 
@@ -1546,6 +1547,7 @@
                 if (displayId != Display.INVALID_DISPLAY && virtualDevice != null && dwpc != null) {
                     mDisplayWindowPolicyControllers.put(
                             displayId, Pair.create(virtualDevice, dwpc));
+                    Slog.d(TAG, "Virtual Display: successfully created virtual display");
                 }
             }
 
@@ -1592,19 +1594,25 @@
                     if (!getProjectionService().setContentRecordingSession(session, projection)) {
                         // Unable to start mirroring, so release VirtualDisplay. Projection service
                         // handles stopping the projection.
+                        Slog.w(TAG, "Content Recording: failed to start mirroring - "
+                                + "releasing virtual display " + displayId);
                         releaseVirtualDisplayInternal(callback.asBinder());
                         return Display.INVALID_DISPLAY;
                     } else if (projection != null) {
                         // Indicate that this projection has been used to record, and can't be used
                         // again.
+                        Slog.d(TAG, "Content Recording: notifying MediaProjection of successful"
+                                + " VirtualDisplay creation.");
                         projection.notifyVirtualDisplayCreated(displayId);
                     }
                 } catch (RemoteException e) {
                     Slog.e(TAG, "Unable to tell MediaProjectionManagerService to set the "
                             + "content recording session", e);
+                    return displayId;
                 }
+                Slog.d(TAG, "Virtual Display: successfully set up virtual display "
+                        + displayId);
             }
-
             return displayId;
         } finally {
             Binder.restoreCallingIdentity(secondToken);
@@ -1628,10 +1636,13 @@
             return -1;
         }
 
+
+        Slog.d(TAG, "Virtual Display: creating DisplayDevice with VirtualDisplayAdapter");
         DisplayDevice device = mVirtualDisplayAdapter.createVirtualDisplayLocked(
                 callback, projection, callingUid, packageName, surface, flags,
                 virtualDisplayConfig);
         if (device == null) {
+            Slog.w(TAG, "Virtual Display: VirtualDisplayAdapter failed to create DisplayDevice");
             return -1;
         }
 
@@ -1709,6 +1720,7 @@
 
             DisplayDevice device =
                     mVirtualDisplayAdapter.releaseVirtualDisplayLocked(appToken);
+            Slog.d(TAG, "Virtual Display: Display Device released");
             if (device != null) {
                 // TODO: multi-display - handle virtual displays the same as other display adapters.
                 mDisplayDeviceRepo.onDisplayDeviceEvent(device,
diff --git a/services/core/java/com/android/server/display/DisplayPowerController2.java b/services/core/java/com/android/server/display/DisplayPowerController2.java
index 5213d31..0f89a6e 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController2.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController2.java
@@ -254,13 +254,6 @@
     // The doze screen brightness.
     private final float mScreenBrightnessDozeConfig;
 
-    // The dim screen brightness.
-    private final float mScreenBrightnessDimConfig;
-
-    // The minimum dim amount to use if the screen brightness is already below
-    // mScreenBrightnessDimConfig.
-    private final float mScreenBrightnessMinimumDimAmount;
-
     // True if auto-brightness should be used.
     private boolean mUseSoftwareAutoBrightnessConfig;
 
@@ -349,7 +342,7 @@
     private boolean mDozing;
 
     private boolean mAppliedDimming;
-    private boolean mAppliedLowPower;
+
     private boolean mAppliedThrottling;
 
     // Reason for which the brightness was last changed. See {@link BrightnessReason} for more
@@ -529,11 +522,6 @@
         // DOZE AND DIM SETTINGS
         mScreenBrightnessDozeConfig = BrightnessUtils.clampAbsoluteBrightness(
                 pm.getBrightnessConstraint(PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_DOZE));
-        mScreenBrightnessDimConfig = BrightnessUtils.clampAbsoluteBrightness(
-                pm.getBrightnessConstraint(PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_DIM));
-        mScreenBrightnessMinimumDimAmount = resources.getFloat(
-                R.dimen.config_screenBrightnessMinimumDimAmountFloat);
-
         loadBrightnessRampRates();
         mSkipScreenOnBrightnessRamp = resources.getBoolean(
                 R.bool.config_skipScreenOnBrightnessRamp);
@@ -565,7 +553,7 @@
                 mUniqueDisplayId,
                 mThermalBrightnessThrottlingDataId,
                 mDisplayDeviceConfig
-        ));
+        ), mContext);
         // Seed the cached brightness
         saveBrightnessInfo(getScreenBrightnessSetting());
         mAutomaticBrightnessStrategy =
@@ -1426,6 +1414,7 @@
         // Note throttling effectively changes the allowed brightness range, so, similarly to HBM,
         // we broadcast this change through setting.
         final float unthrottledBrightnessState = brightnessState;
+
         if (mBrightnessThrottler.isThrottled()) {
             mTempBrightnessEvent.setThermalMax(mBrightnessThrottler.getBrightnessCap());
             brightnessState = Math.min(brightnessState, mBrightnessThrottler.getBrightnessCap());
@@ -1449,42 +1438,12 @@
             mDisplayBrightnessController.updateScreenBrightnessSetting(brightnessState);
         }
 
-        // Apply dimming by at least some minimum amount when user activity
-        // timeout is about to expire.
-        if (mPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
-            if (brightnessState > PowerManager.BRIGHTNESS_MIN) {
-                brightnessState = Math.max(
-                        Math.min(brightnessState - mScreenBrightnessMinimumDimAmount,
-                                mScreenBrightnessDimConfig),
-                        PowerManager.BRIGHTNESS_MIN);
-                mBrightnessReasonTemp.addModifier(BrightnessReason.MODIFIER_DIMMED);
-            }
-            if (!mAppliedDimming) {
-                slowChange = false;
-            }
-            mAppliedDimming = true;
-        } else if (mAppliedDimming) {
-            slowChange = false;
-            mAppliedDimming = false;
-        }
-        // If low power mode is enabled, scale brightness by screenLowPowerBrightnessFactor
-        // as long as it is above the minimum threshold.
-        if (mPowerRequest.lowPowerMode) {
-            if (brightnessState > PowerManager.BRIGHTNESS_MIN) {
-                final float brightnessFactor =
-                        Math.min(mPowerRequest.screenLowPowerBrightnessFactor, 1);
-                final float lowPowerBrightnessFloat = (brightnessState * brightnessFactor);
-                brightnessState = Math.max(lowPowerBrightnessFloat, PowerManager.BRIGHTNESS_MIN);
-                mBrightnessReasonTemp.addModifier(BrightnessReason.MODIFIER_LOW_POWER);
-            }
-            if (!mAppliedLowPower) {
-                slowChange = false;
-            }
-            mAppliedLowPower = true;
-        } else if (mAppliedLowPower) {
-            slowChange = false;
-            mAppliedLowPower = false;
-        }
+        DisplayBrightnessState clampedState = mBrightnessClamperController.clamp(mPowerRequest,
+                brightnessState, slowChange);
+
+        brightnessState = clampedState.getBrightness();
+        slowChange = clampedState.isSlowChange();
+        mBrightnessReasonTemp.addModifier(clampedState.getBrightnessReason().getModifier());
 
         // The current brightness to use has been calculated at this point, and HbmController should
         // be notified so that it can accurately calculate HDR or HBM levels. We specifically do it
@@ -1542,8 +1501,6 @@
             // allowed range.
             float animateValue = clampScreenBrightness(brightnessState);
 
-            animateValue = mBrightnessClamperController.clamp(animateValue);
-
             // If there are any HDR layers on the screen, we have a special brightness value that we
             // use instead. We still preserve the calculated brightness for Standard Dynamic Range
             // (SDR) layers, but the main brightness value will be the one for HDR.
@@ -2379,7 +2336,6 @@
         pw.println();
         pw.println("Display Power Controller Configuration:");
         pw.println("  mScreenBrightnessDozeConfig=" + mScreenBrightnessDozeConfig);
-        pw.println("  mScreenBrightnessDimConfig=" + mScreenBrightnessDimConfig);
         pw.println("  mUseSoftwareAutoBrightnessConfig=" + mUseSoftwareAutoBrightnessConfig);
         pw.println("  mSkipScreenOnBrightnessRamp=" + mSkipScreenOnBrightnessRamp);
         pw.println("  mColorFadeFadesConfig=" + mColorFadeFadesConfig);
@@ -2411,7 +2367,6 @@
         pw.println("  mPowerRequest=" + mPowerRequest);
         pw.println("  mBrightnessReason=" + mBrightnessReason);
         pw.println("  mAppliedDimming=" + mAppliedDimming);
-        pw.println("  mAppliedLowPower=" + mAppliedLowPower);
         pw.println("  mAppliedThrottling=" + mAppliedThrottling);
         pw.println("  mDozing=" + mDozing);
         pw.println("  mSkipRampState=" + skipRampStateToString(mSkipRampState));
diff --git a/services/core/java/com/android/server/display/LogicalDisplay.java b/services/core/java/com/android/server/display/LogicalDisplay.java
index 4edc8bc..9c271ff5 100644
--- a/services/core/java/com/android/server/display/LogicalDisplay.java
+++ b/services/core/java/com/android/server/display/LogicalDisplay.java
@@ -441,6 +441,9 @@
             if ((deviceInfo.flags & DisplayDeviceInfo.FLAG_ALWAYS_UNLOCKED) != 0) {
                 mBaseDisplayInfo.flags |= Display.FLAG_ALWAYS_UNLOCKED;
             }
+            if ((deviceInfo.flags & DisplayDeviceInfo.FLAG_ROTATES_WITH_CONTENT) != 0) {
+                mBaseDisplayInfo.flags |= Display.FLAG_ROTATES_WITH_CONTENT;
+            }
             if ((deviceInfo.flags & DisplayDeviceInfo.FLAG_TOUCH_FEEDBACK_DISABLED) != 0) {
                 mBaseDisplayInfo.flags |= Display.FLAG_TOUCH_FEEDBACK_DISABLED;
             }
diff --git a/services/core/java/com/android/server/display/VirtualDisplayAdapter.java b/services/core/java/com/android/server/display/VirtualDisplayAdapter.java
index 6191861..6936112 100644
--- a/services/core/java/com/android/server/display/VirtualDisplayAdapter.java
+++ b/services/core/java/com/android/server/display/VirtualDisplayAdapter.java
@@ -147,9 +147,12 @@
         try {
             if (projection != null) {
                 projection.registerCallback(mediaProjectionCallback);
+                Slog.d(TAG, "Virtual Display: registered media projection callback for new "
+                        + "VirtualDisplayDevice");
             }
             appToken.linkToDeath(device, 0);
         } catch (RemoteException ex) {
+            Slog.e(TAG, "Virtual Display: error while setting up VirtualDisplayDevice", ex);
             mVirtualDisplayDevices.remove(appToken);
             device.destroyLocked(false);
             return null;
@@ -445,6 +448,7 @@
         }
 
         public void stopLocked() {
+            Slog.d(TAG, "Virtual Display: stopping device " + mName);
             setSurfaceLocked(null);
             mStopped = true;
         }
diff --git a/services/core/java/com/android/server/display/brightness/clamper/BrightnessClamper.java b/services/core/java/com/android/server/display/brightness/clamper/BrightnessClamper.java
index 9345a3d..54a280f 100644
--- a/services/core/java/com/android/server/display/brightness/clamper/BrightnessClamper.java
+++ b/services/core/java/com/android/server/display/brightness/clamper/BrightnessClamper.java
@@ -21,6 +21,9 @@
 
 import java.io.PrintWriter;
 
+/**
+ * Provides max allowed brightness
+ */
 abstract class BrightnessClamper<T> {
 
     protected float mBrightnessCap = PowerManager.BRIGHTNESS_MAX;
diff --git a/services/core/java/com/android/server/display/brightness/clamper/BrightnessClamperController.java b/services/core/java/com/android/server/display/brightness/clamper/BrightnessClamperController.java
index d0f28c3..9b28989 100644
--- a/services/core/java/com/android/server/display/brightness/clamper/BrightnessClamperController.java
+++ b/services/core/java/com/android/server/display/brightness/clamper/BrightnessClamperController.java
@@ -20,6 +20,8 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.content.Context;
+import android.hardware.display.DisplayManagerInternal;
 import android.os.Handler;
 import android.os.HandlerExecutor;
 import android.os.PowerManager;
@@ -28,6 +30,7 @@
 import android.util.IndentingPrintWriter;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.display.DisplayBrightnessState;
 import com.android.server.display.DisplayDeviceConfig;
 import com.android.server.display.DisplayDeviceConfig.ThermalBrightnessThrottlingData;
 import com.android.server.display.feature.DeviceConfigParameterProvider;
@@ -42,7 +45,7 @@
  */
 public class BrightnessClamperController {
 
-    private static final boolean ENABLED = false;
+    private static final boolean THERMAL_ENABLED = false;
 
     private final DeviceConfigParameterProvider mDeviceConfigParameterProvider;
     private final Handler mHandler;
@@ -50,6 +53,8 @@
 
     private final Executor mExecutor;
     private final List<BrightnessClamper<? super DisplayDeviceData>> mClampers = new ArrayList<>();
+
+    private final List<BrightnessModifier> mModifiers = new ArrayList<>();
     private final DeviceConfig.OnPropertiesChangedListener mOnPropertiesChangedListener =
             properties -> mClampers.forEach(BrightnessClamper::onDeviceConfigChanged);
     private float mBrightnessCap = PowerManager.BRIGHTNESS_MAX;
@@ -57,13 +62,13 @@
     private Type mClamperType = null;
 
     public BrightnessClamperController(Handler handler,
-            ClamperChangeListener clamperChangeListener, DisplayDeviceData data) {
-        this(new Injector(), handler, clamperChangeListener, data);
+            ClamperChangeListener clamperChangeListener, DisplayDeviceData data, Context context) {
+        this(new Injector(), handler, clamperChangeListener, data, context);
     }
 
     @VisibleForTesting
     BrightnessClamperController(Injector injector, Handler handler,
-            ClamperChangeListener clamperChangeListener, DisplayDeviceData data) {
+            ClamperChangeListener clamperChangeListener, DisplayDeviceData data, Context context) {
         mDeviceConfigParameterProvider = injector.getDeviceConfigParameterProvider();
         mHandler = handler;
         mClamperChangeListenerExternal = clamperChangeListener;
@@ -77,11 +82,13 @@
             }
         };
 
-        if (ENABLED) {
+        if (THERMAL_ENABLED) {
             mClampers.add(
                     new BrightnessThermalClamper(handler, clamperChangeListenerInternal, data));
-            start();
         }
+        mModifiers.add(new DisplayDimModifier(context));
+        mModifiers.add(new BrightnessLowPowerModeModifier());
+        start();
     }
 
     /**
@@ -95,8 +102,19 @@
      * Applies clamping
      * Called in DisplayControllerHandler
      */
-    public float clamp(float value) {
-        return Math.min(value, mBrightnessCap);
+    public DisplayBrightnessState clamp(DisplayManagerInternal.DisplayPowerRequest request,
+            float brightnessValue, boolean slowChange) {
+        float cappedBrightness = Math.min(brightnessValue, mBrightnessCap);
+
+        DisplayBrightnessState.Builder builder = DisplayBrightnessState.builder();
+        builder.setIsSlowChange(slowChange);
+        builder.setBrightness(cappedBrightness);
+
+        for (int i = 0; i < mModifiers.size(); i++) {
+            mModifiers.get(i).apply(request, builder);
+        }
+
+        return builder.build();
     }
 
     /**
@@ -108,6 +126,7 @@
         writer.println("  mClamperType: " + mClamperType);
         IndentingPrintWriter ipw = new IndentingPrintWriter(writer, "    ");
         mClampers.forEach(clamper -> clamper.dump(ipw));
+        mModifiers.forEach(modifier -> modifier.dump(ipw));
     }
 
     /**
@@ -144,8 +163,10 @@
     }
 
     private void start() {
-        mDeviceConfigParameterProvider.addOnPropertiesChangedListener(
-                mExecutor, mOnPropertiesChangedListener);
+        if (!mClampers.isEmpty()) {
+            mDeviceConfigParameterProvider.addOnPropertiesChangedListener(
+                    mExecutor, mOnPropertiesChangedListener);
+        }
     }
 
     /**
diff --git a/services/core/java/com/android/server/display/brightness/clamper/BrightnessLowPowerModeModifier.java b/services/core/java/com/android/server/display/brightness/clamper/BrightnessLowPowerModeModifier.java
new file mode 100644
index 0000000..b478952
--- /dev/null
+++ b/services/core/java/com/android/server/display/brightness/clamper/BrightnessLowPowerModeModifier.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.brightness.clamper;
+
+import android.hardware.display.DisplayManagerInternal;
+import android.os.PowerManager;
+import android.util.IndentingPrintWriter;
+
+import com.android.server.display.brightness.BrightnessReason;
+
+import java.io.PrintWriter;
+
+class BrightnessLowPowerModeModifier extends BrightnessModifier {
+
+    @Override
+    boolean shouldApply(DisplayManagerInternal.DisplayPowerRequest request) {
+        return request.lowPowerMode;
+    }
+
+
+    @Override
+    float getBrightnessAdjusted(float currentBrightness,
+            DisplayManagerInternal.DisplayPowerRequest request) {
+        final float brightnessFactor =
+                Math.min(request.screenLowPowerBrightnessFactor, 1);
+        return Math.max((currentBrightness * brightnessFactor), PowerManager.BRIGHTNESS_MIN);
+    }
+
+    @Override
+    int getModifier() {
+        return BrightnessReason.MODIFIER_LOW_POWER;
+    }
+
+    @Override
+    public void dump(PrintWriter pw) {
+        pw.println("BrightnessLowPowerModeModifier:");
+        IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "    ");
+        super.dump(ipw);
+    }
+}
diff --git a/services/core/java/com/android/server/display/brightness/clamper/BrightnessModifier.java b/services/core/java/com/android/server/display/brightness/clamper/BrightnessModifier.java
new file mode 100644
index 0000000..112e63d
--- /dev/null
+++ b/services/core/java/com/android/server/display/brightness/clamper/BrightnessModifier.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.brightness.clamper;
+
+import android.hardware.display.DisplayManagerInternal;
+import android.os.PowerManager;
+
+import com.android.server.display.DisplayBrightnessState;
+
+import java.io.PrintWriter;
+
+/**
+ * Modifies current brightness based on request
+ */
+abstract class BrightnessModifier {
+
+    private boolean mApplied = false;
+
+    abstract boolean shouldApply(DisplayManagerInternal.DisplayPowerRequest request);
+
+    abstract float getBrightnessAdjusted(float currentBrightness,
+            DisplayManagerInternal.DisplayPowerRequest request);
+
+    abstract int getModifier();
+
+    void apply(DisplayManagerInternal.DisplayPowerRequest request,
+            DisplayBrightnessState.Builder stateBuilder) {
+        // If low power mode is enabled, scale brightness by screenLowPowerBrightnessFactor
+        // as long as it is above the minimum threshold.
+        if (shouldApply(request)) {
+            float value = stateBuilder.getBrightness();
+            if (value > PowerManager.BRIGHTNESS_MIN) {
+                stateBuilder.setBrightness(getBrightnessAdjusted(value, request));
+                stateBuilder.getBrightnessReason().addModifier(getModifier());
+            }
+            if (!mApplied) {
+                stateBuilder.setIsSlowChange(false);
+            }
+            mApplied = true;
+        } else if (mApplied) {
+            stateBuilder.setIsSlowChange(false);
+            mApplied = false;
+        }
+    }
+
+    void dump(PrintWriter pw) {
+        pw.println("BrightnessModifier:");
+        pw.println("  mApplied=" + mApplied);
+    }
+}
diff --git a/services/core/java/com/android/server/display/brightness/clamper/DisplayDimModifier.java b/services/core/java/com/android/server/display/brightness/clamper/DisplayDimModifier.java
new file mode 100644
index 0000000..4ff7bdb
--- /dev/null
+++ b/services/core/java/com/android/server/display/brightness/clamper/DisplayDimModifier.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.brightness.clamper;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.hardware.display.DisplayManagerInternal;
+import android.os.PowerManager;
+import android.util.IndentingPrintWriter;
+
+import com.android.internal.R;
+import com.android.server.display.brightness.BrightnessReason;
+import com.android.server.display.brightness.BrightnessUtils;
+
+import java.io.PrintWriter;
+import java.util.Objects;
+
+class DisplayDimModifier extends BrightnessModifier {
+
+    // The dim screen brightness.
+    private final float mScreenBrightnessDimConfig;
+
+    // The minimum dim amount to use if the screen brightness is already below
+    // mScreenBrightnessDimConfig.
+    private final float mScreenBrightnessMinimumDimAmount;
+
+    DisplayDimModifier(Context context) {
+        PowerManager pm = Objects.requireNonNull(context.getSystemService(PowerManager.class));
+        Resources resources = context.getResources();
+
+        mScreenBrightnessDimConfig = BrightnessUtils.clampAbsoluteBrightness(
+                pm.getBrightnessConstraint(PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_DIM));
+        mScreenBrightnessMinimumDimAmount = resources.getFloat(
+                R.dimen.config_screenBrightnessMinimumDimAmountFloat);
+    }
+
+
+    @Override
+    boolean shouldApply(DisplayManagerInternal.DisplayPowerRequest request) {
+        return request.policy == DisplayManagerInternal.DisplayPowerRequest.POLICY_DIM;
+    }
+
+    @Override
+    float getBrightnessAdjusted(float currentBrightness,
+            DisplayManagerInternal.DisplayPowerRequest request) {
+        return Math.max(
+                Math.min(currentBrightness - mScreenBrightnessMinimumDimAmount,
+                        mScreenBrightnessDimConfig),
+                PowerManager.BRIGHTNESS_MIN);
+    }
+
+    @Override
+    int getModifier() {
+        return BrightnessReason.MODIFIER_DIMMED;
+    }
+
+    @Override
+    public void dump(PrintWriter pw) {
+        pw.println("DisplayDimModifier:");
+        pw.println("  mScreenBrightnessDimConfig=" + mScreenBrightnessDimConfig);
+        pw.println("  mScreenBrightnessMinimumDimAmount=" + mScreenBrightnessMinimumDimAmount);
+        IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "    ");
+        super.dump(ipw);
+    }
+}
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 4ad26c4..7ea576d 100644
--- a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
@@ -63,10 +63,15 @@
     // high errors. This default is introduced to provide a fixed display color
     // temperature when sensor readings become unreliable.
     private final float mLowLightAmbientColorTemperature;
+    // As above, but used when in strong mode (idle screen brightness mode).
+    private final float mLowLightAmbientColorTemperatureStrong;
+
     // 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;
+    // As above, but used when in strong mode (idle screen brightness mode).
+    private final float mHighLightAmbientColorTemperatureStrong;
 
     private final boolean mLightModeAllowed;
 
@@ -97,9 +102,11 @@
     // ambient color temperature to the defaults. A piecewise linear relationship
     // between low light brightness and low light bias.
     private Spline.LinearSpline mLowLightAmbientBrightnessToBiasSpline;
+    private Spline.LinearSpline mLowLightAmbientBrightnessToBiasSplineStrong;
 
     // A piecewise linear relationship between high light brightness and high light bias.
     private Spline.LinearSpline mHighLightAmbientBrightnessToBiasSpline;
+    private Spline.LinearSpline mHighLightAmbientBrightnessToBiasSplineStrong;
 
     private float mLatestAmbientColorTemperature;
     private float mLatestAmbientBrightness;
@@ -134,17 +141,29 @@
      * @param lowLightAmbientBrightnesses
      *      The ambient brightness used to map the ambient brightnesses to the biases used to
      *      interpolate to lowLightAmbientColorTemperature.
+     * @param lowLightAmbientBrightnessesStrong
+     *      The ambient brightness used to map the ambient brightnesses to the biases used to
+     *      interpolate to lowLightAmbientColorTemperature.
      * @param lowLightAmbientBiases
      *      The biases used to map the ambient brightnesses to the biases used to interpolate to
      *      lowLightAmbientColorTemperature.
+     * @param lowLightAmbientBiasesStrong
+     *      The biases used to map the ambient brightnesses to the biases used to interpolate to
+     *      lowLightAmbientColorTemperature.
      * @param lowLightAmbientColorTemperature
      *      The ambient color temperature to which we interpolate to based on the low light curve.
      * @param highLightAmbientBrightnesses
      *      The ambient brightness used to map the ambient brightnesses to the biases used to
      *      interpolate to highLightAmbientColorTemperature.
+     * @param highLightAmbientBrightnessesStrong
+     *      The ambient brightness used to map the ambient brightnesses to the biases used to
+     *      interpolate to highLightAmbientColorTemperature.
      * @param highLightAmbientBiases
      *      The biases used to map the ambient brightnesses to the biases used to interpolate to
      *      highLightAmbientColorTemperature.
+     * @param highLightAmbientBiasesStrong
+     *      The biases used to map the ambient brightnesses to the biases used to interpolate to
+     *      highLightAmbientColorTemperature.
      * @param highLightAmbientColorTemperature
      *      The ambient color temperature to which we interpolate to based on the high light curve.
      * @param ambientColorTemperatures
@@ -170,11 +189,17 @@
             @NonNull AmbientFilter colorTemperatureFilter,
             @NonNull DisplayWhiteBalanceThrottler throttler,
             float[] lowLightAmbientBrightnesses,
+            float[] lowLightAmbientBrightnessesStrong,
             float[] lowLightAmbientBiases,
+            float[] lowLightAmbientBiasesStrong,
             float lowLightAmbientColorTemperature,
+            float lowLightAmbientColorTemperatureStrong,
             float[] highLightAmbientBrightnesses,
+            float[] highLightAmbientBrightnessesStrong,
             float[] highLightAmbientBiases,
+            float[] highLightAmbientBiasesStrong,
             float highLightAmbientColorTemperature,
+            float highLightAmbientColorTemperatureStrong,
             float[] ambientColorTemperatures,
             float[] displayColorTemperatures,
             float[] strongAmbientColorTemperatures,
@@ -188,7 +213,9 @@
         mColorTemperatureFilter = colorTemperatureFilter;
         mThrottler = throttler;
         mLowLightAmbientColorTemperature = lowLightAmbientColorTemperature;
+        mLowLightAmbientColorTemperatureStrong = lowLightAmbientColorTemperatureStrong;
         mHighLightAmbientColorTemperature = highLightAmbientColorTemperature;
+        mHighLightAmbientColorTemperatureStrong = highLightAmbientColorTemperatureStrong;
         mAmbientColorTemperature = -1.0f;
         mPendingAmbientColorTemperature = -1.0f;
         mLastAmbientColorTemperature = -1.0f;
@@ -214,6 +241,23 @@
         }
 
         try {
+            mLowLightAmbientBrightnessToBiasSplineStrong = new Spline.LinearSpline(
+                    lowLightAmbientBrightnessesStrong, lowLightAmbientBiasesStrong);
+        } catch (Exception e) {
+            Slog.e(TAG, "failed to create strong low light ambient brightness to bias spline.", e);
+            mLowLightAmbientBrightnessToBiasSplineStrong = null;
+        }
+        if (mLowLightAmbientBrightnessToBiasSplineStrong != null) {
+            if (mLowLightAmbientBrightnessToBiasSplineStrong.interpolate(0.0f) != 0.0f
+                    || mLowLightAmbientBrightnessToBiasSplineStrong.interpolate(
+                    Float.POSITIVE_INFINITY) != 1.0f) {
+                Slog.d(TAG, "invalid strong low light ambient brightness to bias spline, "
+                        + "bias must begin at 0.0 and end at 1.0.");
+                mLowLightAmbientBrightnessToBiasSplineStrong = null;
+            }
+        }
+
+        try {
             mHighLightAmbientBrightnessToBiasSpline = new Spline.LinearSpline(
                     highLightAmbientBrightnesses, highLightAmbientBiases);
         } catch (Exception e) {
@@ -230,6 +274,23 @@
             }
         }
 
+        try {
+            mHighLightAmbientBrightnessToBiasSplineStrong = new Spline.LinearSpline(
+                    highLightAmbientBrightnessesStrong, highLightAmbientBiasesStrong);
+        } catch (Exception e) {
+            Slog.e(TAG, "failed to create strong high light ambient brightness to bias spline.", e);
+            mHighLightAmbientBrightnessToBiasSplineStrong = null;
+        }
+        if (mHighLightAmbientBrightnessToBiasSplineStrong != null) {
+            if (mHighLightAmbientBrightnessToBiasSplineStrong.interpolate(0.0f) != 0.0f
+                    || mHighLightAmbientBrightnessToBiasSplineStrong.interpolate(
+                    Float.POSITIVE_INFINITY) != 1.0f) {
+                Slog.d(TAG, "invalid strong high light ambient brightness to bias spline, "
+                        + "bias must begin at 0.0 and end at 1.0.");
+                mHighLightAmbientBrightnessToBiasSplineStrong = null;
+            }
+        }
+
         if (mLowLightAmbientBrightnessToBiasSpline != null &&
                 mHighLightAmbientBrightnessToBiasSpline != null) {
             if (lowLightAmbientBrightnesses[lowLightAmbientBrightnesses.length - 1] >
@@ -241,6 +302,18 @@
             }
         }
 
+        if (mLowLightAmbientBrightnessToBiasSplineStrong != null
+                && mHighLightAmbientBrightnessToBiasSplineStrong != null) {
+            if (lowLightAmbientBrightnessesStrong[lowLightAmbientBrightnessesStrong.length - 1]
+                    > highLightAmbientBrightnessesStrong[0]) {
+                Slog.d(TAG,
+                        "invalid strong low light and high light ambient brightness to bias "
+                                + "spline combination, defined domains must not intersect.");
+                mLowLightAmbientBrightnessToBiasSplineStrong = null;
+                mHighLightAmbientBrightnessToBiasSplineStrong = null;
+            }
+        }
+
         try {
             mAmbientToDisplayColorTemperatureSpline = new Spline.LinearSpline(
                     ambientColorTemperatures, displayColorTemperatures);
@@ -365,7 +438,11 @@
         mColorTemperatureFilter.dump(writer);
         mThrottler.dump(writer);
         writer.println("  mLowLightAmbientColorTemperature=" + mLowLightAmbientColorTemperature);
+        writer.println("  mLowLightAmbientColorTemperatureStrong="
+                + mLowLightAmbientColorTemperatureStrong);
         writer.println("  mHighLightAmbientColorTemperature=" + mHighLightAmbientColorTemperature);
+        writer.println("  mHighLightAmbientColorTemperatureStrong="
+                + mHighLightAmbientColorTemperatureStrong);
         writer.println("  mAmbientColorTemperature=" + mAmbientColorTemperature);
         writer.println("  mPendingAmbientColorTemperature=" + mPendingAmbientColorTemperature);
         writer.println("  mLastAmbientColorTemperature=" + mLastAmbientColorTemperature);
@@ -377,8 +454,12 @@
                 + mStrongAmbientToDisplayColorTemperatureSpline);
         writer.println("  mLowLightAmbientBrightnessToBiasSpline="
                 + mLowLightAmbientBrightnessToBiasSpline);
+        writer.println("  mLowLightAmbientBrightnessToBiasSplineStrong="
+                + mLowLightAmbientBrightnessToBiasSplineStrong);
         writer.println("  mHighLightAmbientBrightnessToBiasSpline="
                 + mHighLightAmbientBrightnessToBiasSpline);
+        writer.println("  mHighLightAmbientBrightnessToBiasSplineStrong="
+                + mHighLightAmbientBrightnessToBiasSplineStrong);
     }
 
     @Override // AmbientSensor.AmbientBrightnessSensor.Callbacks
@@ -400,6 +481,17 @@
      */
     public void updateAmbientColorTemperature() {
         final long time = System.currentTimeMillis();
+        final float lowLightAmbientColorTemperature = mStrongModeEnabled
+                ? mLowLightAmbientColorTemperatureStrong : mLowLightAmbientColorTemperature;
+        final float highLightAmbientColorTemperature = mStrongModeEnabled
+                ? mHighLightAmbientColorTemperatureStrong : mHighLightAmbientColorTemperature;
+        final Spline.LinearSpline lowLightAmbientBrightnessToBiasSpline = mStrongModeEnabled
+                ? mLowLightAmbientBrightnessToBiasSplineStrong
+                : mLowLightAmbientBrightnessToBiasSpline;
+        final Spline.LinearSpline highLightAmbientBrightnessToBiasSpline = mStrongModeEnabled
+                ? mHighLightAmbientBrightnessToBiasSplineStrong
+                : mHighLightAmbientBrightnessToBiasSpline;
+
         float ambientColorTemperature = mColorTemperatureFilter.getEstimate(time);
         mLatestAmbientColorTemperature = ambientColorTemperature;
 
@@ -423,19 +515,19 @@
         mLatestAmbientBrightness = ambientBrightness;
 
         if (ambientColorTemperature != -1.0f && ambientBrightness != -1.0f
-                && mLowLightAmbientBrightnessToBiasSpline != null) {
-            float bias = mLowLightAmbientBrightnessToBiasSpline.interpolate(ambientBrightness);
+                && lowLightAmbientBrightnessToBiasSpline != null) {
+            float bias = lowLightAmbientBrightnessToBiasSpline.interpolate(ambientBrightness);
             ambientColorTemperature =
                     bias * ambientColorTemperature + (1.0f - bias)
-                    * mLowLightAmbientColorTemperature;
+                    * lowLightAmbientColorTemperature;
             mLatestLowLightBias = bias;
         }
         if (ambientColorTemperature != -1.0f && ambientBrightness != -1.0f
-                && mHighLightAmbientBrightnessToBiasSpline != null) {
-            float bias = mHighLightAmbientBrightnessToBiasSpline.interpolate(ambientBrightness);
+                && highLightAmbientBrightnessToBiasSpline != null) {
+            float bias = highLightAmbientBrightnessToBiasSpline.interpolate(ambientBrightness);
             ambientColorTemperature =
                     (1.0f - bias) * ambientColorTemperature + bias
-                    * mHighLightAmbientColorTemperature;
+                    * highLightAmbientColorTemperature;
             mLatestHighLightBias = 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 62f813f..39e6b3f 100644
--- a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
@@ -70,21 +70,39 @@
         final float[] displayWhiteBalanceLowLightAmbientBrightnesses = getFloatArray(resources,
                 com.android.internal.R.array
                 .config_displayWhiteBalanceLowLightAmbientBrightnesses);
+        final float[] displayWhiteBalanceLowLightAmbientBrightnessesStrong = getFloatArray(
+                resources, com.android.internal.R.array
+                .config_displayWhiteBalanceLowLightAmbientBrightnessesStrong);
         final float[] displayWhiteBalanceLowLightAmbientBiases = getFloatArray(resources,
                 com.android.internal.R.array
                 .config_displayWhiteBalanceLowLightAmbientBiases);
+        final float[] displayWhiteBalanceLowLightAmbientBiasesStrong = getFloatArray(resources,
+                com.android.internal.R.array
+                .config_displayWhiteBalanceLowLightAmbientBiasesStrong);
         final float lowLightAmbientColorTemperature = getFloat(resources,
                 com.android.internal.R.dimen
                 .config_displayWhiteBalanceLowLightAmbientColorTemperature);
+        final float lowLightAmbientColorTemperatureStrong = getFloat(resources,
+                com.android.internal.R.dimen
+                .config_displayWhiteBalanceLowLightAmbientColorTemperatureStrong);
         final float[] displayWhiteBalanceHighLightAmbientBrightnesses = getFloatArray(resources,
                 com.android.internal.R.array
                 .config_displayWhiteBalanceHighLightAmbientBrightnesses);
+        final float[] displayWhiteBalanceHighLightAmbientBrightnessesStrong = getFloatArray(
+                resources, com.android.internal.R.array
+                .config_displayWhiteBalanceHighLightAmbientBrightnessesStrong);
         final float[] displayWhiteBalanceHighLightAmbientBiases = getFloatArray(resources,
                 com.android.internal.R.array
                 .config_displayWhiteBalanceHighLightAmbientBiases);
+        final float[] displayWhiteBalanceHighLightAmbientBiasesStrong = getFloatArray(resources,
+                com.android.internal.R.array
+                .config_displayWhiteBalanceHighLightAmbientBiasesStrong);
         final float highLightAmbientColorTemperature = getFloat(resources,
                 com.android.internal.R.dimen
                 .config_displayWhiteBalanceHighLightAmbientColorTemperature);
+        final float highLightAmbientColorTemperatureStrong = getFloat(resources,
+                com.android.internal.R.dimen
+                .config_displayWhiteBalanceHighLightAmbientColorTemperatureStrong);
         final float[] ambientColorTemperatures = getFloatArray(resources,
                 com.android.internal.R.array.config_displayWhiteBalanceAmbientColorTemperatures);
         final float[] displayColorTemperatures = getFloatArray(resources,
@@ -100,9 +118,15 @@
         final DisplayWhiteBalanceController controller = new DisplayWhiteBalanceController(
                 brightnessSensor, brightnessFilter, colorTemperatureSensor, colorTemperatureFilter,
                 throttler, displayWhiteBalanceLowLightAmbientBrightnesses,
-                displayWhiteBalanceLowLightAmbientBiases, lowLightAmbientColorTemperature,
+                displayWhiteBalanceLowLightAmbientBrightnessesStrong,
+                displayWhiteBalanceLowLightAmbientBiases,
+                displayWhiteBalanceLowLightAmbientBiasesStrong, lowLightAmbientColorTemperature,
+                lowLightAmbientColorTemperatureStrong,
                 displayWhiteBalanceHighLightAmbientBrightnesses,
-                displayWhiteBalanceHighLightAmbientBiases, highLightAmbientColorTemperature,
+                displayWhiteBalanceHighLightAmbientBrightnessesStrong,
+                displayWhiteBalanceHighLightAmbientBiases,
+                displayWhiteBalanceHighLightAmbientBiasesStrong, highLightAmbientColorTemperature,
+                highLightAmbientColorTemperatureStrong,
                 ambientColorTemperatures, displayColorTemperatures, strongAmbientColorTemperatures,
                 strongDisplayColorTemperatures, lightModeAllowed);
         brightnessSensor.setCallbacks(controller);
diff --git a/services/core/java/com/android/server/hdmi/AbsoluteVolumeAudioStatusAction.java b/services/core/java/com/android/server/hdmi/AbsoluteVolumeAudioStatusAction.java
index d764ec4..9172dc0 100644
--- a/services/core/java/com/android/server/hdmi/AbsoluteVolumeAudioStatusAction.java
+++ b/services/core/java/com/android/server/hdmi/AbsoluteVolumeAudioStatusAction.java
@@ -32,6 +32,10 @@
 
     private int mInitialAudioStatusRetriesLeft = 2;
 
+    // Flag to notify AudioService of the next audio status reported,
+    // regardless of whether the audio status changed.
+    private boolean mForceNextAudioStatusUpdate = false;
+
     private static final int STATE_WAIT_FOR_INITIAL_AUDIO_STATUS = 1;
     private static final int STATE_MONITOR_AUDIO_STATUS = 2;
 
@@ -70,6 +74,17 @@
         return false;
     }
 
+
+    /**
+     * If AVB has been enabled, send <Give Audio Status> and notify AudioService of the response.
+     */
+    void requestAndUpdateAudioStatus() {
+        if (mState == STATE_MONITOR_AUDIO_STATUS) {
+            mForceNextAudioStatusUpdate = true;
+            sendGiveAudioStatus();
+        }
+    }
+
     private boolean handleReportAudioStatus(HdmiCecMessage cmd) {
         if (mTargetAddress != cmd.getSource() || cmd.getParams().length == 0) {
             return false;
@@ -89,12 +104,15 @@
             localDevice().getService().enableAbsoluteVolumeBehavior(audioStatus);
             mState = STATE_MONITOR_AUDIO_STATUS;
         } else if (mState == STATE_MONITOR_AUDIO_STATUS) {
-            if (audioStatus.getVolume() != mLastAudioStatus.getVolume()) {
+            if (mForceNextAudioStatusUpdate
+                    || audioStatus.getVolume() != mLastAudioStatus.getVolume()) {
                 localDevice().getService().notifyAvbVolumeChange(audioStatus.getVolume());
             }
-            if (audioStatus.getMute() != mLastAudioStatus.getMute()) {
+            if (mForceNextAudioStatusUpdate
+                    || audioStatus.getMute() != mLastAudioStatus.getMute()) {
                 localDevice().getService().notifyAvbMuteChange(audioStatus.getMute());
             }
+            mForceNextAudioStatusUpdate = false;
         }
         mLastAudioStatus = audioStatus;
 
diff --git a/services/core/java/com/android/server/hdmi/Constants.java b/services/core/java/com/android/server/hdmi/Constants.java
index 77213bf..b78f8a7 100644
--- a/services/core/java/com/android/server/hdmi/Constants.java
+++ b/services/core/java/com/android/server/hdmi/Constants.java
@@ -357,7 +357,7 @@
 
     static final int INVALID_PORT_ID = HdmiDeviceInfo.PORT_INVALID;
     static final int INVALID_PHYSICAL_ADDRESS = HdmiDeviceInfo.PATH_INVALID;
-    static final int PATH_INTERNAL = HdmiDeviceInfo.PATH_INTERNAL;
+    static final int TV_PHYSICAL_ADDRESS = HdmiDeviceInfo.PATH_INTERNAL;
 
     // The relationship from one path (physical address) to another.
     @IntDef({
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecAtomWriter.java b/services/core/java/com/android/server/hdmi/HdmiCecAtomWriter.java
index 7ae7d5c..53c0217 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecAtomWriter.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecAtomWriter.java
@@ -222,6 +222,21 @@
         );
     }
 
+    /**
+     * Writes a HdmiSoundbarModeStatusReported atom representing a Dynamic soundbar mode status
+     * change.
+     * @param isSupported         Whether the hardware supports ARC.
+     * @param isEnabled           Whether DSM is enabled.
+     * @param enumLogReason       The event that triggered the log.
+     */
+    public void dsmStatusChanged(boolean isSupported, boolean isEnabled, int enumLogReason) {
+        FrameworkStatsLog.write(
+                FrameworkStatsLog.HDMI_SOUNDBAR_MODE_STATUS_REPORTED,
+                isSupported,
+                isEnabled,
+                enumLogReason);
+    }
+
     private int earcStateToEnum(int earcState) {
         switch (earcState) {
             case HDMI_EARC_STATUS_IDLE:
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevice.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevice.java
index 207d38e..0671464 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevice.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevice.java
@@ -1048,6 +1048,19 @@
     }
 
     /**
+     * If AVB has been enabled, request the System Audio device's audio status and notify
+     * AudioService of its response.
+     */
+    @ServiceThreadOnly
+    void requestAndUpdateAvbAudioStatus() {
+        assertRunOnServiceThread();
+        for (AbsoluteVolumeAudioStatusAction action :
+                getActions(AbsoluteVolumeAudioStatusAction.class)) {
+            action.requestAndUpdateAudioStatus();
+        }
+    }
+
+    /**
      * Determines whether {@code targetAddress} supports <Set Audio Volume Level>. Does two things
      * in parallel: send <Give Features> (to get <Report Features> in response),
      * and send <Set Audio Volume Level> (to see if it gets a <Feature Abort> in response).
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
index dc416b2..824c8db 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
@@ -518,6 +518,18 @@
     @ServiceThreadOnly
     protected void handleRoutingChangeAndInformation(int physicalAddress, HdmiCecMessage message) {
         assertRunOnServiceThread();
+        // If the device is active source and received a <Routing Change> or <Routing Information>
+        // message to a physical address in the same active path do not change the Active Source
+        // status.
+        // E.g. TV [0.0.0.0] ------ Switch [2.0.0.0] ------ OTT [2.1.0.0] (Active Source)
+        // TV sends <Routing Change>[2.0.0.0] -> OTT is still Active Source
+        // TV sends <Routing Change>[0.0.0.0] -> OTT is not Active Source anymore.
+        // TV sends <Routing Change>[3.0.0.0] -> OTT is not Active Source anymore.
+        if (HdmiUtils.isInActiveRoutingPath(mService.getPhysicalAddress(), physicalAddress)
+                && physicalAddress != Constants.TV_PHYSICAL_ADDRESS
+                && isActiveSource()) {
+            return;
+        }
         if (physicalAddress != mService.getPhysicalAddress()) {
             setActiveSource(physicalAddress,
                     "HdmiCecLocalDevicePlayback#handleRoutingChangeAndInformation()");
diff --git a/services/core/java/com/android/server/hdmi/HdmiControlService.java b/services/core/java/com/android/server/hdmi/HdmiControlService.java
index dd45307..99fa3a3 100644
--- a/services/core/java/com/android/server/hdmi/HdmiControlService.java
+++ b/services/core/java/com/android/server/hdmi/HdmiControlService.java
@@ -694,13 +694,13 @@
                 HdmiControlManager.CEC_SETTING_NAME_HDMI_CEC_ENABLED);
 
         mSoundbarModeFeatureFlagEnabled = mDeviceConfig.getBoolean(
-                Constants.DEVICE_CONFIG_FEATURE_FLAG_SOUNDBAR_MODE, false);
+                Constants.DEVICE_CONFIG_FEATURE_FLAG_SOUNDBAR_MODE, true);
         mEarcTxFeatureFlagEnabled = mDeviceConfig.getBoolean(
-                Constants.DEVICE_CONFIG_FEATURE_FLAG_ENABLE_EARC_TX, false);
+                Constants.DEVICE_CONFIG_FEATURE_FLAG_ENABLE_EARC_TX, true);
         mTransitionFromArcToEarcTxEnabled = mDeviceConfig.getBoolean(
-                Constants.DEVICE_CONFIG_FEATURE_FLAG_TRANSITION_ARC_TO_EARC_TX, false);
+                Constants.DEVICE_CONFIG_FEATURE_FLAG_TRANSITION_ARC_TO_EARC_TX, true);
         mNumericSoundbarVolumeUiOnTvFeatureFlagEnabled = mDeviceConfig.getBoolean(
-                Constants.DEVICE_CONFIG_FEATURE_FLAG_TV_NUMERIC_SOUNDBAR_VOLUME_UI, false);
+                Constants.DEVICE_CONFIG_FEATURE_FLAG_TV_NUMERIC_SOUNDBAR_VOLUME_UI, true);
 
         synchronized (mLock) {
             mEarcEnabled = (mHdmiCecConfig.getIntValue(
@@ -857,7 +857,7 @@
                         public void onPropertiesChanged(DeviceConfig.Properties properties) {
                             mEarcTxFeatureFlagEnabled = properties.getBoolean(
                                     Constants.DEVICE_CONFIG_FEATURE_FLAG_ENABLE_EARC_TX,
-                                    false);
+                                    true);
                             boolean earcEnabledSetting = mHdmiCecConfig.getIntValue(
                                     HdmiControlManager.SETTING_NAME_EARC_ENABLED)
                                     == EARC_FEATURE_ENABLED;
@@ -891,7 +891,7 @@
                     public void onPropertiesChanged(DeviceConfig.Properties properties) {
                         mSoundbarModeFeatureFlagEnabled = properties.getBoolean(
                                 Constants.DEVICE_CONFIG_FEATURE_FLAG_SOUNDBAR_MODE,
-                                false);
+                                true);
                         boolean soundbarModeSetting = mHdmiCecConfig.getIntValue(
                                 HdmiControlManager.CEC_SETTING_NAME_SOUNDBAR_MODE)
                                 == SOUNDBAR_MODE_ENABLED;
@@ -917,7 +917,7 @@
                     public void onPropertiesChanged(DeviceConfig.Properties properties) {
                         mTransitionFromArcToEarcTxEnabled = properties.getBoolean(
                                 Constants.DEVICE_CONFIG_FEATURE_FLAG_TRANSITION_ARC_TO_EARC_TX,
-                                false);
+                                true);
                     }
                 });
 
@@ -927,7 +927,7 @@
                     public void onPropertiesChanged(DeviceConfig.Properties properties) {
                         mNumericSoundbarVolumeUiOnTvFeatureFlagEnabled = properties.getBoolean(
                                 Constants.DEVICE_CONFIG_FEATURE_FLAG_TV_NUMERIC_SOUNDBAR_VOLUME_UI,
-                                false);
+                                true);
                         checkAndUpdateAbsoluteVolumeBehavior();
                     }
                 });
@@ -1064,13 +1064,18 @@
      */
     @VisibleForTesting
     public void setSoundbarMode(final int settingValue) {
+        boolean isArcSupported = isArcSupported();
         HdmiCecLocalDevicePlayback playback = playback();
         HdmiCecLocalDeviceAudioSystem audioSystem = audioSystem();
+        getAtomWriter().dsmStatusChanged(isArcSupported,
+                settingValue == SOUNDBAR_MODE_ENABLED,
+                HdmiStatsEnums.LOG_REASON_DSM_SETTING_TOGGLED);
+
         if (playback == null) {
             Slog.w(TAG, "Device type not compatible to change soundbar mode.");
             return;
         }
-        if (!SystemProperties.getBoolean(Constants.PROPERTY_ARC_SUPPORT, true)) {
+        if (!isArcSupported) {
             Slog.w(TAG, "Device type doesn't support ARC.");
             return;
         }
@@ -1269,11 +1274,8 @@
     @ServiceThreadOnly
     private List<Integer> getCecLocalDeviceTypes() {
         ArrayList<Integer> allLocalDeviceTypes = new ArrayList<>(mCecLocalDevices);
-        if (mHdmiCecConfig.getIntValue(HdmiControlManager.CEC_SETTING_NAME_SOUNDBAR_MODE)
-                == SOUNDBAR_MODE_ENABLED
-                && !allLocalDeviceTypes.contains(HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM)
-                && SystemProperties.getBoolean(Constants.PROPERTY_ARC_SUPPORT, true)
-                && mSoundbarModeFeatureFlagEnabled) {
+        if (isDsmEnabled() && !allLocalDeviceTypes.contains(HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM)
+                && isArcSupported() && mSoundbarModeFeatureFlagEnabled) {
             allLocalDeviceTypes.add(HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM);
         }
         return allLocalDeviceTypes;
@@ -3589,6 +3591,16 @@
         }
     }
 
+    private boolean isDsmEnabled() {
+        return mHdmiCecConfig.getIntValue(HdmiControlManager.CEC_SETTING_NAME_SOUNDBAR_MODE)
+                == SOUNDBAR_MODE_ENABLED;
+    }
+
+    @VisibleForTesting
+    protected boolean isArcSupported() {
+        return SystemProperties.getBoolean(Constants.PROPERTY_ARC_SUPPORT, true);
+    }
+
     @ServiceThreadOnly
     int getPowerStatus() {
         assertRunOnServiceThread();
@@ -3705,6 +3717,9 @@
             int earcStatus = getEarcStatus();
             getAtomWriter().earcStatusChanged(isEarcSupported(), isEarcEnabled(),
                     earcStatus, earcStatus, HdmiStatsEnums.LOG_REASON_WAKE);
+        } else if (isPlaybackDevice()) {
+            getAtomWriter().dsmStatusChanged(isArcSupported(), isDsmEnabled(),
+                    HdmiStatsEnums.LOG_REASON_DSM_WAKE);
         }
         // TODO: Initialize MHL local devices.
     }
@@ -4646,6 +4661,13 @@
                     // same keycode for all three mute options.
                     keyCode = KeyEvent.KEYCODE_VOLUME_MUTE;
                     break;
+                case AudioManager.ADJUST_SAME:
+                    // Query the current audio status of the Audio System and display UI for it
+                    // Only for TVs, because Playback devices don't display UI when using AVB
+                    if (tv() != null) {
+                        tv().requestAndUpdateAvbAudioStatus();
+                    }
+                    return;
                 default:
                     return;
             }
diff --git a/services/core/java/com/android/server/hdmi/SystemAudioAction.java b/services/core/java/com/android/server/hdmi/SystemAudioAction.java
index e7a3db7..e96963b9 100644
--- a/services/core/java/com/android/server/hdmi/SystemAudioAction.java
+++ b/services/core/java/com/android/server/hdmi/SystemAudioAction.java
@@ -113,7 +113,7 @@
         }
         int param = tv().getActivePath();
         return param != Constants.INVALID_PHYSICAL_ADDRESS
-                ? param : Constants.PATH_INTERNAL;
+                ? param : Constants.TV_PHYSICAL_ADDRESS;
     }
 
     private void handleSendSystemAudioModeRequestTimeout() {
diff --git a/services/core/java/com/android/server/input/FocusEventDebugGlobalMonitor.java b/services/core/java/com/android/server/input/FocusEventDebugGlobalMonitor.java
new file mode 100644
index 0000000..67c221f
--- /dev/null
+++ b/services/core/java/com/android/server/input/FocusEventDebugGlobalMonitor.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.input;
+
+import android.view.Display;
+import android.view.InputEvent;
+import android.view.InputEventReceiver;
+import android.view.MotionEvent;
+
+import com.android.server.UiThread;
+
+/**
+ * Receives input events before they are dispatched and reports them to FocusEventDebugView.
+ */
+class FocusEventDebugGlobalMonitor extends InputEventReceiver {
+    private final FocusEventDebugView mDebugView;
+
+    FocusEventDebugGlobalMonitor(FocusEventDebugView debugView, InputManagerService service) {
+        super(service.monitorInput("FocusEventDebugGlobalMonitor", Display.DEFAULT_DISPLAY),
+            UiThread.getHandler().getLooper());
+        mDebugView = debugView;
+    }
+
+    @Override
+    public void onInputEvent(InputEvent event) {
+        try {
+            if (event instanceof MotionEvent) {
+                mDebugView.reportMotionEvent((MotionEvent) event);
+            }
+        } finally {
+            finishInputEvent(event, false);
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/input/FocusEventDebugView.java b/services/core/java/com/android/server/input/FocusEventDebugView.java
index fba2aa6..4b8fabde 100644
--- a/services/core/java/com/android/server/input/FocusEventDebugView.java
+++ b/services/core/java/com/android/server/input/FocusEventDebugView.java
@@ -22,35 +22,47 @@
 
 import android.animation.LayoutTransition;
 import android.annotation.AnyThread;
+import android.annotation.Nullable;
 import android.content.Context;
+import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.ColorFilter;
 import android.graphics.ColorMatrixColorFilter;
+import android.graphics.Paint;
 import android.graphics.Typeface;
+import android.util.DisplayMetrics;
 import android.util.Pair;
 import android.util.Slog;
 import android.util.TypedValue;
 import android.view.Gravity;
-import android.view.InputEvent;
+import android.view.InputDevice;
 import android.view.KeyEvent;
+import android.view.MotionEvent;
 import android.view.RoundedCorner;
 import android.view.View;
+import android.view.ViewConfiguration;
 import android.view.WindowInsets;
 import android.view.animation.AccelerateInterpolator;
 import android.widget.HorizontalScrollView;
 import android.widget.LinearLayout;
+import android.widget.RelativeLayout;
 import android.widget.TextView;
 
 import com.android.internal.R;
+import com.android.internal.annotations.VisibleForTesting;
 
 import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Locale;
 import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
 
 /**
  *  Displays focus events, such as physical keyboard KeyEvents and non-pointer MotionEvents on
  *  the screen.
  */
-class FocusEventDebugView extends LinearLayout {
+class FocusEventDebugView extends RelativeLayout {
 
     private static final String TAG = FocusEventDebugView.class.getSimpleName();
 
@@ -63,43 +75,45 @@
     private static final int KEY_VIEW_VERTICAL_PADDING_DP = 8;
     private static final int KEY_VIEW_MIN_WIDTH_DP = 32;
     private static final int KEY_VIEW_TEXT_SIZE_SP = 12;
+    private static final double ROTATY_GRAPH_HEIGHT_FRACTION = 0.5;
 
+    private final InputManagerService mService;
     private final int mOuterPadding;
+    private final DisplayMetrics mDm;
 
     // Tracks all keys that are currently pressed/down.
     private final Map<Pair<Integer /*deviceId*/, Integer /*scanCode*/>, PressedKeyView>
             mPressedKeys = new HashMap<>();
 
-    private final PressedKeyContainer mPressedKeyContainer;
-    private final PressedKeyContainer mPressedModifierContainer;
+    @Nullable
+    private FocusEventDebugGlobalMonitor mFocusEventDebugGlobalMonitor;
+    @Nullable
+    private PressedKeyContainer mPressedKeyContainer;
+    @Nullable
+    private PressedKeyContainer mPressedModifierContainer;
+    private final Supplier<RotaryInputValueView> mRotaryInputValueViewFactory;
+    @Nullable
+    private RotaryInputValueView mRotaryInputValueView;
+    private final Supplier<RotaryInputGraphView> mRotaryInputGraphViewFactory;
+    @Nullable
+    private RotaryInputGraphView mRotaryInputGraphView;
 
-    FocusEventDebugView(Context c) {
+    @VisibleForTesting
+    FocusEventDebugView(Context c, InputManagerService service,
+            Supplier<RotaryInputValueView> rotaryInputValueViewFactory,
+            Supplier<RotaryInputGraphView> rotaryInputGraphViewFactory) {
         super(c);
         setFocusableInTouchMode(true);
 
-        final var dm = mContext.getResources().getDisplayMetrics();
-        mOuterPadding = (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, OUTER_PADDING_DP, dm);
+        mService = service;
+        mRotaryInputValueViewFactory = rotaryInputValueViewFactory;
+        mRotaryInputGraphViewFactory = rotaryInputGraphViewFactory;
+        mDm = mContext.getResources().getDisplayMetrics();
+        mOuterPadding = (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, OUTER_PADDING_DP, mDm);
+    }
 
-        setOrientation(HORIZONTAL);
-        setLayoutDirection(LAYOUT_DIRECTION_RTL);
-        setGravity(Gravity.START | Gravity.BOTTOM);
-
-        mPressedKeyContainer = new PressedKeyContainer(mContext);
-        mPressedKeyContainer.setOrientation(HORIZONTAL);
-        mPressedKeyContainer.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
-        mPressedKeyContainer.setLayoutDirection(LAYOUT_DIRECTION_LTR);
-        final var scroller = new HorizontalScrollView(mContext);
-        scroller.addView(mPressedKeyContainer);
-        scroller.setHorizontalScrollBarEnabled(false);
-        scroller.addOnLayoutChangeListener(
-                (view, l, t, r, b, ol, ot, or, ob) -> scroller.fullScroll(View.FOCUS_RIGHT));
-        scroller.setHorizontalFadingEdgeEnabled(true);
-        addView(scroller, new LayoutParams(0, WRAP_CONTENT, 1));
-
-        mPressedModifierContainer = new PressedKeyContainer(mContext);
-        mPressedModifierContainer.setOrientation(VERTICAL);
-        mPressedModifierContainer.setGravity(Gravity.LEFT | Gravity.BOTTOM);
-        addView(mPressedModifierContainer, new LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
+    FocusEventDebugView(Context c, InputManagerService service) {
+        this(c, service, () -> new RotaryInputValueView(c), () -> new RotaryInputGraphView(c));
     }
 
     @Override
@@ -108,13 +122,13 @@
 
         final RoundedCorner bottomLeft =
                 insets.getRoundedCorner(RoundedCorner.POSITION_BOTTOM_LEFT);
-        if (bottomLeft != null) {
+        if (bottomLeft != null && !insets.isRound()) {
             paddingBottom = bottomLeft.getRadius();
         }
 
         final RoundedCorner bottomRight =
                 insets.getRoundedCorner(RoundedCorner.POSITION_BOTTOM_RIGHT);
-        if (bottomRight != null) {
+        if (bottomRight != null && !insets.isRound()) {
             paddingBottom = Math.max(paddingBottom, bottomRight.getRadius());
         }
 
@@ -135,17 +149,106 @@
         return super.dispatchKeyEvent(event);
     }
 
-    /** Report an input event to the debug view. */
     @AnyThread
-    public void reportEvent(InputEvent event) {
-        if (!(event instanceof KeyEvent)) {
-            // TODO: Support non-pointer MotionEvents.
+    public void updateShowKeyPresses(boolean enabled) {
+        post(() -> handleUpdateShowKeyPresses(enabled));
+    }
+
+    @AnyThread
+    public void updateShowRotaryInput(boolean enabled) {
+        post(() -> handleUpdateShowRotaryInput(enabled));
+    }
+
+    private void handleUpdateShowKeyPresses(boolean enabled) {
+        if (enabled == showKeyPresses()) {
             return;
         }
+
+        if (!enabled) {
+            removeView(mPressedKeyContainer);
+            mPressedKeyContainer = null;
+            removeView(mPressedModifierContainer);
+            mPressedModifierContainer = null;
+            return;
+        }
+
+        mPressedKeyContainer = new PressedKeyContainer(mContext);
+        mPressedKeyContainer.setOrientation(LinearLayout.HORIZONTAL);
+        mPressedKeyContainer.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
+        mPressedKeyContainer.setLayoutDirection(LAYOUT_DIRECTION_LTR);
+        final var scroller = new HorizontalScrollView(mContext);
+        scroller.addView(mPressedKeyContainer);
+        scroller.setHorizontalScrollBarEnabled(false);
+        scroller.addOnLayoutChangeListener(
+                (view, l, t, r, b, ol, ot, or, ob) -> scroller.fullScroll(View.FOCUS_RIGHT));
+        scroller.setHorizontalFadingEdgeEnabled(true);
+        LayoutParams scrollerLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
+        scrollerLayoutParams.addRule(ALIGN_PARENT_BOTTOM);
+        scrollerLayoutParams.addRule(ALIGN_PARENT_RIGHT);
+        addView(scroller, scrollerLayoutParams);
+
+        mPressedModifierContainer = new PressedKeyContainer(mContext);
+        mPressedModifierContainer.setOrientation(LinearLayout.VERTICAL);
+        mPressedModifierContainer.setGravity(Gravity.LEFT | Gravity.BOTTOM);
+        LayoutParams modifierLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
+        modifierLayoutParams.addRule(ALIGN_PARENT_BOTTOM);
+        modifierLayoutParams.addRule(ALIGN_PARENT_LEFT);
+        modifierLayoutParams.addRule(LEFT_OF, scroller.getId());
+        addView(mPressedModifierContainer, modifierLayoutParams);
+    }
+
+    @VisibleForTesting
+    void handleUpdateShowRotaryInput(boolean enabled) {
+        if (enabled == showRotaryInput()) {
+            return;
+        }
+
+        if (!enabled) {
+            mFocusEventDebugGlobalMonitor.dispose();
+            mFocusEventDebugGlobalMonitor = null;
+            removeView(mRotaryInputValueView);
+            mRotaryInputValueView = null;
+            removeView(mRotaryInputGraphView);
+            mRotaryInputGraphView = null;
+            return;
+        }
+
+        mFocusEventDebugGlobalMonitor = new FocusEventDebugGlobalMonitor(this, mService);
+
+        mRotaryInputValueView = mRotaryInputValueViewFactory.get();
+        LayoutParams valueLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
+        valueLayoutParams.addRule(CENTER_HORIZONTAL);
+        valueLayoutParams.addRule(ALIGN_PARENT_BOTTOM);
+        addView(mRotaryInputValueView, valueLayoutParams);
+
+        mRotaryInputGraphView = mRotaryInputGraphViewFactory.get();
+        LayoutParams graphLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
+                (int) (ROTATY_GRAPH_HEIGHT_FRACTION * mDm.heightPixels));
+        graphLayoutParams.addRule(CENTER_IN_PARENT);
+        addView(mRotaryInputGraphView, graphLayoutParams);
+    }
+
+    /** Report a key event to the debug view. */
+    @AnyThread
+    public void reportKeyEvent(KeyEvent event) {
         post(() -> handleKeyEvent(KeyEvent.obtain((KeyEvent) event)));
     }
 
+    /** Report a motion event to the debug view. */
+    @AnyThread
+    public void reportMotionEvent(MotionEvent event) {
+        if (event.getSource() != InputDevice.SOURCE_ROTARY_ENCODER) {
+            return;
+        }
+
+        post(() -> handleRotaryInput(MotionEvent.obtain((MotionEvent) event)));
+    }
+
     private void handleKeyEvent(KeyEvent keyEvent) {
+        if (!showKeyPresses()) {
+            return;
+        }
+
         final var identifier = new Pair<>(keyEvent.getDeviceId(), keyEvent.getScanCode());
         final var container = KeyEvent.isModifierKey(keyEvent.getKeyCode())
                 ? mPressedModifierContainer
@@ -185,6 +288,19 @@
         keyEvent.recycle();
     }
 
+    @VisibleForTesting
+    void handleRotaryInput(MotionEvent motionEvent) {
+        if (!showRotaryInput()) {
+            return;
+        }
+
+        float scrollAxisValue = motionEvent.getAxisValue(MotionEvent.AXIS_SCROLL);
+        mRotaryInputValueView.updateValue(scrollAxisValue);
+        mRotaryInputGraphView.addValue(scrollAxisValue, motionEvent.getEventTime());
+
+        motionEvent.recycle();
+    }
+
     private static String getLabel(KeyEvent event) {
         switch (event.getKeyCode()) {
             case KeyEvent.KEYCODE_SPACE:
@@ -232,6 +348,23 @@
         return label;
     }
 
+    /** Determine whether to show key presses by checking one of the key-related objects. */
+    private boolean showKeyPresses() {
+        return mPressedKeyContainer != null;
+    }
+
+    /** Determine whether to show rotary input by checking one of the rotary-related objects. */
+    private boolean showRotaryInput() {
+        return mRotaryInputValueView != null;
+    }
+
+    /**
+     * Converts a dimension in scaled pixel units to integer display pixels.
+     */
+    private static int applyDimensionSp(int dimensionSp, DisplayMetrics dm) {
+        return (int) TypedValue.applyDimension(COMPLEX_UNIT_SP, dimensionSp, dm);
+    }
+
     private static class PressedKeyView extends TextView {
 
         private static final ColorFilter sInvertColors = new ColorMatrixColorFilter(new float[]{
@@ -340,4 +473,376 @@
             invalidate();
         }
     }
+
+    // TODO(b/286086154): move RotaryInputGraphView and RotaryInputValueView to a subpackage.
+
+    /** Draws the most recent rotary input value and indicates whether the source is active. */
+    @VisibleForTesting
+    static class RotaryInputValueView extends TextView {
+
+        private static final int INACTIVE_TEXT_COLOR = 0xffff00ff;
+        private static final int ACTIVE_TEXT_COLOR = 0xff420f28;
+        private static final int TEXT_SIZE_SP = 8;
+        private static final int SIDE_PADDING_SP = 4;
+        /** Determines how long the active status lasts. */
+        private static final int ACTIVE_STATUS_DURATION = 250 /* milliseconds */;
+        private static final ColorFilter ACTIVE_BACKGROUND_FILTER =
+                new ColorMatrixColorFilter(new float[]{
+                        0, 0, 0, 0, 255, // red
+                        0, 0, 0, 0,   0, // green
+                        0, 0, 0, 0, 255, // blue
+                        0, 0, 0, 0, 200  // alpha
+                });
+
+        private final Runnable mUpdateActivityStatusCallback = () -> updateActivityStatus(false);
+        private final float mScaledVerticalScrollFactor;
+
+        @VisibleForTesting
+        RotaryInputValueView(Context c) {
+            super(c);
+
+            DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
+            mScaledVerticalScrollFactor = ViewConfiguration.get(c).getScaledVerticalScrollFactor();
+
+            setText(getFormattedValue(0));
+            setTextColor(INACTIVE_TEXT_COLOR);
+            setTextSize(applyDimensionSp(TEXT_SIZE_SP, dm));
+            setPaddingRelative(applyDimensionSp(SIDE_PADDING_SP, dm), 0,
+                    applyDimensionSp(SIDE_PADDING_SP, dm), 0);
+            setTypeface(null, Typeface.BOLD);
+            setBackgroundResource(R.drawable.focus_event_rotary_input_background);
+        }
+
+        void updateValue(float value) {
+            removeCallbacks(mUpdateActivityStatusCallback);
+
+            setText(getFormattedValue(value * mScaledVerticalScrollFactor));
+
+            updateActivityStatus(true);
+            postDelayed(mUpdateActivityStatusCallback, ACTIVE_STATUS_DURATION);
+        }
+
+        @VisibleForTesting
+        void updateActivityStatus(boolean active) {
+            if (active) {
+                setTextColor(ACTIVE_TEXT_COLOR);
+                getBackground().setColorFilter(ACTIVE_BACKGROUND_FILTER);
+            } else {
+                setTextColor(INACTIVE_TEXT_COLOR);
+                getBackground().clearColorFilter();
+            }
+        }
+
+        private static String getFormattedValue(float value) {
+            return String.format("%s%.1f", value < 0 ? "-" : "+", Math.abs(value));
+        }
+    }
+
+    /**
+     * Shows a graph with the rotary input values as a function of time.
+     * The graph gets reset if no action is received for a certain amount of time.
+     */
+    @VisibleForTesting
+    static class RotaryInputGraphView extends View {
+
+        private static final int FRAME_COLOR = 0xbf741b47;
+        private static final int FRAME_WIDTH_SP = 2;
+        private static final int FRAME_BORDER_GAP_SP = 10;
+        private static final int FRAME_TEXT_SIZE_SP = 10;
+        private static final int FRAME_TEXT_OFFSET_SP = 2;
+        private static final int GRAPH_COLOR = 0xffff00ff;
+        private static final int GRAPH_LINE_WIDTH_SP = 1;
+        private static final int GRAPH_POINT_RADIUS_SP = 4;
+        private static final long MAX_SHOWN_TIME_INTERVAL = TimeUnit.SECONDS.toMillis(5);
+        private static final float DEFAULT_FRAME_CENTER_POSITION = 0;
+        private static final int MAX_GRAPH_VALUES_SIZE = 400;
+        /** Maximum time between values so that they are considered part of the same gesture. */
+        private static final long MAX_GESTURE_TIME = TimeUnit.SECONDS.toMillis(1);
+
+        private final DisplayMetrics mDm;
+        /**
+         * Distance in position units (amount scrolled in display pixels) from the center to the
+         * top/bottom frame lines.
+         */
+        private final float mFrameCenterToBorderDistance;
+        private final float mScaledVerticalScrollFactor;
+        private final Locale mDefaultLocale;
+        private final Paint mFramePaint = new Paint();
+        private final Paint mFrameTextPaint = new Paint();
+        private final Paint mGraphLinePaint = new Paint();
+        private final Paint mGraphPointPaint = new Paint();
+
+        private final CyclicBuffer mGraphValues = new CyclicBuffer(MAX_GRAPH_VALUES_SIZE);
+        /** Position at which graph values are placed at the center of the graph. */
+        private float mFrameCenterPosition = DEFAULT_FRAME_CENTER_POSITION;
+
+        @VisibleForTesting
+        RotaryInputGraphView(Context c) {
+            super(c);
+
+            mDm = mContext.getResources().getDisplayMetrics();
+            // This makes the center-to-border distance equivalent to the display height, meaning
+            // that the total height of the graph is equivalent to 2x the display height.
+            mFrameCenterToBorderDistance = mDm.heightPixels;
+            mScaledVerticalScrollFactor = ViewConfiguration.get(c).getScaledVerticalScrollFactor();
+            mDefaultLocale = Locale.getDefault();
+
+            mFramePaint.setColor(FRAME_COLOR);
+            mFramePaint.setStrokeWidth(applyDimensionSp(FRAME_WIDTH_SP, mDm));
+
+            mFrameTextPaint.setColor(GRAPH_COLOR);
+            mFrameTextPaint.setTextSize(applyDimensionSp(FRAME_TEXT_SIZE_SP, mDm));
+
+            mGraphLinePaint.setColor(GRAPH_COLOR);
+            mGraphLinePaint.setStrokeWidth(applyDimensionSp(GRAPH_LINE_WIDTH_SP, mDm));
+            mGraphLinePaint.setStrokeCap(Paint.Cap.ROUND);
+            mGraphLinePaint.setStrokeJoin(Paint.Join.ROUND);
+
+            mGraphPointPaint.setColor(GRAPH_COLOR);
+            mGraphPointPaint.setStrokeWidth(applyDimensionSp(GRAPH_POINT_RADIUS_SP, mDm));
+            mGraphPointPaint.setStrokeCap(Paint.Cap.ROUND);
+            mGraphPointPaint.setStrokeJoin(Paint.Join.ROUND);
+        }
+
+        /**
+         * Reads new scroll axis value and updates the list accordingly. Old positions are
+         * kept at the front (what you would get with getFirst), while the recent positions are
+         * kept at the back (what you would get with getLast). Also updates the frame center
+         * position to handle out-of-bounds cases.
+         */
+        void addValue(float scrollAxisValue, long eventTime) {
+            // Remove values that are too old.
+            while (mGraphValues.getSize() > 0
+                    && (eventTime - mGraphValues.getFirst().mTime) > MAX_SHOWN_TIME_INTERVAL) {
+                mGraphValues.removeFirst();
+            }
+
+            // If there are no recent values, reset the frame center.
+            if (mGraphValues.getSize() == 0) {
+                mFrameCenterPosition = DEFAULT_FRAME_CENTER_POSITION;
+            }
+
+            // Handle new value. We multiply the scroll axis value by the scaled scroll factor to
+            // get the amount of pixels to be scrolled. We also compute the accumulated position
+            // by adding the current value to the last one (if not empty).
+            final float displacement = scrollAxisValue * mScaledVerticalScrollFactor;
+            final float prevPos = (mGraphValues.getSize() == 0 ? 0 : mGraphValues.getLast().mPos);
+            final float pos = prevPos + displacement;
+
+            mGraphValues.add(pos, eventTime);
+
+            // The difference between the distance of the most recent position from the center
+            // frame (pos - mFrameCenterPosition) and the maximum allowed distance from the center
+            // frame (mFrameCenterToBorderDistance).
+            final float verticalDiff = Math.abs(pos - mFrameCenterPosition)
+                    - mFrameCenterToBorderDistance;
+            // If needed, translate frame.
+            if (verticalDiff > 0) {
+                final int sign = pos - mFrameCenterPosition < 0 ? -1 : 1;
+                // Here, we update the center frame position by the exact amount needed for us to
+                // stay within the maximum allowed distance from the center frame.
+                mFrameCenterPosition += sign * verticalDiff;
+            }
+
+            // Redraw canvas.
+            invalidate();
+        }
+
+        @Override
+        protected void onDraw(Canvas canvas) {
+            super.onDraw(canvas);
+
+            // Note: vertical coordinates in Canvas go from top to bottom,
+            // that is bottomY > middleY > topY.
+            final int verticalMargin = applyDimensionSp(FRAME_BORDER_GAP_SP, mDm);
+            final int topY = verticalMargin;
+            final int bottomY = getHeight() - verticalMargin;
+            final int middleY = (topY + bottomY) / 2;
+
+            // Note: horizontal coordinates in Canvas go from left to right,
+            // that is rightX > leftX.
+            final int leftX = 0;
+            final int rightX = getWidth();
+
+            // Draw the frame, which includes 3 lines that show the maximum,
+            // minimum and middle positions of the graph.
+            canvas.drawLine(leftX, topY, rightX, topY, mFramePaint);
+            canvas.drawLine(leftX, middleY, rightX, middleY, mFramePaint);
+            canvas.drawLine(leftX, bottomY, rightX, bottomY, mFramePaint);
+
+            // Draw the position that each frame line corresponds to.
+            final int frameTextOffset = applyDimensionSp(FRAME_TEXT_OFFSET_SP, mDm);
+            canvas.drawText(
+                    String.format(mDefaultLocale, "%.1f",
+                            mFrameCenterPosition + mFrameCenterToBorderDistance),
+                    leftX,
+                    topY - frameTextOffset, mFrameTextPaint
+            );
+            canvas.drawText(
+                    String.format(mDefaultLocale, "%.1f", mFrameCenterPosition),
+                    leftX,
+                    middleY - frameTextOffset, mFrameTextPaint
+            );
+            canvas.drawText(
+                    String.format(mDefaultLocale, "%.1f",
+                            mFrameCenterPosition - mFrameCenterToBorderDistance),
+                    leftX,
+                    bottomY - frameTextOffset, mFrameTextPaint
+            );
+
+            // If there are no graph values to be drawn, stop here.
+            if (mGraphValues.getSize() == 0) {
+                return;
+            }
+
+            // Draw the graph using the times and positions.
+            // We start at the most recent value (which should be drawn at the right) and move
+            // to the older values (which should be drawn to the left of more recent ones). Negative
+            // indices are handled by circuling back to the end of the buffer.
+            final long mostRecentTime = mGraphValues.getLast().mTime;
+            float prevCoordX = 0;
+            float prevCoordY = 0;
+            float prevAge = 0;
+            for (Iterator<GraphValue> iter = mGraphValues.reverseIterator(); iter.hasNext();) {
+                final GraphValue value = iter.next();
+
+                final int age = (int) (mostRecentTime - value.mTime);
+                final float pos = value.mPos;
+
+                // We get the horizontal coordinate in time units from left to right with
+                // (MAX_SHOWN_TIME_INTERVAL - age). Then, we rescale it to match the canvas
+                // units by dividing it by the time-domain length (MAX_SHOWN_TIME_INTERVAL)
+                // and by multiplying it by the canvas length (rightX - leftX). Finally, we
+                // offset the coordinate by adding it to leftX.
+                final float coordX = leftX + ((float) (MAX_SHOWN_TIME_INTERVAL - age)
+                        / MAX_SHOWN_TIME_INTERVAL) * (rightX - leftX);
+
+                // We get the vertical coordinate in position units from middle to top with
+                // (pos - mFrameCenterPosition). Then, we rescale it to match the canvas
+                // units by dividing it by half of the position-domain length
+                // (mFrameCenterToBorderDistance) and by multiplying it by half of the canvas
+                // length (middleY - topY). Finally, we offset the coordinate by subtracting
+                // it from middleY (we can't "add" here because the coordinate grows from top
+                // to bottom).
+                final float coordY = middleY - ((pos - mFrameCenterPosition)
+                        / mFrameCenterToBorderDistance) * (middleY - topY);
+
+                // Draw a point for this value.
+                canvas.drawPoint(coordX, coordY, mGraphPointPaint);
+
+                // If this value is part of the same gesture as the previous one, draw a line
+                // between them. We ignore the first value (with age = 0).
+                if (age != 0 && (age - prevAge) <= MAX_GESTURE_TIME) {
+                    canvas.drawLine(prevCoordX, prevCoordY, coordX, coordY, mGraphLinePaint);
+                }
+
+                prevCoordX = coordX;
+                prevCoordY = coordY;
+                prevAge = age;
+            }
+        }
+
+        @VisibleForTesting
+        float getFrameCenterPosition() {
+            return mFrameCenterPosition;
+        }
+
+        /**
+         * Holds data needed to draw each entry in the graph.
+         */
+        private static class GraphValue {
+            /** Position. */
+            float mPos;
+            /** Time when this value was added. */
+            long mTime;
+
+            GraphValue(float pos, long time) {
+                this.mPos = pos;
+                this.mTime = time;
+            }
+        }
+
+        /**
+         * Holds the graph values as a cyclic buffer. It has a fixed capacity, and it replaces the
+         * old values with new ones to avoid creating new objects.
+         */
+        private static class CyclicBuffer {
+            private final GraphValue[] mValues;
+            private final int mCapacity;
+            private int mSize = 0;
+            private int mLastIndex = 0;
+
+            // The iteration index and counter are here to make it easier to reset them.
+            /** Determines the value currently pointed by the iterator. */
+            private int mIteratorIndex;
+            /** Counts how many values have been iterated through. */
+            private int mIteratorCount;
+
+            /** Used traverse the values in reverse order. */
+            private final Iterator<GraphValue> mReverseIterator = new Iterator<GraphValue>() {
+                @Override
+                public boolean hasNext() {
+                    return mIteratorCount <= mSize;
+                }
+
+                @Override
+                public GraphValue next() {
+                    // Returns the value currently pointed by the iterator and moves the iterator to
+                    // the previous one.
+                    mIteratorCount++;
+                    return mValues[(mIteratorIndex-- + mCapacity) % mCapacity];
+                }
+            };
+
+            CyclicBuffer(int capacity) {
+                mCapacity = capacity;
+                mValues = new GraphValue[capacity];
+            }
+
+            /**
+             * Add new graph value. If there is an existing object, we replace its data with the
+             * new one. With this, we re-use old objects instead of creating new ones.
+             */
+            void add(float pos, long time) {
+                mLastIndex = (mLastIndex + 1) % mCapacity;
+                if (mValues[mLastIndex] == null) {
+                    mValues[mLastIndex] = new GraphValue(pos, time);
+                } else {
+                    final GraphValue oldValue = mValues[mLastIndex];
+                    oldValue.mPos = pos;
+                    oldValue.mTime = time;
+                }
+
+                // If needed, account for new value in the buffer size.
+                if (mSize != mCapacity) {
+                    mSize++;
+                }
+            }
+
+            int getSize() {
+                return mSize;
+            }
+
+            GraphValue getFirst() {
+                final int distanceBetweenLastAndFirst = (mCapacity - mSize) + 1;
+                final int firstIndex = (mLastIndex + distanceBetweenLastAndFirst) % mCapacity;
+                return mValues[firstIndex];
+            }
+
+            GraphValue getLast() {
+                return mValues[mLastIndex];
+            }
+
+            void removeFirst() {
+                mSize--;
+            }
+
+            /** Returns an iterator pointing at the last value. */
+            Iterator<GraphValue> reverseIterator() {
+                mIteratorIndex = mLastIndex;
+                mIteratorCount = 1;
+                return mReverseIterator;
+            }
+        }
+    }
 }
diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java
index 6241ebb..b8e9d5d 100644
--- a/services/core/java/com/android/server/input/InputManagerService.java
+++ b/services/core/java/com/android/server/input/InputManagerService.java
@@ -390,6 +390,8 @@
     @GuardedBy("mFocusEventDebugViewLock")
     @Nullable
     private FocusEventDebugView mFocusEventDebugView;
+    private boolean mShowKeyPresses = false;
+    private boolean mShowRotaryInput = false;
 
     /** Point of injection for test dependencies. */
     @VisibleForTesting
@@ -2476,7 +2478,7 @@
     private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
         synchronized (mFocusEventDebugViewLock) {
             if (mFocusEventDebugView != null) {
-                mFocusEventDebugView.reportEvent(event);
+                mFocusEventDebugView.reportKeyEvent(event);
             }
         }
         return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
@@ -3396,14 +3398,45 @@
         mWindowManagerCallbacks.notifyPointerLocationChanged(enabled);
     }
 
-    void updateFocusEventDebugViewEnabled(boolean enabled) {
+    void updateShowKeyPresses(boolean enabled) {
+        if (mShowKeyPresses == enabled) {
+            return;
+        }
+
+        mShowKeyPresses = enabled;
+        updateFocusEventDebugViewEnabled();
+
+        synchronized (mFocusEventDebugViewLock) {
+            if (mFocusEventDebugView != null) {
+                mFocusEventDebugView.updateShowKeyPresses(enabled);
+            }
+        }
+    }
+
+    void updateShowRotaryInput(boolean enabled) {
+        if (mShowRotaryInput == enabled) {
+            return;
+        }
+
+        mShowRotaryInput = enabled;
+        updateFocusEventDebugViewEnabled();
+
+        synchronized (mFocusEventDebugViewLock) {
+            if (mFocusEventDebugView != null) {
+                mFocusEventDebugView.updateShowRotaryInput(enabled);
+            }
+        }
+    }
+
+    private void updateFocusEventDebugViewEnabled() {
+        boolean enabled = mShowKeyPresses || mShowRotaryInput;
         FocusEventDebugView view;
         synchronized (mFocusEventDebugViewLock) {
             if (enabled == (mFocusEventDebugView != null)) {
                 return;
             }
             if (enabled) {
-                mFocusEventDebugView = new FocusEventDebugView(mContext);
+                mFocusEventDebugView = new FocusEventDebugView(mContext, this);
                 view = mFocusEventDebugView;
             } else {
                 view = mFocusEventDebugView;
diff --git a/services/core/java/com/android/server/input/InputSettingsObserver.java b/services/core/java/com/android/server/input/InputSettingsObserver.java
index cf7c692..aab491e 100644
--- a/services/core/java/com/android/server/input/InputSettingsObserver.java
+++ b/services/core/java/com/android/server/input/InputSettingsObserver.java
@@ -86,7 +86,9 @@
                 Map.entry(Settings.Secure.getUriFor(Settings.Secure.KEY_REPEAT_TIMEOUT_MS),
                         (reason) -> updateKeyRepeatInfo(getLatestLongPressTimeoutValue())),
                 Map.entry(Settings.Secure.getUriFor(Settings.Secure.KEY_REPEAT_DELAY_MS),
-                        (reason) -> updateKeyRepeatInfo(getLatestLongPressTimeoutValue())));
+                        (reason) -> updateKeyRepeatInfo(getLatestLongPressTimeoutValue())),
+                Map.entry(Settings.System.getUriFor(Settings.System.SHOW_ROTARY_INPUT),
+                        (reason) -> updateShowRotaryInput()));
     }
 
     /**
@@ -164,8 +166,11 @@
     }
 
     private void updateShowKeyPresses() {
-        mService.updateFocusEventDebugViewEnabled(
-                getBoolean(Settings.System.SHOW_KEY_PRESSES, false));
+        mService.updateShowKeyPresses(getBoolean(Settings.System.SHOW_KEY_PRESSES, false));
+    }
+
+    private void updateShowRotaryInput() {
+        mService.updateShowRotaryInput(getBoolean(Settings.System.SHOW_ROTARY_INPUT, false));
     }
 
     private void updateAccessibilityLargePointer() {
diff --git a/services/core/java/com/android/server/input/KeyboardLayoutManager.java b/services/core/java/com/android/server/input/KeyboardLayoutManager.java
index 5bdf263..a5162c0 100644
--- a/services/core/java/com/android/server/input/KeyboardLayoutManager.java
+++ b/services/core/java/com/android/server/input/KeyboardLayoutManager.java
@@ -169,7 +169,9 @@
     @Override
     @MainThread
     public void onInputDeviceAdded(int deviceId) {
-        onInputDeviceChanged(deviceId);
+        // Logging keyboard configuration data to statsd whenever input device is added. Currently
+        // only logging for New Settings UI where we are using IME to decide the layout information.
+        onInputDeviceChangedInternal(deviceId, true /* shouldLogConfiguration */);
     }
 
     @Override
@@ -182,6 +184,10 @@
     @Override
     @MainThread
     public void onInputDeviceChanged(int deviceId) {
+        onInputDeviceChangedInternal(deviceId, false /* shouldLogConfiguration */);
+    }
+
+    private void onInputDeviceChangedInternal(int deviceId, boolean shouldLogConfiguration) {
         final InputDevice inputDevice = getInputDevice(deviceId);
         if (inputDevice == null || inputDevice.isVirtual() || !inputDevice.isFullKeyboard()) {
             return;
@@ -243,18 +249,15 @@
             synchronized (mDataStore) {
                 try {
                     final String key = keyboardIdentifier.toString();
-                    boolean isFirstConfiguration = !mDataStore.hasInputDeviceEntry(key);
                     if (mDataStore.setSelectedKeyboardLayouts(key, selectedLayouts)) {
                         // Need to show the notification only if layout selection changed
                         // from the previous configuration
                         needToShowNotification = true;
+                    }
 
-                        // Logging keyboard configuration data to statsd only if the
-                        // configuration changed from the previous configuration. Currently
-                        // only logging for New Settings UI where we are using IME to decide
-                        // the layout information.
+                    if (shouldLogConfiguration) {
                         logKeyboardConfigurationEvent(inputDevice, imeInfoList, layoutInfoList,
-                                isFirstConfiguration);
+                                !mDataStore.hasInputDeviceEntry(key));
                     }
                 } finally {
                     mDataStore.saveIfNeeded();
diff --git a/services/core/java/com/android/server/input/KeyboardMetricsCollector.java b/services/core/java/com/android/server/input/KeyboardMetricsCollector.java
index 4b30ae5..08e5977 100644
--- a/services/core/java/com/android/server/input/KeyboardMetricsCollector.java
+++ b/services/core/java/com/android/server/input/KeyboardMetricsCollector.java
@@ -21,10 +21,10 @@
 import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.content.ComponentName;
 import android.content.Intent;
 import android.hardware.input.KeyboardLayout;
 import android.icu.util.ULocale;
+import android.text.TextUtils;
 import android.util.Log;
 import android.util.Slog;
 import android.util.SparseArray;
@@ -41,9 +41,7 @@
 import java.lang.annotation.Retention;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
 
@@ -59,6 +57,7 @@
 
     @Retention(SOURCE)
     @IntDef(prefix = {"LAYOUT_SELECTION_CRITERIA_"}, value = {
+            LAYOUT_SELECTION_CRITERIA_UNSPECIFIED,
             LAYOUT_SELECTION_CRITERIA_USER,
             LAYOUT_SELECTION_CRITERIA_DEVICE,
             LAYOUT_SELECTION_CRITERIA_VIRTUAL_KEYBOARD,
@@ -67,23 +66,26 @@
     public @interface LayoutSelectionCriteria {
     }
 
+    /** Unspecified layout selection criteria */
+    public static final int LAYOUT_SELECTION_CRITERIA_UNSPECIFIED = 0;
+
     /** Manual selection by user */
-    public static final int LAYOUT_SELECTION_CRITERIA_USER = 0;
+    public static final int LAYOUT_SELECTION_CRITERIA_USER = 1;
 
     /** Auto-detection based on device provided language tag and layout type */
-    public static final int LAYOUT_SELECTION_CRITERIA_DEVICE = 1;
+    public static final int LAYOUT_SELECTION_CRITERIA_DEVICE = 2;
 
     /** Auto-detection based on IME provided language tag and layout type */
-    public static final int LAYOUT_SELECTION_CRITERIA_VIRTUAL_KEYBOARD = 2;
+    public static final int LAYOUT_SELECTION_CRITERIA_VIRTUAL_KEYBOARD = 3;
 
     /** Default selection */
-    public static final int LAYOUT_SELECTION_CRITERIA_DEFAULT = 3;
+    public static final int LAYOUT_SELECTION_CRITERIA_DEFAULT = 4;
 
     @VisibleForTesting
-    static final String DEFAULT_LAYOUT = "Default";
+    static final String DEFAULT_LAYOUT_NAME = "Default";
 
     @VisibleForTesting
-    static final String DEFAULT_LANGUAGE_TAG = "None";
+    public static final String DEFAULT_LANGUAGE_TAG = "None";
 
     public enum KeyboardLogEvent {
         UNSPECIFIED(
@@ -536,23 +538,23 @@
                             mLayoutSelectionCriteriaList.get(i);
                     InputMethodSubtype imeSubtype = mImeSubtypeList.get(i);
                     String keyboardLanguageTag = mInputDevice.getKeyboardLanguageTag();
-                    keyboardLanguageTag = keyboardLanguageTag == null ? DEFAULT_LANGUAGE_TAG
-                            : keyboardLanguageTag;
+                    keyboardLanguageTag = TextUtils.isEmpty(keyboardLanguageTag)
+                            ? DEFAULT_LANGUAGE_TAG : keyboardLanguageTag;
                     int keyboardLayoutType = KeyboardLayout.LayoutType.getLayoutTypeEnumValue(
                             mInputDevice.getKeyboardLayoutType());
 
                     ULocale pkLocale = imeSubtype.getPhysicalKeyboardHintLanguageTag();
-                    String canonicalizedLanguageTag =
-                            imeSubtype.getCanonicalizedLanguageTag().equals("")
-                            ? DEFAULT_LANGUAGE_TAG : imeSubtype.getCanonicalizedLanguageTag();
                     String imeLanguageTag = pkLocale != null ? pkLocale.toLanguageTag()
-                            : canonicalizedLanguageTag;
+                            : imeSubtype.getCanonicalizedLanguageTag();
+                    imeLanguageTag = TextUtils.isEmpty(imeLanguageTag) ? DEFAULT_LANGUAGE_TAG
+                            : imeLanguageTag;
                     int imeLayoutType = KeyboardLayout.LayoutType.getLayoutTypeEnumValue(
                             imeSubtype.getPhysicalKeyboardHintLayoutType());
 
                     // Sanitize null values
                     String keyboardLayoutName =
-                            selectedLayout == null ? DEFAULT_LAYOUT : selectedLayout.getLabel();
+                            selectedLayout == null ? DEFAULT_LAYOUT_NAME
+                                    : selectedLayout.getLabel();
 
                     configurationList.add(
                             new LayoutConfiguration(keyboardLayoutType, keyboardLanguageTag,
@@ -601,6 +603,8 @@
     private static String getStringForSelectionCriteria(
             @LayoutSelectionCriteria int layoutSelectionCriteria) {
         switch (layoutSelectionCriteria) {
+            case LAYOUT_SELECTION_CRITERIA_UNSPECIFIED:
+                return "LAYOUT_SELECTION_CRITERIA_UNSPECIFIED";
             case LAYOUT_SELECTION_CRITERIA_USER:
                 return "LAYOUT_SELECTION_CRITERIA_USER";
             case LAYOUT_SELECTION_CRITERIA_DEVICE:
diff --git a/services/core/java/com/android/server/inputmethod/ImeVisibilityStateComputer.java b/services/core/java/com/android/server/inputmethod/ImeVisibilityStateComputer.java
index 9ad4628..2e0274b 100644
--- a/services/core/java/com/android/server/inputmethod/ImeVisibilityStateComputer.java
+++ b/services/core/java/com/android/server/inputmethod/ImeVisibilityStateComputer.java
@@ -23,6 +23,7 @@
 import static android.server.inputmethod.InputMethodManagerServiceProto.SHOW_FORCED;
 import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.Display.INVALID_DISPLAY;
+import static android.view.MotionEvent.TOOL_TYPE_UNKNOWN;
 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE;
 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED;
@@ -44,6 +45,7 @@
 import android.util.Printer;
 import android.util.Slog;
 import android.util.proto.ProtoOutputStream;
+import android.view.MotionEvent;
 import android.view.WindowManager;
 import android.view.inputmethod.ImeTracker;
 import android.view.inputmethod.InputMethod;
@@ -351,7 +353,8 @@
 
     void setWindowState(IBinder windowToken, @NonNull ImeTargetWindowState newState) {
         final ImeTargetWindowState state = mRequestWindowStateMap.get(windowToken);
-        if (state != null && newState.hasEditorFocused()) {
+        if (state != null && newState.hasEditorFocused()
+                && newState.mToolType != MotionEvent.TOOL_TYPE_STYLUS) {
             // Inherit the last requested IME visible state when the target window is still
             // focused with an editor.
             newState.setRequestedImeVisible(state.mRequestedImeVisible);
@@ -652,14 +655,23 @@
      * A class that represents the current state of the IME target window.
      */
     static class ImeTargetWindowState {
+
         ImeTargetWindowState(@SoftInputModeFlags int softInputModeState, int windowFlags,
                 boolean imeFocusChanged, boolean hasFocusedEditor,
                 boolean isStartInputByGainFocus) {
+            this(softInputModeState, windowFlags, imeFocusChanged, hasFocusedEditor,
+                    isStartInputByGainFocus, TOOL_TYPE_UNKNOWN);
+        }
+
+        ImeTargetWindowState(@SoftInputModeFlags int softInputModeState, int windowFlags,
+                boolean imeFocusChanged, boolean hasFocusedEditor,
+                boolean isStartInputByGainFocus, @MotionEvent.ToolType int toolType) {
             mSoftInputModeState = softInputModeState;
             mWindowFlags = windowFlags;
             mImeFocusChanged = imeFocusChanged;
             mHasFocusedEditor = hasFocusedEditor;
             mIsStartInputByGainFocus = isStartInputByGainFocus;
+            mToolType = toolType;
         }
 
         /**
@@ -670,6 +682,11 @@
         private final int mWindowFlags;
 
         /**
+         * {@link MotionEvent#getToolType(int)} that was used to click editor.
+         */
+        private final int mToolType;
+
+        /**
          * {@code true} means the IME focus changed from the previous window, {@code false}
          * otherwise.
          */
@@ -718,6 +735,10 @@
             return mWindowFlags;
         }
 
+        int getToolType() {
+            return mToolType;
+        }
+
         private void setImeDisplayId(int imeDisplayId) {
             mImeDisplayId = imeDisplayId;
         }
diff --git a/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java b/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java
index 1d222e5..20c7029 100644
--- a/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java
+++ b/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java
@@ -40,6 +40,7 @@
 import android.view.WindowManager;
 import android.view.inputmethod.InputMethod;
 import android.view.inputmethod.InputMethodInfo;
+import android.view.inputmethod.InputMethodManager;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
@@ -295,7 +296,12 @@
                     }
                     if (DEBUG) Slog.v(TAG, "Initiating attach with token: " + mCurToken);
                     final InputMethodInfo info = mMethodMap.get(mSelectedMethodId);
+                    boolean supportsStylusHwChanged =
+                            mSupportsStylusHw != info.supportsStylusHandwriting();
                     mSupportsStylusHw = info.supportsStylusHandwriting();
+                    if (supportsStylusHwChanged) {
+                        InputMethodManager.invalidateLocalStylusHandwritingAvailabilityCaches();
+                    }
                     mService.initializeImeLocked(mCurMethod, mCurToken);
                     mService.scheduleNotifyImeUidToAudioService(mCurMethodUid);
                     mService.reRequestCurrentClientSessionLocked();
diff --git a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
index 4ce7e24..8e7baf2 100644
--- a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
@@ -2315,8 +2315,6 @@
             mCurClient = null;
             ImeTracker.forLogging().onFailed(mCurStatsToken, ImeTracker.PHASE_SERVER_WAIT_IME);
             mCurStatsToken = null;
-            InputMethodManager.invalidateLocalStylusHandwritingAvailabilityCaches();
-
             mMenuController.hideInputMethodMenuLocked();
         }
     }
@@ -3794,11 +3792,14 @@
         final boolean isTextEditor = (startInputFlags & StartInputFlags.IS_TEXT_EDITOR) != 0;
         final boolean startInputByWinGainedFocus =
                 (startInputFlags & StartInputFlags.WINDOW_GAINED_FOCUS) != 0;
+        final int toolType = editorInfo != null
+                ? editorInfo.getInitialToolType() : MotionEvent.TOOL_TYPE_UNKNOWN;
 
         // Init the focused window state (e.g. whether the editor has focused or IME focus has
         // changed from another window).
-        final ImeTargetWindowState windowState = new ImeTargetWindowState(softInputMode,
-                windowFlags, !sameWindowFocused, isTextEditor, startInputByWinGainedFocus);
+        final ImeTargetWindowState windowState = new ImeTargetWindowState(
+                softInputMode, windowFlags, !sameWindowFocused, isTextEditor,
+                startInputByWinGainedFocus, toolType);
         mVisibilityStateComputer.setWindowState(windowToken, windowState);
 
         if (sameWindowFocused && isTextEditor) {
@@ -5958,6 +5959,8 @@
             mVisibilityStateComputer.dump(pw);
             p.println("  mInFullscreenMode=" + mInFullscreenMode);
             p.println("  mSystemReady=" + mSystemReady + " mInteractive=" + mIsInteractive);
+            p.println("  ENABLE_HIDE_IME_CAPTION_BAR="
+                    + InputMethodService.ENABLE_HIDE_IME_CAPTION_BAR);
             p.println("  mSettingsObserver=" + mSettingsObserver);
             p.println("  mStylusIds=" + (mStylusIds != null
                     ? Arrays.toString(mStylusIds.toArray()) : ""));
diff --git a/services/core/java/com/android/server/location/LocationManagerService.java b/services/core/java/com/android/server/location/LocationManagerService.java
index 595b2e4..74b7f08 100644
--- a/services/core/java/com/android/server/location/LocationManagerService.java
+++ b/services/core/java/com/android/server/location/LocationManagerService.java
@@ -1750,13 +1750,6 @@
         }
 
         @Override
-        public void sendNiResponse(int notifId, int userResponse) {
-            if (mGnssManagerService != null) {
-                mGnssManagerService.sendNiResponse(notifId, userResponse);
-            }
-        }
-
-        @Override
         public @Nullable LocationTime getGnssTimeMillis() {
             LocationProviderManager gpsManager = getLocationProviderManager(GPS_PROVIDER);
             if (gpsManager == null) {
diff --git a/services/core/java/com/android/server/location/TEST_MAPPING b/services/core/java/com/android/server/location/TEST_MAPPING
index 214d2f3..f5deb2b 100644
--- a/services/core/java/com/android/server/location/TEST_MAPPING
+++ b/services/core/java/com/android/server/location/TEST_MAPPING
@@ -1,7 +1,13 @@
 {
   "presubmit": [
     {
-      "name": "CtsLocationFineTestCases"
+      "name": "CtsLocationFineTestCases",
+      "options": [
+          {
+             // TODO: Wait for test to deflake - b/293934372
+             "exclude-filter":"android.location.cts.fine.ScanningSettingsTest"
+          }
+      ]
     },
     {
       "name": "CtsLocationCoarseTestCases"
@@ -16,4 +22,4 @@
       }]
     }
   ]
-}
\ No newline at end of file
+}
diff --git a/services/core/java/com/android/server/location/gnss/GnssLocationProvider.java b/services/core/java/com/android/server/location/gnss/GnssLocationProvider.java
index ed5c130..6f9b7d6 100644
--- a/services/core/java/com/android/server/location/gnss/GnssLocationProvider.java
+++ b/services/core/java/com/android/server/location/gnss/GnssLocationProvider.java
@@ -62,7 +62,6 @@
 import android.database.ContentObserver;
 import android.location.GnssCapabilities;
 import android.location.GnssStatus;
-import android.location.INetInitiatedListener;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
@@ -109,7 +108,6 @@
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.app.IBatteryStats;
 import com.android.internal.location.GpsNetInitiatedHandler;
-import com.android.internal.location.GpsNetInitiatedHandler.GpsNiNotification;
 import com.android.internal.util.FrameworkStatsLog;
 import com.android.internal.util.HexDump;
 import com.android.server.FgThread;
@@ -297,6 +295,8 @@
     private final PowerManager.WakeLock mDownloadPsdsWakeLock;
     @GuardedBy("mLock")
     private final Set<Integer> mPendingDownloadPsdsTypes = new HashSet<>();
+    @GuardedBy("mLock")
+    private final Set<Integer> mDownloadInProgressPsdsTypes = new HashSet<>();
 
     /**
      * Properties loaded from PROPERTIES_FILE.
@@ -396,7 +396,6 @@
         mC2KServerPort = mGnssConfiguration.getC2KPort(TCP_MIN_PORT);
         mNIHandler.setEmergencyExtensionSeconds(mGnssConfiguration.getEsExtensionSec());
         mSuplEsEnabled = mGnssConfiguration.getSuplEs(0) == 1;
-        mNIHandler.setSuplEsEnabled(mSuplEsEnabled);
         if (mGnssVisibilityControl != null) {
             mGnssVisibilityControl.onConfigurationUpdated(mGnssConfiguration);
         }
@@ -465,7 +464,6 @@
                     }
                 };
         mNIHandler = new GpsNetInitiatedHandler(context,
-                mNetInitiatedListener,
                 emergencyCallCallback,
                 mSuplEsEnabled);
         // Trigger PSDS data download when the network comes up after booting.
@@ -771,8 +769,16 @@
             return;
         }
         synchronized (mLock) {
+            if (mDownloadInProgressPsdsTypes.contains(psdsType)) {
+                if (DEBUG) {
+                    Log.d(TAG,
+                            "PSDS type " + psdsType + " download in progress. Ignore the request.");
+                }
+                return;
+            }
             // hold wake lock while task runs
             mDownloadPsdsWakeLock.acquire(DOWNLOAD_PSDS_DATA_TIMEOUT_MS);
+            mDownloadInProgressPsdsTypes.add(psdsType);
         }
         Log.i(TAG, "WakeLock acquired by handleDownloadPsdsData()");
         Executors.newSingleThreadExecutor().execute(() -> {
@@ -822,6 +828,7 @@
                     Log.e(TAG, "WakeLock expired before release in "
                             + "handleDownloadPsdsData()");
                 }
+                mDownloadInProgressPsdsTypes.remove(psdsType);
             }
         });
     }
@@ -1435,96 +1442,6 @@
         updateRequirements();
     }
 
-    //=============================================================
-    // NI Client support
-    //=============================================================
-    private final INetInitiatedListener mNetInitiatedListener = new INetInitiatedListener.Stub() {
-        // Sends a response for an NI request to HAL.
-        @Override
-        public boolean sendNiResponse(int notificationId, int userResponse) {
-            // TODO Add Permission check
-
-            if (DEBUG) {
-                Log.d(TAG, "sendNiResponse, notifId: " + notificationId
-                        + ", response: " + userResponse);
-            }
-            mGnssNative.sendNiResponse(notificationId, userResponse);
-
-            FrameworkStatsLog.write(FrameworkStatsLog.GNSS_NI_EVENT_REPORTED,
-                    FrameworkStatsLog.GNSS_NI_EVENT_REPORTED__EVENT_TYPE__NI_RESPONSE,
-                    notificationId,
-                    /* niType= */ 0,
-                    /* needNotify= */ false,
-                    /* needVerify= */ false,
-                    /* privacyOverride= */ false,
-                    /* timeout= */ 0,
-                    /* defaultResponse= */ 0,
-                    /* requestorId= */ null,
-                    /* text= */ null,
-                    /* requestorIdEncoding= */ 0,
-                    /* textEncoding= */ 0,
-                    mSuplEsEnabled,
-                    isGpsEnabled(),
-                    userResponse);
-
-            return true;
-        }
-    };
-
-    public INetInitiatedListener getNetInitiatedListener() {
-        return mNetInitiatedListener;
-    }
-
-    /** Reports a NI notification. */
-    private void reportNiNotification(int notificationId, int niType, int notifyFlags, int timeout,
-            int defaultResponse, String requestorId, String text, int requestorIdEncoding,
-            int textEncoding) {
-        Log.i(TAG, "reportNiNotification: entered");
-        Log.i(TAG, "notificationId: " + notificationId
-                + ", niType: " + niType
-                + ", notifyFlags: " + notifyFlags
-                + ", timeout: " + timeout
-                + ", defaultResponse: " + defaultResponse);
-
-        Log.i(TAG, "requestorId: " + requestorId
-                + ", text: " + text
-                + ", requestorIdEncoding: " + requestorIdEncoding
-                + ", textEncoding: " + textEncoding);
-
-        GpsNiNotification notification = new GpsNiNotification();
-
-        notification.notificationId = notificationId;
-        notification.niType = niType;
-        notification.needNotify = (notifyFlags & GpsNetInitiatedHandler.GPS_NI_NEED_NOTIFY) != 0;
-        notification.needVerify = (notifyFlags & GpsNetInitiatedHandler.GPS_NI_NEED_VERIFY) != 0;
-        notification.privacyOverride =
-                (notifyFlags & GpsNetInitiatedHandler.GPS_NI_PRIVACY_OVERRIDE) != 0;
-        notification.timeout = timeout;
-        notification.defaultResponse = defaultResponse;
-        notification.requestorId = requestorId;
-        notification.text = text;
-        notification.requestorIdEncoding = requestorIdEncoding;
-        notification.textEncoding = textEncoding;
-
-        mNIHandler.handleNiNotification(notification);
-        FrameworkStatsLog.write(FrameworkStatsLog.GNSS_NI_EVENT_REPORTED,
-                FrameworkStatsLog.GNSS_NI_EVENT_REPORTED__EVENT_TYPE__NI_REQUEST,
-                notification.notificationId,
-                notification.niType,
-                notification.needNotify,
-                notification.needVerify,
-                notification.privacyOverride,
-                notification.timeout,
-                notification.defaultResponse,
-                notification.requestorId,
-                notification.text,
-                notification.requestorIdEncoding,
-                notification.textEncoding,
-                mSuplEsEnabled,
-                isGpsEnabled(),
-                /* userResponse= */ 0);
-    }
-
     private void demandUtcTimeInjection() {
         if (DEBUG) Log.d(TAG, "demandUtcTimeInjection");
         postWithWakeLockHeld(mNetworkTimeHelper::demandUtcTimeInjection);
@@ -1829,14 +1746,6 @@
     }
 
     @Override
-    public void onReportNiNotification(int notificationId, int niType, int notifyFlags,
-            int timeout, int defaultResponse, String requestorId, String text,
-            int requestorIdEncoding, int textEncoding) {
-        reportNiNotification(notificationId, niType, notifyFlags, timeout,
-                defaultResponse, requestorId, text, requestorIdEncoding, textEncoding);
-    }
-
-    @Override
     public void onRequestSetID(@GnssNative.AGpsCallbacks.AgpsSetIdFlags int flags) {
         TelephonyManager phone = (TelephonyManager)
                 mContext.getSystemService(Context.TELEPHONY_SERVICE);
diff --git a/services/core/java/com/android/server/location/gnss/GnssManagerService.java b/services/core/java/com/android/server/location/gnss/GnssManagerService.java
index c962bc4..133704d 100644
--- a/services/core/java/com/android/server/location/gnss/GnssManagerService.java
+++ b/services/core/java/com/android/server/location/gnss/GnssManagerService.java
@@ -38,7 +38,6 @@
 import android.location.util.identity.CallerIdentity;
 import android.os.BatteryStats;
 import android.os.Binder;
-import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.UserHandle;
 import android.util.IndentingPrintWriter;
@@ -275,17 +274,6 @@
     }
 
     /**
-     * Send Ni Response, indicating a location request initiated by a network carrier.
-     */
-    public void sendNiResponse(int notifId, int userResponse) {
-        try {
-            mGnssLocationProvider.getNetInitiatedListener().sendNiResponse(notifId, userResponse);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
      * Dump info for debugging.
      */
     public void dump(FileDescriptor fd, IndentingPrintWriter ipw, String[] args) {
diff --git a/services/core/java/com/android/server/location/gnss/hal/GnssNative.java b/services/core/java/com/android/server/location/gnss/hal/GnssNative.java
index 7618419..bdd4885 100644
--- a/services/core/java/com/android/server/location/gnss/hal/GnssNative.java
+++ b/services/core/java/com/android/server/location/gnss/hal/GnssNative.java
@@ -284,9 +284,6 @@
 
     /** Callbacks for notifications. */
     public interface NotificationCallbacks {
-        void onReportNiNotification(int notificationId, int niType, int notifyFlags,
-                int timeout, int defaultResponse, String requestorId, String text,
-                int requestorIdEncoding, int textEncoding);
         void onReportNfwNotification(String proxyAppPackageName, byte protocolStack,
                 String otherProtocolStackName, byte requestor, String requestorId,
                 byte responseType, boolean inEmergencyMode, boolean isCachedLocation);
@@ -933,14 +930,6 @@
     }
 
     /**
-     * Send a network initiated respnse.
-     */
-    public void sendNiResponse(int notificationId, int userResponse) {
-        Preconditions.checkState(mRegistered);
-        mGnssHal.sendNiResponse(notificationId, userResponse);
-    }
-
-    /**
      * Request an eventual update of GNSS power statistics.
      */
     public void requestPowerStats() {
@@ -1244,16 +1233,6 @@
     }
 
     @NativeEntryPoint
-    void reportNiNotification(int notificationId, int niType, int notifyFlags,
-            int timeout, int defaultResponse, String requestorId, String text,
-            int requestorIdEncoding, int textEncoding) {
-        Binder.withCleanCallingIdentity(
-                () -> mNotificationCallbacks.onReportNiNotification(notificationId, niType,
-                        notifyFlags, timeout, defaultResponse, requestorId, text,
-                        requestorIdEncoding, textEncoding));
-    }
-
-    @NativeEntryPoint
     void requestSetID(int flags) {
         Binder.withCleanCallingIdentity(() -> mAGpsCallbacks.onRequestSetID(flags));
     }
@@ -1488,10 +1467,6 @@
             return native_is_gnss_visibility_control_supported();
         }
 
-        protected void sendNiResponse(int notificationId, int userResponse) {
-            native_send_ni_response(notificationId, userResponse);
-        }
-
         protected void requestPowerStats() {
             native_request_power_stats();
         }
@@ -1648,8 +1623,6 @@
 
     private static native boolean native_is_gnss_visibility_control_supported();
 
-    private static native void native_send_ni_response(int notificationId, int userResponse);
-
     // power stats APIs
 
     private static native void native_request_power_stats();
diff --git a/services/core/java/com/android/server/locksettings/LockSettingsService.java b/services/core/java/com/android/server/locksettings/LockSettingsService.java
index b3ef869..c3abfc1 100644
--- a/services/core/java/com/android/server/locksettings/LockSettingsService.java
+++ b/services/core/java/com/android/server/locksettings/LockSettingsService.java
@@ -192,9 +192,40 @@
 import javax.crypto.spec.GCMParameterSpec;
 
 /**
- * Keeps the lock pattern/password data and related settings for each user. Used by
- * LockPatternUtils. Needs to be a service because Settings app also needs to be able to save
- * lockscreen information for secondary users.
+ * LockSettingsService (LSS) mainly has the following responsibilities:
+ * <p>
+ * <ul>
+ *   <li>Provide APIs to verify and change the Lock Screen Knowledge Factor (LSKF) ("lockscreen
+ *   credential") of each user.  Unlock users when their correct LSKF is given.</li>
+ *
+ *   <li>Store other lockscreen related settings, such as some Keyguard (UI) settings.</li>
+ *
+ *   <li>Manage each user's synthetic password (SP), which is their main cryptographic secret.
+ *   See {@link SyntheticPasswordManager}.</li>
+ *
+ *   <li>Protect each user's SP using their LSKF.  Use the Gatekeeper or Weaver HAL to ensure that
+ *   guesses of the LSKF are ratelimited by the TEE or secure element.</li>
+ *
+ *   <li>Protect each user's data using their SP.  For example, use the SP to encrypt/decrypt the
+ *   user's credential-encrypted (CE) key for file-based encryption (FBE).</li>
+ *
+ *   <li>Generate, protect, and use profile passwords for managed profiles.</li>
+ *
+ *   <li>Support unlocking the SP by alternative means: resume-on-reboot (reboot escrow) for easier
+ *   OTA updates, and escrow tokens when set up by the Device Policy Controller (DPC).</li>
+ *
+ *   <li>Implement part of the Factory Reset Protection (FRP) and Repair Mode features by storing
+ *   the information needed to verify a user's LSKF on the persist or metadata partition.</li>
+ *
+ *   <li>Support insider attack resistance using the AuthSecret HAL.</li>
+ *
+ *   <li>Implement "recoverable keystore", a feature that enables end-to-end encrypted backups.
+ *   See {@link android.security.keystore.recovery.RecoveryController}.</li>
+ * </ul>
+ * <p>
+ * The main clients of LockSettingsService are Keyguard (i.e. the lockscreen UI, which is part of
+ * System UI), the Settings app (com.android.settings), and other parts of system_server.  Most
+ * methods are protected by ACCESS_KEYGUARD_SECURE_STORAGE which only system processes can have.
  *
  * @hide
  */
@@ -1284,7 +1315,6 @@
         return getCredentialTypeInternal(userId);
     }
 
-    // TODO: this is a hot path, can we optimize it?
     /**
      * Returns the credential type of the user, can be one of {@link #CREDENTIAL_TYPE_NONE},
      * {@link #CREDENTIAL_TYPE_PATTERN}, {@link #CREDENTIAL_TYPE_PIN} and
diff --git a/services/core/java/com/android/server/locksettings/recoverablekeystore/storage/ApplicationKeyStorage.java b/services/core/java/com/android/server/locksettings/recoverablekeystore/storage/ApplicationKeyStorage.java
index 06db6b8..ef56a1e 100644
--- a/services/core/java/com/android/server/locksettings/recoverablekeystore/storage/ApplicationKeyStorage.java
+++ b/services/core/java/com/android/server/locksettings/recoverablekeystore/storage/ApplicationKeyStorage.java
@@ -138,7 +138,7 @@
         } catch (android.security.KeyStoreException e) {
             if (e.getNumericErrorCode()
                     == android.security.KeyStoreException.ERROR_KEY_DOES_NOT_EXIST) {
-                Log.e(TAG, "Failed to get grant for KeyStore key - key not found", e);
+                Log.w(TAG, "Failed to get grant for KeyStore key - key not found");
                 throw new ServiceSpecificException(ERROR_KEY_NOT_FOUND, e.getMessage());
             }
             Log.e(TAG, "Failed to get grant for KeyStore key.", e);
diff --git a/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java b/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
index 63dc59c..37bcfbb 100644
--- a/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
+++ b/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
@@ -1291,13 +1291,18 @@
         }
 
         long uniqueRequestId = toUniqueRequestId(managerRecord.mManagerId, requestId);
-        if (managerRecord.mLastSessionCreationRequest != null) {
+        SessionCreationRequest lastRequest = managerRecord.mLastSessionCreationRequest;
+        if (lastRequest != null) {
+            Slog.i(
+                    TAG,
+                    TextUtils.formatSimple(
+                            "requestCreateSessionWithManagerLocked: Notifying failure for pending"
+                                + " session creation request - oldSession: %s, route: %s",
+                            lastRequest.mOldSession, lastRequest.mRoute));
             managerRecord.mUserRecord.mHandler.notifyRequestFailedToManager(
                     managerRecord.mManager,
-                    toOriginalRequestId(managerRecord.mLastSessionCreationRequest
-                            .mManagerRequestId),
+                    toOriginalRequestId(lastRequest.mManagerRequestId),
                     REASON_UNKNOWN_ERROR);
-            managerRecord.mLastSessionCreationRequest = null;
         }
         managerRecord.mLastSessionCreationRequest = new SessionCreationRequest(routerRecord,
                 MediaRoute2ProviderService.REQUEST_ID_NONE, uniqueRequestId,
diff --git a/services/core/java/com/android/server/media/MediaSessionService.java b/services/core/java/com/android/server/media/MediaSessionService.java
index 3a20cd9..f2242bf 100644
--- a/services/core/java/com/android/server/media/MediaSessionService.java
+++ b/services/core/java/com/android/server/media/MediaSessionService.java
@@ -2188,11 +2188,10 @@
             MediaSessionRecordImpl session = isGlobalPriorityActiveLocked() ? mGlobalPrioritySession
                     : mCurrentFullUserRecord.mPriorityStack.getDefaultVolumeSession();
 
-            boolean preferSuggestedStream = false;
-            if (isValidLocalStreamType(suggestedStream)
-                    && AudioSystem.isStreamActive(suggestedStream, 0)) {
-                preferSuggestedStream = true;
-            }
+            boolean preferSuggestedStream =
+                    isValidLocalStreamType(suggestedStream)
+                            && AudioSystem.isStreamActive(suggestedStream, 0);
+
             if (session == null || preferSuggestedStream) {
                 if (DEBUG_KEY_EVENT) {
                     Log.d(TAG, "Adjusting suggestedStream=" + suggestedStream + " by " + direction
diff --git a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
index 7c3ef19..e7bd68e 100644
--- a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
+++ b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
@@ -225,6 +225,7 @@
         mMediaRouter.rebindAsUser(to.getUserIdentifier());
         synchronized (mLock) {
             if (mProjectionGrant != null) {
+                Slog.d(TAG, "Content Recording: Stopped MediaProjection due to user switching");
                 mProjectionGrant.stop();
             }
         }
@@ -260,6 +261,8 @@
         }
 
         synchronized (mLock) {
+            Slog.d(TAG,
+                    "Content Recording: Stopped MediaProjection due to foreground service change");
             if (mProjectionGrant != null) {
                 mProjectionGrant.stop();
             }
@@ -268,6 +271,8 @@
 
     private void startProjectionLocked(final MediaProjection projection) {
         if (mProjectionGrant != null) {
+            Slog.d(TAG, "Content Recording: Stopped MediaProjection to start new "
+                    + "incoming projection");
             mProjectionGrant.stop();
         }
         if (mMediaRouteInfo != null) {
@@ -279,6 +284,8 @@
     }
 
     private void stopProjectionLocked(final MediaProjection projection) {
+        Slog.d(TAG, "Content Recording: Stopped active MediaProjection and "
+                + "dispatching stop to callbacks");
         mProjectionToken = null;
         mProjectionGrant = null;
         dispatchStop(projection);
@@ -351,6 +358,13 @@
             if (!setSessionSucceeded) {
                 // Unable to start mirroring, so tear down this projection.
                 if (mProjectionGrant != null) {
+                    String projectionType = incomingSession != null
+                            ? ContentRecordingSession.recordContentToString(
+                                    incomingSession.getContentToRecord()) : "none";
+                    Slog.w(TAG, "Content Recording: Stopped MediaProjection due to failing to set "
+                            + "ContentRecordingSession - id= "
+                            + mProjectionGrant.getVirtualDisplayId() + "type=" + projectionType);
+
                     mProjectionGrant.stop();
                 }
                 return false;
@@ -464,6 +478,9 @@
                     // The grant may now be null if setting the session failed.
                     if (mProjectionGrant != null) {
                         // Always stop the projection.
+                        Slog.w(TAG, "Content Recording: Stopped MediaProjection due to user "
+                                + "consent result of CANCEL - "
+                                + "id= " + mProjectionGrant.getVirtualDisplayId());
                         mProjectionGrant.stop();
                     }
                     break;
@@ -666,6 +683,7 @@
             try {
                 synchronized (mLock) {
                     if (mProjectionGrant != null) {
+                        Slog.d(TAG, "Content Recording: Stopping active projection");
                         mProjectionGrant.stop();
                     }
                 }
@@ -864,6 +882,10 @@
                     MEDIA_PROJECTION_TOKEN_EVENT_CREATED);
         }
 
+        int getVirtualDisplayId() {
+            return mVirtualDisplayId;
+        }
+
         @Override // Binder call
         public boolean canProjectVideo() {
             return mType == MediaProjectionManager.TYPE_MIRRORING ||
@@ -937,12 +959,11 @@
                 registerCallback(mCallback);
                 try {
                     mToken = callback.asBinder();
-                    mDeathEater = new IBinder.DeathRecipient() {
-                        @Override
-                        public void binderDied() {
-                            mCallbackDelegate.remove(callback);
-                            stop();
-                        }
+                    mDeathEater = () -> {
+                        Slog.d(TAG, "Content Recording: MediaProjection stopped by Binder death - "
+                                + "id= " + mVirtualDisplayId);
+                        mCallbackDelegate.remove(callback);
+                        stop();
                     };
                     mToken.linkToDeath(mDeathEater, 0);
                 } catch (RemoteException e) {
@@ -1012,6 +1033,9 @@
                         Binder.restoreCallingIdentity(token);
                     }
                 }
+                Slog.d(TAG, "Content Recording: handling stopping this projection token"
+                        + " createTime= " + mCreateTimeMs
+                        + " countStarts= " + mCountStarts);
                 stopProjectionLocked(this);
                 mToken.unlinkToDeath(mDeathEater, 0);
                 mToken = null;
@@ -1125,6 +1149,8 @@
                 if ((type & MediaRouter.ROUTE_TYPE_REMOTE_DISPLAY) != 0) {
                     mMediaRouteInfo = info;
                     if (mProjectionGrant != null) {
+                        Slog.d(TAG, "Content Recording: Stopped MediaProjection due to "
+                                + "route type of REMOTE_DISPLAY not selected");
                         mProjectionGrant.stop();
                     }
                 }
@@ -1296,7 +1322,7 @@
             try {
                 mCallback.onStart(mInfo);
             } catch (RemoteException e) {
-                Slog.w(TAG, "Failed to notify media projection has stopped", e);
+                Slog.w(TAG, "Failed to notify media projection has started", e);
             }
         }
     }
@@ -1370,7 +1396,8 @@
                 return "TYPE_MIRRORING";
             case MediaProjectionManager.TYPE_PRESENTATION:
                 return "TYPE_PRESENTATION";
+            default:
+                return Integer.toString(type);
         }
-        return Integer.toString(type);
     }
 }
diff --git a/services/core/java/com/android/server/net/watchlist/OWNERS b/services/core/java/com/android/server/net/watchlist/OWNERS
index a3d4b85..d0c4e55 100644
--- a/services/core/java/com/android/server/net/watchlist/OWNERS
+++ b/services/core/java/com/android/server/net/watchlist/OWNERS
@@ -1,3 +1,2 @@
-rickywai@google.com
 alanstokes@google.com
 simonjw@google.com
diff --git a/services/core/java/com/android/server/notification/Android.bp b/services/core/java/com/android/server/notification/Android.bp
new file mode 100644
index 0000000..f26a25b
--- /dev/null
+++ b/services/core/java/com/android/server/notification/Android.bp
@@ -0,0 +1,12 @@
+java_aconfig_library {
+    name: "notification_flags_lib",
+    aconfig_declarations: "notification_flags",
+}
+
+aconfig_declarations {
+    name: "notification_flags",
+    package: "com.android.server.notification",
+    srcs: [
+        "flags.aconfig",
+    ],
+}
\ No newline at end of file
diff --git a/services/core/java/com/android/server/notification/ConditionProviders.java b/services/core/java/com/android/server/notification/ConditionProviders.java
index bfc4f53..2da1a68 100644
--- a/services/core/java/com/android/server/notification/ConditionProviders.java
+++ b/services/core/java/com/android/server/notification/ConditionProviders.java
@@ -441,6 +441,58 @@
         return info == null ? null : (IConditionProvider) info.service;
     }
 
+    void resetDefaultFromConfig() {
+        synchronized (mDefaultsLock) {
+            mDefaultComponents.clear();
+            mDefaultPackages.clear();
+        }
+        loadDefaultsFromConfig();
+    }
+
+    boolean removeDefaultFromConfig(int userId) {
+        boolean removed = false;
+        String defaultDndDenied = mContext.getResources().getString(
+                R.string.config_defaultDndDeniedPackages);
+        if (defaultDndDenied != null) {
+            String[] dnds = defaultDndDenied.split(ManagedServices.ENABLED_SERVICES_SEPARATOR);
+            for (int i = 0; i < dnds.length; i++) {
+                if (TextUtils.isEmpty(dnds[i])) {
+                    continue;
+                }
+                removed |= removePackageFromApprovedLists(userId, dnds[i], "remove from config");
+            }
+        }
+        return removed;
+    }
+
+    private boolean removePackageFromApprovedLists(int userId, String pkg, String reason) {
+        boolean removed = false;
+        synchronized (mApproved) {
+            final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.get(
+                    userId);
+            if (approvedByType != null) {
+                int approvedByTypeSize = approvedByType.size();
+                for (int i = 0; i < approvedByTypeSize; i++) {
+                    final ArraySet<String> approved = approvedByType.valueAt(i);
+                    int approvedSize = approved.size();
+                    for (int j = approvedSize - 1; j >= 0; j--) {
+                        final String packageOrComponent = approved.valueAt(j);
+                        final String packageName = getPackageName(packageOrComponent);
+                        if (TextUtils.equals(pkg, packageName)) {
+                            approved.removeAt(j);
+                            removed = true;
+                            if (DEBUG) {
+                                Slog.v(TAG, "Removing " + packageOrComponent
+                                        + " from approved list; " + reason);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        return removed;
+    }
+
     private static class ConditionRecord {
         public final Uri id;
         public final ComponentName component;
diff --git a/services/core/java/com/android/server/notification/NotificationComparator.java b/services/core/java/com/android/server/notification/NotificationComparator.java
index 446c4f7..0e76dfb 100644
--- a/services/core/java/com/android/server/notification/NotificationComparator.java
+++ b/services/core/java/com/android/server/notification/NotificationComparator.java
@@ -25,7 +25,7 @@
 import android.content.IntentFilter;
 import android.telecom.TelecomManager;
 
-import com.android.internal.config.sysui.SystemUiSystemPropertiesFlags;
+import com.android.internal.os.BackgroundThread;
 import com.android.internal.util.NotificationMessagingUtil;
 
 import java.util.Comparator;
@@ -34,21 +34,23 @@
 /**
  * Sorts notifications individually into attention-relevant order.
  */
-public class NotificationComparator
-        implements Comparator<NotificationRecord> {
+class NotificationComparator implements Comparator<NotificationRecord> {
 
     private final Context mContext;
     private final NotificationMessagingUtil mMessagingUtil;
-    private final boolean mSortByInterruptiveness;
     private String mDefaultPhoneApp;
 
+    /**
+     * Lock that must be held during a sort() call that uses this {@link Comparator}, AND to make
+     * any changes to the state of this object that could affect the results of {@link #compare}.
+     */
+    public final Object mStateLock = new Object();
+
     public NotificationComparator(Context context) {
         mContext = context;
         mContext.registerReceiver(mPhoneAppBroadcastReceiver,
                 new IntentFilter(TelecomManager.ACTION_DEFAULT_DIALER_CHANGED));
-        mMessagingUtil = new NotificationMessagingUtil(mContext);
-        mSortByInterruptiveness = !SystemUiSystemPropertiesFlags.getResolver().isEnabled(
-                SystemUiSystemPropertiesFlags.NotificationFlags.NO_SORT_BY_INTERRUPTIVENESS);
+        mMessagingUtil = new NotificationMessagingUtil(mContext, mStateLock);
     }
 
     @Override
@@ -139,14 +141,6 @@
             return -1 * Integer.compare(leftPriority, rightPriority);
         }
 
-        if (mSortByInterruptiveness) {
-            final boolean leftInterruptive = left.isInterruptive();
-            final boolean rightInterruptive = right.isInterruptive();
-            if (leftInterruptive != rightInterruptive) {
-                return -1 * Boolean.compare(leftInterruptive, rightInterruptive);
-            }
-        }
-
         // then break ties by time, most recent first
         return -1 * Long.compare(left.getRankingTimeMs(), right.getRankingTimeMs());
     }
@@ -224,8 +218,13 @@
     private final BroadcastReceiver mPhoneAppBroadcastReceiver = new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
-            mDefaultPhoneApp =
-                    intent.getStringExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME);
+            BackgroundThread.getExecutor().execute(() -> {
+                synchronized (mStateLock) {
+                    mDefaultPhoneApp =
+                            intent.getStringExtra(
+                                    TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME);
+                }
+            });
         }
     };
 }
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 009e097..009cc3b
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -832,12 +832,32 @@
             allowNotificationListener(userId, cn);
         }
 
+        allowDndPackages(userId);
+
+        setDefaultAssistantForUser(userId);
+    }
+
+    @VisibleForTesting
+    void allowDndPackages(int userId) {
         ArraySet<String> defaultDnds = mConditionProviders.getDefaultPackages();
         for (int i = 0; i < defaultDnds.size(); i++) {
             allowDndPackage(userId, defaultDnds.valueAt(i));
         }
+        if (!isDNDMigrationDone(userId)) {
+            setDNDMigrationDone(userId);
+        }
+    }
 
-        setDefaultAssistantForUser(userId);
+    @VisibleForTesting
+    boolean isDNDMigrationDone(int userId) {
+        return Settings.Secure.getIntForUser(getContext().getContentResolver(),
+                Settings.Secure.DND_CONFIGS_MIGRATED, 0, userId) == 1;
+    }
+
+    @VisibleForTesting
+    void setDNDMigrationDone(int userId) {
+        Settings.Secure.putIntForUser(getContext().getContentResolver(),
+                Settings.Secure.DND_CONFIGS_MIGRATED, 1, userId);
     }
 
     protected void migrateDefaultNAS() {
@@ -1024,6 +1044,24 @@
     }
 
     @VisibleForTesting
+    void resetDefaultDndIfNecessary() {
+        boolean removed = false;
+        final List<UserInfo> activeUsers = mUm.getAliveUsers();
+        for (UserInfo userInfo : activeUsers) {
+            int userId = userInfo.getUserHandle().getIdentifier();
+            if (isDNDMigrationDone(userId)) {
+                continue;
+            }
+            removed |= mConditionProviders.removeDefaultFromConfig(userId);
+            mConditionProviders.resetDefaultFromConfig();
+            allowDndPackages(userId);
+        }
+        if (removed) {
+            handleSavePolicyFile();
+        }
+    }
+
+    @VisibleForTesting
     protected void loadPolicyFile() {
         if (DBG) Slog.d(TAG, "loadPolicyFile");
         synchronized (mPolicyFile) {
@@ -1031,6 +1069,13 @@
             try {
                 infile = mPolicyFile.openRead();
                 readPolicyXml(infile, false /*forRestore*/, UserHandle.USER_ALL);
+
+                // We re-load the default dnd packages to allow the newly added and denined.
+                final boolean isWatch = mPackageManagerClient.hasSystemFeature(
+                        PackageManager.FEATURE_WATCH);
+                if (isWatch) {
+                    resetDefaultDndIfNecessary();
+                }
             } catch (FileNotFoundException e) {
                 // No data yet
                 // Load default managed services approvals
@@ -1194,7 +1239,9 @@
                 mNotificationRecordLogger.log(
                         NotificationRecordLogger.NotificationEvent.fromAction(actionIndex,
                                 generatedByAssistant, action.isContextual()), r);
-                EventLogTags.writeNotificationActionClicked(key, actionIndex,
+                EventLogTags.writeNotificationActionClicked(key,
+                        action.actionIntent.getTarget().toString(),
+                        action.actionIntent.getIntent().toString(), actionIndex,
                         r.getLifespanMs(now), r.getFreshnessMs(now), r.getExposureMs(now),
                         nv.rank, nv.count);
                 nv.recycle();
diff --git a/services/core/java/com/android/server/notification/NotificationRecord.java b/services/core/java/com/android/server/notification/NotificationRecord.java
index b2d3fca..100c638 100644
--- a/services/core/java/com/android/server/notification/NotificationRecord.java
+++ b/services/core/java/com/android/server/notification/NotificationRecord.java
@@ -25,8 +25,6 @@
 import static android.service.notification.NotificationListenerService.Ranking.USER_SENTIMENT_POSITIVE;
 
 import android.annotation.Nullable;
-import android.app.ActivityManager;
-import android.app.IActivityManager;
 import android.app.KeyguardManager;
 import android.app.Notification;
 import android.app.NotificationChannel;
@@ -48,6 +46,7 @@
 import android.os.Bundle;
 import android.os.IBinder;
 import android.os.PowerManager;
+import android.os.Trace;
 import android.os.UserHandle;
 import android.os.VibrationEffect;
 import android.provider.Settings;
@@ -98,8 +97,7 @@
     // the period after which a notification is updated where it can make sound
     private static final int MAX_SOUND_DELAY_MS = 2000;
     private final StatusBarNotification sbn;
-    IActivityManager mAm;
-    UriGrantsManagerInternal mUgmInternal;
+    private final UriGrantsManagerInternal mUgmInternal;
     final int mTargetSdkVersion;
     final int mOriginalFlags;
     private final Context mContext;
@@ -223,7 +221,6 @@
         this.sbn = sbn;
         mTargetSdkVersion = LocalServices.getService(PackageManagerInternal.class)
                 .getPackageTargetSdkVersion(sbn.getPackageName());
-        mAm = ActivityManager.getService();
         mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
         mOriginalFlags = sbn.getNotification().flags;
         mRankingTimeMs = calculateRankingTimeMs(0L);
@@ -1387,18 +1384,27 @@
      * Collect all {@link Uri} that should have permission granted to whoever
      * will be rendering it.
      */
-    protected void calculateGrantableUris() {
-        final Notification notification = getNotification();
-        notification.visitUris((uri) -> {
-            visitGrantableUri(uri, false, false);
-        });
+    private void calculateGrantableUris() {
+        Trace.beginSection("NotificationRecord.calculateGrantableUris");
+        try {
+            // We can't grant URI permissions from system.
+            final int sourceUid = getSbn().getUid();
+            if (sourceUid == android.os.Process.SYSTEM_UID) return;
 
-        if (notification.getChannelId() != null) {
-            NotificationChannel channel = getChannel();
-            if (channel != null) {
-                visitGrantableUri(channel.getSound(), (channel.getUserLockedFields()
-                        & NotificationChannel.USER_LOCKED_SOUND) != 0, true);
+            final Notification notification = getNotification();
+            notification.visitUris((uri) -> {
+                visitGrantableUri(uri, false, false);
+            });
+
+            if (notification.getChannelId() != null) {
+                NotificationChannel channel = getChannel();
+                if (channel != null) {
+                    visitGrantableUri(channel.getSound(), (channel.getUserLockedFields()
+                            & NotificationChannel.USER_LOCKED_SOUND) != 0, true);
+                }
             }
+        } finally {
+            Trace.endSection();
         }
     }
 
@@ -1413,13 +1419,14 @@
     private void visitGrantableUri(Uri uri, boolean userOverriddenUri, boolean isSound) {
         if (uri == null || !ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) return;
 
-        // We can't grant Uri permissions from system
-        final int sourceUid = getSbn().getUid();
-        if (sourceUid == android.os.Process.SYSTEM_UID) return;
+        if (mGrantableUris != null && mGrantableUris.contains(uri)) {
+            return; // already verified this URI
+        }
 
+        final int sourceUid = getSbn().getUid();
         final long ident = Binder.clearCallingIdentity();
         try {
-            // This will throw SecurityException if caller can't grant
+            // This will throw a SecurityException if the caller can't grant.
             mUgmInternal.checkGrantUriPermission(sourceUid, null,
                     ContentProvider.getUriWithoutUserId(uri),
                     Intent.FLAG_GRANT_READ_URI_PERMISSION,
diff --git a/services/core/java/com/android/server/notification/PreferencesHelper.java b/services/core/java/com/android/server/notification/PreferencesHelper.java
index 1bb1092..3f799dc 100644
--- a/services/core/java/com/android/server/notification/PreferencesHelper.java
+++ b/services/core/java/com/android/server/notification/PreferencesHelper.java
@@ -2608,7 +2608,12 @@
                             for (NotificationChannel channel : r.channels.values()) {
                                 if (!channel.isSoundRestored()) {
                                     Uri uri = channel.getSound();
-                                    Uri restoredUri = channel.restoreSoundUri(mContext, uri, true);
+                                    Uri restoredUri =
+                                            channel.restoreSoundUri(
+                                                    mContext,
+                                                    uri,
+                                                    true,
+                                                    channel.getAudioAttributes().getUsage());
                                     if (Settings.System.DEFAULT_NOTIFICATION_URI.equals(
                                             restoredUri)) {
                                         Log.w(TAG,
diff --git a/services/core/java/com/android/server/notification/RankingHelper.java b/services/core/java/com/android/server/notification/RankingHelper.java
index b4347e1..773d10b 100644
--- a/services/core/java/com/android/server/notification/RankingHelper.java
+++ b/services/core/java/com/android/server/notification/RankingHelper.java
@@ -103,8 +103,11 @@
             notificationList.get(i).setGlobalSortKey(null);
         }
 
-        // rank each record individually
-        Collections.sort(notificationList, mPreliminaryComparator);
+        // Rank each record individually.
+        // Lock comparator state for consistent compare() results.
+        synchronized (mPreliminaryComparator.mStateLock) {
+            notificationList.sort(mPreliminaryComparator);
+        }
 
         synchronized (mProxyByGroupTmp) {
             // record individual ranking result and nominate proxies for each group
diff --git a/services/core/java/com/android/server/notification/ZenModeFiltering.java b/services/core/java/com/android/server/notification/ZenModeFiltering.java
index 5b7b0c1..f56a67c 100644
--- a/services/core/java/com/android/server/notification/ZenModeFiltering.java
+++ b/services/core/java/com/android/server/notification/ZenModeFiltering.java
@@ -55,7 +55,7 @@
 
     public ZenModeFiltering(Context context) {
         mContext = context;
-        mMessagingUtil = new NotificationMessagingUtil(mContext);
+        mMessagingUtil = new NotificationMessagingUtil(mContext, null);
     }
 
     public ZenModeFiltering(Context context, NotificationMessagingUtil messagingUtil) {
diff --git a/services/core/java/com/android/server/notification/flags.aconfig b/services/core/java/com/android/server/notification/flags.aconfig
new file mode 100644
index 0000000..c0bc6d1
--- /dev/null
+++ b/services/core/java/com/android/server/notification/flags.aconfig
@@ -0,0 +1,8 @@
+package: "com.android.server.notification"
+
+flag {
+  name: "expire_bitmaps"
+  namespace: "systemui"
+  description: "This flag controls removing expired notification bitmaps"
+  bug: "290381858"
+}
\ No newline at end of file
diff --git a/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java b/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
index 3ba307b..1134714 100644
--- a/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
+++ b/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
@@ -307,7 +307,8 @@
                 && mode != BugreportParams.BUGREPORT_MODE_REMOTE
                 && mode != BugreportParams.BUGREPORT_MODE_WEAR
                 && mode != BugreportParams.BUGREPORT_MODE_TELEPHONY
-                && mode != BugreportParams.BUGREPORT_MODE_WIFI) {
+                && mode != BugreportParams.BUGREPORT_MODE_WIFI
+                && mode != BugreportParams.BUGREPORT_MODE_ONBOARDING) {
             Slog.w(TAG, "Unknown bugreport mode: " + mode);
             throw new IllegalArgumentException("Unknown bugreport mode: " + mode);
         }
diff --git a/services/core/java/com/android/server/pm/Android.bp b/services/core/java/com/android/server/pm/Android.bp
new file mode 100644
index 0000000..89c0124
--- /dev/null
+++ b/services/core/java/com/android/server/pm/Android.bp
@@ -0,0 +1,12 @@
+aconfig_declarations {
+    name: "pm_flags",
+    package: "com.android.server.pm",
+    srcs: [
+        "*.aconfig",
+    ],
+}
+
+java_aconfig_library {
+    name: "pm_flags_lib",
+    aconfig_declarations: "pm_flags",
+}
diff --git a/services/core/java/com/android/server/pm/Computer.java b/services/core/java/com/android/server/pm/Computer.java
index 6e75605..f987629 100644
--- a/services/core/java/com/android/server/pm/Computer.java
+++ b/services/core/java/com/android/server/pm/Computer.java
@@ -487,6 +487,8 @@
 
     boolean isPackageSuspendedForUser(@NonNull String packageName, @UserIdInt int userId);
 
+    boolean isPackageQuarantinedForUser(@NonNull String packageName, @UserIdInt int userId);
+
     boolean isSuspendingAnyPackages(@NonNull String suspendingPackage, @UserIdInt int userId);
 
     @NonNull
diff --git a/services/core/java/com/android/server/pm/ComputerEngine.java b/services/core/java/com/android/server/pm/ComputerEngine.java
index 1b52725..1cfc7d7 100644
--- a/services/core/java/com/android/server/pm/ComputerEngine.java
+++ b/services/core/java/com/android/server/pm/ComputerEngine.java
@@ -24,6 +24,7 @@
 import static android.content.Intent.ACTION_MAIN;
 import static android.content.Intent.CATEGORY_DEFAULT;
 import static android.content.Intent.CATEGORY_HOME;
+import static android.content.pm.ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
 import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
 import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
@@ -521,6 +522,7 @@
                 comp != null || pkgName != null /*onlyExposedExplicitly*/,
                 isImplicitImageCaptureIntentAndNotSetByDpc(intent, userId, resolvedType,
                         flags));
+
         List<ResolveInfo> list = Collections.emptyList();
         boolean skipPostResolution = false;
         if (comp != null) {
@@ -642,6 +644,12 @@
         final String instantAppPkgName = getInstantAppPackageName(callingUid);
         flags = updateFlagsForResolve(flags, userId, callingUid, includeInstantApps,
                 false /* isImplicitImageCaptureIntentAndNotSetByDpc */);
+
+        // Only if the query is coming from the system process,
+        // it should be allowed to match quarantined components
+        if (callingUid != Process.SYSTEM_UID) {
+            flags |= PackageManager.FILTER_OUT_QUARANTINED_COMPONENTS;
+        }
         Intent originalIntent = null;
         ComponentName comp = intent.getComponent();
         if (comp == null) {
@@ -1514,11 +1522,17 @@
             ai.uid = UserHandle.getUid(userId, ps.getAppId());
             ai.primaryCpuAbi = ps.getPrimaryCpuAbiLegacy();
             ai.secondaryCpuAbi = ps.getSecondaryCpuAbiLegacy();
+            ai.volumeUuid = ps.getVolumeUuid();
+            ai.storageUuid = StorageManager.convert(ai.volumeUuid);
+            if (ps.isDefaultToDeviceProtectedStorage()) {
+                ai.privateFlags |= PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
+            }
             ai.setVersionCode(ps.getVersionCode());
             ai.flags = ps.getFlags();
             ai.privateFlags = ps.getPrivateFlags();
             pi.applicationInfo = PackageInfoUtils.generateDelegateApplicationInfo(
                     ai, flags, state, userId);
+            pi.signingInfo = ps.getSigningInfo();
 
             if (DEBUG_PACKAGE_INFO) {
                 Log.v(TAG, "ps.pkg is n/a for ["
@@ -4024,6 +4038,9 @@
         flags = updateFlagsForComponent(flags, userId);
         enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */,
                 false /* checkShell */, "get provider info");
+        if (callingUid != Process.SYSTEM_UID) {
+            flags |= PackageManager.FILTER_OUT_QUARANTINED_COMPONENTS;
+        }
         ParsedProvider p = mComponentResolver.getProvider(component);
         if (DEBUG_PACKAGE_INFO) Log.v(
                 TAG, "getProviderInfo " + component + ": " + p);
@@ -4653,6 +4670,9 @@
             int callingUid) {
         if (!mUserManager.exists(userId)) return null;
         flags = updateFlagsForComponent(flags, userId);
+        if (callingUid != Process.SYSTEM_UID) {
+            flags |= PackageManager.FILTER_OUT_QUARANTINED_COMPONENTS;
+        }
         final ProviderInfo providerInfo = mComponentResolver.queryProvider(this, name, flags,
                 userId);
         boolean checkedGrants = false;
@@ -4765,6 +4785,13 @@
                 false /* checkShell */, "queryContentProviders");
         if (!mUserManager.exists(userId)) return ParceledListSlice.emptyList();
         flags = updateFlagsForComponent(flags, userId);
+
+        // Only if the service query is coming from the system process,
+        // it should be allowed to match quarantined components
+        if (callingUid != Process.SYSTEM_UID) {
+            flags |= PackageManager.FILTER_OUT_QUARANTINED_COMPONENTS;
+        }
+
         ArrayList<ProviderInfo> finalList = null;
         final List<ProviderInfo> matchList = mComponentResolver.queryProviders(this, processName,
                 metaDataKey, uid, flags, userId);
@@ -4898,8 +4925,8 @@
         }
     }
 
-    @Override
-    public boolean isPackageSuspendedForUser(@NonNull String packageName, int userId) {
+    private PackageUserStateInternal getUserStageOrDefaultForUser(@NonNull String packageName,
+            int userId) {
         final int callingUid = Binder.getCallingUid();
         enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */,
                 false /* checkShell */, "isPackageSuspendedForUser for user " + userId);
@@ -4907,7 +4934,17 @@
         if (ps == null || shouldFilterApplicationIncludingUninstalled(ps, callingUid, userId)) {
             throw new IllegalArgumentException("Unknown target package: " + packageName);
         }
-        return ps.getUserStateOrDefault(userId).isSuspended();
+        return ps.getUserStateOrDefault(userId);
+    }
+
+    @Override
+    public boolean isPackageSuspendedForUser(@NonNull String packageName, int userId) {
+        return getUserStageOrDefaultForUser(packageName, userId).isSuspended();
+    }
+
+    @Override
+    public boolean isPackageQuarantinedForUser(@NonNull String packageName, @UserIdInt int userId) {
+        return getUserStageOrDefaultForUser(packageName, userId).isQuarantined();
     }
 
     @Override
diff --git a/services/core/java/com/android/server/pm/DeletePackageHelper.java b/services/core/java/com/android/server/pm/DeletePackageHelper.java
index a5a4594..b5ec136 100644
--- a/services/core/java/com/android/server/pm/DeletePackageHelper.java
+++ b/services/core/java/com/android/server/pm/DeletePackageHelper.java
@@ -470,7 +470,6 @@
                         // We need to set it back to 'installed' so the uninstall
                         // broadcasts will be sent correctly.
                         if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
-                        ps.setPkg(null);
                         ps.setInstalled(true, userId);
                         mPm.mSettings.writeKernelMappingLPr(ps);
                         clearPackageStateAndReturn = false;
diff --git a/services/core/java/com/android/server/pm/DexOptHelper.java b/services/core/java/com/android/server/pm/DexOptHelper.java
index 39cd888..8bd2982 100644
--- a/services/core/java/com/android/server/pm/DexOptHelper.java
+++ b/services/core/java/com/android/server/pm/DexOptHelper.java
@@ -1050,7 +1050,7 @@
                 context.unregisterReceiver(this);
                 artManager.scheduleBackgroundDexoptJob();
             }
-        }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
+        }, new IntentFilter(Intent.ACTION_LOCKED_BOOT_COMPLETED));
     }
 
     /**
diff --git a/services/core/java/com/android/server/pm/IPackageManagerBase.java b/services/core/java/com/android/server/pm/IPackageManagerBase.java
index fd47846..76203ac 100644
--- a/services/core/java/com/android/server/pm/IPackageManagerBase.java
+++ b/services/core/java/com/android/server/pm/IPackageManagerBase.java
@@ -955,6 +955,13 @@
 
     @Override
     @Deprecated
+    public final boolean isPackageQuarantinedForUser(@NonNull String packageName,
+            @UserIdInt int userId) {
+        return snapshot().isPackageQuarantinedForUser(packageName, userId);
+    }
+
+    @Override
+    @Deprecated
     public final boolean isSafeMode() {
         // allow instant applications
         return mService.getSafeMode();
diff --git a/services/core/java/com/android/server/pm/InstallPackageHelper.java b/services/core/java/com/android/server/pm/InstallPackageHelper.java
index 7e1560a..3e18387 100644
--- a/services/core/java/com/android/server/pm/InstallPackageHelper.java
+++ b/services/core/java/com/android/server/pm/InstallPackageHelper.java
@@ -2417,7 +2417,8 @@
             final InstallRequest installRequest = reconciledPkg.mInstallRequest;
             final boolean instantApp = ((installRequest.getScanFlags() & SCAN_AS_INSTANT_APP) != 0);
             final boolean isApex = ((installRequest.getScanFlags() & SCAN_AS_APEX) != 0);
-            final AndroidPackage pkg = installRequest.getScannedPackageSetting().getPkg();
+            final PackageSetting ps = installRequest.getScannedPackageSetting();
+            final AndroidPackage pkg = ps.getPkg();
             final String packageName = pkg.getPackageName();
             final String codePath = pkg.getPath();
             final boolean onIncremental = mIncrementalManager != null
@@ -2517,7 +2518,7 @@
                 // Compile the layout resources.
                 if (SystemProperties.getBoolean(PRECOMPILE_LAYOUTS, false)) {
                     Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "compileLayouts");
-                    mViewCompiler.compileLayouts(pkg);
+                    mViewCompiler.compileLayouts(ps, pkg.getBaseApkPath());
                     Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
                 }
 
@@ -3545,6 +3546,7 @@
                         + " no longer exists; its data will be wiped");
                 mInjector.getHandler().post(
                         () -> mRemovePackageHelper.removePackageData(ps, userIds, null, 0, false));
+                expectingBetter.put(ps.getPackageName(), ps.getPath());
             } else {
                 // we still have a disabled system package, but, it still might have
                 // been removed. check the code path still exists and check there's
diff --git a/services/core/java/com/android/server/pm/LauncherAppsService.java b/services/core/java/com/android/server/pm/LauncherAppsService.java
index 12f3aa9..11660a59 100644
--- a/services/core/java/com/android/server/pm/LauncherAppsService.java
+++ b/services/core/java/com/android/server/pm/LauncherAppsService.java
@@ -86,7 +86,10 @@
 import android.os.Process;
 import android.os.RemoteCallbackList;
 import android.os.RemoteException;
+import android.os.ResultReceiver;
 import android.os.ServiceManager;
+import android.os.ShellCallback;
+import android.os.ShellCommand;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.provider.Settings;
@@ -127,6 +130,9 @@
 import java.util.Objects;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
+import java.util.function.BiConsumer;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
 
 /**
  * Service that manages requests and callbacks for launchers that support
@@ -215,7 +221,8 @@
 
         final LauncherAppsServiceInternal mInternal;
 
-        private RemoteCallbackList<IDumpCallback> mDumpCallbacks = new RemoteCallbackList<>();
+        @NonNull
+        private final RemoteCallbackList<IDumpCallback> mDumpCallbacks = new RemoteCallbackList<>();
 
         public LauncherAppsImpl(Context context) {
             mContext = context;
@@ -372,7 +379,12 @@
                 filter.addDataScheme("package");
                 mContext.registerReceiverAsUser(mPackageRemovedListener, UserHandle.ALL, filter,
                         /* broadcastPermission= */ null, mCallbackHandler);
-                mPackageMonitor.register(mContext, UserHandle.ALL, mCallbackHandler);
+                final long identity = Binder.clearCallingIdentity();
+                try {
+                    mPackageMonitor.register(mContext, UserHandle.ALL, mCallbackHandler);
+                } finally {
+                    Binder.restoreCallingIdentity(identity);
+                }
                 mIsWatchingPackageBroadcasts = true;
             }
         }
@@ -1462,46 +1474,124 @@
                     getActivityOptionsForLauncher(opts), user.getIdentifier());
         }
 
+        @Override
+        public void onShellCommand(FileDescriptor in, @NonNull FileDescriptor out,
+                @NonNull FileDescriptor err, @Nullable String[] args, ShellCallback cb,
+                @Nullable ResultReceiver receiver) {
+            final int callingUid = injectBinderCallingUid();
+            if (!(callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID)) {
+                throw new SecurityException("Caller must be shell");
+            }
+
+            final long token = injectClearCallingIdentity();
+            try {
+                int status = (new LauncherAppsShellCommand())
+                        .exec(this, in, out, err, args, cb, receiver);
+                if (receiver != null) {
+                    receiver.send(status, null);
+                }
+            } finally {
+                injectRestoreCallingIdentity(token);
+            }
+        }
+
+        /** Handles Shell commands for LauncherAppsService */
+        private class LauncherAppsShellCommand extends ShellCommand {
+            @Override
+            public int onCommand(@Nullable String cmd) {
+                if ("dump-view-hierarchies".equals(cmd)) {
+                    dumpViewCaptureDataToShell();
+                    return 0;
+                } else {
+                    return handleDefaultCommands(cmd);
+                }
+            }
+
+            private void dumpViewCaptureDataToShell() {
+                try (ZipOutputStream zipOs = new ZipOutputStream(getRawOutputStream())) {
+                    forEachViewCaptureWindow((fileName, is) -> {
+                        try {
+                            zipOs.putNextEntry(new ZipEntry("FS" + fileName));
+                            is.transferTo(zipOs);
+                            zipOs.closeEntry();
+                        } catch (IOException e) {
+                            getErrPrintWriter().write("Failed to output " + fileName
+                                    + " data to shell: " + e.getMessage());
+                        }
+                    });
+                } catch (IOException e) {
+                    getErrPrintWriter().write("Failed to create or close zip output stream: "
+                            + e.getMessage());
+                }
+            }
+
+            @Override
+            public void onHelp() {
+                final PrintWriter pw = getOutPrintWriter();
+                pw.println("Usage: cmd launcherapps COMMAND [options ...]");
+                pw.println();
+                pw.println("cmd launcherapps dump-view-hierarchies");
+                pw.println("    Output captured view hierarchies. Files will be generated in ");
+                pw.println("    `"  + WM_TRACE_DIR + "`. After pulling the data to your device,");
+                pw.println("     you can upload / visualize it at `go/winscope`.");
+                pw.println();
+            }
+        }
 
         /**
          * Using a pipe, outputs view capture data to the wmtrace dir
          */
-        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw,
+                @Nullable String[] args) {
             super.dump(fd, pw, args);
 
             // Before the wmtrace directory is picked up by dumpstate service, some processes need
             // to write their data to that location. They can do that via these dumpCallbacks.
-            int i = mDumpCallbacks.beginBroadcast();
-            while (i > 0) {
-                i--;
-                dumpDataToWmTrace((String) mDumpCallbacks.getBroadcastCookie(i) + "_" + i,
-                        mDumpCallbacks.getBroadcastItem(i));
+            forEachViewCaptureWindow(this::dumpViewCaptureDataToWmTrace);
+        }
+
+        private void dumpViewCaptureDataToWmTrace(@NonNull String fileName,
+                @NonNull InputStream is) {
+            Path outPath = Paths.get(fileName);
+            try {
+                Files.copy(is, outPath, StandardCopyOption.REPLACE_EXISTING);
+                Files.setPosixFilePermissions(outPath, WM_TRACE_FILE_PERMISSIONS);
+            } catch (IOException e) {
+                Log.d(TAG, "failed to write data to " + fileName + " in wmtrace dir", e);
+            }
+        }
+
+        /**
+         * IDumpCallback.onDump alerts the in-process ViewCapture instance to start sending data
+         * to LauncherAppsService via the pipe's input provided. This data (as well as an output
+         * file name) is provided to the consumer via an InputStream to output where it wants (for
+         * example, the winscope trace directory or the shell's stdout).
+         */
+        private void forEachViewCaptureWindow(
+                @NonNull BiConsumer<String, InputStream> outputtingConsumer) {
+            for (int i = mDumpCallbacks.beginBroadcast() - 1; i >= 0; i--) {
+                String packageName = (String) mDumpCallbacks.getBroadcastCookie(i);
+                String fileName = WM_TRACE_DIR + packageName + "_" + i + VC_FILE_SUFFIX;
+
+                try {
+                    // Order is important here. OnDump needs to be called before the BiConsumer
+                    // accepts & starts blocking on reading the input stream.
+                    ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
+                    mDumpCallbacks.getBroadcastItem(i).onDump(pipe[1]);
+
+                    InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(pipe[0]);
+                    outputtingConsumer.accept(fileName, is);
+                    is.close();
+                } catch (Exception e) {
+                    Log.d(TAG, "failed to pipe view capture data", e);
+                }
             }
             mDumpCallbacks.finishBroadcast();
         }
 
-        private void dumpDataToWmTrace(String name, IDumpCallback cb) {
-            ParcelFileDescriptor[] pipe;
-            try {
-                pipe = ParcelFileDescriptor.createPipe();
-                cb.onDump(pipe[1]);
-            } catch (IOException | RemoteException e) {
-                Log.d(TAG, "failed to pipe view capture data", e);
-                return;
-            }
-
-            Path path = Paths.get(WM_TRACE_DIR + Paths.get(name + VC_FILE_SUFFIX).getFileName());
-            try (InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(pipe[0])) {
-                Files.copy(is, path, StandardCopyOption.REPLACE_EXISTING);
-                Files.setPosixFilePermissions(path, WM_TRACE_FILE_PERMISSIONS);
-            } catch (IOException e) {
-                Log.d(TAG, "failed to write data to file in wmtrace dir", e);
-            }
-        }
-
         @RequiresPermission(READ_FRAME_BUFFER)
         @Override
-        public void registerDumpCallback(IDumpCallback cb) {
+        public void registerDumpCallback(@NonNull IDumpCallback cb) {
             int status = checkCallingOrSelfPermissionForPreflight(mContext, READ_FRAME_BUFFER);
             if (PERMISSION_GRANTED == status) {
                 String name = mContext.getPackageManager().getNameForUid(Binder.getCallingUid());
@@ -1513,7 +1603,7 @@
 
         @RequiresPermission(READ_FRAME_BUFFER)
         @Override
-        public void unRegisterDumpCallback(IDumpCallback cb) {
+        public void unRegisterDumpCallback(@NonNull IDumpCallback cb) {
             int status = checkCallingOrSelfPermissionForPreflight(mContext, READ_FRAME_BUFFER);
             if (PERMISSION_GRANTED == status) {
                 mDumpCallbacks.unregister(cb);
diff --git a/services/core/java/com/android/server/pm/MovePackageHelper.java b/services/core/java/com/android/server/pm/MovePackageHelper.java
index 1a5591c..01c2734 100644
--- a/services/core/java/com/android/server/pm/MovePackageHelper.java
+++ b/services/core/java/com/android/server/pm/MovePackageHelper.java
@@ -49,8 +49,8 @@
 import android.os.RemoteException;
 import android.os.UserHandle;
 import android.os.storage.StorageManager;
+import android.os.storage.StorageManagerInternal;
 import android.os.storage.VolumeInfo;
-import android.text.TextUtils;
 import android.util.MathUtils;
 import android.util.Slog;
 import android.util.SparseIntArray;
@@ -64,6 +64,7 @@
 import com.android.server.pm.pkg.PackageStateUtils;
 
 import java.io.File;
+import java.util.ArrayList;
 import java.util.Objects;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
@@ -220,9 +221,7 @@
         }
 
         try {
-            for (int index = 0; index < installedUserIds.length; index++) {
-                prepareUserDataForVolumeIfRequired(volumeUuid, installedUserIds[index], storage);
-            }
+            prepareUserStorageForMove(currentVolumeUuid, volumeUuid, installedUserIds);
         } catch (RuntimeException e) {
             freezer.close();
             throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
@@ -376,27 +375,20 @@
         return true;
     }
 
-    private void prepareUserDataForVolumeIfRequired(String volumeUuid, int userId,
-            StorageManager storageManager) {
-        if (TextUtils.isEmpty(volumeUuid)
-                || doesDataDirectoryExistForUser(volumeUuid, userId)) {
-            return;
-        }
+    private void prepareUserStorageForMove(String fromVolumeUuid, String toVolumeUuid,
+            int[] userIds) {
         if (DEBUG_INSTALL) {
-            Slog.d(TAG, "Preparing user directories for user u" + userId + " for UUID "
-                    + volumeUuid);
+            Slog.d(TAG, "Preparing user directories before moving app, from UUID " + fromVolumeUuid
+                    + " to UUID " + toVolumeUuid);
         }
-        final UserInfo user = mPm.mUserManager.getUserInfo(userId);
-        if (user == null) return;
-        // This call is same as StorageEventHelper#loadPrivatePackagesInner which prepares
-        // the storage before reconciling apps
-        storageManager.prepareUserStorage(volumeUuid, user.id, user.serialNumber,
-                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
-    }
-
-    private boolean doesDataDirectoryExistForUser(String uuid, int userId) {
-        final File userDirectoryFile = Environment.getDataUserCeDirectory(uuid, userId);
-        return userDirectoryFile != null && userDirectoryFile.exists();
+        final StorageManagerInternal smInternal =
+                mPm.mInjector.getLocalService(StorageManagerInternal.class);
+        final ArrayList<UserInfo> users = new ArrayList<>();
+        for (int userId : userIds) {
+            final UserInfo user = mPm.mUserManager.getUserInfo(userId);
+            users.add(user);
+        }
+        smInternal.prepareUserStorageForMove(fromVolumeUuid, toVolumeUuid, users);
     }
 
     public static class MoveCallbacks extends Handler {
diff --git a/services/core/java/com/android/server/pm/PackageInstallerSession.java b/services/core/java/com/android/server/pm/PackageInstallerSession.java
index 303f321..6270655 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerSession.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerSession.java
@@ -68,6 +68,7 @@
 import android.app.admin.DevicePolicyManagerInternal;
 import android.app.compat.CompatChanges;
 import android.compat.annotation.ChangeId;
+import android.compat.annotation.Disabled;
 import android.compat.annotation.EnabledSince;
 import android.content.ComponentName;
 import android.content.Context;
@@ -312,6 +313,19 @@
     private static final long SILENT_INSTALL_ALLOWED = 265131695L;
 
     /**
+     * The system supports pre-approval and update ownership features from
+     * {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE API 34}. The change id is used to make sure
+     * the system includes the fix of pre-approval with update ownership case. When checking the
+     * change id, if it is disabled, it means the build includes the fix. The more detail is on
+     * b/293644536.
+     * See {@link PackageInstaller.SessionParams#setRequestUpdateOwnership(boolean)} and
+     * {@link #requestUserPreapproval(PreapprovalDetails, IntentSender)} for more details.
+     */
+    @Disabled
+    @ChangeId
+    private static final long PRE_APPROVAL_WITH_UPDATE_OWNERSHIP_FIX = 293644536L;
+
+    /**
      * The default value of {@link #mValidatedTargetSdk} is {@link Integer#MAX_VALUE}. If {@link
      * #mValidatedTargetSdk} is compared with {@link Build.VERSION_CODES#S} before getting the
      * target sdk version from a validated apk in {@link #validateApkInstallLocked()}, the compared
@@ -927,16 +941,27 @@
             if (mPermissionsManuallyAccepted) {
                 return USER_ACTION_NOT_NEEDED;
             }
-            packageName = mPackageName;
+            // For pre-pappvoal case, the mPackageName would be null.
+            if (mPackageName != null) {
+                packageName = mPackageName;
+            } else if (mPreapprovalRequested.get() && mPreapprovalDetails != null) {
+                packageName = mPreapprovalDetails.getPackageName();
+            } else {
+                packageName = null;
+            }
             hasDeviceAdminReceiver = mHasDeviceAdminReceiver;
         }
 
-        final boolean forcePermissionPrompt =
+        // For the below cases, force user action prompt
+        // 1. installFlags includes INSTALL_FORCE_PERMISSION_PROMPT
+        // 2. params.requireUserAction is USER_ACTION_REQUIRED
+        final boolean forceUserActionPrompt =
                 (params.installFlags & PackageManager.INSTALL_FORCE_PERMISSION_PROMPT) != 0
                         || params.requireUserAction == SessionParams.USER_ACTION_REQUIRED;
-        if (forcePermissionPrompt) {
-            return USER_ACTION_REQUIRED;
-        }
+        final int userActionNotTypicallyNeededResponse = forceUserActionPrompt
+                ? USER_ACTION_REQUIRED
+                : USER_ACTION_NOT_NEEDED;
+
         // It is safe to access mInstallerUid and mInstallSource without lock
         // because they are immutable after sealing.
         final Computer snapshot = mPm.snapshotComputer();
@@ -990,7 +1015,7 @@
                 || isInstallerDeviceOwnerOrAffiliatedProfileOwner();
 
         if (noUserActionNecessary) {
-            return USER_ACTION_NOT_NEEDED;
+            return userActionNotTypicallyNeededResponse;
         }
 
         if (isUpdateOwnershipEnforcementEnabled
@@ -1003,7 +1028,7 @@
         }
 
         if (isPermissionGranted) {
-            return USER_ACTION_NOT_NEEDED;
+            return userActionNotTypicallyNeededResponse;
         }
 
         if (snapshot.isInstallDisabledForPackage(getInstallerPackageName(), mInstallerUid,
diff --git a/services/core/java/com/android/server/pm/PackageManagerInternalBase.java b/services/core/java/com/android/server/pm/PackageManagerInternalBase.java
index 4e75210..651845e 100644
--- a/services/core/java/com/android/server/pm/PackageManagerInternalBase.java
+++ b/services/core/java/com/android/server/pm/PackageManagerInternalBase.java
@@ -745,6 +745,19 @@
         mService.setPackageStoppedState(snapshot(), packageName, stopped, userId);
     }
 
+    @Override
+    public void notifyComponentUsed(@NonNull String packageName, @UserIdInt int userId,
+            @NonNull String recentCallingPackage, @NonNull String debugInfo) {
+        mService.notifyComponentUsed(snapshot(), packageName, userId,
+                recentCallingPackage, debugInfo);
+    }
+
+    @Override
+    public boolean isPackageQuarantined(@NonNull String packageName,
+            @UserIdInt int userId) {
+        return snapshot().isPackageQuarantinedForUser(packageName, userId);
+    }
+
     @NonNull
     @Override
     @Deprecated
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 770ed8b..6c0aeec 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -4582,6 +4582,24 @@
         }
     }
 
+    void notifyComponentUsed(@NonNull Computer snapshot, @NonNull String packageName,
+            @UserIdInt int userId, @NonNull String recentCallingPackage,
+            @NonNull String debugInfo) {
+        synchronized (mLock) {
+            final PackageUserStateInternal userState = mSettings.getPackageLPr(
+                    packageName).getUserStateOrDefault(userId);
+            if (userState.isQuarantined()) {
+                Slog.i(TAG,
+                        "Component is quarantined+suspended but being used: "
+                                + packageName + " by " + recentCallingPackage + ", debugInfo: "
+                                + debugInfo);
+            }
+        }
+        PackageManagerService.this
+                .setPackageStoppedState(snapshot, packageName, false /* stopped */,
+                        userId);
+    }
+
     public class IPackageManagerImpl extends IPackageManagerBase {
 
         public IPackageManagerImpl() {
@@ -6113,14 +6131,16 @@
         @Override
         public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
                 PersistableBundle appExtras, PersistableBundle launcherExtras,
-                SuspendDialogInfo dialogInfo, String callingPackage, int userId) {
+                SuspendDialogInfo dialogInfo, int flags, String callingPackage, int userId) {
             final int callingUid = Binder.getCallingUid();
             final Computer snapshot = snapshotComputer();
             enforceCanSetPackagesSuspendedAsUser(snapshot, callingPackage, callingUid, userId,
                     "setPackagesSuspendedAsUser");
+            boolean quarantined = ((flags & PackageManager.FLAG_SUSPEND_QUARANTINED) != 0)
+                    && Flags.quarantinedEnabled();
             return mSuspendPackageHelper.setPackagesSuspended(snapshot, packageNames, suspended,
                     appExtras, launcherExtras, dialogInfo, callingPackage, userId, callingUid,
-                    false /* forQuietMode */);
+                    false /* forQuietMode */, quarantined);
         }
 
         @Override
@@ -6244,7 +6264,11 @@
         @Override
         public void registerPackageMonitorCallback(@NonNull IRemoteCallback callback, int userId) {
             int uid = Binder.getCallingUid();
-            mPackageMonitorCallbackHelper.registerPackageMonitorCallback(callback, userId, uid);
+            int targetUserId = ActivityManager.handleIncomingUser(Binder.getCallingPid(), uid,
+                    userId, true, true, "registerPackageMonitorCallback",
+                    mContext.getPackageName());
+            mPackageMonitorCallbackHelper.registerPackageMonitorCallback(callback, targetUserId,
+                    uid);
         }
 
         @Override
diff --git a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
index ce0e7ad7..8bdbe04 100644
--- a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
+++ b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
@@ -226,6 +226,8 @@
                     return runPath();
                 case "dump":
                     return runDump();
+                case "dump-package":
+                    return runDumpPackage();
                 case "list":
                     return runList();
                 case "gc":
@@ -288,9 +290,11 @@
                 case "unhide":
                     return runSetHiddenSetting(false);
                 case "suspend":
-                    return runSuspend(true);
+                    return runSuspend(true, 0);
+                case "suspend-quarantine":
+                    return runSuspend(true, PackageManager.FLAG_SUSPEND_QUARANTINED);
                 case "unsuspend":
-                    return runSuspend(false);
+                    return runSuspend(false, 0);
                 case "set-distracting-restriction":
                     return runSetDistractingRestriction();
                 case "get-distracting-restriction":
@@ -976,6 +980,7 @@
         boolean listInstaller = false;
         boolean showUid = false;
         boolean showVersionCode = false;
+        boolean listQuarantinedOnly = false;
         boolean listApexOnly = false;
         boolean showStopped = false;
         int uid = -1;
@@ -1006,6 +1011,9 @@
                     case "-s":
                         listSystem = true;
                         break;
+                    case "-q":
+                        listQuarantinedOnly = true;
+                        break;
                     case "-U":
                         showUid = true;
                         break;
@@ -1091,6 +1099,10 @@
                         || (listApexOnly && !isApex)) {
                     continue;
                 }
+                if (listQuarantinedOnly && !mInterface.isPackageQuarantinedForUser(info.packageName,
+                        translatedUserId)) {
+                    continue;
+                }
 
                 String name = null;
                 if (showSdks) {
@@ -2644,7 +2656,7 @@
         }
     }
 
-    private int runSuspend(boolean suspendedState) {
+    private int runSuspend(boolean suspendedState, int flags) {
         final PrintWriter pw = getOutPrintWriter();
         int userId = UserHandle.USER_SYSTEM;
         String dialogMessage = null;
@@ -2712,7 +2724,7 @@
             mInterface.setPackagesSuspendedAsUser(packageNames.toArray(new String[] {}),
                     suspendedState, ((appExtras.size() > 0) ? appExtras : null),
                     ((launcherExtras.size() > 0) ? launcherExtras : null),
-                    info, callingPackage, translatedUserId);
+                    info, flags, callingPackage, translatedUserId);
             for (int i = 0; i < packageNames.size(); i++) {
                 final String packageName = packageNames.get(i);
                 pw.println("Package " + packageName + " new suspended state: "
@@ -3596,6 +3608,23 @@
         return 0;
     }
 
+    private int runDumpPackage() {
+        String pkg = getNextArg();
+        if (pkg == null) {
+            getErrPrintWriter().println("Error: no package specified");
+            return 1;
+        }
+        try {
+            ((IBinder) mInterface).dump(getOutFileDescriptor(), new String[]{pkg});
+        } catch (Throwable e) {
+            PrintWriter pw = getErrPrintWriter();
+            pw.println("Failure dumping service:");
+            e.printStackTrace(pw);
+            pw.flush();
+        }
+        return 0;
+    }
+
     private int runSetHarmfulAppWarning() throws RemoteException {
         int userId = UserHandle.USER_CURRENT;
 
@@ -4280,6 +4309,9 @@
         pw.println("  dump PACKAGE");
         pw.println("    Print various system state associated with the given PACKAGE.");
         pw.println("");
+        pw.println("  dump-package PACKAGE");
+        pw.println("    Print package manager state associated with the given PACKAGE.");
+        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");
@@ -4297,7 +4329,7 @@
         pw.println("    Options:");
         pw.println("      -v: shows the location of the library in the device's filesystem");
         pw.println("");
-        pw.println("  list packages [-f] [-d] [-e] [-s] [-3] [-i] [-l] [-u] [-U] ");
+        pw.println("  list packages [-f] [-d] [-e] [-s] [-q] [-3] [-i] [-l] [-u] [-U] ");
         pw.println("      [--show-versioncode] [--apex-only] [--factory-only]");
         pw.println("      [--uid UID] [--user USER_ID] [FILTER]");
         pw.println("    Prints all packages; optionally only those whose name contains");
@@ -4307,6 +4339,7 @@
         pw.println("      -d: filter to only show disabled packages");
         pw.println("      -e: filter to only show enabled packages");
         pw.println("      -s: filter to only show system packages");
+        pw.println("      -q: filter to only show quarantined packages");
         pw.println("      -3: filter to only show third party packages");
         pw.println("      -i: see the installer for the packages");
         pw.println("      -l: ignored (used for compatibility with older releases)");
diff --git a/services/core/java/com/android/server/pm/PackageSetting.java b/services/core/java/com/android/server/pm/PackageSetting.java
index cf4d1b0..14693a6 100644
--- a/services/core/java/com/android/server/pm/PackageSetting.java
+++ b/services/core/java/com/android/server/pm/PackageSetting.java
@@ -20,6 +20,7 @@
 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
 
+import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.UserIdInt;
@@ -80,9 +81,38 @@
  * @hide
  */
 @DataClass(genGetters = true, genConstructor = false, genSetters = false, genBuilder = false)
-@DataClass.Suppress({"getSnapshot", })
+@DataClass.Suppress({"getSnapshot", "getBooleans"})
 public class PackageSetting extends SettingBase implements PackageStateInternal {
 
+    // Use a bitset to store boolean data to save memory
+    private static class Booleans {
+        @IntDef({
+                INSTALL_PERMISSION_FIXED,
+                DEFAULT_TO_DEVICE_PROTECTED_STORAGE,
+                UPDATE_AVAILABLE,
+                FORCE_QUERYABLE_OVERRIDE
+        })
+        public @interface Flags {
+        }
+        private static final int INSTALL_PERMISSION_FIXED = 1;
+        private static final int DEFAULT_TO_DEVICE_PROTECTED_STORAGE = 1 << 1;
+        private static final int UPDATE_AVAILABLE = 1 << 2;
+        private static final int FORCE_QUERYABLE_OVERRIDE = 1 << 3;
+    }
+    private int mBooleans;
+
+    private void setBoolean(@Booleans.Flags int flag, boolean value) {
+        if (value) {
+            mBooleans |= flag;
+        } else {
+            mBooleans &= ~flag;
+        }
+    }
+
+    private boolean getBoolean(@Booleans.Flags int flag) {
+        return (mBooleans & flag) != 0;
+    }
+
     /**
      * The shared user ID lets us link this object to {@link SharedUserSetting}.
      */
@@ -160,8 +190,6 @@
     @NonNull
     private PackageSignatures signatures;
 
-    private boolean installPermissionsFixed;
-
     @NonNull
     private PackageKeySetData keySetData = new PackageKeySetData();
 
@@ -179,11 +207,6 @@
     /** @see PackageState#getCategoryOverride() */
     private int categoryOverride = ApplicationInfo.CATEGORY_UNDEFINED;
 
-    /** @see PackageState#isUpdateAvailable() */
-    private boolean updateAvailable;
-
-    private boolean forceQueryableOverride;
-
     @NonNull
     private final PackageStateUnserialized pkgState = new PackageStateUnserialized(this);
 
@@ -259,7 +282,8 @@
         this.mRealName = realPkgName;
     }
 
-    PackageSetting(@NonNull PackageSetting original, boolean sealedSnapshot)  {
+    @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+    public PackageSetting(@NonNull PackageSetting original, boolean sealedSnapshot)  {
         super(original);
         copyPackageSetting(original, sealedSnapshot);
         if (sealedSnapshot) {
@@ -363,7 +387,7 @@
     }
 
     public PackageSetting setForceQueryableOverride(boolean forceQueryableOverride) {
-        this.forceQueryableOverride = forceQueryableOverride;
+        setBoolean(Booleans.FORCE_QUERYABLE_OVERRIDE, forceQueryableOverride);
         onChanged();
         return this;
     }
@@ -487,13 +511,20 @@
         return this;
     }
 
+    public PackageSetting setDefaultToDeviceProtectedStorage(
+            boolean defaultToDeviceProtectedStorage) {
+        setBoolean(Booleans.DEFAULT_TO_DEVICE_PROTECTED_STORAGE, defaultToDeviceProtectedStorage);
+        onChanged();
+        return this;
+    }
+
     @Override
     public boolean isExternalStorage() {
         return (getFlags() & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
     }
 
     public PackageSetting setUpdateAvailable(boolean updateAvailable) {
-        this.updateAvailable = updateAvailable;
+        setBoolean(Booleans.UPDATE_AVAILABLE, updateAvailable);
         onChanged();
         return this;
     }
@@ -585,7 +616,7 @@
     }
 
     public PackageSetting setInstallPermissionsFixed(boolean installPermissionsFixed) {
-        this.installPermissionsFixed = installPermissionsFixed;
+        setBoolean(Booleans.INSTALL_PERMISSION_FIXED, installPermissionsFixed);
         return this;
     }
 
@@ -635,6 +666,7 @@
 
     public void copyPackageSetting(PackageSetting other, boolean sealedSnapshot) {
         super.copySettingBase(other);
+        mBooleans = other.mBooleans;
         mSharedUserAppId = other.mSharedUserAppId;
         mLoadingProgress = other.mLoadingProgress;
         mLoadingCompletedTime = other.mLoadingCompletedTime;
@@ -652,13 +684,10 @@
         lastUpdateTime = other.lastUpdateTime;
         versionCode = other.versionCode;
         signatures = other.signatures;
-        installPermissionsFixed = other.installPermissionsFixed;
         keySetData = new PackageKeySetData(other.keySetData);
         installSource = other.installSource;
         volumeUuid = other.volumeUuid;
         categoryOverride = other.categoryOverride;
-        updateAvailable = other.updateAvailable;
-        forceQueryableOverride = other.forceQueryableOverride;
         mDomainSetId = other.mDomainSetId;
         mAppMetadataFilePath = other.mAppMetadataFilePath;
 
@@ -908,8 +937,8 @@
                 otherState.isHidden(), otherState.getDistractionFlags(),
                 otherState.getSuspendParams() == null
                         ? null : otherState.getSuspendParams().untrackedStorage(),
-                otherState.isInstantApp(),
-                otherState.isVirtualPreload(), otherState.getLastDisableAppCaller(),
+                otherState.isInstantApp(), otherState.isVirtualPreload(),
+                otherState.getLastDisableAppCaller(),
                 otherState.getEnabledComponentsNoCopy() == null
                         ? null : otherState.getEnabledComponentsNoCopy().untrackedStorage(),
                 otherState.getDisabledComponentsNoCopy() == null
@@ -1282,7 +1311,7 @@
     @NonNull
     @Override
     public List<SharedLibrary> getSharedLibraryDependencies() {
-        return (List<SharedLibrary>) (List<?>) pkgState.getUsesLibraryInfos();
+        return Collections.unmodifiableList(pkgState.getUsesLibraryInfos());
     }
 
     @NonNull
@@ -1294,7 +1323,7 @@
     @NonNull
     @Override
     public List<String> getUsesLibraryFiles() {
-        return pkgState.getUsesLibraryFiles();
+        return Collections.unmodifiableList(pkgState.getUsesLibraryFiles());
     }
 
     @NonNull
@@ -1474,6 +1503,32 @@
         return getAndroidPackage() != null && getAndroidPackage().isApex();
     }
 
+    @Override
+    public boolean isForceQueryableOverride() {
+        return getBoolean(Booleans.FORCE_QUERYABLE_OVERRIDE);
+    }
+
+    /**
+     * @see PackageState#isUpdateAvailable()
+     */
+    @Override
+    public boolean isUpdateAvailable() {
+        return getBoolean(Booleans.UPDATE_AVAILABLE);
+    }
+
+    @Override
+    public boolean isInstallPermissionsFixed() {
+        return getBoolean(Booleans.INSTALL_PERMISSION_FIXED);
+    }
+
+    /**
+     * @see PackageState#isDefaultToDeviceProtectedStorage()
+     */
+    @Override
+    public boolean isDefaultToDeviceProtectedStorage() {
+        return getBoolean(Booleans.DEFAULT_TO_DEVICE_PROTECTED_STORAGE);
+    }
+
 
 
     // Code below generated by codegen v1.0.23.
@@ -1576,11 +1631,6 @@
     }
 
     @DataClass.Generated.Member
-    public boolean isInstallPermissionsFixed() {
-        return installPermissionsFixed;
-    }
-
-    @DataClass.Generated.Member
     public @NonNull PackageKeySetData getKeySetData() {
         return keySetData;
     }
@@ -1606,19 +1656,6 @@
         return categoryOverride;
     }
 
-    /**
-     * @see PackageState#isUpdateAvailable()
-     */
-    @DataClass.Generated.Member
-    public boolean isUpdateAvailable() {
-        return updateAvailable;
-    }
-
-    @DataClass.Generated.Member
-    public boolean isForceQueryableOverride() {
-        return forceQueryableOverride;
-    }
-
     @DataClass.Generated.Member
     public @NonNull PackageStateUnserialized getPkgState() {
         return pkgState;
@@ -1635,10 +1672,10 @@
     }
 
     @DataClass.Generated(
-            time = 1688743336932L,
+            time = 1691185420362L,
             codegenVersion = "1.0.23",
             sourceFile = "frameworks/base/services/core/java/com/android/server/pm/PackageSetting.java",
-            inputSignatures = "private  int mSharedUserAppId\nprivate @android.annotation.Nullable java.util.Map<java.lang.String,java.util.Set<java.lang.String>> mimeGroups\nprivate @java.lang.Deprecated @android.annotation.Nullable java.util.Set<java.lang.String> mOldCodePaths\nprivate @android.annotation.Nullable java.lang.String[] usesSdkLibraries\nprivate @android.annotation.Nullable long[] usesSdkLibrariesVersionsMajor\nprivate @android.annotation.Nullable java.lang.String[] usesStaticLibraries\nprivate @android.annotation.Nullable long[] usesStaticLibrariesVersions\nprivate @android.annotation.Nullable @java.lang.Deprecated java.lang.String legacyNativeLibraryPath\nprivate @android.annotation.NonNull java.lang.String mName\nprivate @android.annotation.Nullable java.lang.String mRealName\nprivate  int mAppId\nprivate @android.annotation.Nullable com.android.server.pm.parsing.pkg.AndroidPackageInternal pkg\nprivate @android.annotation.NonNull java.io.File mPath\nprivate @android.annotation.NonNull java.lang.String mPathString\nprivate  float mLoadingProgress\nprivate  long mLoadingCompletedTime\nprivate @android.annotation.Nullable java.lang.String mPrimaryCpuAbi\nprivate @android.annotation.Nullable java.lang.String mSecondaryCpuAbi\nprivate @android.annotation.Nullable java.lang.String mCpuAbiOverride\nprivate  long mLastModifiedTime\nprivate  long lastUpdateTime\nprivate  long versionCode\nprivate @android.annotation.NonNull com.android.server.pm.PackageSignatures signatures\nprivate  boolean installPermissionsFixed\nprivate @android.annotation.NonNull com.android.server.pm.PackageKeySetData keySetData\nprivate final @android.annotation.NonNull android.util.SparseArray<com.android.server.pm.pkg.PackageUserStateImpl> mUserStates\nprivate @android.annotation.NonNull com.android.server.pm.InstallSource installSource\nprivate @android.annotation.Nullable java.lang.String volumeUuid\nprivate  int categoryOverride\nprivate  boolean updateAvailable\nprivate  boolean forceQueryableOverride\nprivate final @android.annotation.NonNull com.android.server.pm.pkg.PackageStateUnserialized pkgState\nprivate @android.annotation.NonNull java.util.UUID mDomainSetId\nprivate @android.annotation.Nullable java.lang.String mAppMetadataFilePath\nprivate final @android.annotation.NonNull com.android.server.utils.SnapshotCache<com.android.server.pm.PackageSetting> mSnapshot\nprivate  com.android.server.utils.SnapshotCache<com.android.server.pm.PackageSetting> makeCache()\npublic  com.android.server.pm.PackageSetting snapshot()\npublic  void dumpDebug(android.util.proto.ProtoOutputStream,long,java.util.List<android.content.pm.UserInfo>,com.android.server.pm.permission.LegacyPermissionDataProvider)\npublic  com.android.server.pm.PackageSetting setAppId(int)\npublic  com.android.server.pm.PackageSetting setCpuAbiOverride(java.lang.String)\npublic  com.android.server.pm.PackageSetting setFirstInstallTimeFromReplaced(com.android.server.pm.pkg.PackageStateInternal,int[])\npublic  com.android.server.pm.PackageSetting setFirstInstallTime(long,int)\npublic  com.android.server.pm.PackageSetting setForceQueryableOverride(boolean)\npublic  com.android.server.pm.PackageSetting setInstallerPackage(java.lang.String,int)\npublic  com.android.server.pm.PackageSetting setUpdateOwnerPackage(java.lang.String)\npublic  com.android.server.pm.PackageSetting setInstallSource(com.android.server.pm.InstallSource)\n  com.android.server.pm.PackageSetting removeInstallerPackage(java.lang.String)\npublic  com.android.server.pm.PackageSetting setIsOrphaned(boolean)\npublic  com.android.server.pm.PackageSetting setKeySetData(com.android.server.pm.PackageKeySetData)\npublic  com.android.server.pm.PackageSetting setLastModifiedTime(long)\npublic  com.android.server.pm.PackageSetting setLastUpdateTime(long)\npublic  com.android.server.pm.PackageSetting setLongVersionCode(long)\npublic  boolean setMimeGroup(java.lang.String,android.util.ArraySet<java.lang.String>)\npublic  com.android.server.pm.PackageSetting setPkg(com.android.server.pm.pkg.AndroidPackage)\npublic  com.android.server.pm.PackageSetting setPkgStateLibraryFiles(java.util.Collection<java.lang.String>)\npublic  com.android.server.pm.PackageSetting setPrimaryCpuAbi(java.lang.String)\npublic  com.android.server.pm.PackageSetting setSecondaryCpuAbi(java.lang.String)\npublic  com.android.server.pm.PackageSetting setSignatures(com.android.server.pm.PackageSignatures)\npublic  com.android.server.pm.PackageSetting setVolumeUuid(java.lang.String)\npublic @java.lang.Override boolean isExternalStorage()\npublic  com.android.server.pm.PackageSetting setUpdateAvailable(boolean)\npublic  void setSharedUserAppId(int)\npublic @java.lang.Override int getSharedUserAppId()\npublic @java.lang.Override boolean hasSharedUser()\npublic @java.lang.Override java.lang.String toString()\nprotected  void copyMimeGroups(java.util.Map<java.lang.String,java.util.Set<java.lang.String>>)\npublic  void updateFrom(com.android.server.pm.PackageSetting)\n  com.android.server.pm.PackageSetting updateMimeGroups(java.util.Set<java.lang.String>)\npublic @java.lang.Deprecated @java.lang.Override com.android.server.pm.permission.LegacyPermissionState getLegacyPermissionState()\npublic  com.android.server.pm.PackageSetting setInstallPermissionsFixed(boolean)\npublic  boolean isPrivileged()\npublic  boolean isOem()\npublic  boolean isVendor()\npublic  boolean isProduct()\npublic @java.lang.Override boolean isRequiredForSystemUser()\npublic  boolean isSystemExt()\npublic  boolean isOdm()\npublic  boolean isSystem()\npublic  android.content.pm.SigningDetails getSigningDetails()\npublic  com.android.server.pm.PackageSetting setSigningDetails(android.content.pm.SigningDetails)\npublic  void copyPackageSetting(com.android.server.pm.PackageSetting,boolean)\n @com.android.internal.annotations.VisibleForTesting com.android.server.pm.pkg.PackageUserStateImpl modifyUserState(int)\npublic  com.android.server.pm.pkg.PackageUserStateImpl getOrCreateUserState(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateInternal readUserState(int)\n  void setEnabled(int,int,java.lang.String)\n  int getEnabled(int)\n  void setInstalled(boolean,int)\n  boolean getInstalled(int)\n  int getInstallReason(int)\n  void setInstallReason(int,int)\n  int getUninstallReason(int)\n  void setUninstallReason(int,int)\n @android.annotation.NonNull android.content.pm.overlay.OverlayPaths getOverlayPaths(int)\n  boolean setOverlayPathsForLibrary(java.lang.String,android.content.pm.overlay.OverlayPaths,int)\n  boolean isAnyInstalled(int[])\n  int[] queryInstalledUsers(int[],boolean)\n  long getCeDataInode(int)\n  void setCeDataInode(long,int)\n  boolean getStopped(int)\n  void setStopped(boolean,int)\n  boolean getNotLaunched(int)\n  void setNotLaunched(boolean,int)\n  boolean getHidden(int)\n  void setHidden(boolean,int)\n  int getDistractionFlags(int)\n  void setDistractionFlags(int,int)\npublic  boolean getInstantApp(int)\n  void setInstantApp(boolean,int)\n  boolean getVirtualPreload(int)\n  void setVirtualPreload(boolean,int)\n  void setUserState(int,long,int,boolean,boolean,boolean,boolean,int,android.util.ArrayMap<java.lang.String,com.android.server.pm.pkg.SuspendParams>,boolean,boolean,java.lang.String,android.util.ArraySet<java.lang.String>,android.util.ArraySet<java.lang.String>,int,int,java.lang.String,java.lang.String,long,com.android.server.pm.pkg.ArchiveState)\n  void setUserState(int,com.android.server.pm.pkg.PackageUserStateInternal)\n  com.android.server.utils.WatchedArraySet<java.lang.String> getEnabledComponents(int)\n  com.android.server.utils.WatchedArraySet<java.lang.String> getDisabledComponents(int)\n  void setEnabledComponents(com.android.server.utils.WatchedArraySet<java.lang.String>,int)\n  void setDisabledComponents(com.android.server.utils.WatchedArraySet<java.lang.String>,int)\n  void setEnabledComponentsCopy(com.android.server.utils.WatchedArraySet<java.lang.String>,int)\n  void setDisabledComponentsCopy(com.android.server.utils.WatchedArraySet<java.lang.String>,int)\n  com.android.server.pm.pkg.PackageUserStateImpl modifyUserStateComponents(int,boolean,boolean)\n  void addDisabledComponent(java.lang.String,int)\n  void addEnabledComponent(java.lang.String,int)\n  boolean enableComponentLPw(java.lang.String,int)\n  boolean disableComponentLPw(java.lang.String,int)\n  boolean restoreComponentLPw(java.lang.String,int)\n  int getCurrentEnabledStateLPr(java.lang.String,int)\n  void removeUser(int)\npublic  int[] getNotInstalledUserIds()\n  void writePackageUserPermissionsProto(android.util.proto.ProtoOutputStream,long,java.util.List<android.content.pm.UserInfo>,com.android.server.pm.permission.LegacyPermissionDataProvider)\nprotected  void writeUsersInfoToProto(android.util.proto.ProtoOutputStream,long)\nprivate static  void writeArchiveState(android.util.proto.ProtoOutputStream,com.android.server.pm.pkg.ArchiveState)\n  com.android.server.pm.PackageSetting setPath(java.io.File)\npublic @com.android.internal.annotations.VisibleForTesting boolean overrideNonLocalizedLabelAndIcon(android.content.ComponentName,java.lang.String,java.lang.Integer,int)\npublic  void resetOverrideComponentLabelIcon(int)\npublic @android.annotation.Nullable java.lang.String getSplashScreenTheme(int)\npublic  boolean isIncremental()\npublic  boolean isLoading()\npublic  com.android.server.pm.PackageSetting setLoadingProgress(float)\npublic  com.android.server.pm.PackageSetting setLoadingCompletedTime(long)\npublic  com.android.server.pm.PackageSetting setAppMetadataFilePath(java.lang.String)\npublic @android.annotation.NonNull @java.lang.Override long getVersionCode()\npublic @android.annotation.Nullable @java.lang.Override java.util.Map<java.lang.String,java.util.Set<java.lang.String>> getMimeGroups()\npublic @android.annotation.NonNull @java.lang.Override java.lang.String getPackageName()\npublic @android.annotation.Nullable @java.lang.Override com.android.server.pm.pkg.AndroidPackage getAndroidPackage()\npublic @android.annotation.NonNull android.content.pm.SigningInfo getSigningInfo()\npublic @android.annotation.NonNull @java.lang.Override java.lang.String[] getUsesSdkLibraries()\npublic @android.annotation.NonNull @java.lang.Override long[] getUsesSdkLibrariesVersionsMajor()\npublic @android.annotation.NonNull @java.lang.Override java.lang.String[] getUsesStaticLibraries()\npublic @android.annotation.NonNull @java.lang.Override long[] getUsesStaticLibrariesVersions()\npublic @android.annotation.NonNull @java.lang.Override java.util.List<com.android.server.pm.pkg.SharedLibrary> getSharedLibraryDependencies()\npublic @android.annotation.NonNull com.android.server.pm.PackageSetting addUsesLibraryInfo(android.content.pm.SharedLibraryInfo)\npublic @android.annotation.NonNull @java.lang.Override java.util.List<java.lang.String> getUsesLibraryFiles()\npublic @android.annotation.NonNull com.android.server.pm.PackageSetting addUsesLibraryFile(java.lang.String)\npublic @java.lang.Override boolean isHiddenUntilInstalled()\npublic @android.annotation.NonNull @java.lang.Override long[] getLastPackageUsageTime()\npublic @java.lang.Override boolean isUpdatedSystemApp()\npublic @java.lang.Override boolean isApkInUpdatedApex()\npublic @android.annotation.Nullable @java.lang.Override java.lang.String getApexModuleName()\npublic  com.android.server.pm.PackageSetting setDomainSetId(java.util.UUID)\npublic  com.android.server.pm.PackageSetting setCategoryOverride(int)\npublic  com.android.server.pm.PackageSetting setLegacyNativeLibraryPath(java.lang.String)\npublic  com.android.server.pm.PackageSetting setMimeGroups(java.util.Map<java.lang.String,java.util.Set<java.lang.String>>)\npublic  com.android.server.pm.PackageSetting setOldCodePaths(java.util.Set<java.lang.String>)\npublic  com.android.server.pm.PackageSetting setUsesSdkLibraries(java.lang.String[])\npublic  com.android.server.pm.PackageSetting setUsesSdkLibrariesVersionsMajor(long[])\npublic  com.android.server.pm.PackageSetting setUsesStaticLibraries(java.lang.String[])\npublic  com.android.server.pm.PackageSetting setUsesStaticLibrariesVersions(long[])\npublic  com.android.server.pm.PackageSetting setApexModuleName(java.lang.String)\npublic @android.annotation.NonNull @java.lang.Override com.android.server.pm.pkg.PackageStateUnserialized getTransientState()\npublic @android.annotation.NonNull android.util.SparseArray<? extends PackageUserStateInternal> getUserStates()\npublic  com.android.server.pm.PackageSetting addMimeTypes(java.lang.String,java.util.Set<java.lang.String>)\npublic @android.annotation.NonNull @java.lang.Override com.android.server.pm.pkg.PackageUserState getStateForUser(android.os.UserHandle)\npublic @android.annotation.Nullable java.lang.String getPrimaryCpuAbi()\npublic @android.annotation.Nullable java.lang.String getSecondaryCpuAbi()\npublic @android.annotation.Nullable @java.lang.Override java.lang.String getSeInfo()\npublic @android.annotation.Nullable java.lang.String getPrimaryCpuAbiLegacy()\npublic @android.annotation.Nullable java.lang.String getSecondaryCpuAbiLegacy()\npublic @android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy @java.lang.Override int getHiddenApiEnforcementPolicy()\npublic @java.lang.Override boolean isApex()\nclass PackageSetting extends com.android.server.pm.SettingBase implements [com.android.server.pm.pkg.PackageStateInternal]\n@com.android.internal.util.DataClass(genGetters=true, genConstructor=false, genSetters=false, genBuilder=false)")
+            inputSignatures = "private  int mBooleans\nprivate  int mSharedUserAppId\nprivate @android.annotation.Nullable java.util.Map<java.lang.String,java.util.Set<java.lang.String>> mimeGroups\nprivate @java.lang.Deprecated @android.annotation.Nullable java.util.Set<java.lang.String> mOldCodePaths\nprivate @android.annotation.Nullable java.lang.String[] usesSdkLibraries\nprivate @android.annotation.Nullable long[] usesSdkLibrariesVersionsMajor\nprivate @android.annotation.Nullable java.lang.String[] usesStaticLibraries\nprivate @android.annotation.Nullable long[] usesStaticLibrariesVersions\nprivate @android.annotation.Nullable @java.lang.Deprecated java.lang.String legacyNativeLibraryPath\nprivate @android.annotation.NonNull java.lang.String mName\nprivate @android.annotation.Nullable java.lang.String mRealName\nprivate  int mAppId\nprivate @android.annotation.Nullable com.android.server.pm.parsing.pkg.AndroidPackageInternal pkg\nprivate @android.annotation.NonNull java.io.File mPath\nprivate @android.annotation.NonNull java.lang.String mPathString\nprivate  float mLoadingProgress\nprivate  long mLoadingCompletedTime\nprivate @android.annotation.Nullable java.lang.String mPrimaryCpuAbi\nprivate @android.annotation.Nullable java.lang.String mSecondaryCpuAbi\nprivate @android.annotation.Nullable java.lang.String mCpuAbiOverride\nprivate  long mLastModifiedTime\nprivate  long lastUpdateTime\nprivate  long versionCode\nprivate @android.annotation.NonNull com.android.server.pm.PackageSignatures signatures\nprivate @android.annotation.NonNull com.android.server.pm.PackageKeySetData keySetData\nprivate final @android.annotation.NonNull android.util.SparseArray<com.android.server.pm.pkg.PackageUserStateImpl> mUserStates\nprivate @android.annotation.NonNull com.android.server.pm.InstallSource installSource\nprivate @android.annotation.Nullable java.lang.String volumeUuid\nprivate  int categoryOverride\nprivate final @android.annotation.NonNull com.android.server.pm.pkg.PackageStateUnserialized pkgState\nprivate @android.annotation.NonNull java.util.UUID mDomainSetId\nprivate @android.annotation.Nullable java.lang.String mAppMetadataFilePath\nprivate final @android.annotation.NonNull com.android.server.utils.SnapshotCache<com.android.server.pm.PackageSetting> mSnapshot\nprivate  void setBoolean(int,boolean)\nprivate  boolean getBoolean(int)\nprivate  com.android.server.utils.SnapshotCache<com.android.server.pm.PackageSetting> makeCache()\npublic  com.android.server.pm.PackageSetting snapshot()\npublic  void dumpDebug(android.util.proto.ProtoOutputStream,long,java.util.List<android.content.pm.UserInfo>,com.android.server.pm.permission.LegacyPermissionDataProvider)\npublic  com.android.server.pm.PackageSetting setAppId(int)\npublic  com.android.server.pm.PackageSetting setCpuAbiOverride(java.lang.String)\npublic  com.android.server.pm.PackageSetting setFirstInstallTimeFromReplaced(com.android.server.pm.pkg.PackageStateInternal,int[])\npublic  com.android.server.pm.PackageSetting setFirstInstallTime(long,int)\npublic  com.android.server.pm.PackageSetting setForceQueryableOverride(boolean)\npublic  com.android.server.pm.PackageSetting setInstallerPackage(java.lang.String,int)\npublic  com.android.server.pm.PackageSetting setUpdateOwnerPackage(java.lang.String)\npublic  com.android.server.pm.PackageSetting setInstallSource(com.android.server.pm.InstallSource)\n  com.android.server.pm.PackageSetting removeInstallerPackage(java.lang.String)\npublic  com.android.server.pm.PackageSetting setIsOrphaned(boolean)\npublic  com.android.server.pm.PackageSetting setKeySetData(com.android.server.pm.PackageKeySetData)\npublic  com.android.server.pm.PackageSetting setLastModifiedTime(long)\npublic  com.android.server.pm.PackageSetting setLastUpdateTime(long)\npublic  com.android.server.pm.PackageSetting setLongVersionCode(long)\npublic  boolean setMimeGroup(java.lang.String,android.util.ArraySet<java.lang.String>)\npublic  com.android.server.pm.PackageSetting setPkg(com.android.server.pm.pkg.AndroidPackage)\npublic  com.android.server.pm.PackageSetting setPkgStateLibraryFiles(java.util.Collection<java.lang.String>)\npublic  com.android.server.pm.PackageSetting setPrimaryCpuAbi(java.lang.String)\npublic  com.android.server.pm.PackageSetting setSecondaryCpuAbi(java.lang.String)\npublic  com.android.server.pm.PackageSetting setSignatures(com.android.server.pm.PackageSignatures)\npublic  com.android.server.pm.PackageSetting setVolumeUuid(java.lang.String)\npublic  com.android.server.pm.PackageSetting setDefaultToDeviceProtectedStorage(boolean)\npublic @java.lang.Override boolean isExternalStorage()\npublic  com.android.server.pm.PackageSetting setUpdateAvailable(boolean)\npublic  void setSharedUserAppId(int)\npublic @java.lang.Override int getSharedUserAppId()\npublic @java.lang.Override boolean hasSharedUser()\npublic @java.lang.Override java.lang.String toString()\nprotected  void copyMimeGroups(java.util.Map<java.lang.String,java.util.Set<java.lang.String>>)\npublic  void updateFrom(com.android.server.pm.PackageSetting)\n  com.android.server.pm.PackageSetting updateMimeGroups(java.util.Set<java.lang.String>)\npublic @java.lang.Deprecated @java.lang.Override com.android.server.pm.permission.LegacyPermissionState getLegacyPermissionState()\npublic  com.android.server.pm.PackageSetting setInstallPermissionsFixed(boolean)\npublic  boolean isPrivileged()\npublic  boolean isOem()\npublic  boolean isVendor()\npublic  boolean isProduct()\npublic @java.lang.Override boolean isRequiredForSystemUser()\npublic  boolean isSystemExt()\npublic  boolean isOdm()\npublic  boolean isSystem()\npublic  android.content.pm.SigningDetails getSigningDetails()\npublic  com.android.server.pm.PackageSetting setSigningDetails(android.content.pm.SigningDetails)\npublic  void copyPackageSetting(com.android.server.pm.PackageSetting,boolean)\n @com.android.internal.annotations.VisibleForTesting com.android.server.pm.pkg.PackageUserStateImpl modifyUserState(int)\npublic  com.android.server.pm.pkg.PackageUserStateImpl getOrCreateUserState(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateInternal readUserState(int)\n  void setEnabled(int,int,java.lang.String)\n  int getEnabled(int)\n  void setInstalled(boolean,int)\n  boolean getInstalled(int)\n  int getInstallReason(int)\n  void setInstallReason(int,int)\n  int getUninstallReason(int)\n  void setUninstallReason(int,int)\n @android.annotation.NonNull android.content.pm.overlay.OverlayPaths getOverlayPaths(int)\n  boolean setOverlayPathsForLibrary(java.lang.String,android.content.pm.overlay.OverlayPaths,int)\n  boolean isAnyInstalled(int[])\n  int[] queryInstalledUsers(int[],boolean)\n  long getCeDataInode(int)\n  void setCeDataInode(long,int)\n  boolean getStopped(int)\n  void setStopped(boolean,int)\n  boolean getNotLaunched(int)\n  void setNotLaunched(boolean,int)\n  boolean getHidden(int)\n  void setHidden(boolean,int)\n  int getDistractionFlags(int)\n  void setDistractionFlags(int,int)\npublic  boolean getInstantApp(int)\n  void setInstantApp(boolean,int)\n  boolean getVirtualPreload(int)\n  void setVirtualPreload(boolean,int)\n  void setUserState(int,long,int,boolean,boolean,boolean,boolean,int,android.util.ArrayMap<java.lang.String,com.android.server.pm.pkg.SuspendParams>,boolean,boolean,java.lang.String,android.util.ArraySet<java.lang.String>,android.util.ArraySet<java.lang.String>,int,int,java.lang.String,java.lang.String,long,int,com.android.server.pm.pkg.ArchiveState)\n  void setUserState(int,com.android.server.pm.pkg.PackageUserStateInternal)\n  com.android.server.utils.WatchedArraySet<java.lang.String> getEnabledComponents(int)\n  com.android.server.utils.WatchedArraySet<java.lang.String> getDisabledComponents(int)\n  void setEnabledComponents(com.android.server.utils.WatchedArraySet<java.lang.String>,int)\n  void setDisabledComponents(com.android.server.utils.WatchedArraySet<java.lang.String>,int)\n  void setEnabledComponentsCopy(com.android.server.utils.WatchedArraySet<java.lang.String>,int)\n  void setDisabledComponentsCopy(com.android.server.utils.WatchedArraySet<java.lang.String>,int)\n  com.android.server.pm.pkg.PackageUserStateImpl modifyUserStateComponents(int,boolean,boolean)\n  void addDisabledComponent(java.lang.String,int)\n  void addEnabledComponent(java.lang.String,int)\n  boolean enableComponentLPw(java.lang.String,int)\n  boolean disableComponentLPw(java.lang.String,int)\n  boolean restoreComponentLPw(java.lang.String,int)\n  int getCurrentEnabledStateLPr(java.lang.String,int)\n  void removeUser(int)\npublic  int[] getNotInstalledUserIds()\n  void writePackageUserPermissionsProto(android.util.proto.ProtoOutputStream,long,java.util.List<android.content.pm.UserInfo>,com.android.server.pm.permission.LegacyPermissionDataProvider)\nprotected  void writeUsersInfoToProto(android.util.proto.ProtoOutputStream,long)\nprivate static  void writeArchiveState(android.util.proto.ProtoOutputStream,com.android.server.pm.pkg.ArchiveState)\n  com.android.server.pm.PackageSetting setPath(java.io.File)\npublic @com.android.internal.annotations.VisibleForTesting boolean overrideNonLocalizedLabelAndIcon(android.content.ComponentName,java.lang.String,java.lang.Integer,int)\npublic  void resetOverrideComponentLabelIcon(int)\npublic @android.annotation.Nullable java.lang.String getSplashScreenTheme(int)\npublic  boolean isIncremental()\npublic  boolean isLoading()\npublic  com.android.server.pm.PackageSetting setLoadingProgress(float)\npublic  com.android.server.pm.PackageSetting setLoadingCompletedTime(long)\npublic  com.android.server.pm.PackageSetting setAppMetadataFilePath(java.lang.String)\npublic @android.annotation.NonNull @java.lang.Override long getVersionCode()\npublic @android.annotation.Nullable @java.lang.Override java.util.Map<java.lang.String,java.util.Set<java.lang.String>> getMimeGroups()\npublic @android.annotation.NonNull @java.lang.Override java.lang.String getPackageName()\npublic @android.annotation.Nullable @java.lang.Override com.android.server.pm.pkg.AndroidPackage getAndroidPackage()\npublic @android.annotation.NonNull android.content.pm.SigningInfo getSigningInfo()\npublic @android.annotation.NonNull @java.lang.Override java.lang.String[] getUsesSdkLibraries()\npublic @android.annotation.NonNull @java.lang.Override long[] getUsesSdkLibrariesVersionsMajor()\npublic @android.annotation.NonNull @java.lang.Override java.lang.String[] getUsesStaticLibraries()\npublic @android.annotation.NonNull @java.lang.Override long[] getUsesStaticLibrariesVersions()\npublic @android.annotation.NonNull @java.lang.Override java.util.List<com.android.server.pm.pkg.SharedLibrary> getSharedLibraryDependencies()\npublic @android.annotation.NonNull com.android.server.pm.PackageSetting addUsesLibraryInfo(android.content.pm.SharedLibraryInfo)\npublic @android.annotation.NonNull @java.lang.Override java.util.List<java.lang.String> getUsesLibraryFiles()\npublic @android.annotation.NonNull com.android.server.pm.PackageSetting addUsesLibraryFile(java.lang.String)\npublic @java.lang.Override boolean isHiddenUntilInstalled()\npublic @android.annotation.NonNull @java.lang.Override long[] getLastPackageUsageTime()\npublic @java.lang.Override boolean isUpdatedSystemApp()\npublic @java.lang.Override boolean isApkInUpdatedApex()\npublic @android.annotation.Nullable @java.lang.Override java.lang.String getApexModuleName()\npublic  com.android.server.pm.PackageSetting setDomainSetId(java.util.UUID)\npublic  com.android.server.pm.PackageSetting setCategoryOverride(int)\npublic  com.android.server.pm.PackageSetting setLegacyNativeLibraryPath(java.lang.String)\npublic  com.android.server.pm.PackageSetting setMimeGroups(java.util.Map<java.lang.String,java.util.Set<java.lang.String>>)\npublic  com.android.server.pm.PackageSetting setOldCodePaths(java.util.Set<java.lang.String>)\npublic  com.android.server.pm.PackageSetting setUsesSdkLibraries(java.lang.String[])\npublic  com.android.server.pm.PackageSetting setUsesSdkLibrariesVersionsMajor(long[])\npublic  com.android.server.pm.PackageSetting setUsesStaticLibraries(java.lang.String[])\npublic  com.android.server.pm.PackageSetting setUsesStaticLibrariesVersions(long[])\npublic  com.android.server.pm.PackageSetting setApexModuleName(java.lang.String)\npublic @android.annotation.NonNull @java.lang.Override com.android.server.pm.pkg.PackageStateUnserialized getTransientState()\npublic @android.annotation.NonNull android.util.SparseArray<? extends PackageUserStateInternal> getUserStates()\npublic  com.android.server.pm.PackageSetting addMimeTypes(java.lang.String,java.util.Set<java.lang.String>)\npublic @android.annotation.NonNull @java.lang.Override com.android.server.pm.pkg.PackageUserState getStateForUser(android.os.UserHandle)\npublic @android.annotation.Nullable java.lang.String getPrimaryCpuAbi()\npublic @android.annotation.Nullable java.lang.String getSecondaryCpuAbi()\npublic @android.annotation.Nullable @java.lang.Override java.lang.String getSeInfo()\npublic @android.annotation.Nullable java.lang.String getPrimaryCpuAbiLegacy()\npublic @android.annotation.Nullable java.lang.String getSecondaryCpuAbiLegacy()\npublic @android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy @java.lang.Override int getHiddenApiEnforcementPolicy()\npublic @java.lang.Override boolean isApex()\npublic @java.lang.Override boolean isForceQueryableOverride()\npublic @java.lang.Override boolean isUpdateAvailable()\npublic @java.lang.Override boolean isInstallPermissionsFixed()\npublic @java.lang.Override boolean isDefaultToDeviceProtectedStorage()\nclass PackageSetting extends com.android.server.pm.SettingBase implements [com.android.server.pm.pkg.PackageStateInternal]\nprivate static final  int INSTALL_PERMISSION_FIXED\nprivate static final  int DEFAULT_TO_DEVICE_PROTECTED_STORAGE\nprivate static final  int UPDATE_AVAILABLE\nprivate static final  int FORCE_QUERYABLE_OVERRIDE\nclass Booleans extends java.lang.Object implements []\n@com.android.internal.util.DataClass(genGetters=true, genConstructor=false, genSetters=false, genBuilder=false)")
     @Deprecated
     private void __metadata() {}
 
diff --git a/services/core/java/com/android/server/pm/RemovePackageHelper.java b/services/core/java/com/android/server/pm/RemovePackageHelper.java
index 59314a2..6d3b26c 100644
--- a/services/core/java/com/android/server/pm/RemovePackageHelper.java
+++ b/services/core/java/com/android/server/pm/RemovePackageHelper.java
@@ -135,6 +135,7 @@
         cacher.cleanCachedResult(codePath);
     }
 
+    // Used for system apps only
     public void removePackage(AndroidPackage pkg, boolean chatty) {
         synchronized (mPm.mInstallLock) {
             removePackageLI(pkg, chatty);
@@ -284,6 +285,13 @@
         }
 
         removePackageLI(deletedPs.getPackageName(), (flags & PackageManager.DELETE_CHATTY) != 0);
+        if (!deletedPs.isSystem()) {
+            // A non-system app's AndroidPackage object has been removed from the service.
+            // Explicitly nullify the corresponding app's PackageSetting's pkg object to
+            // prevent any future usage of it, in case the PackageSetting object will remain because
+            // of DELETE_KEEP_DATA.
+            deletedPs.setPkg(null);
+        }
 
         if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
             final AndroidPackage resolvedPkg;
diff --git a/services/core/java/com/android/server/pm/ScanPackageUtils.java b/services/core/java/com/android/server/pm/ScanPackageUtils.java
index 1cd44e6..f4dca3f 100644
--- a/services/core/java/com/android/server/pm/ScanPackageUtils.java
+++ b/services/core/java/com/android/server/pm/ScanPackageUtils.java
@@ -462,6 +462,8 @@
                             + " to " + volumeUuid);
             pkgSetting.setVolumeUuid(volumeUuid);
         }
+        pkgSetting.setDefaultToDeviceProtectedStorage(
+                parsedPackage.isDefaultToDeviceProtectedStorage());
 
         SharedLibraryInfo sdkLibraryInfo = null;
         if (!TextUtils.isEmpty(parsedPackage.getSdkLibraryName())) {
diff --git a/services/core/java/com/android/server/pm/Settings.java b/services/core/java/com/android/server/pm/Settings.java
index e5ad01f..b6da462 100644
--- a/services/core/java/com/android/server/pm/Settings.java
+++ b/services/core/java/com/android/server/pm/Settings.java
@@ -1918,9 +1918,9 @@
 
                         ArraySet<String> enabledComponents = null;
                         ArraySet<String> disabledComponents = null;
-                        PersistableBundle suspendedAppExtras = null;
-                        PersistableBundle suspendedLauncherExtras = null;
                         SuspendDialogInfo oldSuspendDialogInfo = null;
+                        PersistableBundle oldSuspendedAppExtras = null;
+                        PersistableBundle oldSuspendedLauncherExtras = null;
                         ArchiveState archiveState = null;
 
                         int packageDepth = parser.getDepth();
@@ -1939,16 +1939,17 @@
                                 case TAG_DISABLED_COMPONENTS:
                                     disabledComponents = readComponentsLPr(parser);
                                     break;
-                                case TAG_SUSPENDED_APP_EXTRAS:
-                                    suspendedAppExtras = PersistableBundle.restoreFromXml(parser);
-                                    break;
-                                case TAG_SUSPENDED_LAUNCHER_EXTRAS:
-                                    suspendedLauncherExtras = PersistableBundle.restoreFromXml(
-                                            parser);
-                                    break;
                                 case TAG_SUSPENDED_DIALOG_INFO:
                                     oldSuspendDialogInfo = SuspendDialogInfo.restoreFromXml(parser);
                                     break;
+                                case TAG_SUSPENDED_APP_EXTRAS:
+                                    oldSuspendedAppExtras = PersistableBundle.restoreFromXml(
+                                            parser);
+                                    break;
+                                case TAG_SUSPENDED_LAUNCHER_EXTRAS:
+                                    oldSuspendedLauncherExtras = PersistableBundle.restoreFromXml(
+                                            parser);
+                                    break;
                                 case TAG_SUSPEND_PARAMS:
                                     final String suspendingPackage = parser.getAttributeValue(null,
                                             ATTR_SUSPENDING_PACKAGE);
@@ -1979,8 +1980,9 @@
                         if (suspended && suspendParamsMap == null) {
                             final SuspendParams suspendParams = new SuspendParams(
                                     oldSuspendDialogInfo,
-                                    suspendedAppExtras,
-                                    suspendedLauncherExtras);
+                                    oldSuspendedAppExtras,
+                                    oldSuspendedLauncherExtras,
+                                    false /* quarantined */);
                             suspendParamsMap = new ArrayMap<>();
                             suspendParamsMap.put(oldSuspendingPackage, suspendParams);
                         }
@@ -1989,13 +1991,12 @@
                             setBlockUninstallLPw(userId, name, true);
                         }
                         ps.setUserState(userId, ceDataInode, enabled, installed, stopped,
-                                notLaunched,
-                                hidden, distractionFlags, suspendParamsMap, instantApp,
-                                virtualPreload,
-                                enabledCaller, enabledComponents, disabledComponents, installReason,
-                                uninstallReason, harmfulAppWarning, splashScreenTheme,
-                                firstInstallTime != 0 ? firstInstallTime :
-                                        origFirstInstallTimes.getOrDefault(name, 0L),
+                                notLaunched, hidden, distractionFlags, suspendParamsMap, instantApp,
+                                virtualPreload, enabledCaller, enabledComponents,
+                                disabledComponents, installReason, uninstallReason,
+                                harmfulAppWarning, splashScreenTheme,
+                                firstInstallTime != 0 ? firstInstallTime
+                                        : origFirstInstallTimes.getOrDefault(name, 0L),
                                 minAspectRatio, archiveState);
 
                         mDomainVerificationManager.setLegacyUserState(name, userId, verifState);
@@ -2914,29 +2915,28 @@
             FileUtils.setPermissions(fstr.getFD(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
 
             StringBuilder sb = new StringBuilder();
-            for (final PackageSetting pkg : mPackages.values()) {
+            for (final PackageSetting ps : mPackages.values()) {
                 // TODO(b/135203078): This doesn't handle multiple users
-                final String dataPath = pkg.getPkg() == null ? null :
-                        PackageInfoUtils.getDataDir(pkg.getPkg(), UserHandle.USER_SYSTEM)
-                                .getAbsolutePath();
+                final String dataPath = PackageInfoUtils.getDataDir(ps, UserHandle.USER_SYSTEM)
+                        .getAbsolutePath();
 
-                if (pkg.getPkg() == null || dataPath == null) {
-                    if (!"android".equals(pkg.getPackageName())) {
-                        Slog.w(TAG, "Skipping " + pkg + " due to missing metadata");
+                if (ps.getPkg() == null || dataPath == null) {
+                    if (!"android".equals(ps.getPackageName())) {
+                        Slog.w(TAG, "Skipping " + ps + " due to missing metadata");
                     }
                     continue;
                 }
-                if (pkg.getPkg().isApex()) {
+                if (ps.getPkg().isApex()) {
                     // Don't persist APEX which doesn't have a valid app id and will cause parsing
                     // error in libpackagelistparser
                     continue;
                 }
 
-                final boolean isDebug = pkg.getPkg().isDebuggable();
+                final boolean isDebug = ps.getPkg().isDebuggable();
                 final IntArray gids = new IntArray();
                 for (final int userId : userIds) {
                     gids.addAll(mPermissionDataProvider.getGidsForUid(UserHandle.getUid(userId,
-                            pkg.getAppId())));
+                            ps.getAppId())));
                 }
 
                 // Avoid any application that has a space in its path.
@@ -2964,13 +2964,13 @@
                 //   system/core/libpackagelistparser
                 //
                 sb.setLength(0);
-                sb.append(pkg.getPkg().getPackageName());
+                sb.append(ps.getPkg().getPackageName());
                 sb.append(" ");
-                sb.append(pkg.getPkg().getUid());
+                sb.append(ps.getPkg().getUid());
                 sb.append(isDebug ? " 1 " : " 0 ");
                 sb.append(dataPath);
                 sb.append(" ");
-                sb.append(pkg.getSeInfo());
+                sb.append(ps.getSeInfo());
                 sb.append(" ");
                 final int gidsSize = gids.size();
                 if (gids != null && gids.size() > 0) {
@@ -2983,19 +2983,19 @@
                     sb.append("none");
                 }
                 sb.append(" ");
-                sb.append(pkg.getPkg().isProfileableByShell() ? "1" : "0");
+                sb.append(ps.getPkg().isProfileableByShell() ? "1" : "0");
                 sb.append(" ");
-                sb.append(pkg.getPkg().getLongVersionCode());
+                sb.append(ps.getPkg().getLongVersionCode());
                 sb.append(" ");
-                sb.append(pkg.getPkg().isProfileable() ? "1" : "0");
+                sb.append(ps.getPkg().isProfileable() ? "1" : "0");
                 sb.append(" ");
-                if (pkg.isSystem()) {
+                if (ps.isSystem()) {
                     sb.append("@system");
-                } else if (pkg.isProduct()) {
+                } else if (ps.isProduct()) {
                     sb.append("@product");
-                } else if (pkg.getInstallSource().mInstallerPackageName != null
-                           && !pkg.getInstallSource().mInstallerPackageName.isEmpty()) {
-                    sb.append(pkg.getInstallSource().mInstallerPackageName);
+                } else if (ps.getInstallSource().mInstallerPackageName != null
+                           && !ps.getInstallSource().mInstallerPackageName.isEmpty()) {
+                    sb.append(ps.getInstallSource().mInstallerPackageName);
                 } else {
                     sb.append("@null");
                 }
@@ -3123,6 +3123,8 @@
         if (pkg.getVolumeUuid() != null) {
             serializer.attribute(null, "volumeUuid", pkg.getVolumeUuid());
         }
+        serializer.attributeBoolean(null, "defaultToDeviceProtectedStorage",
+                pkg.isDefaultToDeviceProtectedStorage());
         if (pkg.getCategoryOverride() != ApplicationInfo.CATEGORY_UNDEFINED) {
             serializer.attributeInt(null, "categoryHint", pkg.getCategoryOverride());
         }
@@ -3911,6 +3913,7 @@
         String installInitiatingPackageName = null;
         boolean installInitiatorUninstalled = false;
         String volumeUuid = null;
+        boolean defaultToDeviceProtectedStorage = false;
         boolean updateAvailable = false;
         int categoryHint = ApplicationInfo.CATEGORY_UNDEFINED;
         int pkgFlags = 0;
@@ -3960,6 +3963,8 @@
             installInitiatorUninstalled = parser.getAttributeBoolean(null,
                     "installInitiatorUninstalled", false);
             volumeUuid = parser.getAttributeValue(null, "volumeUuid");
+            defaultToDeviceProtectedStorage = parser.getAttributeBoolean(
+                    null, "defaultToDeviceProtectedStorage", false);
             categoryHint = parser.getAttributeInt(null, "categoryHint",
                     ApplicationInfo.CATEGORY_UNDEFINED);
             appMetadataFilePath = parser.getAttributeValue(null, "appMetadataFilePath");
@@ -4099,6 +4104,7 @@
                     installInitiatorUninstalled);
             packageSetting.setInstallSource(installSource)
                     .setVolumeUuid(volumeUuid)
+                    .setDefaultToDeviceProtectedStorage(defaultToDeviceProtectedStorage)
                     .setCategoryOverride(categoryHint)
                     .setLegacyNativeLibraryPath(legacyNativeLibraryPathStr)
                     .setPrimaryCpuAbi(primaryCpuAbiString)
@@ -4819,6 +4825,7 @@
                 pw.print(userState.isNotLaunched() ? "l" : "L");
                 pw.print(userState.isInstantApp() ? "IA" : "ia");
                 pw.print(userState.isVirtualPreload() ? "VPI" : "vpi");
+                pw.print(userState.isQuarantined() ? "Q" : "q");
                 String harmfulAppWarning = userState.getHarmfulAppWarning();
                 pw.print(harmfulAppWarning != null ? "HA" : "ha");
                 pw.print(",");
@@ -4886,6 +4893,8 @@
             pw.print("]");
         }
         pw.println();
+        File dataDir = PackageInfoUtils.getDataDir(ps, UserHandle.myUserId());
+        pw.print(prefix); pw.print("  dataDir="); pw.println(dataDir.getAbsolutePath());
         if (pkg != null) {
             pw.print(prefix); pw.print("  versionName="); pw.println(pkg.getVersionName());
             pw.print(prefix); pw.print("  usesNonSdkApi="); pw.println(pkg.isNonSdkApiRequested());
@@ -4917,8 +4926,6 @@
                 pw.append(prefix).append("  queriesIntents=")
                         .println(ps.getPkg().getQueriesIntents());
             }
-            File dataDir = PackageInfoUtils.getDataDir(pkg, UserHandle.myUserId());
-            pw.print(prefix); pw.print("  dataDir="); pw.println(dataDir.getAbsolutePath());
             pw.print(prefix); pw.print("  supportsScreens=[");
             boolean first = true;
             if (pkg.isSmallScreensSupported()) {
@@ -5180,6 +5187,8 @@
             pw.print(userState.isInstantApp());
             pw.print(" virtual=");
             pw.println(userState.isVirtualPreload());
+            pw.print(" quarantined=");
+            pw.print(userState.isQuarantined());
             pw.print("      installReason=");
             pw.println(userState.getInstallReason());
 
@@ -5202,6 +5211,8 @@
                     if (params != null) {
                         pw.print(" dialogInfo=");
                         pw.print(params.getDialogInfo());
+                        pw.print(" quarantined=");
+                        pw.println(params.isQuarantined());
                     }
                     pw.println();
                 }
diff --git a/services/core/java/com/android/server/pm/SuspendPackageHelper.java b/services/core/java/com/android/server/pm/SuspendPackageHelper.java
index 94e09f1..ddb045d 100644
--- a/services/core/java/com/android/server/pm/SuspendPackageHelper.java
+++ b/services/core/java/com/android/server/pm/SuspendPackageHelper.java
@@ -115,17 +115,18 @@
             boolean suspended, @Nullable PersistableBundle appExtras,
             @Nullable PersistableBundle launcherExtras, @Nullable SuspendDialogInfo dialogInfo,
             @NonNull String callingPackage, @UserIdInt int userId, int callingUid,
-            boolean forQuietMode) {
+            boolean forQuietMode, boolean quarantined) {
         if (ArrayUtils.isEmpty(packageNames)) {
             return packageNames;
         }
-        if (suspended && !forQuietMode && !isSuspendAllowedForUser(snapshot, userId, callingUid)) {
+        if (suspended && !quarantined && !forQuietMode && !isSuspendAllowedForUser(snapshot, userId,
+                callingUid)) {
             Slog.w(TAG, "Cannot suspend due to restrictions on user " + userId);
             return packageNames;
         }
 
         final SuspendParams newSuspendParams =
-                new SuspendParams(dialogInfo, appExtras, launcherExtras);
+                new SuspendParams(dialogInfo, appExtras, launcherExtras, quarantined);
 
         final List<String> unmodifiablePackages = new ArrayList<>(packageNames.length);
 
@@ -160,7 +161,6 @@
 
             final WatchedArrayMap<String, SuspendParams> suspendParamsMap =
                     packageState.getUserStateOrDefault(userId).getSuspendParams();
-
             SuspendParams oldSuspendParams = suspendParamsMap == null
                     ? null : suspendParamsMap.get(packageName);
             boolean changed = !Objects.equals(oldSuspendParams, newSuspendParams);
@@ -213,14 +213,15 @@
             sendPackagesSuspendedForUser(
                     suspended ? Intent.ACTION_PACKAGES_SUSPENDED
                             : Intent.ACTION_PACKAGES_UNSUSPENDED,
-                    changedPackages, notifyUids.toArray(), userId);
+                    changedPackages, notifyUids.toArray(), quarantined, userId);
             sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, userId);
             mPm.scheduleWritePackageRestrictions(userId);
         }
         // Send the suspension changed broadcast to ensure suspension state is not stale.
         if (!changedPackagesList.isEmpty()) {
             sendPackagesSuspendedForUser(Intent.ACTION_PACKAGES_SUSPENSION_CHANGED,
-                    changedPackagesList.toArray(new String[0]), changedUids.toArray(), userId);
+                    changedPackagesList.toArray(new String[0]), changedUids.toArray(), quarantined,
+                    userId);
         }
         return unmodifiablePackages.toArray(new String[0]);
     }
@@ -354,7 +355,7 @@
                     new String[unsuspendedPackages.size()]);
             sendMyPackageSuspendedOrUnsuspended(packageArray, false, userId);
             sendPackagesSuspendedForUser(Intent.ACTION_PACKAGES_UNSUSPENDED,
-                    packageArray, unsuspendedUids.toArray(), userId);
+                    packageArray, unsuspendedUids.toArray(), false, userId);
         }
     }
 
@@ -618,11 +619,14 @@
      */
     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
     void sendPackagesSuspendedForUser(@NonNull String intent, @NonNull String[] pkgList,
-            @NonNull int[] uidList, int userId) {
+            @NonNull int[] uidList, boolean quarantined, int userId) {
         final Handler handler = mInjector.getHandler();
         final Bundle extras = new Bundle(3);
         extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
         extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidList);
+        if (quarantined) {
+            extras.putBoolean(Intent.EXTRA_QUARANTINED, true);
+        }
         final int flags = Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND;
         final Bundle options = new BroadcastOptions()
                 .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE)
@@ -672,7 +676,7 @@
                             snapshot, toSuspend.toArray(new String[0]), suspend,
                             null /* appExtras */, null /* launcherExtras */, null /* dialogInfo */,
                             PackageManagerService.PLATFORM_PACKAGE_NAME, userId, Process.SYSTEM_UID,
-                            false /* forQuietMode */)));
+                            false /* forQuietMode */, false /* quarantined */)));
         }
         return unsuspendable.toArray(String[]::new);
     }
@@ -716,7 +720,7 @@
         setPackagesSuspended(snapshot, toSuspend.toArray(new String[0]),
                 suspend, null /* appExtras */, null /* launcherExtras */, null /* dialogInfo */,
                 PackageManagerService.PLATFORM_PACKAGE_NAME, userId, Process.SYSTEM_UID,
-                true /* forQuietMode */);
+                true /* forQuietMode */, false /* quarantined */);
     }
 
     private Set<String> packagesToSuspendInQuietMode(Computer snapshot, int userId) {
diff --git a/services/core/java/com/android/server/pm/TEST_MAPPING b/services/core/java/com/android/server/pm/TEST_MAPPING
index 4ba174d..04d1da6 100644
--- a/services/core/java/com/android/server/pm/TEST_MAPPING
+++ b/services/core/java/com/android/server/pm/TEST_MAPPING
@@ -113,6 +113,9 @@
         },
         {
           "exclude-annotation": "org.junit.Ignore"
+        },
+        {
+          "exclude-filter": "android.content.pm.cts.PackageManagerShellCommandMultiUserTest"
         }
       ]
     }
@@ -134,6 +137,14 @@
     },
     {
       "name": "CtsAppEnumerationTestCases"
+    },
+    {
+      "name": "CtsPackageManagerTestCases",
+      "options": [
+        {
+          "include-filter": "android.content.pm.cts.PackageManagerShellCommandMultiUserTest"
+        }
+      ]
     }
   ],
   "imports": [
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index ac52f9f..f2797eb 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -4882,6 +4882,7 @@
                     UserManager.USER_OPERATION_ERROR_LOW_STORAGE);
         }
 
+        final boolean isMainUser = (flags & UserInfo.FLAG_MAIN) != 0;
         final boolean isProfile = userTypeDetails.isProfile();
         final boolean isGuest = UserManager.isUserTypeGuest(userType);
         final boolean isRestricted = UserManager.isUserTypeRestricted(userType);
@@ -4906,6 +4907,11 @@
                                 USER_OPERATION_ERROR_UNKNOWN);
                     }
                 }
+                if (isMainUser && getMainUserIdUnchecked() != UserHandle.USER_NULL) {
+                    throwCheckedUserOperationException(
+                            "Cannot add user with FLAG_MAIN as main user already exists.",
+                            UserManager.USER_OPERATION_ERROR_MAX_USERS);
+                }
                 if (!preCreate && !canAddMoreUsersOfType(userTypeDetails)) {
                     throwCheckedUserOperationException(
                             "Cannot add more users of type " + userType
@@ -5028,6 +5034,10 @@
                 }
             } else {
                 userTypeDetails.addDefaultRestrictionsTo(restrictions);
+                if (isMainUser) {
+                    restrictions.remove(UserManager.DISALLOW_OUTGOING_CALLS);
+                    restrictions.remove(UserManager.DISALLOW_SMS);
+                }
             }
             synchronized (mRestrictionsLock) {
                 mBaseUserRestrictions.updateRestrictions(userId, restrictions);
diff --git a/services/core/java/com/android/server/pm/UserTypeFactory.java b/services/core/java/com/android/server/pm/UserTypeFactory.java
index f7967c0..d5231b5 100644
--- a/services/core/java/com/android/server/pm/UserTypeFactory.java
+++ b/services/core/java/com/android/server/pm/UserTypeFactory.java
@@ -295,7 +295,8 @@
                         .setMediaSharedWithParent(false)
                         .setShowInLauncher(UserProperties.SHOW_IN_LAUNCHER_SEPARATE)
                         .setCrossProfileIntentFilterAccessControl(
-                                UserProperties.CROSS_PROFILE_INTENT_FILTER_ACCESS_LEVEL_SYSTEM));
+                                UserProperties.CROSS_PROFILE_INTENT_FILTER_ACCESS_LEVEL_SYSTEM)
+                        .setInheritDevicePolicy(UserProperties.INHERIT_DEVICE_POLICY_FROM_PARENT));
     }
 
     /**
diff --git a/services/core/java/com/android/server/pm/dex/ArtManagerService.java b/services/core/java/com/android/server/pm/dex/ArtManagerService.java
index d88b66b..31856f1 100644
--- a/services/core/java/com/android/server/pm/dex/ArtManagerService.java
+++ b/services/core/java/com/android/server/pm/dex/ArtManagerService.java
@@ -61,7 +61,7 @@
 import com.android.server.pm.PackageManagerServiceUtils;
 import com.android.server.pm.parsing.PackageInfoUtils;
 import com.android.server.pm.pkg.AndroidPackage;
-import com.android.server.pm.pkg.PackageState;
+import com.android.server.pm.pkg.PackageStateInternal;
 
 import dalvik.system.DexFile;
 import dalvik.system.VMRuntime;
@@ -542,14 +542,14 @@
     /**
      * Compile layout resources in a given package.
      */
-    public boolean compileLayouts(@NonNull PackageState packageState, @NonNull AndroidPackage pkg) {
+    public boolean compileLayouts(@NonNull PackageStateInternal ps, @NonNull AndroidPackage pkg) {
         try {
             final String packageName = pkg.getPackageName();
             final String apkPath = pkg.getSplits().get(0).getPath();
             // TODO(b/143971007): Use a cross-user directory
-            File dataDir = PackageInfoUtils.getDataDir(pkg, UserHandle.myUserId());
+            File dataDir = PackageInfoUtils.getDataDir(ps, UserHandle.myUserId());
             final String outDexFile = dataDir.getAbsolutePath() + "/code_cache/compiled_view.dex";
-            if (packageState.isPrivileged() || pkg.isUseEmbeddedDex()
+            if (ps.isPrivileged() || pkg.isUseEmbeddedDex()
                     || pkg.isDefaultToDeviceProtectedStorage()) {
                 // Privileged apps prefer to load trusted code so they don't use compiled views.
                 // If the app is not privileged but prefers code integrity, also avoid compiling
diff --git a/services/core/java/com/android/server/pm/dex/ViewCompiler.java b/services/core/java/com/android/server/pm/dex/ViewCompiler.java
index 9ce648f..6405ea5 100644
--- a/services/core/java/com/android/server/pm/dex/ViewCompiler.java
+++ b/services/core/java/com/android/server/pm/dex/ViewCompiler.java
@@ -23,7 +23,7 @@
 import com.android.internal.annotations.GuardedBy;
 import com.android.server.pm.Installer;
 import com.android.server.pm.parsing.PackageInfoUtils;
-import com.android.server.pm.pkg.AndroidPackage;
+import com.android.server.pm.pkg.PackageStateInternal;
 
 import java.io.File;
 
@@ -37,12 +37,11 @@
         mInstaller = installer;
     }
 
-    public boolean compileLayouts(AndroidPackage pkg) {
+    public boolean compileLayouts(PackageStateInternal ps, String apkPath) {
         try {
-            final String packageName = pkg.getPackageName();
-            final String apkPath = pkg.getBaseApkPath();
+            final String packageName = ps.getPackageName();
             // TODO(b/143971007): Use a cross-user directory
-            File dataDir = PackageInfoUtils.getDataDir(pkg, UserHandle.myUserId());
+            File dataDir = PackageInfoUtils.getDataDir(ps, UserHandle.myUserId());
             final String outDexFile = dataDir.getAbsolutePath() + "/code_cache/compiled_view.dex";
             Log.i("PackageManager", "Compiling layouts in " + packageName + " (" + apkPath +
                 ") to " + outDexFile);
@@ -50,7 +49,7 @@
             try {
                 synchronized (mInstallLock) {
                     return mInstaller.compileLayouts(apkPath, packageName, outDexFile,
-                        pkg.getUid());
+                        ps.getAppId());
                 }
             } finally {
                 Binder.restoreCallingIdentity(callingId);
diff --git a/services/core/java/com/android/server/pm/flags.aconfig b/services/core/java/com/android/server/pm/flags.aconfig
new file mode 100644
index 0000000..368a843
--- /dev/null
+++ b/services/core/java/com/android/server/pm/flags.aconfig
@@ -0,0 +1,8 @@
+package: "com.android.server.pm"
+
+flag {
+    name: "quarantined_enabled"
+    namespace: "package_manager_service"
+    description: "Feature flag for Quarantined state"
+    bug: "269127435"
+}
diff --git a/services/core/java/com/android/server/pm/parsing/PackageInfoUtils.java b/services/core/java/com/android/server/pm/parsing/PackageInfoUtils.java
index d55f85c..27812df 100644
--- a/services/core/java/com/android/server/pm/parsing/PackageInfoUtils.java
+++ b/services/core/java/com/android/server/pm/parsing/PackageInfoUtils.java
@@ -379,7 +379,10 @@
                 | flag(state.isVirtualPreload(), ApplicationInfo.PRIVATE_FLAG_VIRTUAL_PRELOAD)
                 | flag(state.isHidden(), ApplicationInfo.PRIVATE_FLAG_HIDDEN);
 
-        if (state.getEnabledState() == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
+        if ((flags & PackageManager.FILTER_OUT_QUARANTINED_COMPONENTS) != 0
+                && state.isQuarantined()) {
+            ai.enabled = false;
+        } else  if (state.getEnabledState() == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
             ai.enabled = true;
         } else if (state.getEnabledState()
                 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
@@ -1082,18 +1085,18 @@
     }
 
     @NonNull
-    public static File getDataDir(AndroidPackage pkg, int userId) {
-        if ("android".equals(pkg.getPackageName())) {
+    public static File getDataDir(PackageStateInternal ps, int userId) {
+        if ("android".equals(ps.getPackageName())) {
             return Environment.getDataSystemDirectory();
         }
 
-        if (pkg.isDefaultToDeviceProtectedStorage()
+        if (ps.isDefaultToDeviceProtectedStorage()
                 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
-            return Environment.getDataUserDePackageDirectory(pkg.getVolumeUuid(), userId,
-                    pkg.getPackageName());
+            return Environment.getDataUserDePackageDirectory(ps.getVolumeUuid(), userId,
+                    ps.getPackageName());
         } else {
-            return Environment.getDataUserCePackageDirectory(pkg.getVolumeUuid(), userId,
-                    pkg.getPackageName());
+            return Environment.getDataUserCePackageDirectory(ps.getVolumeUuid(), userId,
+                    ps.getPackageName());
         }
     }
 
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 7897195..b01a89e 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
@@ -72,7 +72,6 @@
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.Preconditions;
-import com.android.internal.util.function.QuadFunction;
 import com.android.internal.util.function.TriFunction;
 import com.android.server.LocalServices;
 import com.android.server.pm.UserManagerInternal;
@@ -94,6 +93,7 @@
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiFunction;
 
 /**
  * Manages all permissions and handles permissions related tasks.
@@ -233,11 +233,11 @@
         }
 
         if (checkPermissionDelegate == null) {
-            return mPermissionManagerServiceImpl.checkPermission(packageName, permissionName,
-                    deviceId, userId);
+            return mPermissionManagerServiceImpl.checkPermission(
+                    packageName, permissionName, userId);
         }
-        return checkPermissionDelegate.checkPermission(packageName, permissionName,
-                deviceId, userId, mPermissionManagerServiceImpl::checkPermission);
+        return checkPermissionDelegate.checkPermission(packageName, permissionName, userId,
+                mPermissionManagerServiceImpl::checkPermission);
     }
 
     @Override
@@ -254,10 +254,10 @@
         }
 
         if (checkPermissionDelegate == null)  {
-            return mPermissionManagerServiceImpl.checkUidPermission(uid, permissionName, deviceId);
+            return mPermissionManagerServiceImpl.checkUidPermission(uid, permissionName);
         }
         return checkPermissionDelegate.checkUidPermission(uid, permissionName,
-                deviceId, mPermissionManagerServiceImpl::checkUidPermission);
+                mPermissionManagerServiceImpl::checkUidPermission);
     }
 
     @Override
@@ -511,14 +511,14 @@
     public int getPermissionFlags(String packageName, String permissionName, int deviceId,
             int userId) {
         return mPermissionManagerServiceImpl
-                .getPermissionFlags(packageName, permissionName, deviceId, userId);
+                .getPermissionFlags(packageName, permissionName, userId);
     }
 
     @Override
     public void updatePermissionFlags(String packageName, String permissionName, int flagMask,
             int flagValues, boolean checkAdjustPolicyFlagPermission, int deviceId, int userId) {
         mPermissionManagerServiceImpl.updatePermissionFlags(packageName, permissionName, flagMask,
-                flagValues, checkAdjustPolicyFlagPermission, deviceId, userId);
+                flagValues, checkAdjustPolicyFlagPermission, userId);
     }
 
     @Override
@@ -560,15 +560,14 @@
     @Override
     public void grantRuntimePermission(String packageName, String permissionName, int deviceId,
             int userId) {
-        mPermissionManagerServiceImpl.grantRuntimePermission(packageName, permissionName,
-                deviceId, userId);
+        mPermissionManagerServiceImpl.grantRuntimePermission(packageName, permissionName, userId);
     }
 
     @Override
     public void revokeRuntimePermission(String packageName, String permissionName, int deviceId,
             int userId, String reason) {
         mPermissionManagerServiceImpl.revokeRuntimePermission(packageName, permissionName,
-                deviceId, userId, reason);
+                userId, reason);
     }
 
     @Override
@@ -581,14 +580,14 @@
     public boolean shouldShowRequestPermissionRationale(String packageName, String permissionName,
             int deviceId, int userId) {
         return mPermissionManagerServiceImpl.shouldShowRequestPermissionRationale(packageName,
-                permissionName, deviceId, userId);
+                permissionName, userId);
     }
 
     @Override
     public boolean isPermissionRevokedByPolicy(String packageName, String permissionName,
             int deviceId, int userId) {
-        return mPermissionManagerServiceImpl.isPermissionRevokedByPolicy(packageName,
-                permissionName, deviceId, userId);
+        return mPermissionManagerServiceImpl
+                .isPermissionRevokedByPolicy(packageName, permissionName, userId);
     }
 
     @Override
@@ -869,7 +868,6 @@
          *
          * @param packageName the name of the package to be checked
          * @param permissionName the name of the permission to be checked
-         * @param deviceId The device ID
          * @param userId the user ID
          * @param superImpl the original implementation that can be delegated to
          * @return {@link android.content.pm.PackageManager#PERMISSION_GRANTED} if the package has
@@ -878,21 +876,20 @@
          * @see android.content.pm.PackageManager#checkPermission(String, String)
          */
         int checkPermission(@NonNull String packageName, @NonNull String permissionName,
-                int deviceId, @UserIdInt int userId,
-                @NonNull QuadFunction<String, String, Integer, Integer, Integer> superImpl);
+                @UserIdInt int userId,
+                @NonNull TriFunction<String, String, Integer, Integer> superImpl);
 
         /**
          * Check whether the given UID has been granted the specified permission.
          *
          * @param uid the UID to be checked
          * @param permissionName the name of the permission to be checked
-         * @param deviceId The device ID
          * @param superImpl the original implementation that can be delegated to
          * @return {@link android.content.pm.PackageManager#PERMISSION_GRANTED} if the package has
          * the permission, or {@link android.content.pm.PackageManager#PERMISSION_DENIED} otherwise
          */
-        int checkUidPermission(int uid, @NonNull String permissionName, int deviceId,
-                TriFunction<Integer, String, Integer, Integer> superImpl);
+        int checkUidPermission(int uid, @NonNull String permissionName,
+                BiFunction<Integer, String, Integer> superImpl);
 
         /**
          * @return list of delegated permissions
@@ -921,32 +918,31 @@
 
         @Override
         public int checkPermission(@NonNull String packageName, @NonNull String permissionName,
-                int deviceId, int userId,
-                @NonNull QuadFunction<String, String, Integer, Integer, Integer> superImpl) {
+                int userId, @NonNull TriFunction<String, String, Integer, Integer> superImpl) {
             if (mDelegatedPackageName.equals(packageName)
                     && isDelegatedPermission(permissionName)) {
                 final long identity = Binder.clearCallingIdentity();
                 try {
-                    return superImpl.apply("com.android.shell", permissionName, deviceId, userId);
+                    return superImpl.apply("com.android.shell", permissionName, userId);
                 } finally {
                     Binder.restoreCallingIdentity(identity);
                 }
             }
-            return superImpl.apply(packageName, permissionName, deviceId, userId);
+            return superImpl.apply(packageName, permissionName, userId);
         }
 
         @Override
-        public int checkUidPermission(int uid, @NonNull String permissionName, int deviceId,
-                @NonNull TriFunction<Integer, String, Integer, Integer> superImpl) {
+        public int checkUidPermission(int uid, @NonNull String permissionName,
+                @NonNull BiFunction<Integer, String, Integer> superImpl) {
             if (uid == mDelegatedUid && isDelegatedPermission(permissionName)) {
                 final long identity = Binder.clearCallingIdentity();
                 try {
-                    return superImpl.apply(Process.SHELL_UID, permissionName, deviceId);
+                    return superImpl.apply(Process.SHELL_UID, permissionName);
                 } finally {
                     Binder.restoreCallingIdentity(identity);
                 }
             }
-            return superImpl.apply(uid, permissionName, deviceId);
+            return superImpl.apply(uid, permissionName);
         }
 
         @Override
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
index 6764e08..4353c57 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
@@ -681,7 +681,7 @@
     }
 
     @Override
-    public int getPermissionFlags(String packageName, String permName, int deviceId, int userId) {
+    public int getPermissionFlags(String packageName, String permName, int userId) {
         final int callingUid = Binder.getCallingUid();
         return getPermissionFlagsInternal(packageName, permName, callingUid, userId);
     }
@@ -724,7 +724,7 @@
 
     @Override
     public void updatePermissionFlags(String packageName, String permName, int flagMask,
-            int flagValues, boolean checkAdjustPolicyFlagPermission, int deviceId, int userId) {
+            int flagValues, boolean checkAdjustPolicyFlagPermission, int userId) {
         final int callingUid = Binder.getCallingUid();
         boolean overridePolicy = false;
 
@@ -908,12 +908,8 @@
         }
     }
 
-    private int checkPermission(String pkgName, String permName, int userId) {
-        return checkPermission(pkgName, permName, Context.DEVICE_ID_DEFAULT, userId);
-    }
-
     @Override
-    public int checkPermission(String pkgName, String permName, int deviceId, int userId) {
+    public int checkPermission(String pkgName, String permName, int userId) {
         if (!mUserManagerInt.exists(userId)) {
             return PackageManager.PERMISSION_DENIED;
         }
@@ -979,12 +975,8 @@
         return true;
     }
 
-    private int checkUidPermission(int uid, String permName) {
-        return checkUidPermission(uid, permName, Context.DEVICE_ID_DEFAULT);
-    }
-
     @Override
-    public int checkUidPermission(int uid, String permName, int deviceId) {
+    public int checkUidPermission(int uid, String permName) {
         final int userId = UserHandle.getUserId(uid);
         if (!mUserManagerInt.exists(userId)) {
             return PackageManager.PERMISSION_DENIED;
@@ -1303,8 +1295,7 @@
     }
 
     @Override
-    public void grantRuntimePermission(String packageName, String permName, int deviceId,
-            int userId) {
+    public void grantRuntimePermission(String packageName, String permName, final int userId) {
         final int callingUid = Binder.getCallingUid();
         final boolean overridePolicy =
                 checkUidPermission(callingUid, ADJUST_RUNTIME_PERMISSIONS_POLICY)
@@ -1477,11 +1468,11 @@
     }
 
     @Override
-    public void revokeRuntimePermission(String packageName, String permName, int deviceId,
-            int userId, String reason) {
+    public void revokeRuntimePermission(String packageName, String permName, int userId,
+            String reason) {
         final int callingUid = Binder.getCallingUid();
         final boolean overridePolicy =
-                checkUidPermission(callingUid, ADJUST_RUNTIME_PERMISSIONS_POLICY, deviceId)
+                checkUidPermission(callingUid, ADJUST_RUNTIME_PERMISSIONS_POLICY)
                         == PackageManager.PERMISSION_GRANTED;
 
         revokeRuntimePermissionInternal(packageName, permName, overridePolicy, callingUid, userId,
@@ -1868,7 +1859,7 @@
 
     @Override
     public boolean shouldShowRequestPermissionRationale(String packageName, String permName,
-            int deviceId, @UserIdInt int userId) {
+            @UserIdInt int userId) {
         final int callingUid = Binder.getCallingUid();
         if (UserHandle.getCallingUserId() != userId) {
             mContext.enforceCallingPermission(
@@ -1931,8 +1922,7 @@
     }
 
     @Override
-    public boolean isPermissionRevokedByPolicy(String packageName, String permName, int deviceId,
-            int userId) {
+    public boolean isPermissionRevokedByPolicy(String packageName, String permName, int userId) {
         if (UserHandle.getCallingUserId() != userId) {
             mContext.enforceCallingPermission(
                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
@@ -2069,8 +2059,8 @@
                     continue;
                 }
                 boolean isSystemOrPolicyFixed = (getPermissionFlags(newPackage.getPackageName(),
-                        permInfo.name, Context.DEVICE_ID_DEFAULT, userId) & (
-                        FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_POLICY_FIXED)) != 0;
+                        permInfo.name, userId) & (FLAG_PERMISSION_SYSTEM_FIXED
+                        | FLAG_PERMISSION_POLICY_FIXED)) != 0;
                 if (isSystemOrPolicyFixed) {
                     continue;
                 }
@@ -2236,8 +2226,7 @@
                 for (final int userId : userIds) {
                     final int permissionState = checkPermission(packageName, permName,
                             userId);
-                    final int flags = getPermissionFlags(packageName, permName,
-                            Context.DEVICE_ID_DEFAULT, userId);
+                    final int flags = getPermissionFlags(packageName, permName, userId);
                     final int flagMask = FLAG_PERMISSION_SYSTEM_FIXED
                             | FLAG_PERMISSION_POLICY_FIXED
                             | FLAG_PERMISSION_GRANTED_BY_DEFAULT
@@ -5133,7 +5122,8 @@
 
     @NonNull
     @Override
-    public Set<String> getGrantedPermissions(@NonNull String packageName, @UserIdInt int userId) {
+    public Set<String> getGrantedPermissions(@NonNull String packageName,
+            @UserIdInt int userId) {
         Objects.requireNonNull(packageName, "packageName");
         Preconditions.checkArgumentNonNegative(userId, "userId");
         return getGrantedPermissionsInternal(packageName, userId);
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInterface.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInterface.java
index 2d824aa..128f847 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInterface.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInterface.java
@@ -25,6 +25,7 @@
 import android.content.pm.PermissionInfo;
 import android.content.pm.permission.SplitPermissionInfoParcelable;
 import android.permission.IOnPermissionsChangeListener;
+import android.permission.PermissionManager;
 import android.permission.PermissionManagerInternal;
 
 import com.android.server.pm.pkg.AndroidPackage;
@@ -136,16 +137,14 @@
     void removePermission(String permName);
 
     /**
-     * Gets the permission state flags associated with a permission.
+     * Gets the state flags associated with a permission.
      *
      * @param packageName the package name for which to get the flags
      * @param permName the permission for which to get the flags
-     * @param deviceId The device for which to get the flags
      * @param userId the user for which to get permission flags
      * @return the permission flags
      */
-    int getPermissionFlags(String packageName, String permName, int deviceId,
-            @UserIdInt int userId);
+    int getPermissionFlags(String packageName, String permName, int userId);
 
     /**
      * Updates the flags associated with a permission by replacing the flags in the specified mask
@@ -155,11 +154,10 @@
      * @param permName The permission for which to update the flags
      * @param flagMask The flags which to replace
      * @param flagValues The flags with which to replace
-     * @param deviceId The device for which to update the permission flags
      * @param userId The user for which to update the permission flags
      */
-    void updatePermissionFlags(String packageName, String permName, int flagMask, int flagValues,
-            boolean checkAdjustPolicyFlagPermission, int deviceId, @UserIdInt int userId);
+    void updatePermissionFlags(String packageName, String permName, int flagMask,
+            int flagValues, boolean checkAdjustPolicyFlagPermission, int userId);
 
     /**
      * Update the permission flags for all packages and runtime permissions of a user in order
@@ -293,13 +291,11 @@
      *
      * @param packageName the package to which to grant the permission
      * @param permName the permission name to grant
-     * @param deviceId the device for which to grant the permission
      * @param userId the user for which to grant the permission
      *
-     * @see #revokeRuntimePermission(String, String, int, int, String)
+     * @see #revokeRuntimePermission(String, String, android.os.UserHandle, String)
      */
-    void grantRuntimePermission(String packageName, String permName, int deviceId,
-            @UserIdInt int userId);
+    void grantRuntimePermission(String packageName, String permName, int userId);
 
     /**
      * Revoke a runtime permission that was previously granted by
@@ -314,14 +310,13 @@
      *
      * @param packageName the package from which to revoke the permission
      * @param permName the permission name to revoke
-     * @param deviceId the device for which to revoke the permission
      * @param userId the user for which to revoke the permission
      * @param reason the reason for the revoke, or {@code null} for unspecified
      *
-     * @see #grantRuntimePermission(String, String, int, int)
+     * @see #grantRuntimePermission(String, String, android.os.UserHandle)
      */
-    void revokeRuntimePermission(String packageName, String permName, int deviceId,
-            @UserIdInt int userId, String reason);
+    void revokeRuntimePermission(String packageName, String permName, int userId,
+            String reason);
 
     /**
      * Revoke the POST_NOTIFICATIONS permission, without killing the app. This method must ONLY BE
@@ -338,29 +333,24 @@
      * does not clearly communicate to the user what would be the benefit from grating this
      * permission.
      *
-     * @param packageName the package name
      * @param permName a permission your app wants to request
-     * @param deviceId the device for which to check the permission
-     * @param userId the user for which to check the permission
      * @return whether you can show permission rationale UI
      */
     boolean shouldShowRequestPermissionRationale(String packageName, String permName,
-            int deviceId, @UserIdInt int userId);
+            @UserIdInt int userId);
 
     /**
-     * Checks whether a particular permission has been revoked for a package by policy. Typically,
+     * Checks whether a particular permissions has been revoked for a package by policy. Typically
      * the device owner or the profile owner may apply such a policy. The user cannot grant policy
      * revoked permissions, hence the only way for an app to get such a permission is by a policy
      * change.
      *
      * @param packageName the name of the package you are checking against
      * @param permName the name of the permission you are checking for
-     * @param deviceId the device for which you are checking the permission
-     * @param userId the device for which you are checking the permission
+     *
      * @return whether the permission is restricted by policy
      */
-    boolean isPermissionRevokedByPolicy(String packageName, String permName, int deviceId,
-            @UserIdInt int userId);
+    boolean isPermissionRevokedByPolicy(String packageName, String permName, int userId);
 
     /**
      * Get set of permissions that have been split into more granular or dependent permissions.
@@ -383,25 +373,14 @@
     List<SplitPermissionInfoParcelable> getSplitPermissions();
 
     /**
-     * Check whether a permission is granted or not to a package.
-     *
-     * @param pkgName package name
-     * @param permName permission name
-     * @param deviceId device ID
-     * @param userId user ID
-     * @return permission result {@link PackageManager.PermissionResult}
+     * TODO:theianchen add doc describing this is the old checkPermissionImpl
      */
-    int checkPermission(String pkgName, String permName, int deviceId, @UserIdInt int userId);
+    int checkPermission(String pkgName, String permName, int userId);
 
     /**
-     * Check whether a permission is granted or not to an UID.
-     *
-     * @param uid UID
-     * @param permName permission name
-     * @param deviceId device ID
-     * @return permission result {@link PackageManager.PermissionResult}
+     * TODO:theianchen add doc describing this is the old checkUidPermissionImpl
      */
-    int checkUidPermission(int uid, String permName, int deviceId);
+    int checkUidPermission(int uid, String permName);
 
     /**
      * Get all the package names requesting app op permissions.
@@ -421,11 +400,15 @@
             @UserIdInt int userId);
 
     /**
-     * Reset the runtime permission state changes for a package for all devices.
+     * Reset the runtime permission state changes for a package.
      *
      * TODO(zhanghai): Turn this into package change callback?
+     *
+     * @param pkg the package
+     * @param userId the user ID
      */
-    void resetRuntimePermissions(@NonNull AndroidPackage pkg, @UserIdInt int userId);
+    void resetRuntimePermissions(@NonNull AndroidPackage pkg,
+            @UserIdInt int userId);
 
     /**
      * Reset the runtime permission state changes for all packages in a user.
@@ -466,8 +449,8 @@
     /**
      * Get all the permissions granted to a package.
      *
-     * @param packageName package name
-     * @param userId user ID
+     * @param packageName the name of the package
+     * @param userId the user ID
      * @return the names of the granted permissions
      */
     @NonNull
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceLoggingDecorator.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceLoggingDecorator.java
index dacb8c6..7f98e21 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceLoggingDecorator.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceLoggingDecorator.java
@@ -120,21 +120,21 @@
     }
 
     @Override
-    public int getPermissionFlags(String packageName, String permName, int deviceId, int userId) {
+    public int getPermissionFlags(String packageName, String permName, int userId) {
         Log.i(LOG_TAG, "getPermissionFlags(packageName = " + packageName + ", permName = "
-                + permName + ", deviceId = " + deviceId +  ", userId = " + userId + ")");
-        return mService.getPermissionFlags(packageName, permName, deviceId, userId);
+                + permName + ", userId = " + userId + ")");
+        return mService.getPermissionFlags(packageName, permName, userId);
     }
 
     @Override
     public void updatePermissionFlags(String packageName, String permName, int flagMask,
-            int flagValues, boolean checkAdjustPolicyFlagPermission, int deviceId, int userId) {
+            int flagValues, boolean checkAdjustPolicyFlagPermission, int userId) {
         Log.i(LOG_TAG, "updatePermissionFlags(packageName = " + packageName + ", permName = "
                 + permName + ", flagMask = " + flagMask + ", flagValues = " + flagValues
                 + ", checkAdjustPolicyFlagPermission = " + checkAdjustPolicyFlagPermission
-                + ", deviceId = " + deviceId + ", userId = " + userId + ")");
+                + ", userId = " + userId + ")");
         mService.updatePermissionFlags(packageName, permName, flagMask, flagValues,
-                checkAdjustPolicyFlagPermission, deviceId, userId);
+                checkAdjustPolicyFlagPermission, userId);
     }
 
     @Override
@@ -182,20 +182,18 @@
     }
 
     @Override
-    public void grantRuntimePermission(String packageName, String permName, int deviceId,
-            int userId) {
+    public void grantRuntimePermission(String packageName, String permName, int userId) {
         Log.i(LOG_TAG, "grantRuntimePermission(packageName = " + packageName + ", permName = "
-                + permName + ", deviceId = " + deviceId + ", userId = " + userId + ")");
-        mService.grantRuntimePermission(packageName, permName, deviceId, userId);
+                + permName + ", userId = " + userId + ")");
+        mService.grantRuntimePermission(packageName, permName, userId);
     }
 
     @Override
-    public void revokeRuntimePermission(String packageName, String permName, int deviceId,
-            int userId, String reason) {
+    public void revokeRuntimePermission(String packageName, String permName, int userId,
+            String reason) {
         Log.i(LOG_TAG, "revokeRuntimePermission(packageName = " + packageName + ", permName = "
-                + permName + ", deviceId = " + deviceId + ", userId = " + userId
-                + ", reason = " + reason + ")");
-        mService.revokeRuntimePermission(packageName, permName, deviceId, userId, reason);
+                + permName + ", userId = " + userId + ", reason = " + reason + ")");
+        mService.revokeRuntimePermission(packageName, permName, userId, reason);
     }
 
     @Override
@@ -207,20 +205,17 @@
 
     @Override
     public boolean shouldShowRequestPermissionRationale(String packageName, String permName,
-            int deviceId, int userId) {
+            int userId) {
         Log.i(LOG_TAG, "shouldShowRequestPermissionRationale(packageName = " + packageName
-                + ", permName = " + permName + ", deviceId = " + deviceId
-                +  ", userId = " + userId + ")");
-        return mService.shouldShowRequestPermissionRationale(packageName, permName, deviceId,
-                userId);
+                + ", permName = " + permName + ", userId = " + userId + ")");
+        return mService.shouldShowRequestPermissionRationale(packageName, permName, userId);
     }
 
     @Override
-    public boolean isPermissionRevokedByPolicy(String packageName, String permName, int deviceId,
-            int userId) {
+    public boolean isPermissionRevokedByPolicy(String packageName, String permName, int userId) {
         Log.i(LOG_TAG, "isPermissionRevokedByPolicy(packageName = " + packageName + ", permName = "
-                + permName + ", deviceId = " + deviceId + ", userId = " + userId + ")");
-        return mService.isPermissionRevokedByPolicy(packageName, permName, deviceId, userId);
+                + permName + ", userId = " + userId + ")");
+        return mService.isPermissionRevokedByPolicy(packageName, permName, userId);
     }
 
     @Override
@@ -230,17 +225,16 @@
     }
 
     @Override
-    public int checkPermission(String pkgName, String permName, int deviceId, int userId) {
+    public int checkPermission(String pkgName, String permName, int userId) {
         Log.i(LOG_TAG, "checkPermission(pkgName = " + pkgName + ", permName = " + permName
-                + ", deviceId = " + deviceId + ", userId = " + userId + ")");
-        return mService.checkPermission(pkgName, permName, deviceId, userId);
+                + ", userId = " + userId + ")");
+        return mService.checkPermission(pkgName, permName, userId);
     }
 
     @Override
-    public int checkUidPermission(int uid, String permName, int deviceId) {
-        Log.i(LOG_TAG, "checkUidPermission(uid = " + uid + ", permName = " + permName
-                + ", deviceId = " + deviceId + ")");
-        return mService.checkUidPermission(uid, permName, deviceId);
+    public int checkUidPermission(int uid, String permName) {
+        Log.i(LOG_TAG, "checkUidPermission(uid = " + uid + ", permName = " + permName + ")");
+        return mService.checkUidPermission(uid, permName);
     }
 
     @Override
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceTestingShim.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceTestingShim.java
index 35d165b..d4c6d42 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceTestingShim.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceTestingShim.java
@@ -153,10 +153,9 @@
     }
 
     @Override
-    public int getPermissionFlags(String packageName, String permName, int deviceId,
-            @UserIdInt int userId) {
-        int oldVal = mOldImplementation.getPermissionFlags(packageName, permName, deviceId, userId);
-        int newVal = mNewImplementation.getPermissionFlags(packageName, permName, deviceId, userId);
+    public int getPermissionFlags(String packageName, String permName, int userId) {
+        int oldVal = mOldImplementation.getPermissionFlags(packageName, permName, userId);
+        int newVal = mNewImplementation.getPermissionFlags(packageName, permName, userId);
 
         if (!Objects.equals(oldVal, newVal)) {
             signalImplDifference("getPermissionFlags");
@@ -166,12 +165,11 @@
 
     @Override
     public void updatePermissionFlags(String packageName, String permName, int flagMask,
-            int flagValues, boolean checkAdjustPolicyFlagPermission, int deviceId,
-            @UserIdInt int userId) {
+            int flagValues, boolean checkAdjustPolicyFlagPermission, int userId) {
         mOldImplementation.updatePermissionFlags(packageName, permName, flagMask, flagValues,
-                checkAdjustPolicyFlagPermission, deviceId, userId);
+                checkAdjustPolicyFlagPermission, userId);
         mNewImplementation.updatePermissionFlags(packageName, permName, flagMask, flagValues,
-                checkAdjustPolicyFlagPermission, deviceId, userId);
+                checkAdjustPolicyFlagPermission, userId);
     }
 
     @Override
@@ -236,17 +234,16 @@
     }
 
     @Override
-    public void grantRuntimePermission(String packageName, String permName, int deviceId,
-            @UserIdInt int userId) {
-        mOldImplementation.grantRuntimePermission(packageName, permName, deviceId, userId);
-        mNewImplementation.grantRuntimePermission(packageName, permName, deviceId, userId);
+    public void grantRuntimePermission(String packageName, String permName, int userId) {
+        mOldImplementation.grantRuntimePermission(packageName, permName, userId);
+        mNewImplementation.grantRuntimePermission(packageName, permName, userId);
     }
 
     @Override
-    public void revokeRuntimePermission(String packageName, String permName, int deviceId,
-            @UserIdInt int userId, String reason) {
-        mOldImplementation.revokeRuntimePermission(packageName, permName, deviceId, userId, reason);
-        mNewImplementation.revokeRuntimePermission(packageName, permName, deviceId, userId, reason);
+    public void revokeRuntimePermission(String packageName, String permName, int userId,
+            String reason) {
+        mOldImplementation.grantRuntimePermission(packageName, permName, userId);
+        mNewImplementation.grantRuntimePermission(packageName, permName, userId);
     }
 
     @Override
@@ -258,11 +255,11 @@
 
     @Override
     public boolean shouldShowRequestPermissionRationale(String packageName, String permName,
-            int deviceId, @UserIdInt int userId) {
-        boolean oldVal = mOldImplementation.shouldShowRequestPermissionRationale(packageName,
-                permName, deviceId,  userId);
-        boolean newVal = mNewImplementation.shouldShowRequestPermissionRationale(packageName,
-                permName, deviceId, userId);
+            int userId) {
+        boolean oldVal = mOldImplementation
+                .shouldShowRequestPermissionRationale(packageName, permName, userId);
+        boolean newVal = mNewImplementation
+                .shouldShowRequestPermissionRationale(packageName, permName, userId);
 
         if (!Objects.equals(oldVal, newVal)) {
             signalImplDifference("shouldShowRequestPermissionRationale");
@@ -271,12 +268,11 @@
     }
 
     @Override
-    public boolean isPermissionRevokedByPolicy(String packageName, String permName, int deviceId,
-            @UserIdInt int userId) {
-        boolean oldVal = mOldImplementation.isPermissionRevokedByPolicy(packageName, permName,
-                deviceId, userId);
+    public boolean isPermissionRevokedByPolicy(String packageName, String permName, int userId) {
+        boolean oldVal = mOldImplementation
+                .isPermissionRevokedByPolicy(packageName, permName, userId);
         boolean newVal = mNewImplementation.isPermissionRevokedByPolicy(packageName, permName,
-                deviceId, userId);
+                userId);
 
         if (!Objects.equals(oldVal, newVal)) {
             signalImplDifference("isPermissionRevokedByPolicy");
@@ -296,9 +292,9 @@
     }
 
     @Override
-    public int checkPermission(String pkgName, String permName, int deviceId, int userId) {
-        int oldVal = mOldImplementation.checkPermission(pkgName, permName, deviceId, userId);
-        int newVal = mNewImplementation.checkPermission(pkgName, permName, deviceId, userId);
+    public int checkPermission(String pkgName, String permName, int userId) {
+        int oldVal = mOldImplementation.checkPermission(pkgName, permName, userId);
+        int newVal = mNewImplementation.checkPermission(pkgName, permName, userId);
 
         if (!Objects.equals(oldVal, newVal)) {
             signalImplDifference("checkPermission");
@@ -307,9 +303,9 @@
     }
 
     @Override
-    public int checkUidPermission(int uid, String permName, int deviceId) {
-        int oldVal = mOldImplementation.checkUidPermission(uid, permName, deviceId);
-        int newVal = mNewImplementation.checkUidPermission(uid, permName, deviceId);
+    public int checkUidPermission(int uid, String permName) {
+        int oldVal = mOldImplementation.checkUidPermission(uid, permName);
+        int newVal = mNewImplementation.checkUidPermission(uid, permName);
 
         if (!Objects.equals(oldVal, newVal)) {
             signalImplDifference("checkUidPermission");
@@ -376,7 +372,7 @@
 
     @NonNull
     @Override
-    public Set<String> getGrantedPermissions(@NonNull String packageName, @UserIdInt int userId) {
+    public Set<String> getGrantedPermissions(@NonNull String packageName, int userId) {
         Set<String> oldVal = mOldImplementation.getGrantedPermissions(packageName, userId);
         Set<String> newVal = mNewImplementation.getGrantedPermissions(packageName, userId);
 
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceTracingDecorator.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceTracingDecorator.java
index cbeede0..4e72fae 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceTracingDecorator.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceTracingDecorator.java
@@ -158,10 +158,10 @@
     }
 
     @Override
-    public int getPermissionFlags(String packageName, String permName, int deviceId, int userId) {
+    public int getPermissionFlags(String packageName, String permName, int userId) {
         Trace.traceBegin(TRACE_TAG, "TaggedTracingPermissionManagerServiceImpl#getPermissionFlags");
         try {
-            return mService.getPermissionFlags(packageName, permName, deviceId, userId);
+            return mService.getPermissionFlags(packageName, permName, userId);
         } finally {
             Trace.traceEnd(TRACE_TAG);
         }
@@ -169,12 +169,12 @@
 
     @Override
     public void updatePermissionFlags(String packageName, String permName, int flagMask,
-            int flagValues, boolean checkAdjustPolicyFlagPermission, int deviceId, int userId) {
+            int flagValues, boolean checkAdjustPolicyFlagPermission, int userId) {
         Trace.traceBegin(TRACE_TAG,
                 "TaggedTracingPermissionManagerServiceImpl#updatePermissionFlags");
         try {
             mService.updatePermissionFlags(packageName, permName, flagMask, flagValues,
-                    checkAdjustPolicyFlagPermission, deviceId, userId);
+                    checkAdjustPolicyFlagPermission, userId);
         } finally {
             Trace.traceEnd(TRACE_TAG);
         }
@@ -253,24 +253,23 @@
     }
 
     @Override
-    public void grantRuntimePermission(String packageName, String permName, int deviceId,
-            int userId) {
+    public void grantRuntimePermission(String packageName, String permName, int userId) {
         Trace.traceBegin(TRACE_TAG,
                 "TaggedTracingPermissionManagerServiceImpl#grantRuntimePermission");
         try {
-            mService.grantRuntimePermission(packageName, permName, deviceId, userId);
+            mService.grantRuntimePermission(packageName, permName, userId);
         } finally {
             Trace.traceEnd(TRACE_TAG);
         }
     }
 
     @Override
-    public void revokeRuntimePermission(String packageName, String permName, int deviceId,
-            int userId, String reason) {
+    public void revokeRuntimePermission(String packageName, String permName, int userId,
+            String reason) {
         Trace.traceBegin(TRACE_TAG,
                 "TaggedTracingPermissionManagerServiceImpl#revokeRuntimePermission");
         try {
-            mService.revokeRuntimePermission(packageName, permName, deviceId, userId, reason);
+            mService.revokeRuntimePermission(packageName, permName, userId, reason);
         } finally {
             Trace.traceEnd(TRACE_TAG);
         }
@@ -289,24 +288,22 @@
 
     @Override
     public boolean shouldShowRequestPermissionRationale(String packageName, String permName,
-            int deviceId, int userId) {
+            int userId) {
         Trace.traceBegin(TRACE_TAG,
                 "TaggedTracingPermissionManagerServiceImpl#shouldShowRequestPermissionRationale");
         try {
-            return mService.shouldShowRequestPermissionRationale(
-                    packageName, permName, deviceId, userId);
+            return mService.shouldShowRequestPermissionRationale(packageName, permName, userId);
         } finally {
             Trace.traceEnd(TRACE_TAG);
         }
     }
 
     @Override
-    public boolean isPermissionRevokedByPolicy(String packageName, String permName, int deviceId,
-            int userId) {
+    public boolean isPermissionRevokedByPolicy(String packageName, String permName, int userId) {
         Trace.traceBegin(TRACE_TAG,
                 "TaggedTracingPermissionManagerServiceImpl#isPermissionRevokedByPolicy");
         try {
-            return mService.isPermissionRevokedByPolicy(packageName, permName, deviceId, userId);
+            return mService.isPermissionRevokedByPolicy(packageName, permName, userId);
         } finally {
             Trace.traceEnd(TRACE_TAG);
         }
@@ -324,20 +321,20 @@
     }
 
     @Override
-    public int checkPermission(String pkgName, String permName, int deviceId, int userId) {
+    public int checkPermission(String pkgName, String permName, int userId) {
         Trace.traceBegin(TRACE_TAG, "TaggedTracingPermissionManagerServiceImpl#checkPermission");
         try {
-            return mService.checkPermission(pkgName, permName, deviceId, userId);
+            return mService.checkPermission(pkgName, permName, userId);
         } finally {
             Trace.traceEnd(TRACE_TAG);
         }
     }
 
     @Override
-    public int checkUidPermission(int uid, String permName, int deviceId) {
+    public int checkUidPermission(int uid, String permName) {
         Trace.traceBegin(TRACE_TAG, "TaggedTracingPermissionManagerServiceImpl#checkUidPermission");
         try {
-            return mService.checkUidPermission(uid, permName, deviceId);
+            return mService.checkUidPermission(uid, permName);
         } finally {
             Trace.traceEnd(TRACE_TAG);
         }
diff --git a/services/core/java/com/android/server/pm/pkg/PackageState.java b/services/core/java/com/android/server/pm/pkg/PackageState.java
index 2c37876..3f347e4 100644
--- a/services/core/java/com/android/server/pm/pkg/PackageState.java
+++ b/services/core/java/com/android/server/pm/pkg/PackageState.java
@@ -59,11 +59,6 @@
 public interface PackageState {
 
     /*
-     * Until immutability or read-only caching is enabled, {@link PackageSetting} cannot be
-     * returned directly, so {@link PackageStateImpl} is used to temporarily copy the data.
-     * This is a relatively expensive operation since it has to create an object for every package,
-     * but it's much lighter than the alternative of generating {@link PackageInfo} objects.
-     * <p>
      * TODO: Documentation
      * TODO: Currently missing, should be exposed as API?
      *   - keySetData
@@ -350,6 +345,12 @@
     String getVolumeUuid();
 
     /**
+     * @see AndroidPackage#isDefaultToDeviceProtectedStorage()
+     * @hide
+     */
+    boolean isDefaultToDeviceProtectedStorage();
+
+    /**
      * @see AndroidPackage#isExternalStorage()
      * @hide
      */
diff --git a/services/core/java/com/android/server/pm/pkg/PackageStateImpl.java b/services/core/java/com/android/server/pm/pkg/PackageStateImpl.java
deleted file mode 100644
index ba274e0..0000000
--- a/services/core/java/com/android/server/pm/pkg/PackageStateImpl.java
+++ /dev/null
@@ -1,759 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.pkg;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManagerInternal;
-import android.content.pm.SigningInfo;
-import android.content.pm.overlay.OverlayPaths;
-import android.os.UserHandle;
-import android.util.ArraySet;
-import android.util.SparseArray;
-
-import com.android.internal.util.DataClass;
-import com.android.server.pm.PackageManagerService;
-import com.android.server.pm.PackageSetting;
-import com.android.server.pm.Settings;
-
-import java.io.File;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Consumer;
-
-/**
- * Because a {@link PackageSetting} cannot be returned from {@link Settings} without holding the
- * {@link PackageManagerService#mLock}, this class serves as a memory snapshot of the state of a
- * single package, for use with {@link PackageManagerInternal#getPackageState(String)} and {@link
- * PackageManagerInternal#forEachPackageState(boolean, Consumer)}.
- *
- * @hide
- */
-@DataClass(genConstructor = false)
-@DataClass.Suppress({"mUserStates"})
-public class PackageStateImpl implements PackageState {
-
-    public static PackageState copy(@NonNull PackageStateInternal pkgSetting) {
-        return new PackageStateImpl(pkgSetting, pkgSetting.getPkg());
-    }
-
-    private static class Booleans {
-        @IntDef({
-                SYSTEM,
-                EXTERNAL_STORAGE,
-                PRIVILEGED,
-                OEM,
-                VENDOR,
-                PRODUCT,
-                SYSTEM_EXT,
-                REQUIRED_FOR_SYSTEM_USER,
-                ODM,
-                FORCE_QUERYABLE_OVERRIDE,
-                HIDDEN_UNTIL_INSTALLED,
-                INSTALL_PERMISSIONS_FIXED,
-                UPDATE_AVAILABLE,
-                UPDATED_SYSTEM_APP,
-                APK_IN_UPDATED_APEX,
-        })
-        public @interface Flags {
-        }
-
-        private static final int SYSTEM = 1;
-        private static final int EXTERNAL_STORAGE = 1 << 1;
-        private static final int PRIVILEGED = 1 << 2;
-        private static final int OEM = 1 << 3;
-        private static final int VENDOR = 1 << 4;
-        private static final int PRODUCT = 1 << 5;
-        private static final int SYSTEM_EXT = 1 << 6;
-        private static final int REQUIRED_FOR_SYSTEM_USER = 1 << 7;
-        private static final int ODM = 1 << 8;
-        private static final int FORCE_QUERYABLE_OVERRIDE = 1 << 9;
-        private static final int HIDDEN_UNTIL_INSTALLED = 1 << 10;
-        private static final int INSTALL_PERMISSIONS_FIXED = 1 << 11;
-        private static final int UPDATE_AVAILABLE = 1 << 12;
-        private static final int UPDATED_SYSTEM_APP = 1 << 13;
-        private static final int APK_IN_UPDATED_APEX = 1 << 14;
-    }
-
-    private int mBooleans;
-
-    private void setBoolean(@Booleans.Flags int flag, boolean value) {
-        if (value) {
-            mBooleans |= flag;
-        } else {
-            mBooleans &= ~flag;
-        }
-    }
-
-    private boolean getBoolean(@Booleans.Flags int flag) {
-        return (mBooleans & flag) != 0;
-    }
-
-    @Nullable
-    private final AndroidPackage mAndroidPackage;
-
-    @NonNull
-    private final String mPackageName;
-    @Nullable
-    private final String mVolumeUuid;
-    private final int mAppId;
-    private final int mCategoryOverride;
-    @Nullable
-    private final String mCpuAbiOverride;
-    @ApplicationInfo.HiddenApiEnforcementPolicy
-    private final int mHiddenApiEnforcementPolicy;
-    private final long mLastModifiedTime;
-    private final long mLastUpdateTime;
-    private final long mLongVersionCode;
-    @NonNull
-    private final Map<String, Set<String>> mMimeGroups;
-    @NonNull
-    private final File mPath;
-    @Nullable
-    private final String mPrimaryCpuAbi;
-    @Nullable
-    private final String mSecondaryCpuAbi;
-    @Nullable
-    private final String mSeInfo;
-    private final boolean mHasSharedUser;
-    private final int mSharedUserAppId;
-    @NonNull
-    private final String[] mUsesSdkLibraries;
-    @NonNull
-    private final long[] mUsesSdkLibrariesVersionsMajor;
-    @NonNull
-    private final String[] mUsesStaticLibraries;
-    @NonNull
-    private final long[] mUsesStaticLibrariesVersions;
-    @NonNull
-    private final List<SharedLibrary> mUsesLibraries;
-    @NonNull
-    private final List<String> mUsesLibraryFiles;
-    @NonNull
-    private final long[] mLastPackageUsageTime;
-    @NonNull
-    private final SigningInfo mSigningInfo;
-    @NonNull
-    private final SparseArray<PackageUserState> mUserStates;
-    @Nullable
-    private final String mApexModuleName;
-
-    private PackageStateImpl(@NonNull PackageState pkgState, @Nullable AndroidPackage pkg) {
-        mAndroidPackage = pkg;
-
-        setBoolean(Booleans.SYSTEM, pkgState.isSystem());
-        setBoolean(Booleans.EXTERNAL_STORAGE, pkgState.isExternalStorage());
-        setBoolean(Booleans.PRIVILEGED, pkgState.isPrivileged());
-        setBoolean(Booleans.OEM, pkgState.isOem());
-        setBoolean(Booleans.VENDOR, pkgState.isVendor());
-        setBoolean(Booleans.PRODUCT, pkgState.isProduct());
-        setBoolean(Booleans.SYSTEM_EXT, pkgState.isSystemExt());
-        setBoolean(Booleans.REQUIRED_FOR_SYSTEM_USER, pkgState.isRequiredForSystemUser());
-        setBoolean(Booleans.ODM, pkgState.isOdm());
-
-        mPackageName = pkgState.getPackageName();
-        mVolumeUuid = pkgState.getVolumeUuid();
-        mAppId = pkgState.getAppId();
-        mCategoryOverride = pkgState.getCategoryOverride();
-        mCpuAbiOverride = pkgState.getCpuAbiOverride();
-        mHiddenApiEnforcementPolicy = pkgState.getHiddenApiEnforcementPolicy();
-        mLastModifiedTime = pkgState.getLastModifiedTime();
-        mLastUpdateTime = pkgState.getLastUpdateTime();
-        mLongVersionCode = pkgState.getVersionCode();
-        mMimeGroups = Collections.unmodifiableMap(pkgState.getMimeGroups());
-        mPath = pkgState.getPath();
-        mPrimaryCpuAbi = pkgState.getPrimaryCpuAbi();
-        mSecondaryCpuAbi = pkgState.getSecondaryCpuAbi();
-        mSeInfo = pkgState.getSeInfo();
-        mHasSharedUser = pkgState.hasSharedUser();
-        mSharedUserAppId = pkgState.getSharedUserAppId();
-        mUsesSdkLibraries = pkgState.getUsesSdkLibraries();
-        mUsesSdkLibrariesVersionsMajor = pkgState.getUsesSdkLibrariesVersionsMajor();
-        mUsesStaticLibraries = pkgState.getUsesStaticLibraries();
-        mUsesStaticLibrariesVersions = pkgState.getUsesStaticLibrariesVersions();
-        mUsesLibraries = Collections.unmodifiableList(pkgState.getSharedLibraryDependencies());
-        mUsesLibraryFiles = Collections.unmodifiableList(pkgState.getUsesLibraryFiles());
-        setBoolean(Booleans.FORCE_QUERYABLE_OVERRIDE, pkgState.isForceQueryableOverride());
-        setBoolean(Booleans.HIDDEN_UNTIL_INSTALLED, pkgState.isHiddenUntilInstalled());
-        setBoolean(Booleans.INSTALL_PERMISSIONS_FIXED, pkgState.isInstallPermissionsFixed());
-        setBoolean(Booleans.UPDATE_AVAILABLE, pkgState.isUpdateAvailable());
-        mLastPackageUsageTime = pkgState.getLastPackageUsageTime();
-        setBoolean(Booleans.UPDATED_SYSTEM_APP, pkgState.isUpdatedSystemApp());
-        setBoolean(Booleans.APK_IN_UPDATED_APEX, pkgState.isApkInUpdatedApex());
-        mSigningInfo = pkgState.getSigningInfo();
-
-        SparseArray<? extends PackageUserState> userStates = pkgState.getUserStates();
-        int userStatesSize = userStates.size();
-        mUserStates = new SparseArray<>(userStatesSize);
-        for (int index = 0; index < userStatesSize; index++) {
-            mUserStates.put(userStates.keyAt(index),
-                    UserStateImpl.copy(userStates.valueAt(index)));
-        }
-
-        mApexModuleName = pkgState.getApexModuleName();
-    }
-
-    @NonNull
-    @Override
-    public PackageUserState getStateForUser(@NonNull UserHandle user) {
-        PackageUserState userState = getUserStates().get(user.getIdentifier());
-        return userState == null ? PackageUserState.DEFAULT : userState;
-    }
-
-    @Override
-    public boolean isExternalStorage() {
-        return getBoolean(Booleans.EXTERNAL_STORAGE);
-    }
-
-    @Override
-    public boolean isForceQueryableOverride() {
-        return getBoolean(Booleans.FORCE_QUERYABLE_OVERRIDE);
-    }
-
-    @Override
-    public boolean isHiddenUntilInstalled() {
-        return getBoolean(Booleans.HIDDEN_UNTIL_INSTALLED);
-    }
-
-    @Override
-    public boolean isInstallPermissionsFixed() {
-        return getBoolean(Booleans.INSTALL_PERMISSIONS_FIXED);
-    }
-
-    @Override
-    public boolean isOdm() {
-        return getBoolean(Booleans.ODM);
-    }
-
-    @Override
-    public boolean isOem() {
-        return getBoolean(Booleans.OEM);
-    }
-
-    @Override
-    public boolean isPrivileged() {
-        return getBoolean(Booleans.PRIVILEGED);
-    }
-
-    @Override
-    public boolean isProduct() {
-        return getBoolean(Booleans.PRODUCT);
-    }
-
-    @Override
-    public boolean isRequiredForSystemUser() {
-        return getBoolean(Booleans.REQUIRED_FOR_SYSTEM_USER);
-    }
-
-    @Override
-    public boolean isSystem() {
-        return getBoolean(Booleans.SYSTEM);
-    }
-
-    @Override
-    public boolean isSystemExt() {
-        return getBoolean(Booleans.SYSTEM_EXT);
-    }
-
-    @Override
-    public boolean isUpdateAvailable() {
-        return getBoolean(Booleans.UPDATE_AVAILABLE);
-    }
-
-    @Override
-    public boolean isUpdatedSystemApp() {
-        return getBoolean(Booleans.UPDATED_SYSTEM_APP);
-    }
-
-    @Override
-    public boolean isApkInUpdatedApex() {
-        return getBoolean(Booleans.APK_IN_UPDATED_APEX);
-    }
-
-    @Override
-    public boolean isVendor() {
-        return getBoolean(Booleans.VENDOR);
-    }
-
-    @Override
-    public long getVersionCode() {
-        return mLongVersionCode;
-    }
-
-    @Override
-    public boolean hasSharedUser() {
-        return mHasSharedUser;
-    }
-
-    @Override
-    public boolean isApex() {
-        return getAndroidPackage() != null && getAndroidPackage().isApex();
-    }
-
-    /**
-     * @hide
-     */
-    @DataClass(genConstructor = false)
-    public static class UserStateImpl implements PackageUserState {
-
-        public static PackageUserState copy(@NonNull PackageUserState state) {
-            return new UserStateImpl(state);
-        }
-
-        private static class Booleans {
-            @IntDef({
-                    HIDDEN,
-                    INSTALLED,
-                    INSTANT_APP,
-                    NOT_LAUNCHED,
-                    STOPPED,
-                    SUSPENDED,
-                    VIRTUAL_PRELOAD,
-            })
-            public @interface Flags {
-            }
-
-            private static final int HIDDEN = 1;
-            private static final int INSTALLED = 1 << 1;
-            private static final int INSTANT_APP = 1 << 2;
-            private static final int NOT_LAUNCHED = 1 << 3;
-            private static final int STOPPED = 1 << 4;
-            private static final int SUSPENDED = 1 << 5;
-            private static final int VIRTUAL_PRELOAD = 1 << 6;
-        }
-
-        private int mBooleans;
-
-        private void setBoolean(@Booleans.Flags int flag, boolean value) {
-            if (value) {
-                mBooleans |= flag;
-            } else {
-                mBooleans &= ~flag;
-            }
-        }
-
-        private boolean getBoolean(@Booleans.Flags int flag) {
-            return (mBooleans & flag) != 0;
-        }
-
-        private final long mCeDataInode;
-        @NonNull
-        private final ArraySet<String> mDisabledComponents;
-        @PackageManager.DistractionRestriction
-        private final int mDistractionFlags;
-        @NonNull
-        private final ArraySet<String> mEnabledComponents;
-        private final int mEnabledState;
-        @Nullable
-        private final String mHarmfulAppWarning;
-        @PackageManager.InstallReason
-        private final int mInstallReason;
-        @Nullable
-        private final String mLastDisableAppCaller;
-        @NonNull
-        private final OverlayPaths mOverlayPaths;
-        @NonNull
-        private final Map<String, OverlayPaths> mSharedLibraryOverlayPaths;
-        @PackageManager.UninstallReason
-        private final int mUninstallReason;
-        @Nullable
-        private final String mSplashScreenTheme;
-        @PackageManager.UserMinAspectRatio
-        private final int mMinAspectRatio;
-        private final long mFirstInstallTimeMillis;
-        @Nullable
-        private final ArchiveState mArchiveState;
-
-        private UserStateImpl(@NonNull PackageUserState userState) {
-            mCeDataInode = userState.getCeDataInode();
-            mDisabledComponents = userState.getDisabledComponents();
-            mDistractionFlags = userState.getDistractionFlags();
-            mEnabledComponents = userState.getEnabledComponents();
-            mEnabledState = userState.getEnabledState();
-            mHarmfulAppWarning = userState.getHarmfulAppWarning();
-            mInstallReason = userState.getInstallReason();
-            mLastDisableAppCaller = userState.getLastDisableAppCaller();
-            mOverlayPaths = userState.getOverlayPaths();
-            mSharedLibraryOverlayPaths = userState.getSharedLibraryOverlayPaths();
-            mUninstallReason = userState.getUninstallReason();
-            mSplashScreenTheme = userState.getSplashScreenTheme();
-            mMinAspectRatio = userState.getMinAspectRatio();
-            setBoolean(Booleans.HIDDEN, userState.isHidden());
-            setBoolean(Booleans.INSTALLED, userState.isInstalled());
-            setBoolean(Booleans.INSTANT_APP, userState.isInstantApp());
-            setBoolean(Booleans.NOT_LAUNCHED, userState.isNotLaunched());
-            setBoolean(Booleans.STOPPED, userState.isStopped());
-            setBoolean(Booleans.SUSPENDED, userState.isSuspended());
-            setBoolean(Booleans.VIRTUAL_PRELOAD, userState.isVirtualPreload());
-            mFirstInstallTimeMillis = userState.getFirstInstallTimeMillis();
-            mArchiveState = userState.getArchiveState();
-        }
-
-        @Override
-        public boolean isHidden() {
-            return getBoolean(Booleans.HIDDEN);
-        }
-
-        @Override
-        public boolean isInstalled() {
-            return getBoolean(Booleans.INSTALLED);
-        }
-
-        @Override
-        public boolean isInstantApp() {
-            return getBoolean(Booleans.INSTANT_APP);
-        }
-
-        @Override
-        public boolean isNotLaunched() {
-            return getBoolean(Booleans.NOT_LAUNCHED);
-        }
-
-        @Override
-        public boolean isStopped() {
-            return getBoolean(Booleans.STOPPED);
-        }
-
-        @Override
-        public boolean isSuspended() {
-            return getBoolean(Booleans.SUSPENDED);
-        }
-
-        @Override
-        public boolean isVirtualPreload() {
-            return getBoolean(Booleans.VIRTUAL_PRELOAD);
-        }
-
-        @Override
-        public boolean isComponentEnabled(String componentName) {
-            return mEnabledComponents.contains(componentName);
-        }
-
-        @Override
-        public boolean isComponentDisabled(String componentName) {
-            return mDisabledComponents.contains(componentName);
-        }
-
-        @Override
-        public OverlayPaths getAllOverlayPaths() {
-            if (mOverlayPaths == null && mSharedLibraryOverlayPaths == null) {
-                return null;
-            }
-            final OverlayPaths.Builder newPaths = new OverlayPaths.Builder();
-            newPaths.addAll(mOverlayPaths);
-            if (mSharedLibraryOverlayPaths != null) {
-                for (final OverlayPaths libOverlayPaths : mSharedLibraryOverlayPaths.values()) {
-                    newPaths.addAll(libOverlayPaths);
-                }
-            }
-            return newPaths.build();
-        }
-
-
-
-        // Code below generated by codegen v1.0.23.
-        //
-        // DO NOT MODIFY!
-        // CHECKSTYLE:OFF Generated code
-        //
-        // To regenerate run:
-        // $ codegen $ANDROID_BUILD_TOP/frameworks/base/services/core/java/com/android/server/pm/pkg/PackageStateImpl.java
-        //
-        // To exclude the generated code from IntelliJ auto-formatting enable (one-time):
-        //   Settings > Editor > Code Style > Formatter Control
-        //@formatter:off
-
-
-        @DataClass.Generated.Member
-        public int getBooleans() {
-            return mBooleans;
-        }
-
-        @DataClass.Generated.Member
-        public long getCeDataInode() {
-            return mCeDataInode;
-        }
-
-        @DataClass.Generated.Member
-        public @NonNull ArraySet<String> getDisabledComponents() {
-            return mDisabledComponents;
-        }
-
-        @DataClass.Generated.Member
-        public @PackageManager.DistractionRestriction int getDistractionFlags() {
-            return mDistractionFlags;
-        }
-
-        @DataClass.Generated.Member
-        public @NonNull ArraySet<String> getEnabledComponents() {
-            return mEnabledComponents;
-        }
-
-        @DataClass.Generated.Member
-        public int getEnabledState() {
-            return mEnabledState;
-        }
-
-        @DataClass.Generated.Member
-        public @Nullable String getHarmfulAppWarning() {
-            return mHarmfulAppWarning;
-        }
-
-        @DataClass.Generated.Member
-        public @PackageManager.InstallReason int getInstallReason() {
-            return mInstallReason;
-        }
-
-        @DataClass.Generated.Member
-        public @Nullable String getLastDisableAppCaller() {
-            return mLastDisableAppCaller;
-        }
-
-        @DataClass.Generated.Member
-        public @NonNull OverlayPaths getOverlayPaths() {
-            return mOverlayPaths;
-        }
-
-        @DataClass.Generated.Member
-        public @NonNull Map<String,OverlayPaths> getSharedLibraryOverlayPaths() {
-            return mSharedLibraryOverlayPaths;
-        }
-
-        @DataClass.Generated.Member
-        public @PackageManager.UninstallReason int getUninstallReason() {
-            return mUninstallReason;
-        }
-
-        @DataClass.Generated.Member
-        public @Nullable String getSplashScreenTheme() {
-            return mSplashScreenTheme;
-        }
-
-        @DataClass.Generated.Member
-        public @PackageManager.UserMinAspectRatio int getMinAspectRatio() {
-            return mMinAspectRatio;
-        }
-
-        @DataClass.Generated.Member
-        public long getFirstInstallTimeMillis() {
-            return mFirstInstallTimeMillis;
-        }
-
-        @DataClass.Generated.Member
-        public @Nullable ArchiveState getArchiveState() {
-            return mArchiveState;
-        }
-
-        @DataClass.Generated.Member
-        public @NonNull UserStateImpl setBooleans( int value) {
-            mBooleans = value;
-            return this;
-        }
-
-        @DataClass.Generated(
-                time = 1689171425723L,
-                codegenVersion = "1.0.23",
-                sourceFile = "frameworks/base/services/core/java/com/android/server/pm/pkg/PackageStateImpl.java",
-                inputSignatures = "private  int mBooleans\nprivate final  long mCeDataInode\nprivate final @android.annotation.NonNull android.util.ArraySet<java.lang.String> mDisabledComponents\nprivate final @android.content.pm.PackageManager.DistractionRestriction int mDistractionFlags\nprivate final @android.annotation.NonNull android.util.ArraySet<java.lang.String> mEnabledComponents\nprivate final  int mEnabledState\nprivate final @android.annotation.Nullable java.lang.String mHarmfulAppWarning\nprivate final @android.content.pm.PackageManager.InstallReason int mInstallReason\nprivate final @android.annotation.Nullable java.lang.String mLastDisableAppCaller\nprivate final @android.annotation.NonNull android.content.pm.overlay.OverlayPaths mOverlayPaths\nprivate final @android.annotation.NonNull java.util.Map<java.lang.String,android.content.pm.overlay.OverlayPaths> mSharedLibraryOverlayPaths\nprivate final @android.content.pm.PackageManager.UninstallReason int mUninstallReason\nprivate final @android.annotation.Nullable java.lang.String mSplashScreenTheme\nprivate final @android.content.pm.PackageManager.UserMinAspectRatio int mMinAspectRatio\nprivate final  long mFirstInstallTimeMillis\nprivate final @android.annotation.Nullable com.android.server.pm.pkg.ArchiveState mArchiveState\npublic static  com.android.server.pm.pkg.PackageUserState copy(com.android.server.pm.pkg.PackageUserState)\nprivate  void setBoolean(int,boolean)\nprivate  boolean getBoolean(int)\npublic @java.lang.Override boolean isHidden()\npublic @java.lang.Override boolean isInstalled()\npublic @java.lang.Override boolean isInstantApp()\npublic @java.lang.Override boolean isNotLaunched()\npublic @java.lang.Override boolean isStopped()\npublic @java.lang.Override boolean isSuspended()\npublic @java.lang.Override boolean isVirtualPreload()\npublic @java.lang.Override boolean isComponentEnabled(java.lang.String)\npublic @java.lang.Override boolean isComponentDisabled(java.lang.String)\npublic @java.lang.Override android.content.pm.overlay.OverlayPaths getAllOverlayPaths()\nclass UserStateImpl extends java.lang.Object implements [com.android.server.pm.pkg.PackageUserState]\nprivate static final  int HIDDEN\nprivate static final  int INSTALLED\nprivate static final  int INSTANT_APP\nprivate static final  int NOT_LAUNCHED\nprivate static final  int STOPPED\nprivate static final  int SUSPENDED\nprivate static final  int VIRTUAL_PRELOAD\nclass Booleans extends java.lang.Object implements []\n@com.android.internal.util.DataClass(genConstructor=false)")
-        @Deprecated
-        private void __metadata() {}
-
-
-        //@formatter:on
-        // End of generated code
-
-    }
-
-
-
-    // Code below generated by codegen v1.0.23.
-    //
-    // DO NOT MODIFY!
-    // CHECKSTYLE:OFF Generated code
-    //
-    // To regenerate run:
-    // $ codegen $ANDROID_BUILD_TOP/frameworks/base/services/core/java/com/android/server/pm/pkg/PackageStateImpl.java
-    //
-    // To exclude the generated code from IntelliJ auto-formatting enable (one-time):
-    //   Settings > Editor > Code Style > Formatter Control
-    //@formatter:off
-
-
-    @DataClass.Generated.Member
-    public int getBooleans() {
-        return mBooleans;
-    }
-
-    @DataClass.Generated.Member
-    public @Nullable AndroidPackage getAndroidPackage() {
-        return mAndroidPackage;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull String getPackageName() {
-        return mPackageName;
-    }
-
-    @DataClass.Generated.Member
-    public @Nullable String getVolumeUuid() {
-        return mVolumeUuid;
-    }
-
-    @DataClass.Generated.Member
-    public int getAppId() {
-        return mAppId;
-    }
-
-    @DataClass.Generated.Member
-    public int getCategoryOverride() {
-        return mCategoryOverride;
-    }
-
-    @DataClass.Generated.Member
-    public @Nullable String getCpuAbiOverride() {
-        return mCpuAbiOverride;
-    }
-
-    @DataClass.Generated.Member
-    public @ApplicationInfo.HiddenApiEnforcementPolicy int getHiddenApiEnforcementPolicy() {
-        return mHiddenApiEnforcementPolicy;
-    }
-
-    @DataClass.Generated.Member
-    public long getLastModifiedTime() {
-        return mLastModifiedTime;
-    }
-
-    @DataClass.Generated.Member
-    public long getLastUpdateTime() {
-        return mLastUpdateTime;
-    }
-
-    @DataClass.Generated.Member
-    public long getLongVersionCode() {
-        return mLongVersionCode;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull Map<String,Set<String>> getMimeGroups() {
-        return mMimeGroups;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull File getPath() {
-        return mPath;
-    }
-
-    @DataClass.Generated.Member
-    public @Nullable String getPrimaryCpuAbi() {
-        return mPrimaryCpuAbi;
-    }
-
-    @DataClass.Generated.Member
-    public @Nullable String getSecondaryCpuAbi() {
-        return mSecondaryCpuAbi;
-    }
-
-    @DataClass.Generated.Member
-    public @Nullable String getSeInfo() {
-        return mSeInfo;
-    }
-
-    @DataClass.Generated.Member
-    public boolean isHasSharedUser() {
-        return mHasSharedUser;
-    }
-
-    @DataClass.Generated.Member
-    public int getSharedUserAppId() {
-        return mSharedUserAppId;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull String[] getUsesSdkLibraries() {
-        return mUsesSdkLibraries;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull long[] getUsesSdkLibrariesVersionsMajor() {
-        return mUsesSdkLibrariesVersionsMajor;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull String[] getUsesStaticLibraries() {
-        return mUsesStaticLibraries;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull long[] getUsesStaticLibrariesVersions() {
-        return mUsesStaticLibrariesVersions;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull List<SharedLibrary> getSharedLibraryDependencies() {
-        return mUsesLibraries;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull List<String> getUsesLibraryFiles() {
-        return mUsesLibraryFiles;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull long[] getLastPackageUsageTime() {
-        return mLastPackageUsageTime;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull SigningInfo getSigningInfo() {
-        return mSigningInfo;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull SparseArray<PackageUserState> getUserStates() {
-        return mUserStates;
-    }
-
-    @DataClass.Generated.Member
-    public @Nullable String getApexModuleName() {
-        return mApexModuleName;
-    }
-
-    @DataClass.Generated.Member
-    public @NonNull PackageStateImpl setBooleans( int value) {
-        mBooleans = value;
-        return this;
-    }
-
-    @DataClass.Generated(
-            time = 1689171425753L,
-            codegenVersion = "1.0.23",
-            sourceFile = "frameworks/base/services/core/java/com/android/server/pm/pkg/PackageStateImpl.java",
-            inputSignatures = "private  int mBooleans\nprivate final @android.annotation.Nullable com.android.server.pm.pkg.AndroidPackage mAndroidPackage\nprivate final @android.annotation.NonNull java.lang.String mPackageName\nprivate final @android.annotation.Nullable java.lang.String mVolumeUuid\nprivate final  int mAppId\nprivate final  int mCategoryOverride\nprivate final @android.annotation.Nullable java.lang.String mCpuAbiOverride\nprivate final @android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy int mHiddenApiEnforcementPolicy\nprivate final  long mLastModifiedTime\nprivate final  long mLastUpdateTime\nprivate final  long mLongVersionCode\nprivate final @android.annotation.NonNull java.util.Map<java.lang.String,java.util.Set<java.lang.String>> mMimeGroups\nprivate final @android.annotation.NonNull java.io.File mPath\nprivate final @android.annotation.Nullable java.lang.String mPrimaryCpuAbi\nprivate final @android.annotation.Nullable java.lang.String mSecondaryCpuAbi\nprivate final @android.annotation.Nullable java.lang.String mSeInfo\nprivate final  boolean mHasSharedUser\nprivate final  int mSharedUserAppId\nprivate final @android.annotation.NonNull java.lang.String[] mUsesSdkLibraries\nprivate final @android.annotation.NonNull long[] mUsesSdkLibrariesVersionsMajor\nprivate final @android.annotation.NonNull java.lang.String[] mUsesStaticLibraries\nprivate final @android.annotation.NonNull long[] mUsesStaticLibrariesVersions\nprivate final @android.annotation.NonNull java.util.List<com.android.server.pm.pkg.SharedLibrary> mUsesLibraries\nprivate final @android.annotation.NonNull java.util.List<java.lang.String> mUsesLibraryFiles\nprivate final @android.annotation.NonNull long[] mLastPackageUsageTime\nprivate final @android.annotation.NonNull android.content.pm.SigningInfo mSigningInfo\nprivate final @android.annotation.NonNull android.util.SparseArray<com.android.server.pm.pkg.PackageUserState> mUserStates\nprivate final @android.annotation.Nullable java.lang.String mApexModuleName\npublic static  com.android.server.pm.pkg.PackageState copy(com.android.server.pm.pkg.PackageStateInternal)\nprivate  void setBoolean(int,boolean)\nprivate  boolean getBoolean(int)\npublic @android.annotation.NonNull @java.lang.Override com.android.server.pm.pkg.PackageUserState getStateForUser(android.os.UserHandle)\npublic @java.lang.Override boolean isExternalStorage()\npublic @java.lang.Override boolean isForceQueryableOverride()\npublic @java.lang.Override boolean isHiddenUntilInstalled()\npublic @java.lang.Override boolean isInstallPermissionsFixed()\npublic @java.lang.Override boolean isOdm()\npublic @java.lang.Override boolean isOem()\npublic @java.lang.Override boolean isPrivileged()\npublic @java.lang.Override boolean isProduct()\npublic @java.lang.Override boolean isRequiredForSystemUser()\npublic @java.lang.Override boolean isSystem()\npublic @java.lang.Override boolean isSystemExt()\npublic @java.lang.Override boolean isUpdateAvailable()\npublic @java.lang.Override boolean isUpdatedSystemApp()\npublic @java.lang.Override boolean isApkInUpdatedApex()\npublic @java.lang.Override boolean isVendor()\npublic @java.lang.Override long getVersionCode()\npublic @java.lang.Override boolean hasSharedUser()\npublic @java.lang.Override boolean isApex()\nclass PackageStateImpl extends java.lang.Object implements [com.android.server.pm.pkg.PackageState]\nprivate static final  int SYSTEM\nprivate static final  int EXTERNAL_STORAGE\nprivate static final  int PRIVILEGED\nprivate static final  int OEM\nprivate static final  int VENDOR\nprivate static final  int PRODUCT\nprivate static final  int SYSTEM_EXT\nprivate static final  int REQUIRED_FOR_SYSTEM_USER\nprivate static final  int ODM\nprivate static final  int FORCE_QUERYABLE_OVERRIDE\nprivate static final  int HIDDEN_UNTIL_INSTALLED\nprivate static final  int INSTALL_PERMISSIONS_FIXED\nprivate static final  int UPDATE_AVAILABLE\nprivate static final  int UPDATED_SYSTEM_APP\nprivate static final  int APK_IN_UPDATED_APEX\nclass Booleans extends java.lang.Object implements []\n@com.android.internal.util.DataClass(genConstructor=false)")
-    @Deprecated
-    private void __metadata() {}
-
-
-    //@formatter:on
-    // End of generated code
-
-}
diff --git a/services/core/java/com/android/server/pm/pkg/PackageUserState.java b/services/core/java/com/android/server/pm/pkg/PackageUserState.java
index 81915b4..7bc518c 100644
--- a/services/core/java/com/android/server/pm/pkg/PackageUserState.java
+++ b/services/core/java/com/android/server/pm/pkg/PackageUserState.java
@@ -209,6 +209,13 @@
     boolean isVirtualPreload();
 
     /**
+     * @return whether the package is quarantined in order to minimize ad-spam and pop ups
+     * when-not-in-use.
+     * @hide
+     */
+    boolean isQuarantined();
+
+    /**
      * The "package:type/entry" form of the theme resource ID previously set as the splash screen.
      *
      * @hide
@@ -225,6 +232,7 @@
      */
     @PackageManager.UserMinAspectRatio
     int getMinAspectRatio();
+
     /**
      * Information about the archived state of an app. Set only if an app is archived.
      *
@@ -233,4 +241,5 @@
     @Immutable.Ignore
     @Nullable
     ArchiveState getArchiveState();
+
 }
diff --git a/services/core/java/com/android/server/pm/pkg/PackageUserStateDefault.java b/services/core/java/com/android/server/pm/pkg/PackageUserStateDefault.java
index cce18a8..3534d75 100644
--- a/services/core/java/com/android/server/pm/pkg/PackageUserStateDefault.java
+++ b/services/core/java/com/android/server/pm/pkg/PackageUserStateDefault.java
@@ -129,6 +129,11 @@
         return false;
     }
 
+    @Override
+    public boolean isQuarantined() {
+        return false;
+    }
+
     @Nullable
     @Override
     public String getSplashScreenTheme() {
diff --git a/services/core/java/com/android/server/pm/pkg/PackageUserStateImpl.java b/services/core/java/com/android/server/pm/pkg/PackageUserStateImpl.java
index 6ac7c34..2349fbf 100644
--- a/services/core/java/com/android/server/pm/pkg/PackageUserStateImpl.java
+++ b/services/core/java/com/android/server/pm/pkg/PackageUserStateImpl.java
@@ -17,6 +17,7 @@
 package com.android.server.pm.pkg;
 
 import android.annotation.CurrentTimeMillisLong;
+import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.content.ComponentName;
@@ -45,9 +46,44 @@
 /** @hide */
 @DataClass(genConstructor = false, genBuilder = false, genEqualsHashCode = true)
 @DataClass.Suppress({"mOverlayPathsLock", "mOverlayPaths", "mSharedLibraryOverlayPathsLock",
-        "mSharedLibraryOverlayPaths", "setOverlayPaths", "setCachedOverlayPaths", "getWatchable"})
+        "mSharedLibraryOverlayPaths", "setOverlayPaths", "setCachedOverlayPaths", "getWatchable",
+        "getBooleans"
+})
 public class PackageUserStateImpl extends WatchableImpl implements PackageUserStateInternal,
         Snappable {
+    // Use a bitset to store boolean data to save memory
+    private static class Booleans {
+        @IntDef({
+                INSTALLED,
+                STOPPED,
+                NOT_LAUNCHED,
+                HIDDEN,
+                INSTANT_APP,
+                VIRTUAL_PRELOADED,
+        })
+        public @interface Flags {
+        }
+        private static final int INSTALLED = 1;
+        private static final int STOPPED = 1 << 1;
+        private static final int NOT_LAUNCHED = 1 << 2;
+        // Is the app restricted by owner / admin
+        private static final int HIDDEN = 1 << 3;
+        private static final int INSTANT_APP = 1 << 4;
+        private static final int VIRTUAL_PRELOADED = 1 << 5;
+    }
+    private int mBooleans;
+
+    private void setBoolean(@Booleans.Flags int flag, boolean value) {
+        if (value) {
+            mBooleans |= flag;
+        } else {
+            mBooleans &= ~flag;
+        }
+    }
+
+    private boolean getBoolean(@Booleans.Flags int flag) {
+        return (mBooleans & flag) != 0;
+    }
 
     @Nullable
     protected WatchedArraySet<String> mDisabledComponentsWatched;
@@ -55,13 +91,7 @@
     protected WatchedArraySet<String> mEnabledComponentsWatched;
 
     private long mCeDataInode;
-    private boolean mInstalled = true;
-    private boolean mStopped;
-    private boolean mNotLaunched;
-    private boolean mHidden; // Is the app restricted by owner / admin
     private int mDistractionFlags;
-    private boolean mInstantApp;
-    private boolean mVirtualPreload;
     @PackageManager.EnabledState
     private int mEnabledState = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
     @PackageManager.InstallReason
@@ -122,15 +152,18 @@
         super();
         mWatchable = null;
         mSnapshot = makeCache();
+        setBoolean(Booleans.INSTALLED, true);
     }
 
     public PackageUserStateImpl(@NonNull Watchable watchable) {
         mWatchable = watchable;
         mSnapshot = makeCache();
+        setBoolean(Booleans.INSTALLED, true);
     }
 
     public PackageUserStateImpl(@NonNull Watchable watchable, PackageUserStateImpl other) {
         mWatchable = watchable;
+        mBooleans = other.mBooleans;
         mDisabledComponentsWatched = other.mDisabledComponentsWatched == null
                 ? null : other.mDisabledComponentsWatched.snapshot();
         mEnabledComponentsWatched =  other.mEnabledComponentsWatched == null
@@ -139,13 +172,7 @@
         mSharedLibraryOverlayPaths = other.mSharedLibraryOverlayPaths == null
                 ? null : other.mSharedLibraryOverlayPaths.snapshot();
         mCeDataInode = other.mCeDataInode;
-        mInstalled = other.mInstalled;
-        mStopped = other.mStopped;
-        mNotLaunched = other.mNotLaunched;
-        mHidden = other.mHidden;
         mDistractionFlags = other.mDistractionFlags;
-        mInstantApp = other.mInstantApp;
-        mVirtualPreload = other.mVirtualPreload;
         mEnabledState = other.mEnabledState;
         mInstallReason = other.mInstallReason;
         mUninstallReason = other.mUninstallReason;
@@ -418,25 +445,25 @@
     }
 
     public @NonNull PackageUserStateImpl setInstalled(boolean value) {
-        mInstalled = value;
+        setBoolean(Booleans.INSTALLED, value);
         onChanged();
         return this;
     }
 
     public @NonNull PackageUserStateImpl setStopped(boolean value) {
-        mStopped = value;
+        setBoolean(Booleans.STOPPED, value);
         onChanged();
         return this;
     }
 
     public @NonNull PackageUserStateImpl setNotLaunched(boolean value) {
-        mNotLaunched = value;
+        setBoolean(Booleans.NOT_LAUNCHED, value);
         onChanged();
         return this;
     }
 
     public @NonNull PackageUserStateImpl setHidden(boolean value) {
-        mHidden = value;
+        setBoolean(Booleans.HIDDEN, value);
         onChanged();
         return this;
     }
@@ -448,13 +475,13 @@
     }
 
     public @NonNull PackageUserStateImpl setInstantApp(boolean value) {
-        mInstantApp = value;
+        setBoolean(Booleans.INSTANT_APP, value);
         onChanged();
         return this;
     }
 
     public @NonNull PackageUserStateImpl setVirtualPreload(boolean value) {
-        mVirtualPreload = value;
+        setBoolean(Booleans.VIRTUAL_PRELOADED, value);
         onChanged();
         return this;
     }
@@ -613,6 +640,53 @@
     }
 
 
+    @Override
+    public boolean isInstalled() {
+        return getBoolean(Booleans.INSTALLED);
+    }
+
+    @Override
+    public boolean isStopped() {
+        return getBoolean(Booleans.STOPPED);
+    }
+
+    @Override
+    public boolean isNotLaunched() {
+        return getBoolean(Booleans.NOT_LAUNCHED);
+    }
+
+    @Override
+    public boolean isHidden() {
+        return getBoolean(Booleans.HIDDEN);
+    }
+
+    @Override
+    public boolean isInstantApp() {
+        return getBoolean(Booleans.INSTANT_APP);
+    }
+
+    @Override
+    public boolean isVirtualPreload() {
+        return getBoolean(Booleans.VIRTUAL_PRELOADED);
+    }
+
+    @Override
+    public boolean isQuarantined() {
+        if (!isSuspended()) {
+            return false;
+        }
+        final var suspendParams = mSuspendParams;
+        for (int i = 0, size = suspendParams.size(); i < size; i++) {
+            final SuspendParams params = suspendParams.valueAt(i);
+            if (params.isQuarantined()) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+
+
 
     // Code below generated by codegen v1.0.23.
     //
@@ -643,41 +717,11 @@
     }
 
     @DataClass.Generated.Member
-    public boolean isInstalled() {
-        return mInstalled;
-    }
-
-    @DataClass.Generated.Member
-    public boolean isStopped() {
-        return mStopped;
-    }
-
-    @DataClass.Generated.Member
-    public boolean isNotLaunched() {
-        return mNotLaunched;
-    }
-
-    @DataClass.Generated.Member
-    public boolean isHidden() {
-        return mHidden;
-    }
-
-    @DataClass.Generated.Member
     public int getDistractionFlags() {
         return mDistractionFlags;
     }
 
     @DataClass.Generated.Member
-    public boolean isInstantApp() {
-        return mInstantApp;
-    }
-
-    @DataClass.Generated.Member
-    public boolean isVirtualPreload() {
-        return mVirtualPreload;
-    }
-
-    @DataClass.Generated.Member
     public @PackageManager.EnabledState int getEnabledState() {
         return mEnabledState;
     }
@@ -746,6 +790,12 @@
     }
 
     @DataClass.Generated.Member
+    public @NonNull PackageUserStateImpl setBooleans( int value) {
+        mBooleans = value;
+        return this;
+    }
+
+    @DataClass.Generated.Member
     public @NonNull PackageUserStateImpl setDisabledComponentsWatched(@NonNull WatchedArraySet<String> value) {
         mDisabledComponentsWatched = value;
         return this;
@@ -791,16 +841,11 @@
         PackageUserStateImpl that = (PackageUserStateImpl) o;
         //noinspection PointlessBooleanExpression
         return true
+                && mBooleans == that.mBooleans
                 && Objects.equals(mDisabledComponentsWatched, that.mDisabledComponentsWatched)
                 && Objects.equals(mEnabledComponentsWatched, that.mEnabledComponentsWatched)
                 && mCeDataInode == that.mCeDataInode
-                && mInstalled == that.mInstalled
-                && mStopped == that.mStopped
-                && mNotLaunched == that.mNotLaunched
-                && mHidden == that.mHidden
                 && mDistractionFlags == that.mDistractionFlags
-                && mInstantApp == that.mInstantApp
-                && mVirtualPreload == that.mVirtualPreload
                 && mEnabledState == that.mEnabledState
                 && mInstallReason == that.mInstallReason
                 && mUninstallReason == that.mUninstallReason
@@ -825,16 +870,11 @@
         // int fieldNameHashCode() { ... }
 
         int _hash = 1;
+        _hash = 31 * _hash + mBooleans;
         _hash = 31 * _hash + Objects.hashCode(mDisabledComponentsWatched);
         _hash = 31 * _hash + Objects.hashCode(mEnabledComponentsWatched);
         _hash = 31 * _hash + Long.hashCode(mCeDataInode);
-        _hash = 31 * _hash + Boolean.hashCode(mInstalled);
-        _hash = 31 * _hash + Boolean.hashCode(mStopped);
-        _hash = 31 * _hash + Boolean.hashCode(mNotLaunched);
-        _hash = 31 * _hash + Boolean.hashCode(mHidden);
         _hash = 31 * _hash + mDistractionFlags;
-        _hash = 31 * _hash + Boolean.hashCode(mInstantApp);
-        _hash = 31 * _hash + Boolean.hashCode(mVirtualPreload);
         _hash = 31 * _hash + mEnabledState;
         _hash = 31 * _hash + mInstallReason;
         _hash = 31 * _hash + mUninstallReason;
@@ -854,10 +894,10 @@
     }
 
     @DataClass.Generated(
-            time = 1689171513404L,
+            time = 1691601685901L,
             codegenVersion = "1.0.23",
             sourceFile = "frameworks/base/services/core/java/com/android/server/pm/pkg/PackageUserStateImpl.java",
-            inputSignatures = "protected @android.annotation.Nullable com.android.server.utils.WatchedArraySet<java.lang.String> mDisabledComponentsWatched\nprotected @android.annotation.Nullable com.android.server.utils.WatchedArraySet<java.lang.String> mEnabledComponentsWatched\nprivate  long mCeDataInode\nprivate  boolean mInstalled\nprivate  boolean mStopped\nprivate  boolean mNotLaunched\nprivate  boolean mHidden\nprivate  int mDistractionFlags\nprivate  boolean mInstantApp\nprivate  boolean mVirtualPreload\nprivate @android.content.pm.PackageManager.EnabledState int mEnabledState\nprivate @android.content.pm.PackageManager.InstallReason int mInstallReason\nprivate @android.content.pm.PackageManager.UninstallReason int mUninstallReason\nprivate @android.annotation.Nullable java.lang.String mHarmfulAppWarning\nprivate @android.annotation.Nullable java.lang.String mLastDisableAppCaller\nprivate @android.annotation.Nullable android.content.pm.overlay.OverlayPaths mOverlayPaths\nprotected @android.annotation.Nullable com.android.server.utils.WatchedArrayMap<java.lang.String,android.content.pm.overlay.OverlayPaths> mSharedLibraryOverlayPaths\nprivate @android.annotation.Nullable java.lang.String mSplashScreenTheme\nprivate @android.content.pm.PackageManager.UserMinAspectRatio int mMinAspectRatio\nprivate @android.annotation.Nullable com.android.server.utils.WatchedArrayMap<java.lang.String,com.android.server.pm.pkg.SuspendParams> mSuspendParams\nprivate @android.annotation.Nullable com.android.server.utils.WatchedArrayMap<android.content.ComponentName,android.util.Pair<java.lang.String,java.lang.Integer>> mComponentLabelIconOverrideMap\nprivate @android.annotation.CurrentTimeMillisLong long mFirstInstallTimeMillis\nprivate @android.annotation.Nullable com.android.server.utils.Watchable mWatchable\nprivate @android.annotation.Nullable com.android.server.pm.pkg.ArchiveState mArchiveState\nfinal @android.annotation.NonNull com.android.server.utils.SnapshotCache<com.android.server.pm.pkg.PackageUserStateImpl> mSnapshot\nprivate  com.android.server.utils.SnapshotCache<com.android.server.pm.pkg.PackageUserStateImpl> makeCache()\nprivate  void onChanged()\npublic @android.annotation.NonNull @java.lang.Override com.android.server.pm.pkg.PackageUserStateImpl snapshot()\npublic @android.annotation.Nullable boolean setOverlayPaths(android.content.pm.overlay.OverlayPaths)\npublic  boolean setSharedLibraryOverlayPaths(java.lang.String,android.content.pm.overlay.OverlayPaths)\npublic @android.annotation.Nullable @java.lang.Override com.android.server.utils.WatchedArraySet<java.lang.String> getDisabledComponentsNoCopy()\npublic @android.annotation.Nullable @java.lang.Override com.android.server.utils.WatchedArraySet<java.lang.String> getEnabledComponentsNoCopy()\npublic @android.annotation.NonNull @java.lang.Override android.util.ArraySet<java.lang.String> getDisabledComponents()\npublic @android.annotation.NonNull @java.lang.Override android.util.ArraySet<java.lang.String> getEnabledComponents()\npublic @java.lang.Override boolean isComponentEnabled(java.lang.String)\npublic @java.lang.Override boolean isComponentDisabled(java.lang.String)\npublic @java.lang.Override android.content.pm.overlay.OverlayPaths getAllOverlayPaths()\npublic @com.android.internal.annotations.VisibleForTesting boolean overrideLabelAndIcon(android.content.ComponentName,java.lang.String,java.lang.Integer)\npublic  void resetOverrideComponentLabelIcon()\npublic @android.annotation.Nullable android.util.Pair<java.lang.String,java.lang.Integer> getOverrideLabelIconForComponent(android.content.ComponentName)\npublic @java.lang.Override boolean isSuspended()\npublic  com.android.server.pm.pkg.PackageUserStateImpl putSuspendParams(java.lang.String,com.android.server.pm.pkg.SuspendParams)\npublic  com.android.server.pm.pkg.PackageUserStateImpl removeSuspension(java.lang.String)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setDisabledComponents(android.util.ArraySet<java.lang.String>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setEnabledComponents(android.util.ArraySet<java.lang.String>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setEnabledComponents(com.android.server.utils.WatchedArraySet<java.lang.String>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setDisabledComponents(com.android.server.utils.WatchedArraySet<java.lang.String>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setCeDataInode(long)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setInstalled(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setStopped(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setNotLaunched(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setHidden(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setDistractionFlags(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setInstantApp(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setVirtualPreload(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setEnabledState(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setInstallReason(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setUninstallReason(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setHarmfulAppWarning(java.lang.String)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setLastDisableAppCaller(java.lang.String)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setSharedLibraryOverlayPaths(android.util.ArrayMap<java.lang.String,android.content.pm.overlay.OverlayPaths>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setSplashScreenTheme(java.lang.String)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setMinAspectRatio(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setSuspendParams(android.util.ArrayMap<java.lang.String,com.android.server.pm.pkg.SuspendParams>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setComponentLabelIconOverrideMap(android.util.ArrayMap<android.content.ComponentName,android.util.Pair<java.lang.String,java.lang.Integer>>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setFirstInstallTimeMillis(long)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setArchiveState(com.android.server.pm.pkg.ArchiveState)\npublic @android.annotation.NonNull @java.lang.Override java.util.Map<java.lang.String,android.content.pm.overlay.OverlayPaths> getSharedLibraryOverlayPaths()\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setWatchable(com.android.server.utils.Watchable)\nprivate  boolean watchableEquals(com.android.server.utils.Watchable)\nprivate  int watchableHashCode()\nprivate  boolean snapshotEquals(com.android.server.utils.SnapshotCache<com.android.server.pm.pkg.PackageUserStateImpl>)\nprivate  int snapshotHashCode()\nclass PackageUserStateImpl extends com.android.server.utils.WatchableImpl implements [com.android.server.pm.pkg.PackageUserStateInternal, com.android.server.utils.Snappable]\n@com.android.internal.util.DataClass(genConstructor=false, genBuilder=false, genEqualsHashCode=true)")
+            inputSignatures = "private  int mBooleans\nprotected @android.annotation.Nullable com.android.server.utils.WatchedArraySet<java.lang.String> mDisabledComponentsWatched\nprotected @android.annotation.Nullable com.android.server.utils.WatchedArraySet<java.lang.String> mEnabledComponentsWatched\nprivate  long mCeDataInode\nprivate  int mDistractionFlags\nprivate @android.content.pm.PackageManager.EnabledState int mEnabledState\nprivate @android.content.pm.PackageManager.InstallReason int mInstallReason\nprivate @android.content.pm.PackageManager.UninstallReason int mUninstallReason\nprivate @android.annotation.Nullable java.lang.String mHarmfulAppWarning\nprivate @android.annotation.Nullable java.lang.String mLastDisableAppCaller\nprivate @android.annotation.Nullable android.content.pm.overlay.OverlayPaths mOverlayPaths\nprotected @android.annotation.Nullable com.android.server.utils.WatchedArrayMap<java.lang.String,android.content.pm.overlay.OverlayPaths> mSharedLibraryOverlayPaths\nprivate @android.annotation.Nullable java.lang.String mSplashScreenTheme\nprivate @android.content.pm.PackageManager.UserMinAspectRatio int mMinAspectRatio\nprivate @android.annotation.Nullable com.android.server.utils.WatchedArrayMap<java.lang.String,com.android.server.pm.pkg.SuspendParams> mSuspendParams\nprivate @android.annotation.Nullable com.android.server.utils.WatchedArrayMap<android.content.ComponentName,android.util.Pair<java.lang.String,java.lang.Integer>> mComponentLabelIconOverrideMap\nprivate @android.annotation.CurrentTimeMillisLong long mFirstInstallTimeMillis\nprivate @android.annotation.Nullable com.android.server.utils.Watchable mWatchable\nprivate @android.annotation.Nullable com.android.server.pm.pkg.ArchiveState mArchiveState\nfinal @android.annotation.NonNull com.android.server.utils.SnapshotCache<com.android.server.pm.pkg.PackageUserStateImpl> mSnapshot\nprivate  void setBoolean(int,boolean)\nprivate  boolean getBoolean(int)\nprivate  com.android.server.utils.SnapshotCache<com.android.server.pm.pkg.PackageUserStateImpl> makeCache()\nprivate  void onChanged()\npublic @android.annotation.NonNull @java.lang.Override com.android.server.pm.pkg.PackageUserStateImpl snapshot()\npublic @android.annotation.Nullable boolean setOverlayPaths(android.content.pm.overlay.OverlayPaths)\npublic  boolean setSharedLibraryOverlayPaths(java.lang.String,android.content.pm.overlay.OverlayPaths)\npublic @android.annotation.Nullable @java.lang.Override com.android.server.utils.WatchedArraySet<java.lang.String> getDisabledComponentsNoCopy()\npublic @android.annotation.Nullable @java.lang.Override com.android.server.utils.WatchedArraySet<java.lang.String> getEnabledComponentsNoCopy()\npublic @android.annotation.NonNull @java.lang.Override android.util.ArraySet<java.lang.String> getDisabledComponents()\npublic @android.annotation.NonNull @java.lang.Override android.util.ArraySet<java.lang.String> getEnabledComponents()\npublic @java.lang.Override boolean isComponentEnabled(java.lang.String)\npublic @java.lang.Override boolean isComponentDisabled(java.lang.String)\npublic @java.lang.Override android.content.pm.overlay.OverlayPaths getAllOverlayPaths()\npublic @com.android.internal.annotations.VisibleForTesting boolean overrideLabelAndIcon(android.content.ComponentName,java.lang.String,java.lang.Integer)\npublic  void resetOverrideComponentLabelIcon()\npublic @android.annotation.Nullable android.util.Pair<java.lang.String,java.lang.Integer> getOverrideLabelIconForComponent(android.content.ComponentName)\npublic @java.lang.Override boolean isSuspended()\npublic  com.android.server.pm.pkg.PackageUserStateImpl putSuspendParams(java.lang.String,com.android.server.pm.pkg.SuspendParams)\npublic  com.android.server.pm.pkg.PackageUserStateImpl removeSuspension(java.lang.String)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setDisabledComponents(android.util.ArraySet<java.lang.String>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setEnabledComponents(android.util.ArraySet<java.lang.String>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setEnabledComponents(com.android.server.utils.WatchedArraySet<java.lang.String>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setDisabledComponents(com.android.server.utils.WatchedArraySet<java.lang.String>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setCeDataInode(long)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setInstalled(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setStopped(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setNotLaunched(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setHidden(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setDistractionFlags(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setInstantApp(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setVirtualPreload(boolean)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setEnabledState(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setInstallReason(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setUninstallReason(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setHarmfulAppWarning(java.lang.String)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setLastDisableAppCaller(java.lang.String)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setSharedLibraryOverlayPaths(android.util.ArrayMap<java.lang.String,android.content.pm.overlay.OverlayPaths>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setSplashScreenTheme(java.lang.String)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setMinAspectRatio(int)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setSuspendParams(android.util.ArrayMap<java.lang.String,com.android.server.pm.pkg.SuspendParams>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setComponentLabelIconOverrideMap(android.util.ArrayMap<android.content.ComponentName,android.util.Pair<java.lang.String,java.lang.Integer>>)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setFirstInstallTimeMillis(long)\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setArchiveState(com.android.server.pm.pkg.ArchiveState)\npublic @android.annotation.NonNull @java.lang.Override java.util.Map<java.lang.String,android.content.pm.overlay.OverlayPaths> getSharedLibraryOverlayPaths()\npublic @android.annotation.NonNull com.android.server.pm.pkg.PackageUserStateImpl setWatchable(com.android.server.utils.Watchable)\nprivate  boolean watchableEquals(com.android.server.utils.Watchable)\nprivate  int watchableHashCode()\nprivate  boolean snapshotEquals(com.android.server.utils.SnapshotCache<com.android.server.pm.pkg.PackageUserStateImpl>)\nprivate  int snapshotHashCode()\npublic @java.lang.Override boolean isInstalled()\npublic @java.lang.Override boolean isStopped()\npublic @java.lang.Override boolean isNotLaunched()\npublic @java.lang.Override boolean isHidden()\npublic @java.lang.Override boolean isInstantApp()\npublic @java.lang.Override boolean isVirtualPreload()\nclass PackageUserStateImpl extends com.android.server.utils.WatchableImpl implements [com.android.server.pm.pkg.PackageUserStateInternal, com.android.server.utils.Snappable]\nprivate static final  int INSTALLED\nprivate static final  int STOPPED\nprivate static final  int NOT_LAUNCHED\nprivate static final  int HIDDEN\nprivate static final  int INSTANT_APP\nprivate static final  int VIRTUAL_PRELOADED\nclass Booleans extends java.lang.Object implements []\n@com.android.internal.util.DataClass(genConstructor=false, genBuilder=false, genEqualsHashCode=true)")
     @Deprecated
     private void __metadata() {}
 
diff --git a/services/core/java/com/android/server/pm/pkg/PackageUserStateUtils.java b/services/core/java/com/android/server/pm/pkg/PackageUserStateUtils.java
index 15e3d0c..e342453 100644
--- a/services/core/java/com/android/server/pm/pkg/PackageUserStateUtils.java
+++ b/services/core/java/com/android/server/pm/pkg/PackageUserStateUtils.java
@@ -16,6 +16,7 @@
 
 package com.android.server.pm.pkg;
 
+import static android.content.pm.PackageManager.FILTER_OUT_QUARANTINED_COMPONENTS;
 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
 import static android.content.pm.PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS;
 
@@ -122,6 +123,10 @@
             return true;
         }
 
+        if ((flags & FILTER_OUT_QUARANTINED_COMPONENTS) != 0 && state.isQuarantined()) {
+            return false;
+        }
+
         // First check if the overall package is disabled; if the package is
         // enabled then fall through to check specific component
         switch (state.getEnabledState()) {
diff --git a/services/core/java/com/android/server/pm/pkg/SuspendParams.java b/services/core/java/com/android/server/pm/pkg/SuspendParams.java
index dc48a33..153238fa 100644
--- a/services/core/java/com/android/server/pm/pkg/SuspendParams.java
+++ b/services/core/java/com/android/server/pm/pkg/SuspendParams.java
@@ -42,16 +42,25 @@
     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";
+    private static final String ATTR_QUARANTINED = "quarantined";
 
-    private final SuspendDialogInfo dialogInfo;
-    private final PersistableBundle appExtras;
-    private final PersistableBundle launcherExtras;
+    private final SuspendDialogInfo mDialogInfo;
+    private final PersistableBundle mAppExtras;
+    private final PersistableBundle mLauncherExtras;
+
+    private final boolean mQuarantined;
 
     public SuspendParams(SuspendDialogInfo dialogInfo, PersistableBundle appExtras,
             PersistableBundle launcherExtras) {
-        this.dialogInfo = dialogInfo;
-        this.appExtras = appExtras;
-        this.launcherExtras = launcherExtras;
+        this(dialogInfo, appExtras, launcherExtras, false /* quarantined */);
+    }
+
+    public SuspendParams(SuspendDialogInfo dialogInfo, PersistableBundle appExtras,
+            PersistableBundle launcherExtras, boolean quarantined) {
+        this.mDialogInfo = dialogInfo;
+        this.mAppExtras = appExtras;
+        this.mLauncherExtras = launcherExtras;
+        this.mQuarantined = quarantined;
     }
 
     @Override
@@ -63,13 +72,16 @@
             return false;
         }
         final SuspendParams other = (SuspendParams) obj;
-        if (!Objects.equals(dialogInfo, other.dialogInfo)) {
+        if (!Objects.equals(mDialogInfo, other.mDialogInfo)) {
             return false;
         }
-        if (!BaseBundle.kindofEquals(appExtras, other.appExtras)) {
+        if (!BaseBundle.kindofEquals(mAppExtras, other.mAppExtras)) {
             return false;
         }
-        if (!BaseBundle.kindofEquals(launcherExtras, other.launcherExtras)) {
+        if (!BaseBundle.kindofEquals(mLauncherExtras, other.mLauncherExtras)) {
+            return false;
+        }
+        if (mQuarantined != other.mQuarantined) {
             return false;
         }
         return true;
@@ -77,9 +89,10 @@
 
     @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);
+        int hashCode = Objects.hashCode(mDialogInfo);
+        hashCode = 31 * hashCode + ((mAppExtras != null) ? mAppExtras.size() : 0);
+        hashCode = 31 * hashCode + ((mLauncherExtras != null) ? mLauncherExtras.size() : 0);
+        hashCode = 31 * hashCode + Boolean.hashCode(mQuarantined);
         return hashCode;
     }
 
@@ -89,25 +102,26 @@
      * @param out the {@link XmlSerializer} object
      */
     public void saveToXml(TypedXmlSerializer out) throws IOException {
-        if (dialogInfo != null) {
+        out.attributeBoolean(null, ATTR_QUARANTINED, mQuarantined);
+        if (mDialogInfo != null) {
             out.startTag(null, TAG_DIALOG_INFO);
-            dialogInfo.saveToXml(out);
+            mDialogInfo.saveToXml(out);
             out.endTag(null, TAG_DIALOG_INFO);
         }
-        if (appExtras != null) {
+        if (mAppExtras != null) {
             out.startTag(null, TAG_APP_EXTRAS);
             try {
-                appExtras.saveToXml(out);
+                mAppExtras.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) {
+        if (mLauncherExtras != null) {
             out.startTag(null, TAG_LAUNCHER_EXTRAS);
             try {
-                launcherExtras.saveToXml(out);
+                mLauncherExtras.saveToXml(out);
             } catch (XmlPullParserException e) {
                 Slog.e(LOG_TAG, "Exception while trying to write launcherExtras."
                         + " Will be lost on reboot", e);
@@ -127,6 +141,8 @@
         PersistableBundle readAppExtras = null;
         PersistableBundle readLauncherExtras = null;
 
+        final boolean quarantined = in.getAttributeBoolean(null, ATTR_QUARANTINED, false);
+
         final int currentDepth = in.getDepth();
         int type;
         try {
@@ -157,18 +173,22 @@
             Slog.e(LOG_TAG, "Exception while trying to parse SuspendParams,"
                     + " some fields may default", e);
         }
-        return new SuspendParams(readDialogInfo, readAppExtras, readLauncherExtras);
+        return new SuspendParams(readDialogInfo, readAppExtras, readLauncherExtras, quarantined);
     }
 
     public SuspendDialogInfo getDialogInfo() {
-        return dialogInfo;
+        return mDialogInfo;
     }
 
     public PersistableBundle getAppExtras() {
-        return appExtras;
+        return mAppExtras;
     }
 
     public PersistableBundle getLauncherExtras() {
-        return launcherExtras;
+        return mLauncherExtras;
+    }
+
+    public boolean isQuarantined() {
+        return mQuarantined;
     }
 }
diff --git a/services/core/java/com/android/server/pm/split/DefaultSplitAssetLoader.java b/services/core/java/com/android/server/pm/split/DefaultSplitAssetLoader.java
index 0bb969f..a2177e8 100644
--- a/services/core/java/com/android/server/pm/split/DefaultSplitAssetLoader.java
+++ b/services/core/java/com/android/server/pm/split/DefaultSplitAssetLoader.java
@@ -17,13 +17,13 @@
 
 import android.content.pm.parsing.ApkLiteParseUtils;
 import android.content.pm.parsing.PackageLite;
+import com.android.server.pm.pkg.parsing.ParsingPackageUtils;
+import com.android.server.pm.pkg.parsing.ParsingPackageUtils.ParseFlags;
 import android.content.res.ApkAssets;
 import android.content.res.AssetManager;
 import android.os.Build;
 
 import com.android.internal.util.ArrayUtils;
-import com.android.server.pm.pkg.parsing.ParsingPackageUtils;
-import com.android.server.pm.pkg.parsing.ParsingPackageUtils.ParseFlags;
 
 import libcore.io.IoUtils;
 
@@ -82,8 +82,8 @@
         }
 
         AssetManager assets = new AssetManager();
-        assets.setConfiguration(0, 0, null, new String[0], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-                0, 0, Build.VERSION.RESOURCES_SDK_INT);
+        assets.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                Build.VERSION.RESOURCES_SDK_INT);
         assets.setApkAssets(apkAssets, false /*invalidateCaches*/);
 
         mCachedAssetManager = assets;
diff --git a/services/core/java/com/android/server/pm/split/SplitAssetDependencyLoader.java b/services/core/java/com/android/server/pm/split/SplitAssetDependencyLoader.java
index 56d92fb..1a8c1996 100644
--- a/services/core/java/com/android/server/pm/split/SplitAssetDependencyLoader.java
+++ b/services/core/java/com/android/server/pm/split/SplitAssetDependencyLoader.java
@@ -80,8 +80,8 @@
 
     private static AssetManager createAssetManagerWithAssets(ApkAssets[] apkAssets) {
         final AssetManager assets = new AssetManager();
-        assets.setConfiguration(0, 0, null, new String[0], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-                0, Build.VERSION.RESOURCES_SDK_INT);
+        assets.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                Build.VERSION.RESOURCES_SDK_INT);
         assets.setApkAssets(apkAssets, false /*invalidateCaches*/);
         return assets;
     }
diff --git a/services/core/java/com/android/server/power/PowerManagerService.java b/services/core/java/com/android/server/power/PowerManagerService.java
index 75fcca5..4a4214f 100644
--- a/services/core/java/com/android/server/power/PowerManagerService.java
+++ b/services/core/java/com/android/server/power/PowerManagerService.java
@@ -18,7 +18,6 @@
 
 import static android.hardware.display.DisplayManagerInternal.DisplayPowerRequest.policyToString;
 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL;
-import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_DEFAULT;
 import static android.os.PowerManager.GO_TO_SLEEP_REASON_DISPLAY_GROUPS_TURNED_OFF;
 import static android.os.PowerManager.GO_TO_SLEEP_REASON_DISPLAY_GROUP_REMOVED;
 import static android.os.PowerManager.WAKE_REASON_DISPLAY_GROUP_ADDED;
@@ -309,10 +308,8 @@
     private final ServiceThread mHandlerThread;
     private final Handler mHandler;
     private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
-    private final BatterySaverController mBatterySaverController;
-    private final BatterySaverPolicy mBatterySaverPolicy;
+    @Nullable
     private final BatterySaverStateMachine mBatterySaverStateMachine;
-    private final BatterySavingStats mBatterySavingStats;
     private final LowPowerStandbyController mLowPowerStandbyController;
     private final AttentionDetector mAttentionDetector;
     private final FaceDownDetector mFaceDownDetector;
@@ -326,6 +323,8 @@
     private final PermissionCheckerWrapper mPermissionCheckerWrapper;
     private final PowerPropertiesWrapper mPowerPropertiesWrapper;
     private final DeviceConfigParameterProvider mDeviceConfigProvider;
+    // True if battery saver is supported on this device.
+    private final boolean mBatterySaverSupported;
 
     private boolean mDisableScreenWakeLocksWhileCached;
 
@@ -969,20 +968,13 @@
             return suspendBlocker;
         }
 
-        BatterySaverPolicy createBatterySaverPolicy(
-                Object lock, Context context, BatterySavingStats batterySavingStats) {
-            return new BatterySaverPolicy(lock, context, batterySavingStats);
-        }
-
-        BatterySaverController createBatterySaverController(
-                Object lock, Context context, BatterySaverPolicy batterySaverPolicy,
-                BatterySavingStats batterySavingStats) {
-            return new BatterySaverController(lock, context, BackgroundThread.get().getLooper(),
+        BatterySaverStateMachine createBatterySaverStateMachine(Object lock, Context context) {
+            BatterySavingStats batterySavingStats = new BatterySavingStats(lock);
+            BatterySaverPolicy batterySaverPolicy = new BatterySaverPolicy(lock, context,
+                    batterySavingStats);
+            BatterySaverController batterySaverController = new BatterySaverController(lock,
+                    context, BackgroundThread.get().getLooper(),
                     batterySaverPolicy, batterySavingStats);
-        }
-
-        BatterySaverStateMachine createBatterySaverStateMachine(Object lock, Context context,
-                BatterySaverController batterySaverController) {
             return new BatterySaverStateMachine(lock, context, batterySaverController);
         }
 
@@ -1156,13 +1148,11 @@
         mFaceDownDetector = new FaceDownDetector(this::onFlip);
         mScreenUndimDetector = new ScreenUndimDetector();
 
-        mBatterySavingStats = new BatterySavingStats(mLock);
-        mBatterySaverPolicy =
-                mInjector.createBatterySaverPolicy(mLock, mContext, mBatterySavingStats);
-        mBatterySaverController = mInjector.createBatterySaverController(mLock, mContext,
-                mBatterySaverPolicy, mBatterySavingStats);
-        mBatterySaverStateMachine = mInjector.createBatterySaverStateMachine(mLock, mContext,
-                mBatterySaverController);
+        mBatterySaverSupported = mContext.getResources().getBoolean(
+                com.android.internal.R.bool.config_batterySaverSupported);
+        mBatterySaverStateMachine =
+                mBatterySaverSupported ? mInjector.createBatterySaverStateMachine(mLock, mContext)
+                        : null;
 
         mLowPowerStandbyController = mInjector.createLowPowerStandbyController(mContext,
                 Looper.getMainLooper());
@@ -1280,7 +1270,7 @@
     @Override
     public void onStart() {
         publishBinderService(Context.POWER_SERVICE, mBinderService, /* allowIsolated= */ false,
-                DUMP_FLAG_PRIORITY_DEFAULT | DUMP_FLAG_PRIORITY_CRITICAL);
+                DUMP_FLAG_PRIORITY_CRITICAL);
         publishLocalService(PowerManagerInternal.class, mLocalService);
 
         Watchdog.getInstance().addMonitor(this);
@@ -1301,7 +1291,9 @@
                 mBootCompleted = true;
                 mDirty |= DIRTY_BOOT_COMPLETED;
 
-                mBatterySaverStateMachine.onBootCompleted();
+                if (mBatterySaverSupported) {
+                    mBatterySaverStateMachine.onBootCompleted();
+                }
                 userActivityNoUpdateLocked(
                         now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
 
@@ -1391,8 +1383,9 @@
         final ContentResolver resolver = mContext.getContentResolver();
         mConstants.start(resolver);
 
-        mBatterySaverController.systemReady();
-        mBatterySaverPolicy.systemReady();
+        if (mBatterySaverSupported) {
+            mBatterySaverStateMachine.systemReady();
+        }
         mFaceDownDetector.systemReady(mContext);
         mScreenUndimDetector.systemReady(mContext);
 
@@ -2602,7 +2595,10 @@
                 }
             }
 
-            mBatterySaverStateMachine.setBatteryStatus(mIsPowered, mBatteryLevel, mBatteryLevelLow);
+            if (mBatterySaverSupported) {
+                mBatterySaverStateMachine.setBatteryStatus(mIsPowered, mBatteryLevel,
+                        mBatteryLevelLow);
+            }
         }
     }
 
@@ -3555,7 +3551,11 @@
                         mDozeScreenStateOverrideFromDreamManager,
                         mDozeScreenBrightnessOverrideFromDreamManagerFloat,
                         mDrawWakeLockOverrideFromSidekick,
-                        mBatterySaverPolicy.getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS),
+                        mBatterySaverSupported
+                                ?
+                                mBatterySaverStateMachine.getBatterySaverPolicy()
+                                        .getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS)
+                                : new PowerSaveState.Builder().build(),
                         sQuiescent, mDozeAfterScreenOff, mBootCompleted,
                         mScreenBrightnessBoostInProgress, mRequestWaitForNegativeProximity);
                 int wakefulness = powerGroup.getWakefulnessLocked();
@@ -3885,7 +3885,7 @@
             if (DEBUG) {
                 Slog.d(TAG, "setLowPowerModeInternal " + enabled + " mIsPowered=" + mIsPowered);
             }
-            if (mIsPowered) {
+            if (mIsPowered || !mBatterySaverSupported) {
                 return false;
             }
 
@@ -4379,7 +4379,8 @@
 
     private boolean setPowerModeInternal(int mode, boolean enabled) {
         // Maybe filter the event.
-        if (mode == Mode.LAUNCH && enabled && mBatterySaverController.isLaunchBoostDisabled()) {
+        if (mBatterySaverStateMachine == null || (mode == Mode.LAUNCH && enabled
+                && mBatterySaverStateMachine.getBatterySaverController().isLaunchBoostDisabled())) {
             return false;
         }
         return mNativeWrapper.nativeSetPowerMode(mode, enabled);
@@ -4719,8 +4720,12 @@
             pw.println();
             pw.println("Display Power: " + mDisplayPowerCallbacks);
 
-            mBatterySaverPolicy.dump(pw);
-            mBatterySaverStateMachine.dump(pw);
+            if (mBatterySaverSupported) {
+                mBatterySaverStateMachine.getBatterySaverPolicy().dump(pw);
+                mBatterySaverStateMachine.dump(pw);
+            } else {
+                pw.println("Battery Saver: DISABLED");
+            }
             mAttentionDetector.dump(pw);
 
             pw.println();
@@ -5102,8 +5107,10 @@
                 proto.end(uIDToken);
             }
 
-            mBatterySaverStateMachine.dumpProto(proto,
-                    PowerManagerServiceDumpProto.BATTERY_SAVER_STATE_MACHINE);
+            if (mBatterySaverSupported) {
+                mBatterySaverStateMachine.dumpProto(proto,
+                        PowerManagerServiceDumpProto.BATTERY_SAVER_STATE_MACHINE);
+            }
 
             mHandler.getLooper().dumpDebug(proto, PowerManagerServiceDumpProto.LOOPER);
 
@@ -5987,7 +5994,8 @@
         public boolean isPowerSaveMode() {
             final long ident = Binder.clearCallingIdentity();
             try {
-                return mBatterySaverController.isEnabled();
+                return mBatterySaverSupported
+                        && mBatterySaverStateMachine.getBatterySaverController().isEnabled();
             } finally {
                 Binder.restoreCallingIdentity(ident);
             }
@@ -5997,7 +6005,12 @@
         public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
             final long ident = Binder.clearCallingIdentity();
             try {
-                return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
+                // Return default PowerSaveState if battery saver is not supported.
+                return mBatterySaverSupported
+                        ?
+                        mBatterySaverStateMachine.getBatterySaverPolicy().getBatterySaverPolicy(
+                                serviceType)
+                        : new PowerSaveState.Builder().build();
             } finally {
                 Binder.restoreCallingIdentity(ident);
             }
@@ -6018,11 +6031,24 @@
             }
         }
 
-        @Override // Binder call
-        public BatterySaverPolicyConfig getFullPowerSavePolicy() {
+        @Override
+        public boolean isBatterySaverSupported() {
             final long ident = Binder.clearCallingIdentity();
             try {
-                return mBatterySaverStateMachine.getFullBatterySaverPolicy();
+                return mBatterySaverSupported;
+            } finally {
+                Binder.restoreCallingIdentity(ident);
+            }
+        }
+
+        @Override // Binder call
+        public BatterySaverPolicyConfig getFullPowerSavePolicy() {
+            // Return default BatterySaverPolicyConfig if battery saver is not supported.
+            final long ident = Binder.clearCallingIdentity();
+            try {
+                return mBatterySaverSupported
+                        ? mBatterySaverStateMachine.getFullBatterySaverPolicy()
+                        : new BatterySaverPolicyConfig.Builder().build();
             } finally {
                 Binder.restoreCallingIdentity(ident);
             }
@@ -6037,7 +6063,8 @@
             }
             final long ident = Binder.clearCallingIdentity();
             try {
-                return mBatterySaverStateMachine.setFullBatterySaverPolicy(config);
+                return mBatterySaverSupported
+                        && mBatterySaverStateMachine.setFullBatterySaverPolicy(config);
             } finally {
                 Binder.restoreCallingIdentity(ident);
             }
@@ -6074,7 +6101,8 @@
             }
             final long ident = Binder.clearCallingIdentity();
             try {
-                return mBatterySaverStateMachine.setAdaptiveBatterySaverPolicy(config);
+                return mBatterySaverSupported
+                        && mBatterySaverStateMachine.setAdaptiveBatterySaverPolicy(config);
             } finally {
                 Binder.restoreCallingIdentity(ident);
             }
@@ -6089,7 +6117,8 @@
             }
             final long ident = Binder.clearCallingIdentity();
             try {
-                return mBatterySaverStateMachine.setAdaptiveBatterySaverEnabled(enabled);
+                return mBatterySaverSupported
+                        && mBatterySaverStateMachine.setAdaptiveBatterySaverEnabled(enabled);
             } finally {
                 Binder.restoreCallingIdentity(ident);
             }
@@ -6954,12 +6983,21 @@
 
         @Override
         public PowerSaveState getLowPowerState(@ServiceType int serviceType) {
-            return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
+            // Return default PowerSaveState if battery saver is not supported.
+            return mBatterySaverSupported
+                    ?
+                    mBatterySaverStateMachine.getBatterySaverPolicy().getBatterySaverPolicy(
+                            serviceType) : new PowerSaveState.Builder().build();
         }
 
         @Override
         public void registerLowPowerModeObserver(LowPowerModeListener listener) {
-            mBatterySaverController.addListener(listener);
+            if (mBatterySaverSupported) {
+                mBatterySaverStateMachine.getBatterySaverController().addListener(listener);
+            } else {
+                Slog.w(TAG,
+                        "Battery saver is not supported, no low power mode observer registered");
+            }
         }
 
         @Override
diff --git a/services/core/java/com/android/server/power/TEST_MAPPING b/services/core/java/com/android/server/power/TEST_MAPPING
index 8374997..19086a1 100644
--- a/services/core/java/com/android/server/power/TEST_MAPPING
+++ b/services/core/java/com/android/server/power/TEST_MAPPING
@@ -17,15 +17,6 @@
       ]
     },
     {
-      "name": "FrameworksServicesTests",
-      "options": [
-        {"include-filter": "com.android.server.power"},
-        {"exclude-filter": "com.android.server.power.BatteryStatsTests"},
-        {"exclude-annotation": "android.platform.test.annotations.FlakyTest"},
-        {"exclude-annotation": "androidx.test.filters.FlakyTest"}
-      ]
-    },
-    {
       "name": "PowerServiceTests",
       "options": [
         {"include-filter": "com.android.server.power"},
@@ -48,15 +39,13 @@
     {
       "name": "FrameworksServicesTests",
       "options": [
-        {"include-filter": "com.android.server.power"},
-        {"exclude-filter": "com.android.server.power.BatteryStatsTests"}
+        {"include-filter": "com.android.server.power"}
       ]
     },
     {
       "name": "PowerServiceTests",
       "options": [
         {"include-filter": "com.android.server.power"},
-        {"exclude-filter": "com.android.server.power.BatteryStatsTests"},
         {"exclude-annotation": "org.junit.Ignore"}
       ]
     }
diff --git a/services/core/java/com/android/server/power/batterysaver/BatterySaverController.java b/services/core/java/com/android/server/power/batterysaver/BatterySaverController.java
index 57d69c2..8c1e9a5 100644
--- a/services/core/java/com/android/server/power/batterysaver/BatterySaverController.java
+++ b/services/core/java/com/android/server/power/batterysaver/BatterySaverController.java
@@ -40,7 +40,6 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.server.EventLogTags;
 import com.android.server.LocalServices;
-import com.android.server.power.PowerManagerService;
 import com.android.server.power.batterysaver.BatterySaverPolicy.BatterySaverPolicyListener;
 import com.android.server.power.batterysaver.BatterySaverPolicy.Policy;
 import com.android.server.power.batterysaver.BatterySaverPolicy.PolicyLevel;
@@ -223,7 +222,7 @@
     }
 
     /**
-     * Called by {@link PowerManagerService} on system ready, *with no lock held*.
+     * Called by {@link BatterySaverStateMachine} on system ready, *with no lock held*.
      */
     public void systemReady() {
         final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
diff --git a/services/core/java/com/android/server/power/batterysaver/BatterySaverPolicy.java b/services/core/java/com/android/server/power/batterysaver/BatterySaverPolicy.java
index 07d1844..e3f3638 100644
--- a/services/core/java/com/android/server/power/batterysaver/BatterySaverPolicy.java
+++ b/services/core/java/com/android/server/power/batterysaver/BatterySaverPolicy.java
@@ -41,7 +41,6 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.os.BackgroundThread;
 import com.android.internal.util.ConcurrentUtils;
-import com.android.server.power.PowerManagerService;
 
 import java.io.PrintWriter;
 import java.lang.annotation.Retention;
@@ -283,7 +282,7 @@
     }
 
     /**
-     * Called by {@link PowerManagerService#onBootPhase}, *with no lock held.*
+     * Called by {@link BatterySaverStateMachine#systemReady()}, *with no lock held.*
      */
     public void systemReady() {
         ConcurrentUtils.wtfIfLockHeld(TAG, mLock);
diff --git a/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java b/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java
index e0bbd36..b22e37b 100644
--- a/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java
+++ b/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java
@@ -44,6 +44,7 @@
 import com.android.internal.os.BackgroundThread;
 import com.android.server.EventLogTags;
 import com.android.server.power.BatterySaverStateMachineProto;
+import com.android.server.power.PowerManagerService;
 
 import java.io.PrintWriter;
 import java.time.Duration;
@@ -253,6 +254,24 @@
                 com.android.internal.R.integer.config_dynamicPowerSavingsDefaultDisableThreshold);
     }
 
+    /**
+     * Called by {@link PowerManagerService} on system ready, *with no lock held*.
+     */
+    public void systemReady() {
+        mBatterySaverController.systemReady();
+        getBatterySaverPolicy().systemReady();
+    }
+
+    /** @return Battery saver controller. */
+    public BatterySaverController getBatterySaverController() {
+        return mBatterySaverController;
+    }
+
+    /** @return Battery saver policy. */
+    public BatterySaverPolicy getBatterySaverPolicy() {
+        return mBatterySaverController.getBatterySaverPolicy();
+    }
+
     /** @return true if the automatic percentage based mode should be used */
     private boolean isAutomaticModeActiveLocked() {
         return mSettingAutomaticBatterySaver == PowerManager.POWER_SAVE_MODE_TRIGGER_PERCENTAGE
@@ -937,8 +956,7 @@
             ipw.print(mBatterySaverController.isAdaptiveEnabled());
             if (mBatterySaverController.isAdaptiveEnabled()) {
                 ipw.print(" (advertise=");
-                ipw.print(
-                        mBatterySaverController.getBatterySaverPolicy().shouldAdvertiseIsEnabled());
+                ipw.print(getBatterySaverPolicy().shouldAdvertiseIsEnabled());
                 ipw.print(")");
             }
             ipw.decreaseIndent();
@@ -1005,7 +1023,7 @@
             proto.write(BatterySaverStateMachineProto.IS_ADAPTIVE_ENABLED,
                     mBatterySaverController.isAdaptiveEnabled());
             proto.write(BatterySaverStateMachineProto.SHOULD_ADVERTISE_IS_ENABLED,
-                    mBatterySaverController.getBatterySaverPolicy().shouldAdvertiseIsEnabled());
+                    getBatterySaverPolicy().shouldAdvertiseIsEnabled());
 
             proto.write(BatterySaverStateMachineProto.BOOT_COMPLETED, mBootCompleted);
             proto.write(BatterySaverStateMachineProto.SETTINGS_LOADED, mSettingsLoaded);
diff --git a/services/core/java/com/android/server/power/batterysaver/TEST_MAPPING b/services/core/java/com/android/server/power/batterysaver/TEST_MAPPING
index 17dba7d..c091b8e 100644
--- a/services/core/java/com/android/server/power/batterysaver/TEST_MAPPING
+++ b/services/core/java/com/android/server/power/batterysaver/TEST_MAPPING
@@ -4,7 +4,13 @@
       "name": "CtsLocationCoarseTestCases"
     },
     {
-      "name": "CtsLocationFineTestCases"
+      "name": "CtsLocationFineTestCases",
+      "options": [
+          {
+             // TODO: Wait for test to deflake - b/293934372
+             "exclude-filter":"android.location.cts.fine.ScanningSettingsTest"
+          }
+      ]
     },
     {
       "name": "CtsLocationNoneTestCases"
diff --git a/services/core/java/com/android/server/power/hint/HintManagerService.java b/services/core/java/com/android/server/power/hint/HintManagerService.java
index 1a91d25..33bed3d 100644
--- a/services/core/java/com/android/server/power/hint/HintManagerService.java
+++ b/services/core/java/com/android/server/power/hint/HintManagerService.java
@@ -171,6 +171,8 @@
     public static class NativeWrapper {
         private native void nativeInit();
 
+        private static native long nativeGetHintSessionPreferredRate();
+
         private static native long nativeCreateHintSession(int tgid, int uid, int[] tids,
                 long durationNanos);
 
@@ -190,13 +192,18 @@
 
         private static native void nativeSetThreads(long halPtr, int[] tids);
 
-        private static native long nativeGetHintSessionPreferredRate();
+        private static native void nativeSetMode(long halPtr, int mode, boolean enabled);
 
         /** Wrapper for HintManager.nativeInit */
         public void halInit() {
             nativeInit();
         }
 
+        /** Wrapper for HintManager.nativeGetHintSessionPreferredRate */
+        public long halGetHintSessionPreferredRate() {
+            return nativeGetHintSessionPreferredRate();
+        }
+
         /** Wrapper for HintManager.nativeCreateHintSession */
         public long halCreateHintSession(int tgid, int uid, int[] tids, long durationNanos) {
             return nativeCreateHintSession(tgid, uid, tids, durationNanos);
@@ -234,15 +241,16 @@
             nativeSendHint(halPtr, hint);
         }
 
-        /** Wrapper for HintManager.nativeGetHintSessionPreferredRate */
-        public long halGetHintSessionPreferredRate() {
-            return nativeGetHintSessionPreferredRate();
-        }
-
         /** Wrapper for HintManager.nativeSetThreads */
         public void halSetThreads(long halPtr, int[] tids) {
             nativeSetThreads(halPtr, tids);
         }
+
+        /** Wrapper for HintManager.setMode */
+        public void halSetMode(long halPtr, int mode, boolean enabled) {
+            nativeSetMode(halPtr, mode, enabled);
+        }
+
     }
 
     @VisibleForTesting
@@ -304,7 +312,8 @@
         return mService;
     }
 
-    private boolean checkTidValid(int uid, int tgid, int [] tids) {
+    // returns the first invalid tid or null if not found
+    private Integer checkTidValid(int uid, int tgid, int [] tids) {
         // Make sure all tids belongs to the same UID (including isolated UID),
         // tids can belong to different application processes.
         List<Integer> isolatedPids = null;
@@ -326,19 +335,24 @@
             if (isolatedPids == null) {
                 // To avoid deadlock, do not call into AMS if the call is from system.
                 if (uid == Process.SYSTEM_UID) {
-                    return false;
+                    return threadId;
                 }
                 isolatedPids = mAmInternal.getIsolatedProcesses(uid);
                 if (isolatedPids == null) {
-                    return false;
+                    return threadId;
                 }
             }
             if (isolatedPids.contains(pidOfThreadId)) {
                 continue;
             }
-            return false;
+            return threadId;
         }
-        return true;
+        return null;
+    }
+
+    private String formatTidCheckErrMsg(int callingUid, int[] tids, Integer invalidTid) {
+        return "Tid" + invalidTid + " from list " + Arrays.toString(tids)
+                + " doesn't belong to the calling application" + callingUid;
     }
 
     @VisibleForTesting
@@ -356,8 +370,11 @@
             final int callingTgid = Process.getThreadGroupLeader(Binder.getCallingPid());
             final long identity = Binder.clearCallingIdentity();
             try {
-                if (!checkTidValid(callingUid, callingTgid, tids)) {
-                    throw new SecurityException("Some tid doesn't belong to the application");
+                final Integer invalidTid = checkTidValid(callingUid, callingTgid, tids);
+                if (invalidTid != null) {
+                    final String errMsg = formatTidCheckErrMsg(callingUid, tids, invalidTid);
+                    Slogf.w(TAG, errMsg);
+                    throw new SecurityException(errMsg);
                 }
 
                 long halSessionPtr = mNativeWrapper.halCreateHintSession(callingTgid, callingUid,
@@ -543,7 +560,7 @@
                 if (mHalSessionPtr == 0 || !updateHintAllowed()) {
                     return;
                 }
-                Preconditions.checkArgument(hint >= 0, "the hint ID the hint value should be"
+                Preconditions.checkArgument(hint >= 0, "the hint ID value should be"
                         + " greater than zero.");
                 mNativeWrapper.halSendHint(mHalSessionPtr, hint);
             }
@@ -561,8 +578,11 @@
                 final int callingTgid = Process.getThreadGroupLeader(Binder.getCallingPid());
                 final long identity = Binder.clearCallingIdentity();
                 try {
-                    if (!checkTidValid(callingUid, callingTgid, tids)) {
-                        throw new SecurityException("Some tid doesn't belong to the application.");
+                    final Integer invalidTid = checkTidValid(callingUid, callingTgid, tids);
+                    if (invalidTid != null) {
+                        final String errMsg = formatTidCheckErrMsg(callingUid, tids, invalidTid);
+                        Slogf.w(TAG, errMsg);
+                        throw new SecurityException(errMsg);
                     }
                 } finally {
                     Binder.restoreCallingIdentity(identity);
@@ -581,6 +601,18 @@
             return mThreadIds;
         }
 
+        @Override
+        public void setMode(int mode, boolean enabled) {
+            synchronized (mLock) {
+                if (mHalSessionPtr == 0 || !updateHintAllowed()) {
+                    return;
+                }
+                Preconditions.checkArgument(mode >= 0, "the mode Id value should be"
+                        + " greater than zero.");
+                mNativeWrapper.halSetMode(mHalSessionPtr, mode, enabled);
+            }
+        }
+
         private void onProcStateChanged() {
             updateHintAllowed();
         }
diff --git a/services/core/java/com/android/server/power/hint/OWNERS b/services/core/java/com/android/server/power/hint/OWNERS
new file mode 100644
index 0000000..c28c07a
--- /dev/null
+++ b/services/core/java/com/android/server/power/hint/OWNERS
@@ -0,0 +1,2 @@
+include /ADPF_OWNERS
+
diff --git a/services/core/java/com/android/server/power/stats/BatteryExternalStatsWorker.java b/services/core/java/com/android/server/power/stats/BatteryExternalStatsWorker.java
index d5fd017..f4b2f52 100644
--- a/services/core/java/com/android/server/power/stats/BatteryExternalStatsWorker.java
+++ b/services/core/java/com/android/server/power/stats/BatteryExternalStatsWorker.java
@@ -386,7 +386,11 @@
             }
         }
 
-        return mExecutorService.schedule(syncRunnable, delayMillis, TimeUnit.MILLISECONDS);
+        try {
+            return mExecutorService.schedule(syncRunnable, delayMillis, TimeUnit.MILLISECONDS);
+        } catch (RejectedExecutionException e) {
+            return CompletableFuture.failedFuture(e);
+        }
     }
 
     public synchronized Future<?> scheduleWrite() {
diff --git a/services/core/java/com/android/server/security/rkp/RemoteProvisioningShellCommand.java b/services/core/java/com/android/server/security/rkp/RemoteProvisioningShellCommand.java
index bc39084..187b939 100644
--- a/services/core/java/com/android/server/security/rkp/RemoteProvisioningShellCommand.java
+++ b/services/core/java/com/android/server/security/rkp/RemoteProvisioningShellCommand.java
@@ -49,7 +49,7 @@
             + "  Show this message.\n"
             + "dump\n"
             + "  Dump service diagnostics.\n"
-            + "list [--min-version MIN_VERSION]\n"
+            + "list\n"
             + "  List the names of the IRemotelyProvisionedComponent instances.\n"
             + "csr [--challenge CHALLENGE] NAME\n"
             + "  Generate and print a base64-encoded CSR from the named\n"
diff --git a/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java b/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java
index 76126df..8780991 100644
--- a/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java
+++ b/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java
@@ -27,6 +27,7 @@
 import static android.app.AppOpsManager.OP_PHONE_CALL_MICROPHONE;
 import static android.app.AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO;
 import static android.app.AppOpsManager.OP_RECEIVE_EXPLICIT_USER_INTERACTION_AUDIO;
+import static android.app.AppOpsManager.OP_RECEIVE_SANDBOX_TRIGGER_AUDIO;
 import static android.app.AppOpsManager.OP_RECORD_AUDIO;
 import static android.content.Intent.EXTRA_PACKAGE_NAME;
 import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
@@ -1125,6 +1126,8 @@
                 case MICROPHONE:
                     mAppOpsManagerInternal.setGlobalRestriction(OP_RECORD_AUDIO, enabled,
                             mAppOpsRestrictionToken);
+                    mAppOpsManagerInternal.setGlobalRestriction(
+                                OP_RECEIVE_SANDBOX_TRIGGER_AUDIO, enabled, mAppOpsRestrictionToken);
                     mAppOpsManagerInternal.setGlobalRestriction(OP_PHONE_CALL_MICROPHONE, enabled,
                             mAppOpsRestrictionToken);
                     // We don't show the dialog for RECEIVE_SOUNDTRIGGER_AUDIO, but still want to
diff --git a/services/core/java/com/android/server/tv/TvInputManagerService.java b/services/core/java/com/android/server/tv/TvInputManagerService.java
index f36ecf7..cb09aef 100644
--- a/services/core/java/com/android/server/tv/TvInputManagerService.java
+++ b/services/core/java/com/android/server/tv/TvInputManagerService.java
@@ -333,7 +333,6 @@
                 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
                 userId);
         List<TvInputInfo> inputList = new ArrayList<>();
-        List<ComponentName> hardwareComponents = new ArrayList<>();
         for (ResolveInfo ri : services) {
             ServiceInfo si = ri.serviceInfo;
             if (!android.Manifest.permission.BIND_TV_INPUT.equals(si.permission)) {
@@ -344,17 +343,16 @@
 
             ComponentName component = new ComponentName(si.packageName, si.name);
             if (hasHardwarePermission(pm, component)) {
-                hardwareComponents.add(component);
                 ServiceState serviceState = userState.serviceStateMap.get(component);
                 if (serviceState == null) {
                     // New hardware input found. Create a new ServiceState and connect to the
                     // service to populate the hardware list.
                     serviceState = new ServiceState(component, userId);
                     userState.serviceStateMap.put(component, serviceState);
-                    updateServiceConnectionLocked(component, userId);
                 } else {
                     inputList.addAll(serviceState.hardwareInputMap.values());
                 }
+                updateServiceConnectionLocked(component, userId);
             } else {
                 try {
                     TvInputInfo info = new TvInputInfo.Builder(mContext, ri).build();
@@ -417,15 +415,6 @@
             }
         }
 
-        // Clean up ServiceState corresponding to the removed hardware inputs
-        Iterator<ServiceState> it = userState.serviceStateMap.values().iterator();
-        while (it.hasNext()) {
-            ServiceState serviceState = it.next();
-            if (serviceState.isHardware && !hardwareComponents.contains(serviceState.component)) {
-                it.remove();
-            }
-        }
-
         userState.inputMap.clear();
         userState.inputMap = inputMap;
     }
@@ -890,10 +879,13 @@
                 sessionState.session = null;
             }
         }
-        logExternalInputEvent(FrameworkStatsLog.EXTERNAL_TV_INPUT_EVENT__EVENT_TYPE__RELEASED,
-                mCurrentInputId, sessionState);
-        mCurrentInputId = null;
-        mCurrentSessionState = null;
+        if (mCurrentSessionState == sessionState) {
+            // only log when releasing the current on-screen session
+            logExternalInputEvent(FrameworkStatsLog.EXTERNAL_TV_INPUT_EVENT__EVENT_TYPE__RELEASED,
+                    mCurrentInputId, sessionState);
+            mCurrentInputId = null;
+            mCurrentSessionState = null;
+        }
         removeSessionStateLocked(sessionToken, userId);
         return sessionState;
     }
@@ -3057,6 +3049,7 @@
     }
 
     private void logExternalInputEvent(int eventType, String inputId, SessionState sessionState) {
+        // TODO: handle recording sessions
         UserState userState = getOrCreateUserStateLocked(sessionState.userId);
         TvInputState tvInputState = userState.inputMap.get(inputId);
         TvInputInfo tvInputInfo = tvInputState.info;
@@ -3443,15 +3436,22 @@
                 synchronized (mLock) {
                     mTvInputHardwareManager.addHdmiInput(id, inputInfo);
                     addHardwareInputLocked(inputInfo);
-                    // catch the use case when a CEC device is unplugged from
-                    // an HDMI port, then plugged in to the same HDMI port.
-                    if (mCurrentInputId != null && mCurrentSessionState != null
-                            && mCurrentInputId.equals(inputInfo.getParentId())
-                            && inputInfo.getId().equals(mCurrentSessionState.inputId)) {
-                        logExternalInputEvent(
-                                FrameworkStatsLog.EXTERNAL_TV_INPUT_EVENT__EVENT_TYPE__TUNED,
-                                inputInfo.getId(), mCurrentSessionState);
-                        mCurrentInputId = inputInfo.getId();
+                    if (mCurrentInputId != null && mCurrentSessionState != null) {
+                        if (TextUtils.equals(mCurrentInputId, inputInfo.getParentId())) {
+                            // catch the use case when a CEC device is plugged in an HDMI port,
+                            // and TV app does not explicitly call tune() to the added CEC input.
+                            logExternalInputEvent(
+                                    FrameworkStatsLog.EXTERNAL_TV_INPUT_EVENT__EVENT_TYPE__TUNED,
+                                    inputInfo.getId(), mCurrentSessionState);
+                            mCurrentInputId = inputInfo.getId();
+                        } else if (TextUtils.equals(mCurrentInputId, inputInfo.getId())) {
+                            // catch the use case when a CEC device disconnects itself
+                            // and reconnects to update info.
+                            logExternalInputEvent(
+                                    FrameworkStatsLog
+                                        .EXTERNAL_TV_INPUT_EVENT__EVENT_TYPE__DEVICE_INFO_UPDATED,
+                                    mCurrentInputId, mCurrentSessionState);
+                        }
                     }
                 }
             } finally {
diff --git a/services/core/java/com/android/server/utils/quota/CountQuotaTracker.java b/services/core/java/com/android/server/utils/quota/CountQuotaTracker.java
index 9bf046c..3b930f7 100644
--- a/services/core/java/com/android/server/utils/quota/CountQuotaTracker.java
+++ b/services/core/java/com/android/server/utils/quota/CountQuotaTracker.java
@@ -28,6 +28,7 @@
 import android.os.Looper;
 import android.os.Message;
 import android.util.ArrayMap;
+import android.util.IndentingPrintWriter;
 import android.util.LongArrayQueue;
 import android.util.Slog;
 import android.util.TimeUtils;
@@ -36,7 +37,6 @@
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.IndentingPrintWriter;
 
 import java.util.function.Consumer;
 import java.util.function.Function;
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index a7849c1..cba215a 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -108,7 +108,6 @@
 import static android.os.InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
 import static android.os.Process.SYSTEM_UID;
 import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
-import static android.view.Display.COLOR_MODE_DEFAULT;
 import static android.view.Display.INVALID_DISPLAY;
 import static android.view.Surface.ROTATION_270;
 import static android.view.Surface.ROTATION_90;
@@ -225,6 +224,9 @@
 import static com.android.server.wm.IdentifierProto.USER_ID;
 import static com.android.server.wm.LetterboxConfiguration.DEFAULT_LETTERBOX_ASPECT_RATIO_FOR_MULTI_WINDOW;
 import static com.android.server.wm.LetterboxConfiguration.MIN_FIXED_ORIENTATION_LETTERBOX_ASPECT_RATIO;
+import static com.android.server.wm.StartingData.AFTER_TRANSACTION_COPY_TO_CLIENT;
+import static com.android.server.wm.StartingData.AFTER_TRANSACTION_IDLE;
+import static com.android.server.wm.StartingData.AFTER_TRANSACTION_REMOVE_DIRECTLY;
 import static com.android.server.wm.SurfaceAnimator.ANIMATION_TYPE_APP_TRANSITION;
 import static com.android.server.wm.SurfaceAnimator.ANIMATION_TYPE_PREDICT_BACK;
 import static com.android.server.wm.SurfaceAnimator.ANIMATION_TYPE_RECENTS;
@@ -2691,6 +2693,11 @@
         if (isTransferringSplashScreen()) {
             return true;
         }
+        // Only do transfer after transaction has done when starting window exist.
+        if (mStartingData != null && mStartingData.mWaitForSyncTransactionCommit) {
+            mStartingData.mRemoveAfterTransaction = AFTER_TRANSACTION_COPY_TO_CLIENT;
+            return true;
+        }
         requestCopySplashScreen();
         return isTransferringSplashScreen();
     }
@@ -2791,6 +2798,9 @@
             } else if (isEmbedded()) {
                 associateStartingWindowWithTaskIfNeeded();
             }
+            if (mTransitionController.isCollecting()) {
+                mStartingData.mTransitionId = mTransitionController.getCollectingTransitionId();
+            }
         }
     }
 
@@ -2848,11 +2858,14 @@
         if (mStartingData == null) {
             return;
         }
-        mStartingData.mWaitForSyncTransactionCommit = false;
-        if (mStartingData.mRemoveAfterTransaction) {
-            mStartingData.mRemoveAfterTransaction = false;
-            removeStartingWindowAnimation(mStartingData.mPrepareRemoveAnimation);
+        final StartingData lastData = mStartingData;
+        lastData.mWaitForSyncTransactionCommit = false;
+        if (lastData.mRemoveAfterTransaction == AFTER_TRANSACTION_REMOVE_DIRECTLY) {
+            removeStartingWindowAnimation(lastData.mPrepareRemoveAnimation);
+        } else if (lastData.mRemoveAfterTransaction == AFTER_TRANSACTION_COPY_TO_CLIENT) {
+            removeStartingWindow();
         }
+        lastData.mRemoveAfterTransaction = AFTER_TRANSACTION_IDLE;
     }
 
     void removeStartingWindowAnimation(boolean prepareAnimation) {
@@ -2879,7 +2892,7 @@
         if (mStartingData != null) {
             if (mStartingData.mWaitForSyncTransactionCommit
                     || mTransitionController.inCollectingTransition(startingWindow)) {
-                mStartingData.mRemoveAfterTransaction = true;
+                mStartingData.mRemoveAfterTransaction = AFTER_TRANSACTION_REMOVE_DIRECTLY;
                 mStartingData.mPrepareRemoveAnimation = prepareAnimation;
                 return;
             }
@@ -4703,26 +4716,11 @@
     }
 
     /**
-     * @return Whether we are allowed to show non-starting windows at the moment. We disallow
-     *         showing windows while the transition animation is playing in case we have windows
-     *         that have wide-color-gamut color mode set to avoid jank in the middle of the
-     *         animation.
+     * @return Whether we are allowed to show non-starting windows at the moment.
      */
     boolean canShowWindows() {
-        final boolean drawn = mTransitionController.isShellTransitionsEnabled()
+        return mTransitionController.isShellTransitionsEnabled()
                 ? mSyncState != SYNC_STATE_WAITING_FOR_DRAW : allDrawn;
-        final boolean animating = mTransitionController.isShellTransitionsEnabled()
-                ? mTransitionController.inPlayingTransition(this)
-                : isAnimating(PARENTS, ANIMATION_TYPE_APP_TRANSITION);
-        return drawn && !(animating && hasNonDefaultColorWindow());
-    }
-
-    /**
-     * @return true if we have a window that has a non-default color mode set; false otherwise.
-     */
-    private boolean hasNonDefaultColorWindow() {
-        return forAllWindows(ws -> ws.mAttrs.getColorMode() != COLOR_MODE_DEFAULT,
-                true /* topToBottom */);
     }
 
     @Override
diff --git a/services/core/java/com/android/server/wm/ActivitySnapshotController.java b/services/core/java/com/android/server/wm/ActivitySnapshotController.java
index 105b2bb..148bf9b 100644
--- a/services/core/java/com/android/server/wm/ActivitySnapshotController.java
+++ b/services/core/java/com/android/server/wm/ActivitySnapshotController.java
@@ -16,16 +16,14 @@
 
 package com.android.server.wm;
 
-import static com.android.server.wm.SnapshotController.ACTIVITY_CLOSE;
-import static com.android.server.wm.SnapshotController.ACTIVITY_OPEN;
-import static com.android.server.wm.SnapshotController.TASK_CLOSE;
-import static com.android.server.wm.SnapshotController.TASK_OPEN;
+import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.app.ActivityManager;
 import android.os.Environment;
 import android.os.SystemProperties;
+import android.os.Trace;
 import android.util.ArraySet;
 import android.util.Slog;
 import android.util.SparseArray;
@@ -35,7 +33,6 @@
 import com.android.server.LocalServices;
 import com.android.server.pm.UserManagerInternal;
 import com.android.server.wm.BaseAppSnapshotPersister.PersistInfoProvider;
-import com.android.server.wm.SnapshotController.TransitionState;
 
 import java.io.File;
 import java.util.ArrayList;
@@ -62,12 +59,6 @@
     static final String SNAPSHOTS_DIRNAME = "activity_snapshots";
 
     /**
-     * The pending activities which should capture snapshot when process transition finish.
-     */
-    @VisibleForTesting
-    final ArraySet<ActivityRecord> mPendingCaptureActivity = new ArraySet<>();
-
-    /**
      * The pending activities which should remove snapshot from memory when process transition
      * finish.
      */
@@ -86,6 +77,10 @@
     @VisibleForTesting
     final ArraySet<ActivityRecord> mPendingLoadActivity = new ArraySet<>();
 
+    private final ArraySet<ActivityRecord> mOnBackPressedActivities = new ArraySet<>();
+
+    private final ArrayList<ActivityRecord> mTmpBelowActivities = new ArrayList<>();
+    private final ArrayList<WindowContainer> mTmpTransitionParticipants = new ArrayList<>();
     private final SnapshotPersistQueue mSnapshotPersistQueue;
     private final PersistInfoProvider mPersistInfoProvider;
     private final AppSnapshotLoader mSnapshotLoader;
@@ -117,20 +112,6 @@
         setSnapshotEnabled(snapshotEnabled);
     }
 
-    void systemReady() {
-        if (shouldDisableSnapshots()) {
-            return;
-        }
-        mService.mSnapshotController.registerTransitionStateConsumer(
-                ACTIVITY_OPEN, this::handleOpenActivityTransition);
-        mService.mSnapshotController.registerTransitionStateConsumer(
-                ACTIVITY_CLOSE, this::handleCloseActivityTransition);
-        mService.mSnapshotController.registerTransitionStateConsumer(
-                TASK_OPEN, this::handleOpenTaskTransition);
-        mService.mSnapshotController.registerTransitionStateConsumer(
-                TASK_CLOSE, this::handleCloseTaskTransition);
-    }
-
     @Override
     protected float initSnapshotScale() {
         final float config = mService.mContext.getResources().getFloat(
@@ -173,6 +154,7 @@
 
                         @Override
                         void write() {
+                            Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "cleanUpUserFiles");
                             final File file = mPersistInfoProvider.getDirectory(userId);
                             if (file.exists()) {
                                 final File[] contents = file.listFiles();
@@ -182,15 +164,30 @@
                                     }
                                 }
                             }
+                            Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
                         }
                     });
         }
     }
 
+    void addOnBackPressedActivity(ActivityRecord ar) {
+        if (shouldDisableSnapshots()) {
+            return;
+        }
+        mOnBackPressedActivities.add(ar);
+    }
+
+    void clearOnBackPressedActivities() {
+        if (shouldDisableSnapshots()) {
+            return;
+        }
+        mOnBackPressedActivities.clear();
+    }
+
     /**
-     * Prepare to handle on transition start. Clear all temporary fields.
+     * Prepare to collect any change for snapshots processing. Clear all temporary fields.
      */
-    void preTransitionStart() {
+    void beginSnapshotProcess() {
         if (shouldDisableSnapshots()) {
             return;
         }
@@ -198,18 +195,22 @@
     }
 
     /**
-     * on transition start has notified, start process data.
+     * End collect any change for snapshots processing, start process data.
      */
-    void postTransitionStart() {
+    void endSnapshotProcess() {
         if (shouldDisableSnapshots()) {
             return;
         }
-        onCommitTransition();
+        for (int i = mOnBackPressedActivities.size() - 1; i >= 0; --i) {
+            handleActivityTransition(mOnBackPressedActivities.valueAt(i));
+        }
+        mOnBackPressedActivities.clear();
+        mTmpTransitionParticipants.clear();
+        postProcess();
     }
 
     @VisibleForTesting
     void resetTmpFields() {
-        mPendingCaptureActivity.clear();
         mPendingRemoveActivity.clear();
         mPendingDeleteActivity.clear();
         mPendingLoadActivity.clear();
@@ -218,31 +219,13 @@
     /**
      * Start process all pending activities for a transition.
      */
-    private void onCommitTransition() {
+    private void postProcess() {
         if (DEBUG) {
-            Slog.d(TAG, "ActivitySnapshotController#onCommitTransition result:"
-                    + " capture " + mPendingCaptureActivity
+            Slog.d(TAG, "ActivitySnapshotController#postProcess result:"
                     + " remove " + mPendingRemoveActivity
                     + " delete " + mPendingDeleteActivity
                     + " load " + mPendingLoadActivity);
         }
-        // task snapshots
-        for (int i = mPendingCaptureActivity.size() - 1; i >= 0; i--) {
-            recordSnapshot(mPendingCaptureActivity.valueAt(i));
-        }
-        // clear mTmpRemoveActivity from cache
-        for (int i = mPendingRemoveActivity.size() - 1; i >= 0; i--) {
-            final ActivityRecord ar = mPendingRemoveActivity.valueAt(i);
-            final int code = getSystemHashCode(ar);
-            mCache.onIdRemoved(code);
-        }
-        // clear snapshot on cache and delete files
-        for (int i = mPendingDeleteActivity.size() - 1; i >= 0; i--) {
-            final ActivityRecord ar = mPendingDeleteActivity.valueAt(i);
-            final int code = getSystemHashCode(ar);
-            mCache.onIdRemoved(code);
-            removeIfUserSavedFileExist(code, ar.mUserId);
-        }
         // load snapshot to cache
         for (int i = mPendingLoadActivity.size() - 1; i >= 0; i--) {
             final ActivityRecord ar = mPendingLoadActivity.valueAt(i);
@@ -258,6 +241,8 @@
                             new SnapshotPersistQueue.WriteQueueItem(mPersistInfoProvider) {
                                 @Override
                                 void write() {
+                                    Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER,
+                                            "load_activity_snapshot");
                                     final TaskSnapshot snapshot = mSnapshotLoader.loadTask(code,
                                             userId, false /* loadLowResolutionBitmap */);
                                     synchronized (mService.getWindowManagerLock()) {
@@ -265,16 +250,36 @@
                                             mCache.putSnapshot(ar, snapshot);
                                         }
                                     }
+                                    Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
                                 }
                             });
                 }
             }
         }
+        // clear mTmpRemoveActivity from cache
+        for (int i = mPendingRemoveActivity.size() - 1; i >= 0; i--) {
+            final ActivityRecord ar = mPendingRemoveActivity.valueAt(i);
+            final int code = getSystemHashCode(ar);
+            mCache.onIdRemoved(code);
+        }
+        // clear snapshot on cache and delete files
+        for (int i = mPendingDeleteActivity.size() - 1; i >= 0; i--) {
+            final ActivityRecord ar = mPendingDeleteActivity.valueAt(i);
+            final int code = getSystemHashCode(ar);
+            mCache.onIdRemoved(code);
+            removeIfUserSavedFileExist(code, ar.mUserId);
+        }
         // don't keep any reference
         resetTmpFields();
     }
 
-    private void recordSnapshot(ActivityRecord activity) {
+    void recordSnapshot(ActivityRecord activity) {
+        if (shouldDisableSnapshots()) {
+            return;
+        }
+        if (DEBUG) {
+            Slog.d(TAG, "ActivitySnapshotController#recordSnapshot " + activity);
+        }
         final TaskSnapshot snapshot = recordSnapshotInner(activity, false /* allowSnapshotHome */);
         if (snapshot != null) {
             final int code = getSystemHashCode(activity);
@@ -285,15 +290,20 @@
     /**
      * Called when the visibility of an app changes outside the regular app transition flow.
      */
-    void notifyAppVisibilityChanged(ActivityRecord appWindowToken, boolean visible) {
+    void notifyAppVisibilityChanged(ActivityRecord ar, boolean visible) {
         if (shouldDisableSnapshots()) {
             return;
         }
+        final Task task = ar.getTask();
+        if (task == null) {
+            return;
+        }
+        // Doesn't need to capture activity snapshot when it converts from translucent.
         if (!visible) {
             resetTmpFields();
-            addBelowTopActivityIfExist(appWindowToken.getTask(), mPendingRemoveActivity,
+            addBelowActivityIfExist(ar, mPendingRemoveActivity, false,
                     "remove-snapshot");
-            onCommitTransition();
+            postProcess();
         }
     }
 
@@ -301,65 +311,146 @@
         return System.identityHashCode(activity);
     }
 
-    void handleOpenActivityTransition(TransitionState<ActivityRecord> transitionState) {
-        ArraySet<ActivityRecord> participant = transitionState.getParticipant(false /* open */);
-        for (ActivityRecord ar : participant) {
-            mPendingCaptureActivity.add(ar);
-            // remove the snapshot for the one below close
-            final ActivityRecord below = ar.getTask().getActivityBelow(ar);
-            if (below != null) {
-                mPendingRemoveActivity.add(below);
+    @VisibleForTesting
+    void handleTransitionFinish(@NonNull ArrayList<WindowContainer> windows) {
+        mTmpTransitionParticipants.clear();
+        mTmpTransitionParticipants.addAll(windows);
+        for (int i = mTmpTransitionParticipants.size() - 1; i >= 0; --i) {
+            final WindowContainer next = mTmpTransitionParticipants.get(i);
+            if (next.asTask() != null) {
+                handleTaskTransition(next.asTask());
+            } else if (next.asTaskFragment() != null) {
+                final TaskFragment tf = next.asTaskFragment();
+                final ActivityRecord ar = tf.getTopMostActivity();
+                if (ar != null) {
+                    handleActivityTransition(ar);
+                }
+            } else if (next.asActivityRecord() != null) {
+                handleActivityTransition(next.asActivityRecord());
             }
         }
     }
 
-    void handleCloseActivityTransition(TransitionState<ActivityRecord> transitionState) {
-        ArraySet<ActivityRecord> participant = transitionState.getParticipant(true /* open */);
-        for (ActivityRecord ar : participant) {
+    private void handleActivityTransition(@NonNull ActivityRecord ar) {
+        if (shouldDisableSnapshots()) {
+            return;
+        }
+        if (ar.isVisibleRequested()) {
             mPendingDeleteActivity.add(ar);
             // load next one if exists.
-            final ActivityRecord below = ar.getTask().getActivityBelow(ar);
-            if (below != null) {
-                mPendingLoadActivity.add(below);
-            }
+            addBelowActivityIfExist(ar, mPendingLoadActivity, true, "load-snapshot");
+        } else {
+            // remove the snapshot for the one below close
+            addBelowActivityIfExist(ar, mPendingRemoveActivity, true, "remove-snapshot");
         }
     }
 
-    void handleCloseTaskTransition(TransitionState<Task> closeTaskTransitionRecord) {
-        ArraySet<Task> participant = closeTaskTransitionRecord.getParticipant(false /* open */);
-        for (Task close : participant) {
-            // this is close task transition
-            // remove the N - 1 from cache
-            addBelowTopActivityIfExist(close, mPendingRemoveActivity, "remove-snapshot");
+    private void handleTaskTransition(Task task) {
+        if (shouldDisableSnapshots()) {
+            return;
         }
-    }
-
-    void handleOpenTaskTransition(TransitionState<Task> openTaskTransitionRecord) {
-        ArraySet<Task> participant = openTaskTransitionRecord.getParticipant(true /* open */);
-        for (Task open : participant) {
-            // this is close task transition
-            // remove the N - 1 from cache
-            addBelowTopActivityIfExist(open, mPendingLoadActivity, "load-snapshot");
+        final ActivityRecord topActivity = task.getTopMostActivity();
+        if (topActivity == null) {
+            return;
+        }
+        if (task.isVisibleRequested()) {
+            // this is open task transition
+            // load the N - 1 to cache
+            addBelowActivityIfExist(topActivity, mPendingLoadActivity, true, "load-snapshot");
             // Move the activities to top of mSavedFilesInOrder, so when purge happen, there
             // will trim the persisted files from the most non-accessed.
-            adjustSavedFileOrder(open);
+            adjustSavedFileOrder(task);
+        } else {
+            // this is close task transition
+            // remove the N - 1 from cache
+            addBelowActivityIfExist(topActivity, mPendingRemoveActivity, true, "remove-snapshot");
         }
     }
 
-    // Add the top -1 activity to a set if it exists.
-    private void addBelowTopActivityIfExist(Task task, ArraySet<ActivityRecord> set,
-            String debugMessage) {
-        final ActivityRecord topActivity = task.getTopMostActivity();
-        if (topActivity != null) {
-            final ActivityRecord below = task.getActivityBelow(topActivity);
-            if (below != null) {
-                set.add(below);
-                if (DEBUG) {
-                    Slog.d(TAG, "ActivitySnapshotController#addBelowTopActivityIfExist "
-                            + below + " from " + debugMessage);
-                }
+    /**
+     * Add the top -1 activity to a set if it exists.
+     * @param inTransition true if the activity must participant in transition.
+     */
+    private void addBelowActivityIfExist(ActivityRecord currentActivity,
+            ArraySet<ActivityRecord> set, boolean inTransition, String debugMessage) {
+        getActivityBelow(currentActivity, inTransition, mTmpBelowActivities);
+        for (int i = mTmpBelowActivities.size() - 1; i >= 0; --i) {
+            set.add(mTmpBelowActivities.get(i));
+            if (DEBUG) {
+                Slog.d(TAG, "ActivitySnapshotController#addBelowTopActivityIfExist "
+                        + mTmpBelowActivities.get(i) + " from " + debugMessage);
             }
         }
+        mTmpBelowActivities.clear();
+    }
+
+    private void getActivityBelow(ActivityRecord currentActivity, boolean inTransition,
+            ArrayList<ActivityRecord> result) {
+        final Task currentTask = currentActivity.getTask();
+        if (currentTask == null) {
+            return;
+        }
+        final ActivityRecord initPrev = currentTask.getActivityBelow(currentActivity);
+        if (initPrev == null) {
+            return;
+        }
+        final TaskFragment currTF = currentActivity.getTaskFragment();
+        final TaskFragment prevTF = initPrev.getTaskFragment();
+        final TaskFragment prevAdjacentTF = prevTF != null
+                ? prevTF.getAdjacentTaskFragment() : null;
+        if (currTF == prevTF && currTF != null || prevAdjacentTF == null) {
+            // Current activity and previous one is in the same task fragment, or
+            // previous activity is not in a task fragment, or
+            // previous activity's task fragment doesn't adjacent to any others.
+            if (!inTransition || isInParticipant(initPrev, mTmpTransitionParticipants)) {
+                result.add(initPrev);
+            }
+            return;
+        }
+
+        if (prevAdjacentTF == currTF) {
+            // previous activity A is adjacent to current activity B.
+            // Try to find anyone below previous activityA, which are C and D if exists.
+            // A | B
+            // C (| D)
+            getActivityBelow(initPrev, inTransition, result);
+        } else {
+            // previous activity C isn't adjacent to current activity A.
+            // A
+            // B | C
+            final Task prevAdjacentTask = prevAdjacentTF.getTask();
+            if (prevAdjacentTask == currentTask) {
+                final int currentIndex = currTF != null
+                        ? currentTask.mChildren.indexOf(currTF)
+                        : currentTask.mChildren.indexOf(currentActivity);
+                final int prevAdjacentIndex =
+                        prevAdjacentTask.mChildren.indexOf(prevAdjacentTF);
+                // prevAdjacentTF already above currentActivity
+                if (prevAdjacentIndex > currentIndex) {
+                    return;
+                }
+            }
+            if (!inTransition || isInParticipant(initPrev, mTmpTransitionParticipants)) {
+                result.add(initPrev);
+            }
+            // prevAdjacentTF is adjacent to another one
+            final ActivityRecord prevAdjacentActivity = prevAdjacentTF.getTopMostActivity();
+            if (prevAdjacentActivity != null && (!inTransition
+                    || isInParticipant(prevAdjacentActivity, mTmpTransitionParticipants))) {
+                result.add(prevAdjacentActivity);
+            }
+        }
+    }
+
+    static boolean isInParticipant(ActivityRecord ar,
+            ArrayList<WindowContainer> transitionParticipants) {
+        for (int i = transitionParticipants.size() - 1; i >= 0; --i) {
+            final WindowContainer wc = transitionParticipants.get(i);
+            if (ar == wc || ar.isDescendantOf(wc)) {
+                return true;
+            }
+        }
+        return false;
     }
 
     private void adjustSavedFileOrder(Task nextTopTask) {
@@ -376,6 +467,9 @@
 
     @Override
     void onAppRemoved(ActivityRecord activity) {
+        if (shouldDisableSnapshots()) {
+            return;
+        }
         super.onAppRemoved(activity);
         final int code = getSystemHashCode(activity);
         removeIfUserSavedFileExist(code, activity.mUserId);
@@ -386,6 +480,9 @@
 
     @Override
     void onAppDied(ActivityRecord activity) {
+        if (shouldDisableSnapshots()) {
+            return;
+        }
         super.onAppDied(activity);
         final int code = getSystemHashCode(activity);
         removeIfUserSavedFileExist(code, activity.mUserId);
@@ -440,7 +537,7 @@
     private void removeIfUserSavedFileExist(int code, int userId) {
         final UserSavedFile usf = getUserFiles(userId).get(code);
         if (usf != null) {
-            mUserSavedFiles.remove(code);
+            mUserSavedFiles.get(userId).remove(code);
             mSavedFilesInOrder.remove(usf);
             mPersister.removeSnap(code, userId);
         }
@@ -490,11 +587,13 @@
                     new SnapshotPersistQueue.WriteQueueItem(mPersistInfoProvider) {
                         @Override
                         void write() {
+                            Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activity_remove_files");
                             for (int i = files.size() - 1; i >= 0; --i) {
                                 final UserSavedFile usf = files.get(i);
                                 mSnapshotPersistQueue.deleteSnapshot(
                                         usf.mFileId, usf.mUserId, mPersistInfoProvider);
                             }
+                            Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
                         }
                     });
         }
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
index 8673b90..fb62412 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@@ -2606,9 +2606,6 @@
         final int callingUid = Binder.getCallingUid();
         final long ident = Binder.clearCallingIdentity();
         try {
-            // When a task is locked, dismiss the root pinned task if it exists
-            mRootWindowContainer.removeRootTasksInWindowingModes(WINDOWING_MODE_PINNED);
-
             getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
         } finally {
             Binder.restoreCallingIdentity(ident);
@@ -3029,9 +3026,11 @@
         // Set to activity manager directly to make sure the state can be seen by the subsequent
         // update of scheduling group.
         proc.setRunningAnimationUnsafe();
-        mH.removeMessages(H.UPDATE_PROCESS_ANIMATING_STATE, proc);
-        mH.sendMessageDelayed(mH.obtainMessage(H.UPDATE_PROCESS_ANIMATING_STATE, proc),
+        mH.sendMessage(mH.obtainMessage(H.ADD_WAKEFULNESS_ANIMATING_REASON, proc));
+        mH.removeMessages(H.REMOVE_WAKEFULNESS_ANIMATING_REASON, proc);
+        mH.sendMessageDelayed(mH.obtainMessage(H.REMOVE_WAKEFULNESS_ANIMATING_REASON, proc),
                 DOZE_ANIMATING_STATE_RETAIN_TIME_MS);
+        Trace.instant(TRACE_TAG_WINDOW_MANAGER, "requestWakefulnessAnimating");
     }
 
     @Override
@@ -5657,9 +5656,10 @@
 
     final class H extends Handler {
         static final int REPORT_TIME_TRACKER_MSG = 1;
-        static final int UPDATE_PROCESS_ANIMATING_STATE = 2;
         static final int END_POWER_MODE_UNKNOWN_VISIBILITY_MSG = 3;
         static final int RESUME_FG_APP_SWITCH_MSG = 4;
+        static final int ADD_WAKEFULNESS_ANIMATING_REASON = 5;
+        static final int REMOVE_WAKEFULNESS_ANIMATING_REASON = 6;
 
         static final int FIRST_ACTIVITY_TASK_MSG = 100;
         static final int FIRST_SUPERVISOR_TASK_MSG = 200;
@@ -5676,13 +5676,23 @@
                     tracker.deliverResult(mContext);
                 }
                 break;
-                case UPDATE_PROCESS_ANIMATING_STATE: {
+                case ADD_WAKEFULNESS_ANIMATING_REASON: {
                     final WindowProcessController proc = (WindowProcessController) msg.obj;
                     synchronized (mGlobalLock) {
-                        proc.updateRunningRemoteOrRecentsAnimation();
+                        proc.addAnimatingReason(
+                                WindowProcessController.ANIMATING_REASON_WAKEFULNESS_CHANGE);
                     }
                 }
                 break;
+                case REMOVE_WAKEFULNESS_ANIMATING_REASON: {
+                    final WindowProcessController proc = (WindowProcessController) msg.obj;
+                    synchronized (mGlobalLock) {
+                        proc.removeAnimatingReason(
+                                WindowProcessController.ANIMATING_REASON_WAKEFULNESS_CHANGE);
+                    }
+                    Trace.instant(TRACE_TAG_WINDOW_MANAGER, "finishWakefulnessAnimating");
+                }
+                break;
                 case END_POWER_MODE_UNKNOWN_VISIBILITY_MSG: {
                     synchronized (mGlobalLock) {
                         mRetainPowerModeAndTopProcessState = false;
diff --git a/services/core/java/com/android/server/wm/AsyncRotationController.java b/services/core/java/com/android/server/wm/AsyncRotationController.java
index 4ce21bd..2eceecc 100644
--- a/services/core/java/com/android/server/wm/AsyncRotationController.java
+++ b/services/core/java/com/android/server/wm/AsyncRotationController.java
@@ -33,6 +33,7 @@
 
 import com.android.internal.R;
 
+import java.io.PrintWriter;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.function.Consumer;
@@ -224,7 +225,15 @@
      * operation directly to avoid waiting until timeout.
      */
     void updateTargetWindows() {
-        if (mTransitionOp == OP_LEGACY || !mIsStartTransactionCommitted) return;
+        if (mTransitionOp == OP_LEGACY) return;
+        if (!mIsStartTransactionCommitted) {
+            if (mTimeoutRunnable == null && !mDisplayContent.hasTopFixedRotationLaunchingApp()
+                    && !mDisplayContent.isRotationChanging() && !mDisplayContent.inTransition()) {
+                Slog.d(TAG, "Cancel for no change");
+                mDisplayContent.finishAsyncRotationIfPossible();
+            }
+            return;
+        }
         for (int i = mTargetWindowTokens.size() - 1; i >= 0; i--) {
             final Operation op = mTargetWindowTokens.valueAt(i);
             if (op.mIsCompletionPending || op.mAction == Operation.ACTION_SEAMLESS) {
@@ -608,6 +617,16 @@
         return op.mAction != Operation.ACTION_SEAMLESS;
     }
 
+    void dump(PrintWriter pw, String prefix) {
+        pw.println(prefix + "AsyncRotationController");
+        prefix += "  ";
+        pw.println(prefix + "mTransitionOp=" + mTransitionOp);
+        pw.println(prefix + "mIsStartTransactionCommitted=" + mIsStartTransactionCommitted);
+        pw.println(prefix + "mIsSyncDrawRequested=" + mIsSyncDrawRequested);
+        pw.println(prefix + "mOriginalRotation=" + mOriginalRotation);
+        pw.println(prefix + "mTargetWindowTokens=" + mTargetWindowTokens);
+    }
+
     /** The operation to control the rotation appearance associated with window token. */
     private static class Operation {
         @Retention(RetentionPolicy.SOURCE)
@@ -635,5 +654,10 @@
         Operation(@Action int action) {
             mAction = action;
         }
+
+        @Override
+        public String toString() {
+            return "Operation{a=" + mAction + " pending=" + mIsCompletionPending + '}';
+        }
     }
 }
diff --git a/services/core/java/com/android/server/wm/BackNavigationController.java b/services/core/java/com/android/server/wm/BackNavigationController.java
index 976641b..993c016 100644
--- a/services/core/java/com/android/server/wm/BackNavigationController.java
+++ b/services/core/java/com/android/server/wm/BackNavigationController.java
@@ -1177,6 +1177,8 @@
                 if (!composeAnimations(mCloseTarget, mOpenTarget, openActivity)) {
                     return null;
                 }
+                mCloseTarget.mTransitionController.mSnapshotController
+                        .mActivitySnapshotController.clearOnBackPressedActivities();
                 applyPreviewStrategy(mOpenAdaptor, openActivity);
 
                 final IBackAnimationFinishedCallback callback = makeAnimationFinishedCallback();
@@ -1222,6 +1224,8 @@
             // Call it again to make sure the activity could be visible while handling the pending
             // animation.
             activity.commitVisibility(true, true);
+            activity.mTransitionController.mSnapshotController
+                    .mActivitySnapshotController.addOnBackPressedActivity(activity);
         }
         activity.mLaunchTaskBehind = true;
 
@@ -1248,6 +1252,9 @@
         // Restore the launch-behind state.
         activity.mTaskSupervisor.scheduleLaunchTaskBehindComplete(activity.token);
         activity.mLaunchTaskBehind = false;
+        // Ignore all change
+        activity.mTransitionController.mSnapshotController
+                .mActivitySnapshotController.clearOnBackPressedActivities();
         ProtoLog.d(WM_DEBUG_BACK_PREVIEW,
                 "Setting Activity.mLauncherTaskBehind to false. Activity=%s",
                 activity);
diff --git a/services/core/java/com/android/server/wm/ContentRecorder.java b/services/core/java/com/android/server/wm/ContentRecorder.java
index 2ecbf8a..5aa7c97 100644
--- a/services/core/java/com/android/server/wm/ContentRecorder.java
+++ b/services/core/java/com/android/server/wm/ContentRecorder.java
@@ -87,7 +87,7 @@
     private int mLastOrientation = ORIENTATION_UNDEFINED;
 
     ContentRecorder(@NonNull DisplayContent displayContent) {
-        this(displayContent, new RemoteMediaProjectionManagerWrapper());
+        this(displayContent, new RemoteMediaProjectionManagerWrapper(displayContent.mDisplayId));
     }
 
     @VisibleForTesting
@@ -556,8 +556,14 @@
 
     private static final class RemoteMediaProjectionManagerWrapper implements
             MediaProjectionManagerWrapper {
+
+        private final int mDisplayId;
         @Nullable private IMediaProjectionManager mIMediaProjectionManager = null;
 
+        RemoteMediaProjectionManagerWrapper(int displayId) {
+            mDisplayId = displayId;
+        }
+
         @Override
         public void stopActiveProjection() {
             fetchMediaProjectionManager();
@@ -565,12 +571,15 @@
                 return;
             }
             try {
+                ProtoLog.e(WM_DEBUG_CONTENT_RECORDING,
+                        "Content Recording: stopping active projection for display %d",
+                        mDisplayId);
                 mIMediaProjectionManager.stopActiveProjection();
             } catch (RemoteException e) {
                 ProtoLog.e(WM_DEBUG_CONTENT_RECORDING,
                         "Content Recording: Unable to tell MediaProjectionManagerService to stop "
-                                + "the active projection: %s",
-                        e);
+                                + "the active projection for display %d: %s",
+                        mDisplayId, e);
             }
         }
 
diff --git a/services/core/java/com/android/server/wm/ContentRecordingController.java b/services/core/java/com/android/server/wm/ContentRecordingController.java
index f24ba5a..b589085 100644
--- a/services/core/java/com/android/server/wm/ContentRecordingController.java
+++ b/services/core/java/com/android/server/wm/ContentRecordingController.java
@@ -117,10 +117,11 @@
             }
             incomingDisplayContent.setContentRecordingSession(incomingSession);
             // Updating scenario: Explicitly ask ContentRecorder to update, since no config or
-            // display change will trigger an update from the DisplayContent.
-            if (hasSessionUpdatedWithConsent) {
-                incomingDisplayContent.updateRecording();
-            }
+            // display change will trigger an update from the DisplayContent. There exists a
+            // scenario where a DisplayContent is created, but it's ContentRecordingSession hasn't
+            // been set yet due to a race condition. On creation, updateRecording fails to start
+            // recording, so now this call guarantees recording will be started from somewhere.
+            incomingDisplayContent.updateRecording();
         }
         // Takeover and stopping scenario: stop recording on the pre-existing session.
         if (mSession != null && !hasSessionUpdatedWithConsent) {
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 614493d..5c82dba 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -3453,6 +3453,9 @@
                 if (mFixedRotationLaunchingApp != null) {
                     setSeamlessTransitionForFixedRotation(controller.getCollectingTransition());
                 }
+            } else if (mAsyncRotationController != null && !isRotationChanging()) {
+                Slog.i(TAG, "Finish AsyncRotation for previous intermediate change");
+                finishAsyncRotationIfPossible();
             }
             return;
         }
@@ -3626,6 +3629,9 @@
         if (mFixedRotationLaunchingApp != null) {
             pw.println("  mFixedRotationLaunchingApp=" + mFixedRotationLaunchingApp);
         }
+        if (mAsyncRotationController != null) {
+            mAsyncRotationController.dump(pw, prefix);
+        }
 
         pw.println();
         pw.print(prefix + "mHoldScreenWindow="); pw.print(mHoldScreenWindow);
@@ -6494,6 +6500,13 @@
     }
 
     /**
+     * @return whether the physical display has a fixed orientation and cannot be rotated.
+     */
+    boolean isDisplayOrientationFixed() {
+        return (mDisplayInfo.flags & Display.FLAG_ROTATES_WITH_CONTENT) == 0;
+    }
+
+    /**
      * @return whether AOD is showing on this display
      */
     boolean isAodShowing() {
diff --git a/services/core/java/com/android/server/wm/DisplayRotation.java b/services/core/java/com/android/server/wm/DisplayRotation.java
index 70edf3a..9ef25b6 100644
--- a/services/core/java/com/android/server/wm/DisplayRotation.java
+++ b/services/core/java/com/android/server/wm/DisplayRotation.java
@@ -434,7 +434,8 @@
         final boolean isTv = mContext.getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_LEANBACK);
         mDefaultFixedToUserRotation =
-                (isCar || isTv || mService.mIsPc || mDisplayContent.forceDesktopMode())
+                (isCar || isTv || mService.mIsPc || mDisplayContent.forceDesktopMode()
+                        || mDisplayContent.isDisplayOrientationFixed())
                 // For debug purposes the next line turns this feature off with:
                 // $ adb shell setprop config.override_forced_orient true
                 // $ adb shell wm size reset
diff --git a/services/core/java/com/android/server/wm/InputManagerCallback.java b/services/core/java/com/android/server/wm/InputManagerCallback.java
index 20595ea..73fdfe0 100644
--- a/services/core/java/com/android/server/wm/InputManagerCallback.java
+++ b/services/core/java/com/android/server/wm/InputManagerCallback.java
@@ -25,6 +25,7 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.gui.StalledTransactionInfo;
 import android.os.Debug;
 import android.os.IBinder;
 import android.util.Slog;
@@ -96,7 +97,7 @@
     @Override
     public void notifyNoFocusedWindowAnr(@NonNull InputApplicationHandle applicationHandle) {
         TimeoutRecord timeoutRecord = TimeoutRecord.forInputDispatchNoFocusedWindow(
-                timeoutMessage("Application does not have a focused window"));
+                timeoutMessage(OptionalInt.empty(), "Application does not have a focused window"));
         mService.mAnrController.notifyAppUnresponsive(applicationHandle, timeoutRecord);
     }
 
@@ -104,7 +105,7 @@
     public void notifyWindowUnresponsive(@NonNull IBinder token, @NonNull OptionalInt pid,
             String reason) {
         TimeoutRecord timeoutRecord = TimeoutRecord.forInputDispatchWindowUnresponsive(
-                timeoutMessage(reason));
+                timeoutMessage(pid, reason));
         mService.mAnrController.notifyWindowUnresponsive(token, pid, timeoutRecord);
     }
 
@@ -354,11 +355,21 @@
         mService.mInputManager.setInputDispatchMode(mInputDispatchEnabled, mInputDispatchFrozen);
     }
 
-    private String timeoutMessage(String reason) {
-        if (reason == null) {
-            return "Input dispatching timed out";
+    private String timeoutMessage(OptionalInt pid, String reason) {
+        String message = (reason == null) ? "Input dispatching timed out."
+                : String.format("Input dispatching timed out (%s).", reason);
+        if (pid.isEmpty()) {
+            return message;
         }
-        return "Input dispatching timed out (" + reason + ")";
+        StalledTransactionInfo stalledTransactionInfo =
+                SurfaceControl.getStalledTransactionInfo(pid.getAsInt());
+        if (stalledTransactionInfo == null) {
+            return message;
+        }
+        return String.format("%s Buffer processing for the associated surface is stuck due to an "
+                + "unsignaled fence (window=%s, bufferId=0x%016X, frameNumber=%s). This "
+                + "potentially indicates a GPU hang.", message, stalledTransactionInfo.layerName,
+                stalledTransactionInfo.bufferId, stalledTransactionInfo.frameNumber);
     }
 
     void dump(PrintWriter pw, String prefix) {
diff --git a/services/core/java/com/android/server/wm/Letterbox.java b/services/core/java/com/android/server/wm/Letterbox.java
index 3551370..f9fa9e6 100644
--- a/services/core/java/com/android/server/wm/Letterbox.java
+++ b/services/core/java/com/android/server/wm/Letterbox.java
@@ -20,7 +20,6 @@
 import static android.view.SurfaceControl.HIDDEN;
 import static android.window.TaskConstants.TASK_CHILD_LAYER_LETTERBOX_BACKGROUND;
 
-import android.content.Context;
 import android.graphics.Color;
 import android.graphics.Point;
 import android.graphics.Rect;
@@ -256,11 +255,11 @@
         private final GestureDetector mDoubleTapDetector;
         private final DoubleTapListener mDoubleTapListener;
 
-        TapEventReceiver(InputChannel inputChannel, Context context) {
+        TapEventReceiver(InputChannel inputChannel, WindowManagerService wmService) {
             super(inputChannel, UiThread.getHandler().getLooper());
-            mDoubleTapListener = new DoubleTapListener();
+            mDoubleTapListener = new DoubleTapListener(wmService);
             mDoubleTapDetector = new GestureDetector(
-                    context, mDoubleTapListener, UiThread.getHandler());
+                    wmService.mContext, mDoubleTapListener, UiThread.getHandler());
         }
 
         @Override
@@ -271,14 +270,24 @@
     }
 
     private class DoubleTapListener extends GestureDetector.SimpleOnGestureListener {
+        private final WindowManagerService mWmService;
+
+        private DoubleTapListener(WindowManagerService wmService) {
+            mWmService = wmService;
+        }
+
         @Override
         public boolean onDoubleTapEvent(MotionEvent e) {
-            if (e.getAction() == MotionEvent.ACTION_UP) {
-                mDoubleTapCallbackX.accept((int) e.getRawX());
-                mDoubleTapCallbackY.accept((int) e.getRawY());
-                return true;
+            synchronized (mWmService.mGlobalLock) {
+                // This check prevents late events to be handled in case the Letterbox has been
+                // already destroyed and so mOuter.isEmpty() is true.
+                if (!mOuter.isEmpty() && e.getAction() == MotionEvent.ACTION_UP) {
+                    mDoubleTapCallbackX.accept((int) e.getRawX());
+                    mDoubleTapCallbackY.accept((int) e.getRawY());
+                    return true;
+                }
+                return false;
             }
-            return false;
         }
     }
 
@@ -294,7 +303,7 @@
             mWmService = win.mWmService;
             final String name = namePrefix + (win.mActivityRecord != null ? win.mActivityRecord : win);
             mClientChannel = mWmService.mInputManager.createInputChannel(name);
-            mInputEventReceiver = new TapEventReceiver(mClientChannel, mWmService.mContext);
+            mInputEventReceiver = new TapEventReceiver(mClientChannel, mWmService);
 
             mToken = mClientChannel.getToken();
 
diff --git a/services/core/java/com/android/server/wm/LetterboxUiController.java b/services/core/java/com/android/server/wm/LetterboxUiController.java
index 7d3c87a..01786be 100644
--- a/services/core/java/com/android/server/wm/LetterboxUiController.java
+++ b/services/core/java/com/android/server/wm/LetterboxUiController.java
@@ -63,6 +63,8 @@
 import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_MIN_ASPECT_RATIO_OVERRIDE;
 import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE;
 import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_RESIZEABLE_ACTIVITY_OVERRIDES;
+import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_FULLSCREEN_OVERRIDE;
+import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_OVERRIDE;
 import static android.view.WindowManager.PROPERTY_COMPAT_ENABLE_FAKE_FOCUS;
 import static android.view.WindowManager.PROPERTY_COMPAT_IGNORE_REQUESTED_ORIENTATION;
 
@@ -215,6 +217,11 @@
     @Nullable
     private final Boolean mBooleanPropertyAllowForceResizeOverride;
 
+    @Nullable
+    private final Boolean mBooleanPropertyAllowUserAspectRatioOverride;
+    @Nullable
+    private final Boolean mBooleanPropertyAllowUserAspectRatioFullscreenOverride;
+
     /*
      * WindowContainerListener responsible to make translucent activities inherit
      * constraints from the first opaque activity beneath them. It's null for not
@@ -335,6 +342,15 @@
                         /* gatingCondition */ null,
                         PROPERTY_COMPAT_ALLOW_RESIZEABLE_ACTIVITY_OVERRIDES);
 
+        mBooleanPropertyAllowUserAspectRatioOverride =
+                readComponentProperty(packageManager, mActivityRecord.packageName,
+                        () -> mLetterboxConfiguration.isUserAppAspectRatioSettingsEnabled(),
+                        PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_OVERRIDE);
+        mBooleanPropertyAllowUserAspectRatioFullscreenOverride =
+                readComponentProperty(packageManager, mActivityRecord.packageName,
+                        () -> mLetterboxConfiguration.isUserAppAspectRatioFullscreenEnabled(),
+                        PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_FULLSCREEN_OVERRIDE);
+
         mIsOverrideAnyOrientationEnabled = isCompatChangeEnabled(OVERRIDE_ANY_ORIENTATION);
         mIsOverrideToPortraitOrientationEnabled =
                 isCompatChangeEnabled(OVERRIDE_UNDEFINED_ORIENTATION_TO_PORTRAIT);
@@ -953,8 +969,10 @@
             final Rect innerFrame = hasInheritedLetterboxBehavior()
                     ? mActivityRecord.getBounds() : w.getFrame();
             mLetterbox.layout(spaceToFill, innerFrame, mTmpPoint);
-            // We need to notify Shell that letterbox position has changed.
-            mActivityRecord.getTask().dispatchTaskInfoChangedIfNeeded(true /* force */);
+            if (mDoubleTapEvent) {
+                // We need to notify Shell that letterbox position has changed.
+                mActivityRecord.getTask().dispatchTaskInfoChangedIfNeeded(true /* force */);
+            }
         } else if (mLetterbox != null) {
             mLetterbox.hide();
         }
@@ -1109,7 +1127,8 @@
     }
 
     boolean shouldApplyUserMinAspectRatioOverride() {
-        if (!mLetterboxConfiguration.isUserAppAspectRatioSettingsEnabled()
+        if (FALSE.equals(mBooleanPropertyAllowUserAspectRatioOverride)
+                || !mLetterboxConfiguration.isUserAppAspectRatioSettingsEnabled()
                 || mActivityRecord.mDisplayContent == null
                 || !mActivityRecord.mDisplayContent.getIgnoreOrientationRequest()) {
             return false;
@@ -1122,7 +1141,9 @@
     }
 
     boolean shouldApplyUserFullscreenOverride() {
-        if (!mLetterboxConfiguration.isUserAppAspectRatioFullscreenEnabled()
+        if (FALSE.equals(mBooleanPropertyAllowUserAspectRatioOverride)
+                || FALSE.equals(mBooleanPropertyAllowUserAspectRatioFullscreenOverride)
+                || !mLetterboxConfiguration.isUserAppAspectRatioFullscreenEnabled()
                 || mActivityRecord.mDisplayContent == null
                 || !mActivityRecord.mDisplayContent.getIgnoreOrientationRequest()) {
             return false;
@@ -1151,7 +1172,8 @@
         }
     }
 
-    private int getUserMinAspectRatioOverrideCode() {
+    @VisibleForTesting
+    int getUserMinAspectRatioOverrideCode() {
         try {
             return mActivityRecord.mAtmService.getPackageManager()
                     .getUserMinAspectRatio(mActivityRecord.packageName, mActivityRecord.mUserId);
@@ -1222,6 +1244,7 @@
                                 ? LETTERBOX_POSITION_CHANGED__POSITION_CHANGE__CENTER_TO_LEFT
                                 : LETTERBOX_POSITION_CHANGED__POSITION_CHANGE__RIGHT_TO_CENTER;
             logLetterboxPositionChange(changeToLog);
+            mDoubleTapEvent = true;
         } else if (mLetterbox.getInnerFrame().right < x) {
             // Moving to the next stop on the right side of the app window: left > center > right.
             mLetterboxConfiguration.movePositionForHorizontalReachabilityToNextRightStop(
@@ -1232,8 +1255,8 @@
                                 ? LETTERBOX_POSITION_CHANGED__POSITION_CHANGE__CENTER_TO_RIGHT
                                 : LETTERBOX_POSITION_CHANGED__POSITION_CHANGE__LEFT_TO_CENTER;
             logLetterboxPositionChange(changeToLog);
+            mDoubleTapEvent = true;
         }
-        mDoubleTapEvent = true;
         // TODO(197549949): Add animation for transition.
         mActivityRecord.recomputeConfiguration();
     }
@@ -1261,6 +1284,7 @@
                                 ? LETTERBOX_POSITION_CHANGED__POSITION_CHANGE__CENTER_TO_TOP
                                 : LETTERBOX_POSITION_CHANGED__POSITION_CHANGE__BOTTOM_TO_CENTER;
             logLetterboxPositionChange(changeToLog);
+            mDoubleTapEvent = true;
         } else if (mLetterbox.getInnerFrame().bottom < y) {
             // Moving to the next stop on the bottom side of the app window: top > center > bottom.
             mLetterboxConfiguration.movePositionForVerticalReachabilityToNextBottomStop(
@@ -1271,8 +1295,8 @@
                                 ? LETTERBOX_POSITION_CHANGED__POSITION_CHANGE__CENTER_TO_BOTTOM
                                 : LETTERBOX_POSITION_CHANGED__POSITION_CHANGE__TOP_TO_CENTER;
             logLetterboxPositionChange(changeToLog);
+            mDoubleTapEvent = true;
         }
-        mDoubleTapEvent = true;
         // TODO(197549949): Add animation for transition.
         mActivityRecord.recomputeConfiguration();
     }
diff --git a/services/core/java/com/android/server/wm/LockTaskController.java b/services/core/java/com/android/server/wm/LockTaskController.java
index 0c98fb5..0f9998c 100644
--- a/services/core/java/com/android/server/wm/LockTaskController.java
+++ b/services/core/java/com/android/server/wm/LockTaskController.java
@@ -19,6 +19,7 @@
 import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
 import static android.app.ActivityManager.LOCK_TASK_MODE_PINNED;
+import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
 import static android.content.Context.DEVICE_POLICY_SERVICE;
 import static android.content.Context.STATUS_BAR_SERVICE;
@@ -669,6 +670,9 @@
             }
         }
 
+        // When a task is locked, dismiss the root pinned task if it exists 
+        mSupervisor.mRootWindowContainer.removeRootTasksInWindowingModes(WINDOWING_MODE_PINNED);
+
         // System can only initiate screen pinning, not full lock task mode
         ProtoLog.w(WM_DEBUG_LOCKTASK, "%s", isSystemCaller ? "Locking pinned" : "Locking fully");
         setLockTaskMode(task, isSystemCaller ? LOCK_TASK_MODE_PINNED : LOCK_TASK_MODE_LOCKED,
diff --git a/services/core/java/com/android/server/wm/OWNERS b/services/core/java/com/android/server/wm/OWNERS
index 0af9fe9..26abe51 100644
--- a/services/core/java/com/android/server/wm/OWNERS
+++ b/services/core/java/com/android/server/wm/OWNERS
@@ -18,4 +18,4 @@
 yunfanc@google.com
 
 per-file BackgroundActivityStartController.java = set noparent
-per-file BackgroundActivityStartController.java = brufino@google.com, ogunwale@google.com, louischang@google.com, lus@google.com, rickywai@google.com
+per-file BackgroundActivityStartController.java = brufino@google.com, ogunwale@google.com, louischang@google.com, lus@google.com
diff --git a/services/core/java/com/android/server/wm/SnapshotController.java b/services/core/java/com/android/server/wm/SnapshotController.java
index badcfa9..37f9730 100644
--- a/services/core/java/com/android/server/wm/SnapshotController.java
+++ b/services/core/java/com/android/server/wm/SnapshotController.java
@@ -16,185 +16,36 @@
 
 package com.android.server.wm;
 
+import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
+import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
 import static android.view.WindowManager.TRANSIT_CLOSE;
 import static android.view.WindowManager.TRANSIT_FIRST_CUSTOM;
 import static android.view.WindowManager.TRANSIT_OPEN;
 import static android.view.WindowManager.TRANSIT_TO_BACK;
 import static android.view.WindowManager.TRANSIT_TO_FRONT;
 
-import android.annotation.IntDef;
-import android.util.ArraySet;
-import android.util.Slog;
-import android.util.SparseArray;
+import android.os.Trace;
 import android.view.WindowManager;
 
-import com.android.internal.annotations.VisibleForTesting;
-
 import java.io.PrintWriter;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
 import java.util.ArrayList;
-import java.util.function.Consumer;
 
 /**
  * Integrates common functionality from TaskSnapshotController and ActivitySnapshotController.
  */
 class SnapshotController {
-    private static final boolean DEBUG = false;
-    private static final String TAG = AbsAppSnapshotController.TAG;
-
-    static final int ACTIVITY_OPEN = 1;
-    static final int ACTIVITY_CLOSE = 2;
-    static final int TASK_OPEN = 4;
-    static final int TASK_CLOSE = 8;
-    /** @hide */
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef(
-            value = {ACTIVITY_OPEN,
-                    ACTIVITY_CLOSE,
-                    TASK_OPEN,
-                    TASK_CLOSE})
-    @interface TransitionStateType {}
-
     private final SnapshotPersistQueue mSnapshotPersistQueue;
     final TaskSnapshotController mTaskSnapshotController;
     final ActivitySnapshotController mActivitySnapshotController;
 
-    private final ArraySet<Task> mTmpCloseTasks = new ArraySet<>();
-    private final ArraySet<Task> mTmpOpenTasks = new ArraySet<>();
-
-    private final SparseArray<TransitionState> mTmpOpenCloseRecord = new SparseArray<>();
-    private final ArraySet<Integer> mTmpAnalysisRecord = new ArraySet<>();
-    private final SparseArray<ArrayList<Consumer<TransitionState>>> mTransitionStateConsumer =
-            new SparseArray<>();
-    private int mActivatedType;
-
-    private final ActivityOrderCheck mActivityOrderCheck = new ActivityOrderCheck();
-    private final ActivityOrderCheck.AnalysisResult mResultHandler = (type, close, open) -> {
-        addTransitionRecord(type, true/* open */, open);
-        addTransitionRecord(type, false/* open */, close);
-    };
-
-    private static class ActivityOrderCheck {
-        private ActivityRecord mOpenActivity;
-        private ActivityRecord mCloseActivity;
-        private int mOpenIndex = -1;
-        private int mCloseIndex = -1;
-
-        private void reset() {
-            mOpenActivity = null;
-            mCloseActivity = null;
-            mOpenIndex = -1;
-            mCloseIndex = -1;
-        }
-
-        private void setTarget(boolean open, ActivityRecord ar, int index) {
-            if (open) {
-                mOpenActivity = ar;
-                mOpenIndex = index;
-            } else {
-                mCloseActivity = ar;
-                mCloseIndex = index;
-            }
-        }
-
-        void analysisOrder(ArraySet<ActivityRecord> closeApps,
-                ArraySet<ActivityRecord> openApps, Task task, AnalysisResult result) {
-            for (int j = closeApps.size() - 1; j >= 0; j--) {
-                final ActivityRecord ar = closeApps.valueAt(j);
-                if (ar.getTask() == task) {
-                    setTarget(false, ar, task.mChildren.indexOf(ar));
-                    break;
-                }
-            }
-            for (int j = openApps.size() - 1; j >= 0; j--) {
-                final ActivityRecord ar = openApps.valueAt(j);
-                if (ar.getTask() == task) {
-                    setTarget(true, ar, task.mChildren.indexOf(ar));
-                    break;
-                }
-            }
-            if (mOpenIndex > mCloseIndex && mCloseIndex != -1) {
-                result.onCheckResult(ACTIVITY_OPEN, mCloseActivity, mOpenActivity);
-            } else if (mOpenIndex < mCloseIndex && mOpenIndex != -1) {
-                result.onCheckResult(ACTIVITY_CLOSE, mCloseActivity, mOpenActivity);
-            }
-            reset();
-        }
-        private interface AnalysisResult {
-            void onCheckResult(@TransitionStateType int type,
-                    ActivityRecord close, ActivityRecord open);
-        }
-    }
-
-    private void addTransitionRecord(int type, boolean open, WindowContainer target) {
-        TransitionState record = mTmpOpenCloseRecord.get(type);
-        if (record == null) {
-            record =  new TransitionState();
-            mTmpOpenCloseRecord.set(type, record);
-        }
-        record.addParticipant(target, open);
-        mTmpAnalysisRecord.add(type);
-    }
-
-    private void clearRecord() {
-        mTmpOpenCloseRecord.clear();
-        mTmpAnalysisRecord.clear();
-    }
-
-    static class TransitionState<TYPE extends WindowContainer> {
-        private final ArraySet<TYPE> mOpenParticipant = new ArraySet<>();
-        private final ArraySet<TYPE> mCloseParticipant = new ArraySet<>();
-
-        void addParticipant(TYPE target, boolean open) {
-            final ArraySet<TYPE> participant = open
-                    ? mOpenParticipant : mCloseParticipant;
-            participant.add(target);
-        }
-
-        ArraySet<TYPE> getParticipant(boolean open) {
-            return open ? mOpenParticipant : mCloseParticipant;
-        }
-    }
-
     SnapshotController(WindowManagerService wms) {
         mSnapshotPersistQueue = new SnapshotPersistQueue();
         mTaskSnapshotController = new TaskSnapshotController(wms, mSnapshotPersistQueue);
         mActivitySnapshotController = new ActivitySnapshotController(wms, mSnapshotPersistQueue);
     }
 
-    void registerTransitionStateConsumer(@TransitionStateType int type,
-            Consumer<TransitionState> consumer) {
-        ArrayList<Consumer<TransitionState>> consumers = mTransitionStateConsumer.get(type);
-        if (consumers == null) {
-            consumers = new ArrayList<>();
-            mTransitionStateConsumer.set(type, consumers);
-        }
-        if (!consumers.contains(consumer)) {
-            consumers.add(consumer);
-        }
-        mActivatedType |= type;
-    }
-
-    void unregisterTransitionStateConsumer(int type, Consumer<TransitionState> consumer) {
-        final ArrayList<Consumer<TransitionState>> consumers = mTransitionStateConsumer.get(type);
-        if (consumers == null) {
-            return;
-        }
-        consumers.remove(consumer);
-        if (consumers.size() == 0) {
-            mActivatedType &= ~type;
-        }
-    }
-
-    private boolean hasTransitionStateConsumer(@TransitionStateType int type) {
-        return (mActivatedType & type) != 0;
-    }
-
     void systemReady() {
         mSnapshotPersistQueue.systemReady();
-        mTaskSnapshotController.systemReady();
-        mActivitySnapshotController.systemReady();
     }
 
     void setPause(boolean paused) {
@@ -212,47 +63,69 @@
     }
 
     void notifyAppVisibilityChanged(ActivityRecord appWindowToken, boolean visible) {
-        if (!visible && hasTransitionStateConsumer(TASK_CLOSE)) {
-            final Task task = appWindowToken.getTask();
-            if (task == null || task.isVisibleRequested()) {
-                return;
+        mActivitySnapshotController.notifyAppVisibilityChanged(appWindowToken, visible);
+    }
+
+    // For legacy transition, which won't support activity snapshot
+    void onTransitionStarting(DisplayContent displayContent) {
+        mTaskSnapshotController.handleClosingApps(displayContent.mClosingApps);
+    }
+
+    // For shell transition, record snapshots before transaction start.
+    void onTransactionReady(@WindowManager.TransitionType int type,
+            ArrayList<Transition.ChangeInfo> changeInfos) {
+        final boolean isTransitionOpen = isTransitionOpen(type);
+        final boolean isTransitionClose = isTransitionClose(type);
+        if (!isTransitionOpen && !isTransitionClose && type < TRANSIT_FIRST_CUSTOM) {
+            return;
+        }
+        for (int i = changeInfos.size() - 1; i >= 0; --i) {
+            Transition.ChangeInfo info = changeInfos.get(i);
+            // Intentionally skip record snapshot for changes originated from PiP.
+            if (info.mWindowingMode == WINDOWING_MODE_PINNED) continue;
+            if (info.mContainer.asTask() != null && !info.mContainer.isVisibleRequested()) {
+                mTaskSnapshotController.recordSnapshot(info.mContainer.asTask(),
+                        false /* allowSnapshotHome */);
             }
-            // close task transition
-            addTransitionRecord(TASK_CLOSE, false /*open*/, task);
-            mActivitySnapshotController.preTransitionStart();
-            notifyTransition(TASK_CLOSE);
-            mActivitySnapshotController.postTransitionStart();
-            clearRecord();
+            // Won't need to capture activity snapshot in close transition.
+            if (isTransitionClose) {
+                continue;
+            }
+            if (info.mContainer.asActivityRecord() != null
+                    || info.mContainer.asTaskFragment() != null) {
+                final TaskFragment tf = info.mContainer.asTaskFragment();
+                final ActivityRecord ar = tf != null ? tf.getTopMostActivity()
+                        : info.mContainer.asActivityRecord();
+                final boolean taskVis = ar != null && ar.getTask().isVisibleRequested();
+                if (ar != null && !ar.isVisibleRequested() && taskVis) {
+                    mActivitySnapshotController.recordSnapshot(ar);
+                }
+            }
         }
     }
 
-    // For legacy transition
-    void onTransitionStarting(DisplayContent displayContent) {
-        handleAppTransition(displayContent.mClosingApps, displayContent.mOpeningApps);
-    }
-
-    // For shell transition, adapt to legacy transition.
-    void onTransitionReady(@WindowManager.TransitionType int type,
-            ArraySet<WindowContainer> participants) {
+    void onTransitionFinish(@WindowManager.TransitionType int type,
+            ArrayList<Transition.ChangeInfo> changeInfos) {
         final boolean isTransitionOpen = isTransitionOpen(type);
         final boolean isTransitionClose = isTransitionClose(type);
         if (!isTransitionOpen && !isTransitionClose && type < TRANSIT_FIRST_CUSTOM
-                || (mActivatedType == 0)) {
+                || (changeInfos.isEmpty())) {
             return;
         }
-        final ArraySet<ActivityRecord> openingApps = new ArraySet<>();
-        final ArraySet<ActivityRecord> closingApps = new ArraySet<>();
-
-        for (int i = participants.size() - 1; i >= 0; --i) {
-            final ActivityRecord ar = participants.valueAt(i).asActivityRecord();
-            if (ar == null || ar.getTask() == null) continue;
-            if (ar.isVisibleRequested()) {
-                openingApps.add(ar);
-            } else {
-                closingApps.add(ar);
+        Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "SnapshotController_analysis");
+        mActivitySnapshotController.beginSnapshotProcess();
+        final ArrayList<WindowContainer> windows = new ArrayList<>();
+        for (int i = changeInfos.size() - 1; i >= 0; --i) {
+            final WindowContainer wc = changeInfos.get(i).mContainer;
+            if (wc.asTask() == null && wc.asTaskFragment() == null
+                    && wc.asActivityRecord() == null) {
+                continue;
             }
+            windows.add(wc);
         }
-        handleAppTransition(closingApps, openingApps);
+        mActivitySnapshotController.handleTransitionFinish(windows);
+        mActivitySnapshotController.endSnapshotProcess();
+        Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
     }
 
     private static boolean isTransitionOpen(int type) {
@@ -262,78 +135,6 @@
         return type == TRANSIT_CLOSE || type == TRANSIT_TO_BACK;
     }
 
-    @VisibleForTesting
-    void handleAppTransition(ArraySet<ActivityRecord> closingApps,
-            ArraySet<ActivityRecord> openApps) {
-        if (mActivatedType == 0) {
-            return;
-        }
-        analysisTransition(closingApps, openApps);
-        mActivitySnapshotController.preTransitionStart();
-        for (Integer transitionType : mTmpAnalysisRecord) {
-            notifyTransition(transitionType);
-        }
-        mActivitySnapshotController.postTransitionStart();
-        clearRecord();
-    }
-
-    private void notifyTransition(int transitionType) {
-        final TransitionState record = mTmpOpenCloseRecord.get(transitionType);
-        final ArrayList<Consumer<TransitionState>> consumers =
-                mTransitionStateConsumer.get(transitionType);
-        for (Consumer<TransitionState> consumer : consumers) {
-            consumer.accept(record);
-        }
-    }
-
-    private void analysisTransition(ArraySet<ActivityRecord> closingApps,
-            ArraySet<ActivityRecord> openingApps) {
-        getParticipantTasks(closingApps, mTmpCloseTasks, false /* isOpen */);
-        getParticipantTasks(openingApps, mTmpOpenTasks, true /* isOpen */);
-        if (DEBUG) {
-            Slog.d(TAG, "AppSnapshotController#analysisTransition participants"
-                    + " mTmpCloseTasks " + mTmpCloseTasks
-                    + " mTmpOpenTasks " + mTmpOpenTasks);
-        }
-        for (int i = mTmpCloseTasks.size() - 1; i >= 0; i--) {
-            final Task closeTask = mTmpCloseTasks.valueAt(i);
-            if (mTmpOpenTasks.contains(closeTask)) {
-                if (hasTransitionStateConsumer(ACTIVITY_OPEN)
-                        || hasTransitionStateConsumer(ACTIVITY_CLOSE)) {
-                    mActivityOrderCheck.analysisOrder(closingApps, openingApps, closeTask,
-                            mResultHandler);
-                }
-            } else if (hasTransitionStateConsumer(TASK_CLOSE)) {
-                // close task transition
-                addTransitionRecord(TASK_CLOSE, false /*open*/, closeTask);
-            }
-        }
-        if (hasTransitionStateConsumer(TASK_OPEN)) {
-            for (int i = mTmpOpenTasks.size() - 1; i >= 0; i--) {
-                final Task openTask = mTmpOpenTasks.valueAt(i);
-                if (!mTmpCloseTasks.contains(openTask)) {
-                    // this is open task transition
-                    addTransitionRecord(TASK_OPEN, true /*open*/, openTask);
-                }
-            }
-        }
-        mTmpCloseTasks.clear();
-        mTmpOpenTasks.clear();
-    }
-
-    private void getParticipantTasks(ArraySet<ActivityRecord> activityRecords, ArraySet<Task> tasks,
-            boolean isOpen) {
-        for (int i = activityRecords.size() - 1; i >= 0; i--) {
-            final ActivityRecord activity = activityRecords.valueAt(i);
-            final Task task = activity.getTask();
-            if (task == null) continue;
-
-            if (isOpen == activity.isVisibleRequested()) {
-                tasks.add(task);
-            }
-        }
-    }
-
     void dump(PrintWriter pw, String prefix) {
         mTaskSnapshotController.dump(pw, prefix);
         mActivitySnapshotController.dump(pw, prefix);
diff --git a/services/core/java/com/android/server/wm/SnapshotPersistQueue.java b/services/core/java/com/android/server/wm/SnapshotPersistQueue.java
index 58e1c54..f4f641f 100644
--- a/services/core/java/com/android/server/wm/SnapshotPersistQueue.java
+++ b/services/core/java/com/android/server/wm/SnapshotPersistQueue.java
@@ -17,6 +17,7 @@
 package com.android.server.wm;
 
 import static android.graphics.Bitmap.CompressFormat.JPEG;
+import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
 
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
@@ -26,6 +27,7 @@
 import android.graphics.Bitmap;
 import android.os.Process;
 import android.os.SystemClock;
+import android.os.Trace;
 import android.util.AtomicFile;
 import android.util.Slog;
 import android.window.TaskSnapshot;
@@ -249,6 +251,7 @@
 
         @Override
         void write() {
+            Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "StoreWriteQueueItem");
             if (!mPersistInfoProvider.createDirectory(mUserId)) {
                 Slog.e(TAG, "Unable to create snapshot directory for user dir="
                         + mPersistInfoProvider.getDirectory(mUserId));
@@ -263,6 +266,7 @@
             if (failed) {
                 deleteSnapshot(mId, mUserId, mPersistInfoProvider);
             }
+            Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
         }
 
         boolean writeProto() {
@@ -373,7 +377,9 @@
 
         @Override
         void write() {
+            Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "DeleteWriteQueueItem");
             deleteSnapshot(mId, mUserId, mPersistInfoProvider);
+            Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
         }
     }
 }
diff --git a/services/core/java/com/android/server/wm/StartingData.java b/services/core/java/com/android/server/wm/StartingData.java
index 2b22d75..a23547e 100644
--- a/services/core/java/com/android/server/wm/StartingData.java
+++ b/services/core/java/com/android/server/wm/StartingData.java
@@ -16,6 +16,8 @@
 
 package com.android.server.wm;
 
+import android.annotation.IntDef;
+
 import com.android.server.wm.StartingSurfaceController.StartingSurface;
 
 /**
@@ -23,6 +25,20 @@
  */
 public abstract class StartingData {
 
+    /** Nothing need to do after transaction */
+    static final int AFTER_TRANSACTION_IDLE = 0;
+    /** Remove the starting window directly after transaction done. */
+    static final int AFTER_TRANSACTION_REMOVE_DIRECTLY = 1;
+    /** Do copy splash screen to client after transaction done. */
+    static final int AFTER_TRANSACTION_COPY_TO_CLIENT = 2;
+
+    @IntDef(prefix = { "AFTER_TRANSACTION" }, value = {
+            AFTER_TRANSACTION_IDLE,
+            AFTER_TRANSACTION_REMOVE_DIRECTLY,
+            AFTER_TRANSACTION_COPY_TO_CLIENT,
+    })
+    @interface AfterTransaction {}
+
     protected final WindowManagerService mService;
     protected final int mTypeParams;
 
@@ -60,11 +76,14 @@
      * This starting window should be removed after applying the start transaction of transition,
      * which ensures the app window has shown.
      */
-    boolean mRemoveAfterTransaction;
+    @AfterTransaction int mRemoveAfterTransaction;
 
     /** Whether to prepare the removal animation. */
     boolean mPrepareRemoveAnimation;
 
+    /** Non-zero if this starting window is added in a collecting transition. */
+    int mTransitionId;
+
     protected StartingData(WindowManagerService service, int typeParams) {
         mService = service;
         mTypeParams = typeParams;
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 4e95c84..43430dd 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -2878,8 +2878,8 @@
             // No need to check if allowed if it's leaving dragResize
             if (dragResizing
                     && !(getRootTask().getWindowingMode() == WINDOWING_MODE_FREEFORM)) {
-                throw new IllegalArgumentException("Drag resize not allow for root task id="
-                        + getRootTaskId());
+                Slog.e(TAG, "Drag resize isn't allowed for root task id=" + getRootTaskId());
+                return;
             }
             mDragResizing = dragResizing;
             resetDragResizingChangeReported();
@@ -3459,6 +3459,8 @@
         info.topActivityLetterboxHorizontalPosition = TaskInfo.PROPERTY_VALUE_UNSET;
         info.topActivityLetterboxWidth = TaskInfo.PROPERTY_VALUE_UNSET;
         info.topActivityLetterboxHeight = TaskInfo.PROPERTY_VALUE_UNSET;
+        info.isUserFullscreenOverrideEnabled = top != null
+                && top.mLetterboxUiController.shouldApplyUserFullscreenOverride();
         info.isFromLetterboxDoubleTap = top != null && top.mLetterboxUiController.isFromDoubleTap();
         if (info.isLetterboxDoubleTapEnabled) {
             info.topActivityLetterboxWidth = top.getBounds().width();
@@ -5737,7 +5739,7 @@
             }
         }
         ActivityRecord topActivity = getDisplayArea().topRunningActivity();
-        Task topRootTask = topActivity.getRootTask();
+        Task topRootTask = topActivity == null ? null : topActivity.getRootTask();
         if (topRootTask != null && topRootTask != this && topActivity.isState(RESUMED)) {
             // Usually resuming a top activity triggers the next app transition, but nothing's got
             // resumed in this case, so we need to execute it explicitly.
diff --git a/services/core/java/com/android/server/wm/TaskFragment.java b/services/core/java/com/android/server/wm/TaskFragment.java
index 83949cc..6dc896a 100644
--- a/services/core/java/com/android/server/wm/TaskFragment.java
+++ b/services/core/java/com/android/server/wm/TaskFragment.java
@@ -86,7 +86,6 @@
 import android.graphics.Rect;
 import android.hardware.HardwareBuffer;
 import android.os.IBinder;
-import android.os.RemoteException;
 import android.os.UserHandle;
 import android.util.DisplayMetrics;
 import android.util.Slog;
@@ -1176,7 +1175,7 @@
     }
 
     final boolean resumeTopActivity(ActivityRecord prev, ActivityOptions options,
-            boolean deferPause) {
+            boolean skipPause) {
         ActivityRecord next = topRunningActivity(true /* focusableOnly */);
         if (next == null || !next.canResumeByCompat()) {
             return false;
@@ -1184,11 +1183,9 @@
 
         next.delayedResume = false;
 
-        // If we are currently pausing an activity, then don't do anything until that is done.
-        final boolean allPausedComplete = mRootWindowContainer.allPausedActivitiesComplete();
-        if (!allPausedComplete) {
-            ProtoLog.v(WM_DEBUG_STATES,
-                    "resumeTopActivity: Skip resume: some activity pausing.");
+        if (!skipPause && !mRootWindowContainer.allPausedActivitiesComplete()) {
+            // If we aren't skipping pause, then we have to wait for currently pausing activities.
+            ProtoLog.v(WM_DEBUG_STATES, "resumeTopActivity: Skip resume: some activity pausing.");
             return false;
         }
 
@@ -1252,7 +1249,7 @@
             lastResumed = lastFocusedRootTask.getTopResumedActivity();
         }
 
-        boolean pausing = !deferPause && taskDisplayArea.pauseBackTasks(next);
+        boolean pausing = !skipPause && taskDisplayArea.pauseBackTasks(next);
         if (mResumedActivity != null) {
             ProtoLog.d(WM_DEBUG_STATES, "resumeTopActivity: Pausing %s", mResumedActivity);
             pausing |= startPausing(mTaskSupervisor.mUserLeaving, false /* uiSleeping */,
@@ -1325,14 +1322,12 @@
             }
         }
 
-        // Launching this app's activity, make sure the app is no longer
-        // considered stopped.
         try {
             mTaskSupervisor.getActivityMetricsLogger()
                     .notifyBeforePackageUnstopped(next.packageName);
-            mAtmService.getPackageManager().setPackageStoppedState(
-                    next.packageName, false, next.mUserId); /* TODO: Verify if correct userid */
-        } catch (RemoteException e1) {
+            mAtmService.getPackageManagerInternalLocked().notifyComponentUsed(
+                    next.packageName, next.mUserId,
+                    next.packageName, next.toString()); /* TODO: Verify if correct userid */
         } catch (IllegalArgumentException e) {
             Slog.w(TAG, "Failed trying to unstop package "
                     + next.packageName + ": " + e);
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotController.java b/services/core/java/com/android/server/wm/TaskSnapshotController.java
index c747c09..4eb4290 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotController.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotController.java
@@ -16,7 +16,6 @@
 
 package com.android.server.wm;
 
-import static com.android.server.wm.SnapshotController.TASK_CLOSE;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SCREENSHOT;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
@@ -77,13 +76,6 @@
         setSnapshotEnabled(snapshotEnabled);
     }
 
-    void systemReady() {
-        if (!shouldDisableSnapshots()) {
-            mService.mSnapshotController.registerTransitionStateConsumer(TASK_CLOSE,
-                    this::handleTaskClose);
-        }
-    }
-
     static PersistInfoProvider createPersistInfoProvider(WindowManagerService service,
             BaseAppSnapshotPersister.DirectoryResolver resolver) {
         final float highResTaskSnapshotScale = service.mContext.getResources().getFloat(
@@ -116,20 +108,23 @@
                 enableLowResSnapshots, lowResScaleFactor, use16BitFormat);
     }
 
-    void handleTaskClose(SnapshotController.TransitionState<Task> closeTaskTransitionRecord) {
+    // Still needed for legacy transition.(AppTransitionControllerTest)
+    void handleClosingApps(ArraySet<ActivityRecord> closingApps) {
         if (shouldDisableSnapshots()) {
             return;
         }
+        // We need to take a snapshot of the task if and only if all activities of the task are
+        // either closing or hidden.
         mTmpTasks.clear();
-        final ArraySet<Task> tasks = closeTaskTransitionRecord.getParticipant(false /* open */);
-        if (mService.mAtmService.getTransitionController().isShellTransitionsEnabled()) {
-            mTmpTasks.addAll(tasks);
-        } else {
-            for (Task task : tasks) {
-                getClosingTasksInner(task, mTmpTasks);
-            }
+        for (int i = closingApps.size() - 1; i >= 0; i--) {
+            final ActivityRecord activity = closingApps.valueAt(i);
+            final Task task = activity.getTask();
+            if (task == null) continue;
+
+            getClosingTasksInner(task, mTmpTasks);
         }
         snapshotTasks(mTmpTasks);
+        mTmpTasks.clear();
         mSkipClosingAppSnapshotTasks.clear();
     }
 
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotPersister.java b/services/core/java/com/android/server/wm/TaskSnapshotPersister.java
index cd15119..3e8c017 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotPersister.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotPersister.java
@@ -16,6 +16,9 @@
 
 package com.android.server.wm;
 
+import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
+
+import android.os.Trace;
 import android.util.ArraySet;
 import android.window.TaskSnapshot;
 
@@ -102,6 +105,7 @@
 
         @Override
         void write() {
+            Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "RemoveObsoleteFilesQueueItem");
             final ArraySet<Integer> newPersistedTaskIds;
             synchronized (mLock) {
                 newPersistedTaskIds = new ArraySet<>(mPersistedTaskIdsSinceLastRemoveObsolete);
@@ -120,6 +124,7 @@
                     }
                 }
             }
+            Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
         }
 
         @VisibleForTesting
diff --git a/services/core/java/com/android/server/wm/Transition.java b/services/core/java/com/android/server/wm/Transition.java
index aad17aa..1566bb2c 100644
--- a/services/core/java/com/android/server/wm/Transition.java
+++ b/services/core/java/com/android/server/wm/Transition.java
@@ -1191,8 +1191,6 @@
                                         "  Skipping post-transition snapshot for task %d",
                                         task.mTaskId);
                             }
-                            snapController.mActivitySnapshotController
-                                    .notifyAppVisibilityChanged(ar, false /* visible */);
                         }
                         ar.commitVisibility(false /* visible */, false /* performLayout */,
                                 true /* fromTransition */);
@@ -1389,6 +1387,7 @@
         // Handle back animation if it's already started.
         mController.mAtm.mBackNavigationController.onTransitionFinish(mTargets, this);
         mController.mFinishingTransition = null;
+        mController.mSnapshotController.onTransitionFinish(mType, mTargets);
     }
 
     void abort() {
@@ -1593,16 +1592,7 @@
         // transferred. If transition is transient, IME won't be moved during the transition and
         // the tasks are still live, so we take the snapshot at the end of the transition instead.
         if (mTransientLaunches == null) {
-            for (int i = mParticipants.size() - 1; i >= 0; --i) {
-                final ActivityRecord ar = mParticipants.valueAt(i).asActivityRecord();
-                if (ar == null || ar.getTask() == null
-                        || ar.getTask().isVisibleRequested()) continue;
-                final ChangeInfo change = mChanges.get(ar);
-                // Intentionally skip record snapshot for changes originated from PiP.
-                if (change != null && change.mWindowingMode == WINDOWING_MODE_PINNED) continue;
-                mController.mSnapshotController.mTaskSnapshotController.recordSnapshot(
-                        ar.getTask(), false /* allowSnapshotHome */);
-            }
+            mController.mSnapshotController.onTransactionReady(mType, mTargets);
         }
 
         // This is non-null only if display has changes. It handles the visible windows that don't
diff --git a/services/core/java/com/android/server/wm/TransitionTracer.java b/services/core/java/com/android/server/wm/TransitionTracer.java
index af8fb02..c59d2d3 100644
--- a/services/core/java/com/android/server/wm/TransitionTracer.java
+++ b/services/core/java/com/android/server/wm/TransitionTracer.java
@@ -145,6 +145,27 @@
         }
     }
 
+    void logRemovingStartingWindow(@NonNull StartingData startingData) {
+        if (startingData.mTransitionId == 0) {
+            return;
+        }
+        try {
+            final ProtoOutputStream outputStream = new ProtoOutputStream(CHUNK_SIZE);
+            final long protoToken = outputStream
+                    .start(com.android.server.wm.shell.TransitionTraceProto.TRANSITIONS);
+            outputStream.write(com.android.server.wm.shell.Transition.ID,
+                    startingData.mTransitionId);
+            outputStream.write(
+                    com.android.server.wm.shell.Transition.STARTING_WINDOW_REMOVE_TIME_NS,
+                    SystemClock.elapsedRealtimeNanos());
+            outputStream.end(protoToken);
+
+            mTraceBuffer.add(outputStream);
+        } catch (Exception e) {
+            Log.e(LOG_TAG, "Unexpected exception thrown while logging transitions", e);
+        }
+    }
+
     private void dumpTransitionTargetsToProto(ProtoOutputStream outputStream,
             Transition transition, ArrayList<ChangeInfo> targets) {
         Trace.beginSection("TransitionTracer#dumpTransitionTargetsToProto");
diff --git a/services/core/java/com/android/server/wm/WallpaperWindowToken.java b/services/core/java/com/android/server/wm/WallpaperWindowToken.java
index 6630e20..c7fd147 100644
--- a/services/core/java/com/android/server/wm/WallpaperWindowToken.java
+++ b/services/core/java/com/android/server/wm/WallpaperWindowToken.java
@@ -156,7 +156,7 @@
                 linkFixedRotationTransform(wallpaperTarget.mToken);
             }
         }
-        if (mTransitionController.isShellTransitionsEnabled()) {
+        if (mTransitionController.inTransition(this)) {
             // If wallpaper is in transition, setVisible() will be called from commitVisibility()
             // when finishing transition. Otherwise commitVisibility() is already called from above
             // setVisibility().
diff --git a/services/core/java/com/android/server/wm/WindowContextListenerController.java b/services/core/java/com/android/server/wm/WindowContextListenerController.java
index 626ad15..21f251f 100644
--- a/services/core/java/com/android/server/wm/WindowContextListenerController.java
+++ b/services/core/java/com/android/server/wm/WindowContextListenerController.java
@@ -26,7 +26,6 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.app.IWindowToken;
 import android.app.servertransaction.WindowContextInfoChangeItem;
 import android.app.servertransaction.WindowContextWindowRemovalItem;
 import android.content.Context;
@@ -142,7 +141,7 @@
             final WindowContextListenerImpl listener = mListeners.valueAt(i);
             if (listener.getWindowContainer().getDisplayContent().getDisplayId() == displayId
                     && listener.mHasPendingConfiguration) {
-                listener.reportConfigToWindowTokenClient();
+                listener.dispatchWindowContextInfoChange();
             }
         }
     }
@@ -208,7 +207,7 @@
         @NonNull
         private final WindowProcessController mWpc;
         @NonNull
-        private final IWindowToken mClientToken;
+        private final IBinder mClientToken;
         @NonNull
         private WindowContainer<?> mContainer;
         /**
@@ -230,7 +229,7 @@
                 @NonNull IBinder clientToken, @NonNull WindowContainer<?> container,
                 @WindowType int type, @Nullable Bundle options) {
             mWpc = Objects.requireNonNull(wpc);
-            mClientToken = IWindowToken.Stub.asInterface(clientToken);
+            mClientToken = clientToken;
             mContainer = Objects.requireNonNull(container);
             mType = type;
             mOptions = options;
@@ -272,7 +271,7 @@
         }
 
         private void register(boolean shouldDispatchConfig) {
-            final IBinder token = mClientToken.asBinder();
+            final IBinder token = mClientToken;
             if (mDeathRecipient == null) {
                 throw new IllegalStateException("Invalid client token: " + token);
             }
@@ -282,7 +281,7 @@
 
         private void unregister() {
             mContainer.unregisterWindowContainerListener(this);
-            mListeners.remove(mClientToken.asBinder());
+            mListeners.remove(mClientToken);
         }
 
         private void clear() {
@@ -292,17 +291,17 @@
 
         @Override
         public void onMergedOverrideConfigurationChanged(Configuration mergedOverrideConfig) {
-            reportConfigToWindowTokenClient();
+            dispatchWindowContextInfoChange();
         }
 
         @Override
         public void onDisplayChanged(DisplayContent dc) {
-            reportConfigToWindowTokenClient();
+            dispatchWindowContextInfoChange();
         }
 
-        private void reportConfigToWindowTokenClient() {
+        private void dispatchWindowContextInfoChange() {
             if (mDeathRecipient == null) {
-                throw new IllegalStateException("Invalid client token: " + mClientToken.asBinder());
+                throw new IllegalStateException("Invalid client token: " + mClientToken);
             }
             final DisplayContent dc = mContainer.getDisplayContent();
             if (!dc.isReady()) {
@@ -332,14 +331,14 @@
             mLastReportedDisplay = displayId;
 
             mWpc.scheduleClientTransactionItem(WindowContextInfoChangeItem.obtain(
-                    mClientToken.asBinder(), config, displayId));
+                    mClientToken, config, displayId));
             mHasPendingConfiguration = false;
         }
 
         @Override
         public void onRemoved() {
             if (mDeathRecipient == null) {
-                throw new IllegalStateException("Invalid client token: " + mClientToken.asBinder());
+                throw new IllegalStateException("Invalid client token: " + mClientToken);
             }
             final WindowToken windowToken = mContainer.asWindowToken();
             if (windowToken != null && windowToken.isFromClient()) {
@@ -357,14 +356,13 @@
                 }
             }
             mDeathRecipient.unlinkToDeath();
-            mWpc.scheduleClientTransactionItem(WindowContextWindowRemovalItem.obtain(
-                    mClientToken.asBinder()));
+            mWpc.scheduleClientTransactionItem(WindowContextWindowRemovalItem.obtain(mClientToken));
             unregister();
         }
 
         @Override
         public String toString() {
-            return "WindowContextListenerImpl{clientToken=" + mClientToken.asBinder() + ", "
+            return "WindowContextListenerImpl{clientToken=" + mClientToken + ", "
                     + "container=" + mContainer + "}";
         }
 
@@ -378,11 +376,11 @@
             }
 
             void linkToDeath() throws RemoteException {
-                mClientToken.asBinder().linkToDeath(this, 0);
+                mClientToken.linkToDeath(this, 0);
             }
 
             void unlinkToDeath() {
-                mClientToken.asBinder().unlinkToDeath(this, 0);
+                mClientToken.unlinkToDeath(this, 0);
             }
         }
     }
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 261d6bc..03efb1b 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -4648,7 +4648,14 @@
     void reportSystemGestureExclusionChanged(Session session, IWindow window,
             List<Rect> exclusionRects) {
         synchronized (mGlobalLock) {
-            final WindowState win = windowForClientLocked(session, window, true);
+            final WindowState win = windowForClientLocked(session, window,
+                    false /* throwOnError */);
+            if (win == null) {
+                Slog.i(TAG_WM,
+                        "reportSystemGestureExclusionChanged(): No window state for package:"
+                                + session.mPackageName);
+                return;
+            }
             if (win.setSystemGestureExclusion(exclusionRects)) {
                 win.getDisplayContent().updateSystemGestureExclusion();
             }
@@ -4658,7 +4665,14 @@
     void reportKeepClearAreasChanged(Session session, IWindow window,
             List<Rect> restricted, List<Rect> unrestricted) {
         synchronized (mGlobalLock) {
-            final WindowState win = windowForClientLocked(session, window, true);
+            final WindowState win = windowForClientLocked(session, window,
+                    false /* throwOnError */);
+            if (win == null) {
+                Slog.i(TAG_WM,
+                        "reportKeepClearAreasChanged(): No window state for package:"
+                                + session.mPackageName);
+                return;
+            }
             if (win.setKeepClearAreas(restricted, unrestricted)) {
                 win.getDisplayContent().updateKeepClearAreas();
             }
diff --git a/services/core/java/com/android/server/wm/WindowOrganizerController.java b/services/core/java/com/android/server/wm/WindowOrganizerController.java
index a84749a..6d7e297 100644
--- a/services/core/java/com/android/server/wm/WindowOrganizerController.java
+++ b/services/core/java/com/android/server/wm/WindowOrganizerController.java
@@ -309,6 +309,14 @@
                                 applyTransaction(wct, -1 /* syncId */, nextTransition, caller,
                                         deferred);
                                 if (needsSetReady) {
+                                    // TODO(b/294925498): Remove this once we have accurate ready
+                                    //                    tracking.
+                                    if (hasActivityLaunch(wct) && !mService.mRootWindowContainer
+                                            .allPausedActivitiesComplete()) {
+                                        // WCT is launching an activity, so we need to wait for its
+                                        // lifecycle events.
+                                        return;
+                                    }
                                     nextTransition.setAllReady();
                                 }
                             });
@@ -344,6 +352,15 @@
         }
     }
 
+    private static boolean hasActivityLaunch(WindowContainerTransaction wct) {
+        for (int i = 0; i < wct.getHierarchyOps().size(); ++i) {
+            if (wct.getHierarchyOps().get(i).getType() == HIERARCHY_OP_TYPE_LAUNCH_TASK) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     @Override
     public int startLegacyTransition(int type, @NonNull RemoteAnimationAdapter adapter,
             @NonNull IWindowContainerTransactionCallback callback,
@@ -382,18 +399,13 @@
     }
 
     @Override
-    public int finishTransition(@NonNull IBinder transitionToken,
-            @Nullable WindowContainerTransaction t,
-            @Nullable IWindowContainerTransactionCallback callback) {
+    public void finishTransition(@NonNull IBinder transitionToken,
+            @Nullable WindowContainerTransaction t) {
         enforceTaskPermission("finishTransition()");
         final CallerInfo caller = new CallerInfo();
         final long ident = Binder.clearCallingIdentity();
         try {
             synchronized (mGlobalLock) {
-                int syncId = -1;
-                if (t != null && callback != null) {
-                    syncId = startSyncWithOrganizer(callback);
-                }
                 final Transition transition = Transition.fromBinder(transitionToken);
                 // apply the incoming transaction before finish in case it alters the visibility
                 // of the participants.
@@ -402,14 +414,10 @@
                     // changes of the transition participants will only set visible-requested
                     // and still let finishTransition handle the participants.
                     mTransitionController.mFinishingTransition = transition;
-                    applyTransaction(t, syncId, null /*transition*/, caller, transition);
+                    applyTransaction(t, -1 /* syncId */, null /*transition*/, caller, transition);
                 }
                 mTransitionController.finishTransition(transition);
                 mTransitionController.mFinishingTransition = null;
-                if (syncId >= 0) {
-                    setSyncReady(syncId);
-                }
-                return syncId;
             }
         } finally {
             Binder.restoreCallingIdentity(ident);
@@ -1649,9 +1657,18 @@
     }
 
     private int setAdjacentRootsHierarchyOp(WindowContainerTransaction.HierarchyOp hop) {
-        final TaskFragment root1 = WindowContainer.fromBinder(hop.getContainer()).asTaskFragment();
-        final TaskFragment root2 =
-                WindowContainer.fromBinder(hop.getAdjacentRoot()).asTaskFragment();
+        final WindowContainer wc1 = WindowContainer.fromBinder(hop.getContainer());
+        if (wc1 == null || !wc1.isAttached()) {
+            Slog.e(TAG, "Attempt to operate on unknown or detached container: " + wc1);
+            return TRANSACT_EFFECTS_NONE;
+        }
+        final TaskFragment root1 = wc1.asTaskFragment();
+        final WindowContainer wc2 = WindowContainer.fromBinder(hop.getAdjacentRoot());
+        if (wc2 == null || !wc2.isAttached()) {
+            Slog.e(TAG, "Attempt to operate on unknown or detached container: " + wc2);
+            return TRANSACT_EFFECTS_NONE;
+        }
+        final TaskFragment root2 = wc2.asTaskFragment();
         if (!root1.mCreatedByOrganizer || !root2.mCreatedByOrganizer) {
             throw new IllegalArgumentException("setAdjacentRootsHierarchyOp: Not created by"
                     + " organizer root1=" + root1 + " root2=" + root2);
@@ -1664,7 +1681,12 @@
     }
 
     private int clearAdjacentRootsHierarchyOp(WindowContainerTransaction.HierarchyOp hop) {
-        final TaskFragment root = WindowContainer.fromBinder(hop.getContainer()).asTaskFragment();
+        final WindowContainer wc = WindowContainer.fromBinder(hop.getContainer());
+        if (wc == null || !wc.isAttached()) {
+            Slog.e(TAG, "Attempt to operate on unknown or detached container: " + wc);
+            return TRANSACT_EFFECTS_NONE;
+        }
+        final TaskFragment root = wc.asTaskFragment();
         if (!root.mCreatedByOrganizer) {
             throw new IllegalArgumentException("clearAdjacentRootsHierarchyOp: Not created by"
                     + " organizer root=" + root);
diff --git a/services/core/java/com/android/server/wm/WindowProcessController.java b/services/core/java/com/android/server/wm/WindowProcessController.java
index 83e8646..e769a27 100644
--- a/services/core/java/com/android/server/wm/WindowProcessController.java
+++ b/services/core/java/com/android/server/wm/WindowProcessController.java
@@ -48,6 +48,7 @@
 import static java.util.Objects.requireNonNull;
 
 import android.Manifest;
+import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.app.ActivityManager;
@@ -76,7 +77,6 @@
 import android.util.Log;
 import android.util.Slog;
 import android.util.proto.ProtoOutputStream;
-import android.view.IRemoteAnimationRunner;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
@@ -88,6 +88,8 @@
 
 import java.io.IOException;
 import java.io.PrintWriter;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -250,11 +252,30 @@
     @Nullable
     private ArrayMap<ActivityRecord, int[]> mRemoteActivities;
 
-    /** Whether our process is currently running a {@link RecentsAnimation} */
-    private boolean mRunningRecentsAnimation;
+    /**
+     * It can be set for a running transition player ({@link android.window.ITransitionPlayer}) or
+     * remote animators (running {@link android.window.IRemoteTransition}).
+     */
+    static final int ANIMATING_REASON_REMOTE_ANIMATION = 1;
+    /** It is set for wakefulness transition. */
+    static final int ANIMATING_REASON_WAKEFULNESS_CHANGE = 1 << 1;
+    /** Whether the legacy {@link RecentsAnimation} is running. */
+    static final int ANIMATING_REASON_LEGACY_RECENT_ANIMATION = 1 << 2;
 
-    /** Whether our process is currently running a {@link IRemoteAnimationRunner} */
-    private boolean mRunningRemoteAnimation;
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef({
+            ANIMATING_REASON_REMOTE_ANIMATION,
+            ANIMATING_REASON_WAKEFULNESS_CHANGE,
+            ANIMATING_REASON_LEGACY_RECENT_ANIMATION,
+    })
+    @interface AnimatingReason {}
+
+    /**
+     * Non-zero if this process is currently running an important animation. This should be never
+     * set for system server.
+     */
+    @AnimatingReason
+    private int mAnimatingReasons;
 
     // The bits used for mActivityStateFlags.
     private static final int ACTIVITY_STATE_FLAG_IS_VISIBLE = 1 << 16;
@@ -1869,30 +1890,45 @@
     }
 
     void setRunningRecentsAnimation(boolean running) {
-        if (mRunningRecentsAnimation == running) {
-            return;
+        if (running) {
+            addAnimatingReason(ANIMATING_REASON_LEGACY_RECENT_ANIMATION);
+        } else {
+            removeAnimatingReason(ANIMATING_REASON_LEGACY_RECENT_ANIMATION);
         }
-        mRunningRecentsAnimation = running;
-        updateRunningRemoteOrRecentsAnimation();
     }
 
     void setRunningRemoteAnimation(boolean running) {
-        if (mRunningRemoteAnimation == running) {
-            return;
+        if (running) {
+            addAnimatingReason(ANIMATING_REASON_REMOTE_ANIMATION);
+        } else {
+            removeAnimatingReason(ANIMATING_REASON_REMOTE_ANIMATION);
         }
-        mRunningRemoteAnimation = running;
-        updateRunningRemoteOrRecentsAnimation();
     }
 
-    void updateRunningRemoteOrRecentsAnimation() {
+    void addAnimatingReason(@AnimatingReason int reason) {
+        final int prevReasons = mAnimatingReasons;
+        mAnimatingReasons |= reason;
+        if (prevReasons == 0) {
+            setAnimating(true);
+        }
+    }
+
+    void removeAnimatingReason(@AnimatingReason int reason) {
+        final int prevReasons = mAnimatingReasons;
+        mAnimatingReasons &= ~reason;
+        if (prevReasons != 0 && mAnimatingReasons == 0) {
+            setAnimating(false);
+        }
+    }
+
+    /** Applies the animating state to activity manager for updating process priority. */
+    private void setAnimating(boolean animating) {
         // Posting on handler so WM lock isn't held when we call into AM.
-        mAtm.mH.sendMessage(PooledLambda.obtainMessage(
-                WindowProcessListener::setRunningRemoteAnimation, mListener,
-                isRunningRemoteTransition()));
+        mAtm.mH.post(() -> mListener.setRunningRemoteAnimation(animating));
     }
 
     boolean isRunningRemoteTransition() {
-        return mRunningRecentsAnimation || mRunningRemoteAnimation;
+        return (mAnimatingReasons & ANIMATING_REASON_REMOTE_ANIMATION) != 0;
     }
 
     /** Adjusts scheduling group for animation. This method MUST NOT be called inside WM lock. */
@@ -1946,6 +1982,21 @@
         pw.println(prefix + " mLastReportedConfiguration=" + (mHasCachedConfiguration
                 ? ("(cached) " + mLastReportedConfiguration) : mLastReportedConfiguration));
 
+        final int animatingReasons = mAnimatingReasons;
+        if (animatingReasons != 0) {
+            pw.print(prefix + " mAnimatingReasons=");
+            if ((animatingReasons & ANIMATING_REASON_REMOTE_ANIMATION) != 0) {
+                pw.print("remote-animation|");
+            }
+            if ((animatingReasons & ANIMATING_REASON_WAKEFULNESS_CHANGE) != 0) {
+                pw.print("wakefulness|");
+            }
+            if ((animatingReasons & ANIMATING_REASON_LEGACY_RECENT_ANIMATION) != 0) {
+                pw.print("legacy-recents");
+            }
+            pw.println();
+        }
+
         final int stateFlags = mActivityStateFlags;
         if (stateFlags != ACTIVITY_STATE_FLAG_MASK_MIN_TASK_LAYER) {
             pw.print(prefix + " mActivityStateFlags=");
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index 029f46f..5a45fe1 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -2334,6 +2334,8 @@
             mDisplayContent.updateImeControlTarget(isImeLayeringTarget() /* updateImeParent */);
             // Fix the starting window to task when Activity has changed.
             if (mStartingData != null && mStartingData.mAssociatedTask == null
+                    && mTempConfiguration.windowConfiguration.getRotation()
+                            == selfConfiguration.windowConfiguration.getRotation()
                     && !mTempConfiguration.windowConfiguration.getBounds().equals(getBounds())) {
                 mStartingData.mResizedFromTransfer = true;
                 // Lock the starting window to task, so it won't resize from transfer anymore.
@@ -2410,7 +2412,7 @@
         ProtoLog.v(WM_DEBUG_ADD_REMOVE,
                 "removeIfPossible: %s callers=%s", this, Debug.getCallers(5));
 
-        final boolean startingWindow = mAttrs.type == TYPE_APPLICATION_STARTING;
+        final boolean startingWindow = mStartingData != null;
         if (startingWindow) {
             ProtoLog.d(WM_DEBUG_STARTING_WINDOW, "Starting window removed %s", this);
             // Cancel the remove starting window animation on shell. The main window might changed
@@ -2424,6 +2426,7 @@
                     return false;
                 }, true);
             }
+            mTransitionController.mTransitionTracer.logRemovingStartingWindow(mStartingData);
         } else if (mAttrs.type == TYPE_BASE_APPLICATION
                 && isSelfAnimating(0, ANIMATION_TYPE_STARTING_REVEAL)) {
             // Cancel the remove starting window animation in case the binder dead before remove
diff --git a/services/core/jni/Android.bp b/services/core/jni/Android.bp
index 101af4d..405b133 100644
--- a/services/core/jni/Android.bp
+++ b/services/core/jni/Android.bp
@@ -94,7 +94,10 @@
 
 cc_defaults {
     name: "libservices.core-libs",
-    defaults: ["android.hardware.graphics.common-ndk_shared"],
+    defaults: [
+        "android.hardware.graphics.common-ndk_shared",
+        "android.hardware.power-ndk_shared",
+    ],
     shared_libs: [
         "libadb_pairing_server",
         "libadb_pairing_connection",
@@ -177,7 +180,6 @@
         "android.hardware.power@1.1",
         "android.hardware.power@1.2",
         "android.hardware.power@1.3",
-        "android.hardware.power-V4-ndk",
         "android.hardware.power.stats@1.0",
         "android.hardware.power.stats-V1-ndk",
         "android.hardware.thermal@1.0",
diff --git a/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp b/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
index 4343edd..cfc63f0 100644
--- a/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
+++ b/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
@@ -233,6 +233,7 @@
 // process_madvise on failure
 int madviseVmasFromBatch(unique_fd& pidfd, VmaBatch& batch, int madviseType,
                          uint64_t* outBytesProcessed) {
+    static const size_t kPageSize = getpagesize();
     if (batch.totalVmas == 0 || batch.totalBytes == 0) {
         // No VMAs in Batch, skip.
         *outBytesProcessed = 0;
@@ -258,7 +259,7 @@
     } else if (bytesProcessedInSend < batch.totalBytes) {
         // Partially processed the bytes requested
         // skip last page which is where it failed.
-        bytesProcessedInSend += PAGE_SIZE;
+        bytesProcessedInSend += kPageSize;
     }
     bytesProcessedInSend = consumeBytes(batch, bytesProcessedInSend);
 
diff --git a/services/core/jni/com_android_server_companion_virtual_InputController.cpp b/services/core/jni/com_android_server_companion_virtual_InputController.cpp
index ad098b7..4cd018b 100644
--- a/services/core/jni/com_android_server_companion_virtual_InputController.cpp
+++ b/services/core/jni/com_android_server_companion_virtual_InputController.cpp
@@ -144,12 +144,20 @@
             }
             uinput_abs_setup slotAbsSetup;
             slotAbsSetup.code = ABS_MT_SLOT;
-            slotAbsSetup.absinfo.maximum = MAX_POINTERS;
+            slotAbsSetup.absinfo.maximum = MAX_POINTERS - 1;
             slotAbsSetup.absinfo.minimum = 0;
             if (ioctl(fd, UI_ABS_SETUP, &slotAbsSetup) != 0) {
                 ALOGE("Error creating touchscreen uinput slots: %s", strerror(errno));
                 return invalidFd();
             }
+            uinput_abs_setup trackingIdAbsSetup;
+            trackingIdAbsSetup.code = ABS_MT_TRACKING_ID;
+            trackingIdAbsSetup.absinfo.maximum = MAX_POINTERS - 1;
+            trackingIdAbsSetup.absinfo.minimum = 0;
+            if (ioctl(fd, UI_ABS_SETUP, &trackingIdAbsSetup) != 0) {
+                ALOGE("Error creating touchscreen uinput tracking ids: %s", strerror(errno));
+                return invalidFd();
+            }
         }
         if (ioctl(fd, UI_DEV_SETUP, &setup) != 0) {
             ALOGE("Error creating uinput device: %s", strerror(errno));
diff --git a/services/core/jni/com_android_server_hint_HintManagerService.cpp b/services/core/jni/com_android_server_hint_HintManagerService.cpp
index e148b94..7edf445 100644
--- a/services/core/jni/com_android_server_hint_HintManagerService.cpp
+++ b/services/core/jni/com_android_server_hint_HintManagerService.cpp
@@ -31,6 +31,7 @@
 
 using aidl::android::hardware::power::IPowerHintSession;
 using aidl::android::hardware::power::SessionHint;
+using aidl::android::hardware::power::SessionMode;
 using aidl::android::hardware::power::WorkDuration;
 
 using android::base::StringPrintf;
@@ -41,6 +42,15 @@
 static std::unordered_map<jlong, std::shared_ptr<IPowerHintSession>> gSessionMap;
 static std::mutex gSessionMapLock;
 
+static int64_t getHintSessionPreferredRate() {
+    int64_t rate = -1;
+    auto result = gPowerHalController.getHintSessionPreferredRate();
+    if (result.isOk()) {
+        rate = result.value();
+    }
+    return rate;
+}
+
 static jlong createHintSession(JNIEnv* env, int32_t tgid, int32_t uid,
                                std::vector<int32_t> threadIds, int64_t durationNanos) {
     auto result = gPowerHalController.createHintSession(tgid, uid, threadIds, durationNanos);
@@ -93,13 +103,9 @@
     appSession->setThreads(threadIds);
 }
 
-static int64_t getHintSessionPreferredRate() {
-    int64_t rate = -1;
-    auto result = gPowerHalController.getHintSessionPreferredRate();
-    if (result.isOk()) {
-        rate = result.value();
-    }
-    return rate;
+static void setMode(int64_t session_ptr, SessionMode mode, bool enabled) {
+    auto appSession = reinterpret_cast<IPowerHintSession*>(session_ptr);
+    appSession->setMode(mode, enabled);
 }
 
 // ----------------------------------------------------------------------------
@@ -107,6 +113,10 @@
     gPowerHalController.init();
 }
 
+static jlong nativeGetHintSessionPreferredRate(JNIEnv* /* env */, jclass /* clazz */) {
+    return static_cast<jlong>(getHintSessionPreferredRate());
+}
+
 static jlong nativeCreateHintSession(JNIEnv* env, jclass /* clazz */, jint tgid, jint uid,
                                      jintArray tids, jlong durationNanos) {
     ScopedIntArrayRO tidArray(env, tids);
@@ -165,14 +175,16 @@
     setThreads(session_ptr, threadIds);
 }
 
-static jlong nativeGetHintSessionPreferredRate(JNIEnv* /* env */, jclass /* clazz */) {
-    return static_cast<jlong>(getHintSessionPreferredRate());
+static void nativeSetMode(JNIEnv* env, jclass /* clazz */, jlong session_ptr, jint mode,
+                          jboolean enabled) {
+    setMode(session_ptr, static_cast<SessionMode>(mode), enabled);
 }
 
 // ----------------------------------------------------------------------------
 static const JNINativeMethod sHintManagerServiceMethods[] = {
         /* name, signature, funcPtr */
         {"nativeInit", "()V", (void*)nativeInit},
+        {"nativeGetHintSessionPreferredRate", "()J", (void*)nativeGetHintSessionPreferredRate},
         {"nativeCreateHintSession", "(II[IJ)J", (void*)nativeCreateHintSession},
         {"nativePauseHintSession", "(J)V", (void*)nativePauseHintSession},
         {"nativeResumeHintSession", "(J)V", (void*)nativeResumeHintSession},
@@ -181,7 +193,7 @@
         {"nativeReportActualWorkDuration", "(J[J[J)V", (void*)nativeReportActualWorkDuration},
         {"nativeSendHint", "(JI)V", (void*)nativeSendHint},
         {"nativeSetThreads", "(J[I)V", (void*)nativeSetThreads},
-        {"nativeGetHintSessionPreferredRate", "()J", (void*)nativeGetHintSessionPreferredRate},
+        {"nativeSetMode", "(JIZ)V", (void*)nativeSetMode},
 };
 
 int register_android_server_HintManagerService(JNIEnv* env) {
diff --git a/services/core/jni/com_android_server_location_GnssLocationProvider.cpp b/services/core/jni/com_android_server_location_GnssLocationProvider.cpp
index e1de05c..11c40d7 100644
--- a/services/core/jni/com_android_server_location_GnssLocationProvider.cpp
+++ b/services/core/jni/com_android_server_location_GnssLocationProvider.cpp
@@ -69,7 +69,6 @@
 
 static jclass class_gnssPowerStats;
 
-static jmethodID method_reportNiNotification;
 static jmethodID method_reportGnssPowerStats;
 static jmethodID method_reportNfwNotification;
 static jmethodID method_isInEmergencySession;
@@ -92,8 +91,6 @@
 using android::hardware::gnss::V1_0::GnssLocationFlags;
 using android::hardware::gnss::V1_0::IGnssNavigationMessage;
 using android::hardware::gnss::V1_0::IGnssNavigationMessageCallback;
-using android::hardware::gnss::V1_0::IGnssNi;
-using android::hardware::gnss::V1_0::IGnssNiCallback;
 using android::hardware::gnss::V1_0::IGnssXtra;
 using android::hardware::gnss::V1_0::IGnssXtraCallback;
 using android::hardware::gnss::V2_0::ElapsedRealtimeFlags;
@@ -127,7 +124,6 @@
 using GnssLocationAidl = android::hardware::gnss::GnssLocation;
 using IGnssAntennaInfoAidl = android::hardware::gnss::IGnssAntennaInfo;
 
-sp<IGnssNi> gnssNiIface = nullptr;
 sp<IGnssPowerIndication> gnssPowerIndicationIface = nullptr;
 
 std::unique_ptr<android::gnss::GnssHal> gnssHal = nullptr;
@@ -195,42 +191,6 @@
     return Status::ok();
 }
 
-/*
- * GnssNiCallback implements callback methods required by the IGnssNi interface.
- */
-struct GnssNiCallback : public IGnssNiCallback {
-    Return<void> niNotifyCb(const IGnssNiCallback::GnssNiNotification& notification)
-            override;
-};
-
-Return<void> GnssNiCallback::niNotifyCb(
-        const IGnssNiCallback::GnssNiNotification& notification) {
-    JNIEnv* env = getJniEnv();
-    jstring requestorId = env->NewStringUTF(notification.requestorId.c_str());
-    jstring text = env->NewStringUTF(notification.notificationMessage.c_str());
-
-    if (requestorId && text) {
-        env->CallVoidMethod(mCallbacksObj, method_reportNiNotification,
-                            notification.notificationId, notification.niType,
-                            notification.notifyFlags, notification.timeoutSec,
-                            notification.defaultResponse, requestorId, text,
-                            notification.requestorIdEncoding,
-                            notification.notificationIdEncoding);
-    } else {
-        ALOGE("%s: OOM Error\n", __func__);
-    }
-
-    if (requestorId) {
-        env->DeleteLocalRef(requestorId);
-    }
-
-    if (text) {
-        env->DeleteLocalRef(text);
-    }
-    checkAndClearExceptionFromCallback(env, __FUNCTION__);
-    return Void();
-}
-
 /* Initializes the GNSS service handle. */
 static void android_location_gnss_hal_GnssNative_set_gps_service_handle() {
     gnssHal = std::make_unique<gnss::GnssHal>();
@@ -242,10 +202,6 @@
     android_location_gnss_hal_GnssNative_set_gps_service_handle();
 
     // Cache methodIDs and class IDs.
-
-    method_reportNiNotification = env->GetMethodID(clazz, "reportNiNotification",
-            "(IIIIILjava/lang/String;Ljava/lang/String;II)V");
-
     method_reportNfwNotification = env->GetMethodID(clazz, "reportNfwNotification",
             "(Ljava/lang/String;BLjava/lang/String;BLjava/lang/String;BZZ)V");
     method_reportGnssPowerStats =
@@ -305,7 +261,6 @@
     gnssAntennaInfoIface = gnssHal->getGnssAntennaInfoInterface();
     gnssMeasurementCorrectionsIface = gnssHal->getMeasurementCorrectionsInterface();
     gnssDebugIface = gnssHal->getGnssDebugInterface();
-    gnssNiIface = gnssHal->getGnssNiInterface();
     gnssConfigurationIface = gnssHal->getGnssConfigurationInterface();
     gnssGeofencingIface = gnssHal->getGnssGeofenceInterface();
     gnssBatchingIface = gnssHal->getGnssBatchingInterface();
@@ -376,15 +331,6 @@
         ALOGI("Unable to initialize IGnssGeofencing interface.");
     }
 
-    // Set IGnssNi.hal callback.
-    sp<IGnssNiCallback> gnssNiCbIface = new GnssNiCallback();
-    if (gnssNiIface != nullptr) {
-        auto status = gnssNiIface->setCallback(gnssNiCbIface);
-        checkHidlReturn(status, "IGnssNi setCallback() failed.");
-    } else {
-        ALOGI("Unable to initialize IGnssNi interface.");
-    }
-
     // Set IAGnssRil callback.
     if (agnssRilIface == nullptr ||
         !agnssRilIface->setCallback(std::make_unique<gnss::AGnssRilCallback>())) {
@@ -592,18 +538,6 @@
     }
 }
 
-static void android_location_gnss_hal_GnssNative_send_ni_response(JNIEnv* /* env */, jclass,
-                                                                  jint notifId, jint response) {
-    if (gnssNiIface == nullptr) {
-        ALOGE("%s: IGnssNi interface not available.", __func__);
-        return;
-    }
-
-    auto result = gnssNiIface->respond(notifId,
-            static_cast<IGnssNiCallback::GnssUserResponseType>(response));
-    checkHidlReturn(result, "IGnssNi respond() failed.");
-}
-
 static jstring android_location_gnss_hal_GnssNative_get_internal_state(JNIEnv* env, jclass) {
     /*
      * TODO: Create a jobject to represent GnssDebug.
@@ -987,8 +921,6 @@
          reinterpret_cast<void*>(android_location_gnss_hal_GnssNative_set_agps_server)},
         {"native_inject_ni_supl_message_data", "([BII)V",
          reinterpret_cast<void*>(android_location_gnss_hal_GnssNative_inject_ni_supl_message_data)},
-        {"native_send_ni_response", "(II)V",
-         reinterpret_cast<void*>(android_location_gnss_hal_GnssNative_send_ni_response)},
         {"native_get_internal_state", "()Ljava/lang/String;",
          reinterpret_cast<void*>(android_location_gnss_hal_GnssNative_get_internal_state)},
         {"native_is_gnss_visibility_control_supported", "()Z",
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyCacheImpl.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyCacheImpl.java
index 522ee34..e7855bc 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyCacheImpl.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyCacheImpl.java
@@ -79,14 +79,7 @@
 
     @Override
     public boolean isScreenCaptureAllowed(int userHandle) {
-        if (DevicePolicyManagerService.isPolicyEngineForFinanceFlagEnabled()) {
-            return isScreenCaptureAllowedInPolicyEngine(userHandle);
-        } else {
-            synchronized (mLock) {
-                return mScreenCaptureDisallowedUser != UserHandle.USER_ALL
-                        && mScreenCaptureDisallowedUser != userHandle;
-            }
-        }
+        return isScreenCaptureAllowedInPolicyEngine(userHandle);
     }
 
     private boolean isScreenCaptureAllowedInPolicyEngine(int userHandle) {
@@ -182,11 +175,7 @@
         synchronized (mLock) {
             pw.println("Device policy cache:");
             pw.increaseIndent();
-            if (DevicePolicyManagerService.isPolicyEngineForFinanceFlagEnabled()) {
-                pw.println("Screen capture disallowed users: " + mScreenCaptureDisallowedUsers);
-            } else {
-                pw.println("Screen capture disallowed user: " + mScreenCaptureDisallowedUser);
-            }
+            pw.println("Screen capture disallowed users: " + mScreenCaptureDisallowedUsers);
             pw.println("Password quality: " + mPasswordQuality);
             pw.println("Permission policy: " + mPermissionPolicy);
             pw.println("Admin can grant sensors permission: " + mCanGrantSensorsPermissions.get());
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index c323a7f..af1bac8 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -241,6 +241,7 @@
 import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI;
 import static android.provider.Telephony.Carriers.INVALID_APN_ID;
 import static android.security.keystore.AttestationUtils.USE_INDIVIDUAL_ATTESTATION;
+
 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
@@ -1190,9 +1191,7 @@
                         maybeResumeDeviceWideLoggingLocked();
                     }
                 }
-                if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
-                    mDevicePolicyEngine.handleUserRemoved(userHandle);
-                }
+                mDevicePolicyEngine.handleUserRemoved(userHandle);
             } else if (Intent.ACTION_USER_STARTED.equals(action)) {
                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle);
                 synchronized (getLockObject()) {
@@ -1442,10 +1441,7 @@
                     && (owner.getPackageName().equals(packageName))) {
                 startOwnerService(userHandle, "package-broadcast");
             }
-            if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
-                mDevicePolicyEngine.handlePackageChanged(
-                        packageName, userHandle, removedAdminPackage);
-            }
+            mDevicePolicyEngine.handlePackageChanged(packageName, userHandle, removedAdminPackage);
             // Persist updates if the removed package was an admin or delegate.
             if (removedAdmin || removedDelegate) {
                 saveSettingsLocked(policy.mUserId);
@@ -1453,7 +1449,6 @@
         }
         if (removedAdmin) {
             // The removed admin might have disabled camera, so update user restrictions.
-            pushUserRestrictions(userHandle);
             pushMeteredDisabledPackages(userHandle);
         }
     }
@@ -2144,9 +2139,7 @@
         mUserManagerInternal.addUserLifecycleListener(new UserLifecycleListener());
 
         mDeviceManagementResourcesProvider.load();
-        if (isPermissionCheckFlagEnabled() || isPolicyEngineForFinanceFlagEnabled()) {
-            mDevicePolicyEngine.load();
-        }
+        mDevicePolicyEngine.load();
 
         mContactSystemRoleHolders = fetchOemSystemHolders(/* roleResIds...= */
                 com.android.internal.R.string.config_defaultSms,
@@ -2278,11 +2271,9 @@
                 if (parentAdmin != null) {
                     parentAdmin.userRestrictions = null;
                 }
-                pushUserRestrictions(userHandle);
             }
             mOwners.removeProfileOwner(userHandle);
             mOwners.writeProfileOwner(userHandle);
-            pushScreenCapturePolicy(userHandle);
 
             DevicePolicyData policy = mUserData.get(userHandle);
             if (policy != null) {
@@ -2640,20 +2631,14 @@
             ActiveAdmin profileOwner, boolean newOwner) {
         if (newOwner || mInjector.settingsSecureGetIntForUser(
                 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
-            if (isPolicyEngineForFinanceFlagEnabled()) {
-                mDevicePolicyEngine.setLocalPolicy(
-                        PolicyDefinition.getPolicyDefinitionForUserRestriction(
-                                UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
-                        EnforcingAdmin.createEnterpriseEnforcingAdmin(
-                                profileOwner.info.getComponent(),
-                                profileOwner.getUserHandle().getIdentifier()),
-                        new BooleanPolicyValue(true),
-                        userId);
-            } else {
-                profileOwner.ensureUserRestrictions().putBoolean(
-                        UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
-                saveUserRestrictionsLocked(userId);
-            }
+            mDevicePolicyEngine.setLocalPolicy(
+                    PolicyDefinition.getPolicyDefinitionForUserRestriction(
+                            UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
+                    EnforcingAdmin.createEnterpriseEnforcingAdmin(
+                            profileOwner.info.getComponent(),
+                            profileOwner.getUserHandle().getIdentifier()),
+                    new BooleanPolicyValue(true),
+                    userId);
             mInjector.settingsSecurePutIntForUser(
                     Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
         }
@@ -2668,41 +2653,18 @@
         if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
             return; // The same set of default restrictions has been already applied.
         }
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            for (String restriction : defaultRestrictions) {
-                mDevicePolicyEngine.setLocalPolicy(
-                        PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction),
-                        EnforcingAdmin.createEnterpriseEnforcingAdmin(
-                                admin.info.getComponent(),
-                                admin.getUserHandle().getIdentifier()),
-                        new BooleanPolicyValue(true),
-                        userId);
-            }
-            admin.defaultEnabledRestrictionsAlreadySet.addAll(defaultRestrictions);
-            Slogf.i(LOG_TAG, "Enabled the following restrictions by default: " +
-                    defaultRestrictions);
-            return;
+        for (String restriction : defaultRestrictions) {
+            mDevicePolicyEngine.setLocalPolicy(
+                    PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction),
+                    EnforcingAdmin.createEnterpriseEnforcingAdmin(
+                            admin.info.getComponent(),
+                            admin.getUserHandle().getIdentifier()),
+                    new BooleanPolicyValue(true),
+                    userId);
         }
-
-        Slogf.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId);
-
-        if (VERBOSE_LOG) {
-            Slogf.d(LOG_TAG, "Default enabled restrictions: "
-                    + defaultRestrictions
-                    + ". Restrictions already enabled: "
-                    + admin.defaultEnabledRestrictionsAlreadySet);
-        }
-
-        final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions);
-        restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet);
-        if (!restrictionsToSet.isEmpty()) {
-            for (final String restriction : restrictionsToSet) {
-                admin.ensureUserRestrictions().putBoolean(restriction, true);
-            }
-            admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet);
-            Slogf.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet);
-            saveUserRestrictionsLocked(userId);
-        }
+        admin.defaultEnabledRestrictionsAlreadySet.addAll(defaultRestrictions);
+        Slogf.i(LOG_TAG, "Enabled the following restrictions by default: "
+                + defaultRestrictions);
     }
 
     private void setDeviceOwnershipSystemPropertyLocked() {
@@ -2765,7 +2727,6 @@
                     // Apply user restriction to parent active admin instead
                     parent.ensureUserRestrictions().putBoolean(
                             UserManager.DISALLOW_CONFIG_DATE_TIME, true);
-                    pushUserRestrictions(userId);
                 }
             }
         }
@@ -3297,10 +3258,6 @@
 
         policy.validatePasswordOwner();
         updateMaximumTimeToLockLocked(userHandle);
-        if (!isPolicyEngineForFinanceFlagEnabled()) {
-            updateLockTaskPackagesLocked(mContext, policy.mLockTaskPackages, userHandle);
-            updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle);
-        }
         if (policy.mStatusBarDisabled) {
             setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
         }
@@ -3470,9 +3427,6 @@
             }
 
             revertTransferOwnershipIfNecessaryLocked();
-            if (!isPolicyEngineForFinanceFlagEnabled()) {
-                updateUsbDataSignal(mContext, isUsbDataSignalingEnabledInternalLocked());
-            }
         }
 
         // In case flag value has changed, we apply it during boot to avoid doing it concurrently
@@ -3545,9 +3499,6 @@
             deleteTransferOwnershipBundleLocked(metadata.userId);
         }
         updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
-        if (!isPolicyEngineForFinanceFlagEnabled()) {
-            pushUserControlDisabledPackagesLocked(metadata.userId);
-        }
     }
 
     private void maybeLogStart() {
@@ -3584,13 +3535,6 @@
     }
 
     void handleStartUser(int userId) {
-        synchronized (getLockObject()) {
-            pushScreenCapturePolicy(userId);
-            if (!isPolicyEngineForFinanceFlagEnabled()) {
-                pushUserControlDisabledPackagesLocked(userId);
-            }
-        }
-        pushUserRestrictions(userId);
         // When system user is started (device boot), load cache for all users.
         // This is to mitigate the potential race between loading the cache and keyguard
         // reading the value during user switch, due to onStartUser() being asynchronous.
@@ -3615,9 +3559,7 @@
         }
 
         startOwnerService(userId, "start-user");
-        if (isPermissionCheckFlagEnabled() || isPolicyEngineForFinanceFlagEnabled()) {
-            mDevicePolicyEngine.handleStartUser(userId);
-        }
+        mDevicePolicyEngine.handleStartUser(userId);
     }
 
     void pushUserControlDisabledPackagesLocked(int userId) {
@@ -3642,9 +3584,7 @@
 
     void handleUnlockUser(int userId) {
         startOwnerService(userId, "unlock-user");
-        if (isPermissionCheckFlagEnabled() || isPolicyEngineForFinanceFlagEnabled()) {
-            mDevicePolicyEngine.handleUnlockUser(userId);
-        }
+        mDevicePolicyEngine.handleUnlockUser(userId);
     }
 
     void handleOnUserUnlocked(int userId) {
@@ -3654,9 +3594,7 @@
     void handleStopUser(int userId) {
         updateNetworkPreferenceForUser(userId, List.of(PreferentialNetworkServiceConfig.DEFAULT));
         mDeviceAdminServiceController.stopServicesForUser(userId, /* actionForLog= */ "stop-user");
-        if (isPermissionCheckFlagEnabled() || isPolicyEngineForFinanceFlagEnabled()) {
-            mDevicePolicyEngine.handleStopUser(userId);
-        }
+        mDevicePolicyEngine.handleStopUser(userId);
     }
 
     private void startOwnerService(int userId, String actionForLog) {
@@ -3690,9 +3628,7 @@
         }
         for (Integer userId : deletedUsers) {
             removeUserData(userId);
-            if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
-                mDevicePolicyEngine.handleUserRemoved(userId);
-            }
+            mDevicePolicyEngine.handleUserRemoved(userId);
         }
     }
 
@@ -3879,16 +3815,14 @@
         final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver);
         final int oldAdminUid = adminToTransfer.getUid();
 
-        if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
-            EnforcingAdmin oldAdmin =
-                    EnforcingAdmin.createEnterpriseEnforcingAdmin(
-                            outgoingReceiver, userHandle, adminToTransfer);
-            EnforcingAdmin newAdmin =
-                    EnforcingAdmin.createEnterpriseEnforcingAdmin(
-                            incomingReceiver, userHandle, adminToTransfer);
+        EnforcingAdmin oldAdmin =
+                EnforcingAdmin.createEnterpriseEnforcingAdmin(
+                        outgoingReceiver, userHandle, adminToTransfer);
+        EnforcingAdmin newAdmin =
+                EnforcingAdmin.createEnterpriseEnforcingAdmin(
+                        incomingReceiver, userHandle, adminToTransfer);
 
-            mDevicePolicyEngine.transferPolicies(oldAdmin, newAdmin);
-        }
+        mDevicePolicyEngine.transferPolicies(oldAdmin, newAdmin);
 
         adminToTransfer.transfer(incomingDeviceInfo);
         policy.mAdminMap.remove(outgoingReceiver);
@@ -4194,11 +4128,9 @@
             mInjector.binderWithCleanCallingIdentity(() ->
                     removeActiveAdminLocked(adminReceiver, userHandle));
         }
-        if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
-            mDevicePolicyEngine.removePoliciesForAdmin(
-                    EnforcingAdmin.createEnterpriseEnforcingAdmin(
-                            adminReceiver, userHandle, admin));
-        }
+        mDevicePolicyEngine.removePoliciesForAdmin(
+                EnforcingAdmin.createEnterpriseEnforcingAdmin(
+                        adminReceiver, userHandle, admin));
     }
 
     private boolean canSetPasswordQualityOnParent(String packageName, final CallerIdentity caller) {
@@ -7558,47 +7490,17 @@
         if (!mHasFeature && !hasCallingOrSelfPermission(permission.MASTER_CLEAR)) {
             return;
         }
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(callerPackageName);
-        }  else {
-            caller = getCallerIdentity();
-        }
-        ActiveAdmin admin;
+        CallerIdentity caller = getCallerIdentity(callerPackageName);
 
         boolean calledByProfileOwnerOnOrgOwnedDevice =
                 isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId());
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
-                    /*admin=*/ null,
-                    /*permission=*/ new String[]{MANAGE_DEVICE_POLICY_WIPE_DATA, MASTER_CLEAR},
-                    USES_POLICY_WIPE_DATA,
-                    caller.getPackageName(),
-                    factoryReset ? UserHandle.USER_ALL : getAffectedUser(calledOnParentInstance));
-            admin = enforcingAdmin.getActiveAdmin();
-        } else {
-            if (calledOnParentInstance) {
-                Preconditions.checkCallAuthorization(calledByProfileOwnerOnOrgOwnedDevice,
-                        "Wiping the entire device can only be done by a profile owner on "
-                                + "organization-owned device.");
-            }
-            if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
-                Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
-                                || calledByProfileOwnerOnOrgOwnedDevice
-                                || isFinancedDeviceOwner(caller),
-                        "Only device owners or profile owners of organization-owned device can set "
-                                + "WIPE_RESET_PROTECTION_DATA");
-            }
-            synchronized (getLockObject()) {
-                admin = getActiveAdminWithPolicyForUidLocked(/* who= */ null,
-                        DeviceAdminInfo.USES_POLICY_WIPE_DATA, caller.getUid());
-            }
-            Preconditions.checkCallAuthorization(
-                    (admin != null) || hasCallingOrSelfPermission(permission.MASTER_CLEAR),
-                    "No active admin for user %d and caller %d does not hold MASTER_CLEAR "
-                            + "permission",
-                    caller.getUserId(), caller.getUid());
-        }
+        EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
+                /*admin=*/ null,
+                /*permission=*/ new String[]{MANAGE_DEVICE_POLICY_WIPE_DATA, MASTER_CLEAR},
+                USES_POLICY_WIPE_DATA,
+                caller.getPackageName(),
+                factoryReset ? UserHandle.USER_ALL : getAffectedUser(calledOnParentInstance));
+        ActiveAdmin admin = enforcingAdmin.getActiveAdmin();
 
         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_WIPE_DATA);
 
@@ -8639,62 +8541,36 @@
             return;
         }
 
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackage);
-        } else {
-            Objects.requireNonNull(who, "ComponentName is null");
-            caller = getCallerIdentity(who);
-            if (parent) {
-                Preconditions.checkCallAuthorization(
-                        isProfileOwnerOfOrganizationOwnedDevice(caller));
+        CallerIdentity caller = getCallerIdentity(who, callerPackage);
+        int callerUserId = Binder.getCallingUserHandle().getIdentifier();
+        int targetUserId = parent ? getProfileParentId(callerUserId) : callerUserId;
+        EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
+                who, MANAGE_DEVICE_POLICY_SCREEN_CAPTURE, caller.getPackageName(),
+                targetUserId);
+        if ((parent && isProfileOwnerOfOrganizationOwnedDevice(caller))
+                || isDefaultDeviceOwner(caller)) {
+            if (disabled) {
+                mDevicePolicyEngine.setGlobalPolicy(
+                        PolicyDefinition.SCREEN_CAPTURE_DISABLED,
+                        admin,
+                        new BooleanPolicyValue(disabled));
             } else {
-                Preconditions.checkCallAuthorization(isProfileOwner(caller)
-                        || isDefaultDeviceOwner(caller));
-            }
-        }
-
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            int callerUserId = Binder.getCallingUserHandle().getIdentifier();
-            int targetUserId = parent ? getProfileParentId(callerUserId) : callerUserId;
-            EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
-                    who, MANAGE_DEVICE_POLICY_SCREEN_CAPTURE, caller.getPackageName(),
-                    targetUserId);
-            if ((parent && isProfileOwnerOfOrganizationOwnedDevice(caller))
-                    || isDefaultDeviceOwner(caller)) {
-                if (disabled) {
-                    mDevicePolicyEngine.setGlobalPolicy(
-                            PolicyDefinition.SCREEN_CAPTURE_DISABLED,
-                            admin,
-                            new BooleanPolicyValue(disabled));
-                } else {
-                    mDevicePolicyEngine.removeGlobalPolicy(
-                            PolicyDefinition.SCREEN_CAPTURE_DISABLED,
-                            admin);
-                }
-            } else {
-                if (disabled) {
-                    mDevicePolicyEngine.setLocalPolicy(
-                            PolicyDefinition.SCREEN_CAPTURE_DISABLED,
-                            admin,
-                            new BooleanPolicyValue(disabled),
-                            callerUserId);
-                } else {
-                    mDevicePolicyEngine.removeLocalPolicy(
-                            PolicyDefinition.SCREEN_CAPTURE_DISABLED,
-                            admin,
-                            callerUserId);
-                }
+                mDevicePolicyEngine.removeGlobalPolicy(
+                        PolicyDefinition.SCREEN_CAPTURE_DISABLED,
+                        admin);
             }
         } else {
-            synchronized (getLockObject()) {
-                ActiveAdmin ap = getParentOfAdminIfRequired(
-                        getProfileOwnerOrDefaultDeviceOwnerLocked(caller.getUserId()), parent);
-                if (ap.disableScreenCapture != disabled) {
-                    ap.disableScreenCapture = disabled;
-                    saveSettingsLocked(caller.getUserId());
-                    pushScreenCapturePolicy(caller.getUserId());
-                }
+            if (disabled) {
+                mDevicePolicyEngine.setLocalPolicy(
+                        PolicyDefinition.SCREEN_CAPTURE_DISABLED,
+                        admin,
+                        new BooleanPolicyValue(disabled),
+                        callerUserId);
+            } else {
+                mDevicePolicyEngine.removeLocalPolicy(
+                        PolicyDefinition.SCREEN_CAPTURE_DISABLED,
+                        admin,
+                        callerUserId);
             }
         }
         DevicePolicyEventLogger
@@ -8704,42 +8580,6 @@
                 .write();
     }
 
-    // Push the screen capture policy for a given userId. If screen capture is disabled by the
-    // DO or COPE PO on the parent profile, then this takes precedence as screen capture will
-    // be disabled device-wide.
-    private void pushScreenCapturePolicy(int adminUserId) {
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            return;
-        }
-        // Update screen capture device-wide if disabled by the DO or COPE PO on the parent profile.
-        // TODO(b/261999445): remove
-        ActiveAdmin admin;
-        if (isHeadlessFlagEnabled()) {
-            admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceParentLocked(
-                    mUserManagerInternal.getProfileParentId(adminUserId));
-        } else {
-            admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceParentLocked(
-                    UserHandle.USER_SYSTEM);
-        }
-        if (admin != null && admin.disableScreenCapture) {
-            setScreenCaptureDisabled(UserHandle.USER_ALL);
-            return;
-        }
-        // Otherwise, update screen capture only for the calling user.
-        admin = getProfileOwnerAdminLocked(adminUserId);
-        if (admin != null && admin.disableScreenCapture) {
-            setScreenCaptureDisabled(adminUserId);
-            return;
-        }
-        // If the admin is permission based, update only for the calling user.
-        admin = getUserData(adminUserId).createOrGetPermissionBasedAdmin(adminUserId);
-        if (admin != null && admin.disableScreenCapture) {
-            setScreenCaptureDisabled(adminUserId);
-            return;
-        }
-        setScreenCaptureDisabled(UserHandle.USER_NULL);
-    }
-
     // Set the latest screen capture policy, overriding any existing ones.
     // userHandle can be one of USER_ALL, USER_NULL or a concrete userId.
     private void setScreenCaptureDisabled(int userHandle) {
@@ -8766,14 +8606,10 @@
             Preconditions.checkCallAuthorization(
                     isProfileOwnerOfOrganizationOwnedDevice(getCallerIdentity().getUserId()));
         }
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            Boolean disallowed = mDevicePolicyEngine.getResolvedPolicy(
-                    PolicyDefinition.SCREEN_CAPTURE_DISABLED,
-                    userHandle);
-            return disallowed != null && disallowed;
-        } else {
-            return !mPolicyCache.isScreenCaptureAllowed(userHandle);
-        }
+        Boolean disallowed = mDevicePolicyEngine.getResolvedPolicy(
+                PolicyDefinition.SCREEN_CAPTURE_DISABLED,
+                userHandle);
+        return disallowed != null && disallowed;
     }
 
     private void updateScreenCaptureDisabled() {
@@ -8882,23 +8718,9 @@
             Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()),
                     "Managed profile cannot set auto time required");
 
-            if (isPolicyEngineForFinanceFlagEnabled()) {
-                EnforcingAdmin admin = getEnforcingAdminForCaller(who, who.getPackageName());
-                setGlobalUserRestrictionInternal(
-                        admin, UserManager.DISALLOW_CONFIG_DATE_TIME, required);
-            } else {
-                ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
-                if (admin.requireAutoTime != required) {
-                    admin.requireAutoTime = required;
-                    saveSettingsLocked(caller.getUserId());
-                    requireAutoTimeChanged = true;
-                }
-                // requireAutoTime is now backed by DISALLOW_CONFIG_DATE_TIME restriction, so
-                // propagate updated restrictions to the framework.
-                if (requireAutoTimeChanged) {
-                    pushUserRestrictions(caller.getUserId());
-                }
-            }
+            EnforcingAdmin admin = getEnforcingAdminForCaller(who, who.getPackageName());
+            setGlobalUserRestrictionInternal(
+                    admin, UserManager.DISALLOW_CONFIG_DATE_TIME, required);
         }
         // Turn AUTO_TIME on in settings if it is required
         if (required) {
@@ -8921,31 +8743,11 @@
         if (!mHasFeature) {
             return false;
         }
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            Boolean required = mDevicePolicyEngine.getResolvedPolicy(
-                    PolicyDefinition.getPolicyDefinitionForUserRestriction(
-                            UserManager.DISALLOW_CONFIG_DATE_TIME),
-                    mInjector.binderGetCallingUserHandle().getIdentifier());
-            return required != null && required;
-        } else {
-            synchronized (getLockObject()) {
-                ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
-                if (deviceOwner != null && deviceOwner.requireAutoTime) {
-                    // If the device owner enforces auto time, we don't need to check the PO's
-                    return true;
-                }
-
-                // Now check to see if any profile owner on any user enforces auto time
-                for (Integer userId : mOwners.getProfileOwnerKeys()) {
-                    ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
-                    if (profileOwner != null && profileOwner.requireAutoTime) {
-                        return true;
-                    }
-                }
-
-                return false;
-            }
-        }
+        Boolean required = mDevicePolicyEngine.getResolvedPolicy(
+                PolicyDefinition.getPolicyDefinitionForUserRestriction(
+                        UserManager.DISALLOW_CONFIG_DATE_TIME),
+                mInjector.binderGetCallingUserHandle().getIdentifier());
+        return required != null && required;
     }
 
     /**
@@ -9240,47 +9042,23 @@
             return;
         }
 
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
         final int userId = caller.getUserId();
 
         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_CAMERA_DISABLED);
-
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
-                    who,
-                    MANAGE_DEVICE_POLICY_CAMERA,
-                    caller.getPackageName(),
-                    getProfileParentUserIfRequested(userId, parent));
-            try {
-                setBackwardCompatibleUserRestriction(
-                        caller, enforcingAdmin, UserManager.DISALLOW_CAMERA, disabled, parent);
-            } catch (IllegalStateException e) {
-                throw new IllegalStateException(
-                        "Please use addUserRestriction or addUserRestrictionGlobally using the key"
-                                + " UserManager.DISALLOW_CAMERA to disable the camera locally or"
-                                + " globally, respectively");
-            }
-        } else {
-            Objects.requireNonNull(who, "ComponentName is null");
-            if (parent) {
-                Preconditions.checkCallAuthorization(
-                        isProfileOwnerOfOrganizationOwnedDevice(caller));
-            }
-            synchronized (getLockObject()) {
-                ActiveAdmin admin = getActiveAdminForCallerLocked(who,
-                        DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA, parent);
-                if (admin.disableCamera != disabled) {
-                    admin.disableCamera = disabled;
-                    saveSettingsLocked(userId);
-                }
-            }
-            // Tell the user manager that the restrictions have changed.
-            pushUserRestrictions(userId);
+        EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
+                who,
+                MANAGE_DEVICE_POLICY_CAMERA,
+                caller.getPackageName(),
+                getProfileParentUserIfRequested(userId, parent));
+        try {
+            setBackwardCompatibleUserRestriction(
+                    caller, enforcingAdmin, UserManager.DISALLOW_CAMERA, disabled, parent);
+        } catch (IllegalStateException e) {
+            throw new IllegalStateException(
+                    "Please use addUserRestriction or addUserRestrictionGlobally using the key"
+                            + " UserManager.DISALLOW_CAMERA to disable the camera locally or"
+                            + " globally, respectively");
         }
 
         final int affectedUserId = parent ? getProfileParentId(userId) : userId;
@@ -9306,66 +9084,26 @@
         if (!mHasFeature) {
             return false;
         }
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-        }
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            Preconditions.checkCallAuthorization(
-                    hasFullCrossUsersPermission(caller, userHandle)
-                            || isCameraServerUid(caller)
-                            || hasPermission(MANAGE_DEVICE_POLICY_CAMERA,
-                                caller.getPackageName(), userHandle)
-                            || hasPermission(QUERY_ADMIN_POLICY, caller.getPackageName()));
-        } else {
-            Preconditions.checkCallAuthorization(
-                    hasFullCrossUsersPermission(caller, userHandle) || isCameraServerUid(caller));
-            if (parent) {
-                Preconditions.checkCallAuthorization(
-                        isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()));
-            }
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
+        Preconditions.checkCallAuthorization(
+                hasFullCrossUsersPermission(caller, userHandle)
+                        || isCameraServerUid(caller)
+                        || hasPermission(MANAGE_DEVICE_POLICY_CAMERA,
+                            caller.getPackageName(), userHandle)
+                        || hasPermission(QUERY_ADMIN_POLICY, caller.getPackageName()));
 
         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
-
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            PolicyDefinition<Boolean> policy =
-                    PolicyDefinition.getPolicyDefinitionForUserRestriction(
-                            UserManager.DISALLOW_CAMERA);
-            if (who != null) {
-                EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackageName);
-                return Boolean.TRUE.equals(
-                        mDevicePolicyEngine.getLocalPolicySetByAdmin(
-                                policy, admin, affectedUserId));
-            } else {
-                return Boolean.TRUE.equals(
-                        mDevicePolicyEngine.getResolvedPolicy(policy, affectedUserId));
-            }
+        PolicyDefinition<Boolean> policy =
+                PolicyDefinition.getPolicyDefinitionForUserRestriction(
+                        UserManager.DISALLOW_CAMERA);
+        if (who != null) {
+            EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackageName);
+            return Boolean.TRUE.equals(
+                    mDevicePolicyEngine.getLocalPolicySetByAdmin(
+                            policy, admin, affectedUserId));
         } else {
-            synchronized (getLockObject()) {
-                if (who != null) {
-                    ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
-                    return (admin != null) && admin.disableCamera;
-                }
-                // First, see if DO has set it.  If so, it's device-wide.
-                final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
-                if (deviceOwner != null && deviceOwner.disableCamera) {
-                    return true;
-                }
-
-                // Return the strictest policy across all participating admins.
-                List<ActiveAdmin> admins = getActiveAdminsForAffectedUserLocked(affectedUserId);
-
-                // Determine whether or not the device camera is disabled for any active admins.
-                for (ActiveAdmin activeAdmin : admins) {
-                    if (activeAdmin.disableCamera) {
-                        return true;
-                    }
-                }
-                return false;
-            }
+            return Boolean.TRUE.equals(
+                    mDevicePolicyEngine.getResolvedPolicy(policy, affectedUserId));
         }
     }
 
@@ -10117,9 +9855,6 @@
         clearUserPoliciesLocked(userId);
         clearOverrideApnUnchecked();
         clearApplicationRestrictions(userId);
-        if (!isPolicyEngineForFinanceFlagEnabled()) {
-            mInjector.getPackageManagerInternal().clearBlockUninstallForUser(userId);
-        }
 
         mOwners.clearDeviceOwner();
         mOwners.writeDeviceOwner();
@@ -10131,16 +9866,11 @@
         setNetworkLoggingActiveInternal(false);
         deleteTransferOwnershipBundleLocked(userId);
         toggleBackupServiceActive(UserHandle.USER_SYSTEM, true);
-        if (!isPolicyEngineForFinanceFlagEnabled()) {
-            pushUserControlDisabledPackagesLocked(userId);
-        }
         setGlobalSettingDeviceOwnerType(DEVICE_OWNER_TYPE_DEFAULT);
 
-        if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
-            mDevicePolicyEngine.removePoliciesForAdmin(
-                    EnforcingAdmin.createEnterpriseEnforcingAdmin(
-                            admin.info.getComponent(), userId, admin));
-        }
+        mDevicePolicyEngine.removePoliciesForAdmin(
+                EnforcingAdmin.createEnterpriseEnforcingAdmin(
+                        admin.info.getComponent(), userId, admin));
     }
 
     private void clearApplicationRestrictions(int userId) {
@@ -10289,11 +10019,9 @@
         applyProfileRestrictionsIfDeviceOwnerLocked();
         setNetworkLoggingActiveInternal(false);
 
-        if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
-            mDevicePolicyEngine.removePoliciesForAdmin(
-                    EnforcingAdmin.createEnterpriseEnforcingAdmin(
-                            admin.info.getComponent(), userId, admin));
-        }
+        mDevicePolicyEngine.removePoliciesForAdmin(
+                EnforcingAdmin.createEnterpriseEnforcingAdmin(
+                        admin.info.getComponent(), userId, admin));
     }
 
     @Override
@@ -10337,9 +10065,6 @@
         policy.mAffiliationIds.clear();
         resetAffiliationCacheLocked();
         policy.mLockTaskPackages.clear();
-        if (!isPolicyEngineForFinanceFlagEnabled()) {
-            updateLockTaskPackagesLocked(mContext, policy.mLockTaskPackages, userId);
-        }
         policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
         saveSettingsLocked(userId);
 
@@ -10347,7 +10072,6 @@
             mIPermissionManager.updatePermissionFlagsForAllApps(
                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
                     0  /* flagValues */, userId);
-            pushUserRestrictions(userId);
         } catch (RemoteException re) {
             // Shouldn't happen.
             Slogf.wtf(LOG_TAG, "Failing in updatePermissionFlagsForAllApps", re);
@@ -11280,25 +11004,18 @@
         }
     }
 
-    private void dumpPerUserData(IndentingPrintWriter pw) {
+    private void dumpPersonalAppInfoForSystemUserNoLock(IndentingPrintWriter pw) {
+        wtfIfInLock();
+        PersonalAppsSuspensionHelper.forUser(mContext, UserHandle.USER_SYSTEM).dump(pw);
+    }
+
+    private void dumpPerUserPolicyData(IndentingPrintWriter pw) {
         int userCount = mUserData.size();
         for (int i = 0; i < userCount; i++) {
             int userId = mUserData.keyAt(i);
             DevicePolicyData policy = getUserData(userId);
             policy.dump(pw);
             pw.println();
-
-            if (userId == UserHandle.USER_SYSTEM) {
-                pw.increaseIndent();
-                PersonalAppsSuspensionHelper.forUser(mContext, userId).dump(pw);
-                pw.decreaseIndent();
-                pw.println();
-            } else {
-                // pm.getUnsuspendablePackages() will fail if it's called for a different user;
-                // as this dump is mostly useful for system user anyways, we can just ignore the
-                // others (rather than changing the permission check in the PM method)
-                Slogf.d(LOG_TAG, "skipping PersonalAppsSuspensionHelper.dump() for user " + userId);
-            }
         }
     }
 
@@ -11316,7 +11033,7 @@
                 pw.println();
                 mDeviceAdminServiceController.dump(pw);
                 pw.println();
-                dumpPerUserData(pw);
+                dumpPerUserPolicyData(pw);
                 pw.println();
                 mConstants.dump(pw);
                 pw.println();
@@ -11343,6 +11060,7 @@
                 mStateCache.dump(pw);
                 pw.println();
             }
+            dumpPersonalAppInfoForSystemUserNoLock(pw);
 
             synchronized (mSubscriptionsChangedListenerLock) {
                 pw.println("Subscription changed listener : " + mSubscriptionsChangedListener);
@@ -11434,53 +11152,30 @@
     @Override
     public void addPersistentPreferredActivity(ComponentName who, String callerPackageName,
             IntentFilter filter, ComponentName activity) {
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
 
         final int userId = caller.getUserId();
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            EnforcingAdmin enforcingAdmin;
-            if (who == null) {
-                enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
-                        who,
-                        MANAGE_DEVICE_POLICY_LOCK_TASK,
-                        caller.getPackageName(),
-                        userId);
-            } else {
-                Preconditions.checkCallAuthorization(isProfileOwner(caller)
-                        || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
-                enforcingAdmin = getEnforcingAdminForCaller(who, callerPackageName);
-            }
-            if (!isPackageInstalledForUser(activity.getPackageName(), userId)) {
-                // Fail early as packageManager doesn't persist the activity if its not installed.
-                return;
-            }
-            mDevicePolicyEngine.setLocalPolicy(
-                    PolicyDefinition.PERSISTENT_PREFERRED_ACTIVITY(filter),
-                    enforcingAdmin,
-                    new ComponentNamePolicyValue(activity),
+        EnforcingAdmin enforcingAdmin;
+        if (who == null) {
+            enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
+                    who,
+                    MANAGE_DEVICE_POLICY_LOCK_TASK,
+                    caller.getPackageName(),
                     userId);
         } else {
-            Objects.requireNonNull(who, "ComponentName is null");
             Preconditions.checkCallAuthorization(isProfileOwner(caller)
                     || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
-            synchronized (getLockObject()) {
-                long id = mInjector.binderClearCallingIdentity();
-                try {
-                    mIPackageManager.addPersistentPreferredActivity(filter, activity, userId);
-                    mIPackageManager.flushPackageRestrictionsAsUser(userId);
-                } catch (RemoteException re) {
-                    // Shouldn't happen
-                    Slog.wtf(LOG_TAG, "Error adding persistent preferred activity", re);
-                } finally {
-                    mInjector.binderRestoreCallingIdentity(id);
-                }
-            }
+            enforcingAdmin = getEnforcingAdminForCaller(who, callerPackageName);
         }
+        if (!isPackageInstalledForUser(activity.getPackageName(), userId)) {
+            // Fail early as packageManager doesn't persist the activity if its not installed.
+            return;
+        }
+        mDevicePolicyEngine.setLocalPolicy(
+                PolicyDefinition.PERSISTENT_PREFERRED_ACTIVITY(filter),
+                enforcingAdmin,
+                new ComponentNamePolicyValue(activity),
+                userId);
         final String activityPackage =
                 (activity != null ? activity.getPackageName() : null);
         DevicePolicyEventLogger
@@ -11493,51 +11188,25 @@
     @Override
     public void clearPackagePersistentPreferredActivities(ComponentName who,
             String callerPackageName, String packageName) {
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
         final int userId = caller.getUserId();
 
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            EnforcingAdmin enforcingAdmin;
-            if (who == null) {
-                enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
-                        who,
-                        MANAGE_DEVICE_POLICY_LOCK_TASK,
-                        caller.getPackageName(),
-                        userId);
-            } else {
-                Preconditions.checkCallAuthorization(isProfileOwner(caller)
-                        || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
-                enforcingAdmin = getEnforcingAdminForCaller(who, callerPackageName);
-            }
-            clearPackagePersistentPreferredActivitiesFromPolicyEngine(
-                    enforcingAdmin,
-                    packageName,
+        EnforcingAdmin enforcingAdmin;
+        if (who == null) {
+            enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
+                    who,
+                    MANAGE_DEVICE_POLICY_LOCK_TASK,
+                    caller.getPackageName(),
                     userId);
         } else {
-            Objects.requireNonNull(who, "ComponentName is null");
             Preconditions.checkCallAuthorization(isProfileOwner(caller)
                     || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
-            synchronized (getLockObject()) {
-                long id = mInjector.binderClearCallingIdentity();
-                try {
-                    mIPackageManager.clearPackagePersistentPreferredActivities(packageName,
-                            userId);
-                    mIPackageManager.flushPackageRestrictionsAsUser(userId);
-                } catch (RemoteException re) {
-                    // Shouldn't happen
-                    Slogf.wtf(
-                            LOG_TAG, "Error when clearing package persistent preferred activities",
-                            re);
-                } finally {
-                    mInjector.binderRestoreCallingIdentity(id);
-                }
-            }
+            enforcingAdmin = getEnforcingAdminForCaller(who, callerPackageName);
         }
+        clearPackagePersistentPreferredActivitiesFromPolicyEngine(
+                enforcingAdmin,
+                packageName,
+                userId);
     }
 
     /**
@@ -12274,28 +11943,15 @@
             return false;
         }
 
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-            Objects.requireNonNull(who, "ComponentName is null");
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
 
         int userId = getProfileParentUserIfRequested(
                 caller.getUserId(), calledOnParentInstance);
         if (calledOnParentInstance) {
-            if (!isPolicyEngineForFinanceFlagEnabled()) {
-                Preconditions.checkCallAuthorization(
-                        isProfileOwnerOfOrganizationOwnedDevice(caller));
-            }
             Preconditions.checkArgument(packageList == null || packageList.isEmpty(),
                     "Permitted input methods must allow all input methods or only "
                             + "system input methods when called on the parent instance of an "
                             + "organization-owned device");
-        } else if (!isPolicyEngineForFinanceFlagEnabled()) {
-            Preconditions.checkCallAuthorization(
-                    isDefaultDeviceOwner(caller) || isProfileOwner(caller));
         }
 
         if (packageList != null) {
@@ -12320,28 +11976,20 @@
         }
 
         synchronized (getLockObject()) {
-            if (isPolicyEngineForFinanceFlagEnabled()) {
-                EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
-                        who, MANAGE_DEVICE_POLICY_INPUT_METHODS,
-                        caller.getPackageName(), userId);
-                if (packageList == null) {
-                    mDevicePolicyEngine.removeLocalPolicy(
-                            PolicyDefinition.PERMITTED_INPUT_METHODS,
-                            admin,
-                            userId);
-                } else {
-                    mDevicePolicyEngine.setLocalPolicy(
-                            PolicyDefinition.PERMITTED_INPUT_METHODS,
-                            admin,
-                            new StringSetPolicyValue(new HashSet<>(packageList)),
-                            userId);
-                }
+            EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
+                    who, MANAGE_DEVICE_POLICY_INPUT_METHODS,
+                    caller.getPackageName(), userId);
+            if (packageList == null) {
+                mDevicePolicyEngine.removeLocalPolicy(
+                        PolicyDefinition.PERMITTED_INPUT_METHODS,
+                        admin,
+                        userId);
             } else {
-                ActiveAdmin admin = getParentOfAdminIfRequired(
-                        getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()),
-                        calledOnParentInstance);
-                admin.permittedInputMethods = packageList;
-                saveSettingsLocked(caller.getUserId());
+                mDevicePolicyEngine.setLocalPolicy(
+                        PolicyDefinition.PERMITTED_INPUT_METHODS,
+                        admin,
+                        new StringSetPolicyValue(new HashSet<>(packageList)),
+                        userId);
             }
         }
 
@@ -12371,37 +12019,14 @@
             return null;
         }
 
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-            Objects.requireNonNull(who, "ComponentName is null");
-        }
-
-        if (!isPolicyEngineForFinanceFlagEnabled()) {
-            if (calledOnParentInstance) {
-                Preconditions.checkCallAuthorization(
-                        isProfileOwnerOfOrganizationOwnedDevice(caller));
-            } else {
-                Preconditions.checkCallAuthorization(
-                        isDefaultDeviceOwner(caller) || isProfileOwner(caller));
-            }
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
 
         synchronized (getLockObject()) {
-            if (isPolicyEngineForFinanceFlagEnabled()) {
-                int affectedUser = calledOnParentInstance ? getProfileParentId(
-                        caller.getUserId()) : caller.getUserId();
-                Set<String> policy = mDevicePolicyEngine.getResolvedPolicy(
-                        PolicyDefinition.PERMITTED_INPUT_METHODS, affectedUser);
-                return policy == null ? null : new ArrayList<>(policy);
-            } else {
-                ActiveAdmin admin = getParentOfAdminIfRequired(
-                        getProfileOwnerOrDeviceOwnerLocked(
-                                caller.getUserId()), calledOnParentInstance);
-                return admin.permittedInputMethods;
-            }
+            int affectedUser = calledOnParentInstance ? getProfileParentId(
+                    caller.getUserId()) : caller.getUserId();
+            Set<String> policy = mDevicePolicyEngine.getResolvedPolicy(
+                    PolicyDefinition.PERMITTED_INPUT_METHODS, affectedUser);
+            return policy == null ? null : new ArrayList<>(policy);
         }
     }
 
@@ -12419,29 +12044,9 @@
     }
 
     private @Nullable List<String> getPermittedInputMethodsUnchecked(@UserIdInt int userId) {
-        List<String> result = null;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            Set<String> policy = mDevicePolicyEngine.getResolvedPolicy(
-                    PolicyDefinition.PERMITTED_INPUT_METHODS, userId);
-            result = policy == null ? null : new ArrayList<>(policy);
-        } else {
-            synchronized (getLockObject()) {
-                // Only device or profile owners can have permitted lists set.
-                List<ActiveAdmin> admins =
-                        getActiveAdminsForAffectedUserInclPermissionBasedAdminLocked(
-                                userId);
-                for (ActiveAdmin admin : admins) {
-                    List<String> fromAdmin = admin.permittedInputMethods;
-                    if (fromAdmin != null) {
-                        if (result == null) {
-                            result = new ArrayList<String>(fromAdmin);
-                        } else {
-                            result.retainAll(fromAdmin);
-                        }
-                    }
-                }
-            }
-        }
+        Set<String> policy = mDevicePolicyEngine.getResolvedPolicy(
+                PolicyDefinition.PERMITTED_INPUT_METHODS, userId);
+        List<String> result = policy == null ? null : new ArrayList<>(policy);
 
         // If we have a permitted list add all system input methods.
         if (result != null) {
@@ -12472,39 +12077,23 @@
                 String.format(NOT_SYSTEM_CALLER_MSG,
                         "query if an input method is disabled by admin"));
 
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            int affectedUser = calledOnParentInstance ? getProfileParentId(userHandle) : userHandle;
-            Map<EnforcingAdmin, PolicyValue<Set<String>>> policies =
-                    mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
-                            PolicyDefinition.PERMITTED_INPUT_METHODS, affectedUser);
-            EnforcingAdmin admin = null;
-            for (EnforcingAdmin a : policies.keySet()) {
-                if (a.getPackageName().equals(who.getPackageName())) {
-                    if (policies.get(a).getValue() == null) {
-                        return true;
-                    } else {
-                        return checkPackagesInPermittedListOrSystem(
-                                Collections.singletonList(packageName),
-                                new ArrayList<>(policies.get(a).getValue()), affectedUser);
-                    }
-                }
-            }
-            // Admin didn't set a policy
-            return false;
-        } else {
-            synchronized (getLockObject()) {
-                ActiveAdmin admin = getParentOfAdminIfRequired(
-                        getActiveAdminUncheckedLocked(who, userHandle), calledOnParentInstance);
-                if (admin == null) {
-                    return false;
-                }
-                if (admin.permittedInputMethods == null) {
+        int affectedUser = calledOnParentInstance ? getProfileParentId(userHandle) : userHandle;
+        Map<EnforcingAdmin, PolicyValue<Set<String>>> policies =
+                mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
+                        PolicyDefinition.PERMITTED_INPUT_METHODS, affectedUser);
+        for (EnforcingAdmin a : policies.keySet()) {
+            if (a.getPackageName().equals(who.getPackageName())) {
+                if (policies.get(a).getValue() == null) {
                     return true;
+                } else {
+                    return checkPackagesInPermittedListOrSystem(
+                            Collections.singletonList(packageName),
+                            new ArrayList<>(policies.get(a).getValue()), affectedUser);
                 }
-                return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
-                        admin.permittedInputMethods, userHandle);
             }
         }
+        // Admin didn't set a policy
+        return false;
     }
 
     @Override
@@ -12775,12 +12364,9 @@
                     + ", token=" + token);
         }
 
+        mDevicePolicyEngine.handleUserCreated(user);
+
         final int userId = user.id;
-
-        if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
-            mDevicePolicyEngine.handleUserCreated(user);
-        }
-
         if (token != null) {
             synchronized (getLockObject()) {
                 if (mPendingUserCreatedCallbackTokens.contains(token)) {
@@ -13374,79 +12960,54 @@
             ComponentName who, String callerPackage, String key, boolean enabledFromThisOwner,
             boolean parent) {
 
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackage);
-        } else {
-            caller = getCallerIdentity(who);
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackage);
         int userId = caller.getUserId();
         int affectedUserId = parent ? getProfileParentId(userId) : userId;
 
         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION);
 
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            if (!isDeviceOwner(caller) && !isProfileOwner(caller)) {
-                EnforcingAdmin admin = enforcePermissionForUserRestriction(
-                        who,
-                        key,
-                        caller.getPackageName(),
-                        affectedUserId);
-                if (!mInjector.isChangeEnabled(ENABLE_COEXISTENCE_CHANGE, callerPackage, userId)) {
-                    throw new IllegalStateException("Calling package is not targeting Android U.");
-                }
-                if (!UserRestrictionsUtils.isValidRestriction(key)) {
-                    throw new IllegalArgumentException("Invalid restriction key: " + key);
-                }
-                PolicyDefinition<Boolean> policyDefinition =
-                        PolicyDefinition.getPolicyDefinitionForUserRestriction(key);
-                if (enabledFromThisOwner) {
-                    setLocalUserRestrictionInternal(
-                            admin, key, /* enabled= */ true, affectedUserId);
-                } else {
-                    // Remove any local and global policy that was set by the admin
-                    if (!policyDefinition.isLocalOnlyPolicy()) {
-                        setGlobalUserRestrictionInternal(admin, key, /* enabled= */ false);
-                    }
-                    if (!policyDefinition.isGlobalOnlyPolicy()) {
-                        setLocalUserRestrictionInternal(admin, key, /* enabled= */ false,
-                                userId);
-
-                        int parentUserId = getProfileParentId(userId);
-                        if (parentUserId != userId) {
-                            setLocalUserRestrictionInternal(
-                                    admin, key, /* enabled= */ false, parentUserId);
-                        }
-                    }
-                }
+        if (!isDeviceOwner(caller) && !isProfileOwner(caller)) {
+            EnforcingAdmin admin = enforcePermissionForUserRestriction(
+                    who,
+                    key,
+                    caller.getPackageName(),
+                    affectedUserId);
+            if (!mInjector.isChangeEnabled(ENABLE_COEXISTENCE_CHANGE, callerPackage, userId)) {
+                throw new IllegalStateException("Calling package is not targeting Android U.");
+            }
+            if (!UserRestrictionsUtils.isValidRestriction(key)) {
+                throw new IllegalArgumentException("Invalid restriction key: " + key);
+            }
+            PolicyDefinition<Boolean> policyDefinition =
+                    PolicyDefinition.getPolicyDefinitionForUserRestriction(key);
+            if (enabledFromThisOwner) {
+                setLocalUserRestrictionInternal(
+                        admin, key, /* enabled= */ true, affectedUserId);
             } else {
-                if (!UserRestrictionsUtils.isValidRestriction(key)) {
-                    return;
+                // Remove any local and global policy that was set by the admin
+                if (!policyDefinition.isLocalOnlyPolicy()) {
+                    setGlobalUserRestrictionInternal(admin, key, /* enabled= */ false);
                 }
-                Objects.requireNonNull(who, "ComponentName is null");
-                EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
-                checkAdminCanSetRestriction(caller, parent, key);
-                setBackwardCompatibleUserRestriction(
-                        caller, admin, key, enabledFromThisOwner, parent);
+                if (!policyDefinition.isGlobalOnlyPolicy()) {
+                    setLocalUserRestrictionInternal(admin, key, /* enabled= */ false,
+                            userId);
+
+                    int parentUserId = getProfileParentId(userId);
+                    if (parentUserId != userId) {
+                        setLocalUserRestrictionInternal(
+                                admin, key, /* enabled= */ false, parentUserId);
+                    }
+                }
             }
         } else {
             if (!UserRestrictionsUtils.isValidRestriction(key)) {
                 return;
             }
             Objects.requireNonNull(who, "ComponentName is null");
+            EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
             checkAdminCanSetRestriction(caller, parent, key);
-            synchronized (getLockObject()) {
-                final ActiveAdmin activeAdmin = getParentOfAdminIfRequired(
-                        getProfileOwnerOrDeviceOwnerLocked(userId), parent);
-                // Save the restriction to ActiveAdmin.
-                final Bundle restrictions = activeAdmin.ensureUserRestrictions();
-                if (enabledFromThisOwner) {
-                    restrictions.putBoolean(key, true);
-                } else {
-                    restrictions.remove(key);
-                }
-                saveUserRestrictionsLocked(userId);
-            }
+            setBackwardCompatibleUserRestriction(
+                    caller, admin, key, enabledFromThisOwner, parent);
         }
         logUserRestrictionCall(key, enabledFromThisOwner, parent, caller);
     }
@@ -13532,9 +13093,6 @@
 
         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION);
 
-        if (!isPolicyEngineForFinanceFlagEnabled()) {
-            throw new IllegalStateException("Feature flag is not enabled.");
-        }
         if (isDeviceOwner(caller) || isProfileOwner(caller)) {
             throw new SecurityException("Admins are not allowed to call this API.");
         }
@@ -13604,121 +13162,33 @@
                 key, enabled, caller.toString());
     }
 
-    private void saveUserRestrictionsLocked(int userId) {
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            // User restrictions are handled in the policy engine
-            return;
-        }
-        saveSettingsLocked(userId);
-        pushUserRestrictions(userId);
-        sendChangedNotification(userId);
-    }
-
-    /**
-     * Pushes the user restrictions originating from a specific user.
-     *
-     * If called by the profile owner of an organization-owned device, the global and local
-     * user restrictions will be an accumulation of the global user restrictions from the profile
-     * owner active admin and its parent active admin. The key of the local user restrictions set
-     * will be the target user id.
-     */
-    private void pushUserRestrictions(int originatingUserId) {
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            // User restrictions are handled in the policy engine
-            return;
-        }
-        final Bundle global;
-        final RestrictionsSet local = new RestrictionsSet();
-        final boolean isDeviceOwner;
-        synchronized (getLockObject()) {
-            isDeviceOwner = mOwners.isDeviceOwnerUserId(originatingUserId);
-            if (isDeviceOwner) {
-                final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
-                if (deviceOwner == null) {
-                    return; // Shouldn't happen.
-                }
-                global = deviceOwner.getGlobalUserRestrictions(OWNER_TYPE_DEVICE_OWNER);
-                local.updateRestrictions(originatingUserId, deviceOwner.getLocalUserRestrictions(
-                        OWNER_TYPE_DEVICE_OWNER));
-            } else {
-                final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(originatingUserId);
-                if (profileOwner == null) {
-                    return;
-                }
-                global = profileOwner.getGlobalUserRestrictions(OWNER_TYPE_PROFILE_OWNER);
-                local.updateRestrictions(originatingUserId, profileOwner.getLocalUserRestrictions(
-                        OWNER_TYPE_PROFILE_OWNER));
-                // Global (device-wide) and local user restrictions set by the profile owner of an
-                // organization-owned device are stored in the parent ActiveAdmin instance.
-                if (isProfileOwnerOfOrganizationOwnedDevice(
-                        profileOwner.getUserHandle().getIdentifier())) {
-                    // The global restrictions set on the parent ActiveAdmin instance need to be
-                    // merged with the global restrictions set on the profile owner ActiveAdmin
-                    // instance, since both are to be applied device-wide.
-                    UserRestrictionsUtils.merge(global,
-                            profileOwner.getParentActiveAdmin().getGlobalUserRestrictions(
-                                    OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
-                    // The local restrictions set on the parent ActiveAdmin instance are only to be
-                    // applied to the primary user. They therefore need to be added the local
-                    // restriction set with the primary user id as the key, in this case the
-                    // primary user id is the target user.
-                    local.updateRestrictions(
-                            getProfileParentId(profileOwner.getUserHandle().getIdentifier()),
-                            profileOwner.getParentActiveAdmin().getLocalUserRestrictions(
-                                    OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
-                }
-            }
-        }
-        mUserManagerInternal.setDevicePolicyUserRestrictions(originatingUserId, global, local,
-                isDeviceOwner);
-    }
-
     @Override
     public Bundle getUserRestrictions(ComponentName who, String callerPackage, boolean parent) {
         if (!mHasFeature) {
             return null;
         }
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackage);
-        } else {
-            caller = getCallerIdentity(who);
-        }
-
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            int targetUserId = parent
-                    ? getProfileParentId(caller.getUserId()) : caller.getUserId();
-            EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
-            if (isDeviceOwner(caller) || isProfileOwner(caller)) {
-                Objects.requireNonNull(who, "ComponentName is null");
-                Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
-                        || isFinancedDeviceOwner(caller)
-                        || isProfileOwner(caller)
-                        || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller)));
-
-                Bundle restrictions = getUserRestrictionsFromPolicyEngine(admin, targetUserId);
-                // Add global restrictions set by the admin as well.
-                restrictions.putAll(
-                        getUserRestrictionsFromPolicyEngine(admin, UserHandle.USER_ALL));
-                return restrictions;
-            } else {
-                if (!mInjector.isChangeEnabled(
-                        ENABLE_COEXISTENCE_CHANGE, callerPackage, caller.getUserId())) {
-                    throw new IllegalStateException("Calling package is not targeting Android U.");
-                }
-                return getUserRestrictionsFromPolicyEngine(admin, targetUserId);
-            }
-        } else {
+        CallerIdentity caller = getCallerIdentity(who, callerPackage);
+        int targetUserId = parent
+                ? getProfileParentId(caller.getUserId()) : caller.getUserId();
+        EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
+        if (isDeviceOwner(caller) || isProfileOwner(caller)) {
             Objects.requireNonNull(who, "ComponentName is null");
             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
                     || isFinancedDeviceOwner(caller)
                     || isProfileOwner(caller)
                     || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller)));
-            synchronized (getLockObject()) {
-                final ActiveAdmin activeAdmin = getParentOfAdminIfRequired(
-                        getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), parent);
-                return activeAdmin.userRestrictions;
+
+            Bundle restrictions = getUserRestrictionsFromPolicyEngine(admin, targetUserId);
+            // Add global restrictions set by the admin as well.
+            restrictions.putAll(
+                    getUserRestrictionsFromPolicyEngine(admin, UserHandle.USER_ALL));
+            return restrictions;
+        } else {
+            if (!mInjector.isChangeEnabled(
+                    ENABLE_COEXISTENCE_CHANGE, callerPackage, caller.getUserId())) {
+                throw new IllegalStateException("Calling package is not targeting Android U.");
             }
+            return getUserRestrictionsFromPolicyEngine(admin, targetUserId);
         }
     }
 
@@ -13889,10 +13359,6 @@
             return null;
         }
         final CallerIdentity caller = getCallerIdentity(callerPackage);
-        if (!isPolicyEngineForFinanceFlagEnabled()) {
-            throw new IllegalStateException("Feature flag is not enabled.");
-        }
-
         EnforcingAdmin admin = getEnforcingAdminForCaller(/*who=*/ null, caller.getPackageName());
 
         return getUserRestrictionsFromPolicyEngine(admin,
@@ -13922,13 +13388,7 @@
             boolean hidden, boolean parent) {
         CallerIdentity caller = getCallerIdentity(who, callerPackage);
         final int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);
-        } else {
-            Preconditions.checkCallAuthorization((caller.hasAdminComponent()
-                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
-                    || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS)));
-        }
+        enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);
 
         List<String> exemptApps = listPolicyExemptAppsUnchecked(mContext);
         if (exemptApps.contains(packageName)) {
@@ -13940,11 +13400,6 @@
         boolean result;
         synchronized (getLockObject()) {
             if (parent) {
-                if (!isPolicyEngineForFinanceFlagEnabled()) {
-                    Preconditions.checkCallAuthorization(
-                            isProfileOwnerOfOrganizationOwnedDevice(
-                                    caller.getUserId()) && isManagedProfile(caller.getUserId()));
-                }
                 // Ensure the package provided is a system package, this is to ensure that this
                 // API cannot be used to leak if certain non-system package exists in the person
                 // profile.
@@ -13957,29 +13412,24 @@
                 Slogf.v(LOG_TAG, "calling pm.setApplicationHiddenSettingAsUser(%s, %b, %d)",
                         packageName, hidden, userId);
             }
-            if (isPolicyEngineForFinanceFlagEnabled()) {
-                EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
-                mDevicePolicyEngine.setLocalPolicy(
-                        PolicyDefinition.APPLICATION_HIDDEN(packageName),
-                        admin,
-                        new BooleanPolicyValue(hidden),
-                        userId);
-                result = mInjector.binderWithCleanCallingIdentity(() -> {
-                    try {
-                        // This is a best effort to continue returning the same value that was
-                        // returned before the policy engine migration.
-                        return mInjector.getIPackageManager().getPackageInfo(
-                                packageName, MATCH_UNINSTALLED_PACKAGES, userId) != null
-                                && (mIPackageManager.getApplicationHiddenSettingAsUser(
-                                        packageName, userId) == hidden);
-                    } catch (RemoteException e) {
-                        return false;
-                    }
-                });
-            } else {
-                result = mInjector.binderWithCleanCallingIdentity(() -> mIPackageManager
-                        .setApplicationHiddenSettingAsUser(packageName, hidden, userId));
-            }
+            EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
+            mDevicePolicyEngine.setLocalPolicy(
+                    PolicyDefinition.APPLICATION_HIDDEN(packageName),
+                    admin,
+                    new BooleanPolicyValue(hidden),
+                    userId);
+            result = mInjector.binderWithCleanCallingIdentity(() -> {
+                try {
+                    // This is a best effort to continue returning the same value that was
+                    // returned before the policy engine migration.
+                    return mInjector.getIPackageManager().getPackageInfo(
+                            packageName, MATCH_UNINSTALLED_PACKAGES, userId) != null
+                            && (mIPackageManager.getApplicationHiddenSettingAsUser(
+                                    packageName, userId) == hidden);
+                } catch (RemoteException e) {
+                    return false;
+                }
+            });
         }
         DevicePolicyEventLogger
                 .createEvent(DevicePolicyEnums.SET_APPLICATION_HIDDEN)
@@ -13996,23 +13446,11 @@
             String packageName, boolean parent) {
         CallerIdentity caller = getCallerIdentity(who, callerPackage);
         int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            // TODO: Also support DELEGATION_PACKAGE_ACCESS
-            enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);
-        } else {
-            Preconditions.checkCallAuthorization((caller.hasAdminComponent()
-                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
-                    || (caller.hasPackage() && isCallerDelegate(
-                            caller, DELEGATION_PACKAGE_ACCESS)));
-        }
+        // TODO: Also support DELEGATION_PACKAGE_ACCESS
+        enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);
 
         synchronized (getLockObject()) {
             if (parent) {
-                if (!isPolicyEngineForFinanceFlagEnabled()) {
-                    Preconditions.checkCallAuthorization(
-                            isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId())
-                                    && isManagedProfile(caller.getUserId()));
-                }
                 // Ensure the package provided is a system package.
                 mInjector.binderWithCleanCallingIdentity(() ->
                         enforcePackageIsSystemPackage(packageName, userId));
@@ -14199,57 +13637,26 @@
 
         enforceMaxStringLength(accountType, "account type");
 
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
         synchronized (getLockObject()) {
-            if (isPolicyEngineForFinanceFlagEnabled()) {
-                int affectedUser = getAffectedUser(parent);
-                EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
-                        who,
-                        MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
-                        caller.getPackageName(),
-                        affectedUser
-                );
-                if (disabled) {
-                    mDevicePolicyEngine.setLocalPolicy(
-                            PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
-                            enforcingAdmin,
-                            new BooleanPolicyValue(disabled),
-                            affectedUser);
-                } else {
-                    mDevicePolicyEngine.removeLocalPolicy(
-                            PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
-                            enforcingAdmin,
-                            affectedUser);
-                }
+            int affectedUser = getAffectedUser(parent);
+            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
+                    who,
+                    MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
+                    caller.getPackageName(),
+                    affectedUser
+            );
+            if (disabled) {
+                mDevicePolicyEngine.setLocalPolicy(
+                        PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
+                        enforcingAdmin,
+                        new BooleanPolicyValue(disabled),
+                        affectedUser);
             } else {
-                final ActiveAdmin ap;
-                Objects.requireNonNull(who, "ComponentName is null");
-                /*
-                 * When called on the parent DPM instance (parent == true), affects active admin
-                 * selection in two ways:
-                 * * The ActiveAdmin must be of an org-owned profile owner.
-                 * * The parent ActiveAdmin instance should be used for managing the restriction.
-                 */
-                if (parent) {
-                    ap = getParentOfAdminIfRequired(getOrganizationOwnedProfileOwnerLocked(caller),
-                            parent);
-                } else {
-                    Preconditions.checkCallAuthorization(
-                            isDefaultDeviceOwner(caller) || isProfileOwner(caller));
-                    ap = getParentOfAdminIfRequired(
-                            getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), parent);
-                }
-                if (disabled) {
-                    ap.accountTypesWithManagementDisabled.add(accountType);
-                } else {
-                    ap.accountTypesWithManagementDisabled.remove(accountType);
-                }
-                saveSettingsLocked(UserHandle.getCallingUserId());
+                mDevicePolicyEngine.removeLocalPolicy(
+                        PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
+                        enforcingAdmin,
+                        affectedUser);
             }
         }
     }
@@ -14266,62 +13673,35 @@
         if (!mHasFeature) {
             return null;
         }
-        CallerIdentity caller;
+        CallerIdentity caller = getCallerIdentity(callerPackageName);
         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
         final ArraySet<String> resultSet = new ArraySet<>();
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            int affectedUser = parent ? getProfileParentId(userId) : userId;
-            caller = getCallerIdentity(callerPackageName);
-            if (!hasPermission(MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
-                    callerPackageName, affectedUser)
-                    && !hasFullCrossUsersPermission(caller, userId)) {
-                throw new SecurityException("Caller does not have permission to call this on user: "
-                        + affectedUser);
+        int affectedUser = parent ? getProfileParentId(userId) : userId;
+        if (!hasPermission(MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
+                callerPackageName, affectedUser)
+                && !hasFullCrossUsersPermission(caller, userId)) {
+            throw new SecurityException("Caller does not have permission to call this on user: "
+                    + affectedUser);
+        }
+        Set<PolicyKey> keys = mDevicePolicyEngine.getLocalPolicyKeysSetByAllAdmins(
+                PolicyDefinition.GENERIC_ACCOUNT_MANAGEMENT_DISABLED,
+                affectedUser);
+
+        for (PolicyKey key : keys) {
+            if (!(key instanceof AccountTypePolicyKey)) {
+                throw new IllegalStateException("PolicyKey for "
+                        + "MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT is not of type "
+                        + "AccountTypePolicyKey");
             }
-            Set<PolicyKey> keys = mDevicePolicyEngine.getLocalPolicyKeysSetByAllAdmins(
-                    PolicyDefinition.GENERIC_ACCOUNT_MANAGEMENT_DISABLED,
+            AccountTypePolicyKey parsedKey =
+                    (AccountTypePolicyKey) key;
+            String accountType = Objects.requireNonNull(parsedKey.getAccountType());
+
+            Boolean disabled = mDevicePolicyEngine.getResolvedPolicy(
+                    PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
                     affectedUser);
-
-            for (PolicyKey key : keys) {
-                if (!(key instanceof AccountTypePolicyKey)) {
-                    throw new IllegalStateException("PolicyKey for "
-                            + "MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT is not of type "
-                            + "AccountTypePolicyKey");
-                }
-                AccountTypePolicyKey parsedKey =
-                        (AccountTypePolicyKey) key;
-                String accountType = Objects.requireNonNull(parsedKey.getAccountType());
-
-                Boolean disabled = mDevicePolicyEngine.getResolvedPolicy(
-                        PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
-                        affectedUser);
-                if (disabled != null && disabled) {
-                    resultSet.add(accountType);
-                }
-            }
-        } else {
-            caller = getCallerIdentity();
-            Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
-
-            synchronized (getLockObject()) {
-                if (!parent) {
-                    final DevicePolicyData policy = getUserData(userId);
-                    for (ActiveAdmin admin : policy.mAdminList) {
-                        resultSet.addAll(admin.accountTypesWithManagementDisabled);
-                    }
-                }
-
-                // Check if there's a profile owner of an org-owned device and the method is called
-                // for the parent user of this profile owner.
-                final ActiveAdmin orgOwnedAdmin =
-                        getProfileOwnerOfOrganizationOwnedDeviceLocked(userId);
-                final boolean shouldGetParentAccounts = orgOwnedAdmin != null && (parent
-                        || UserHandle.getUserId(orgOwnedAdmin.getUid()) != userId);
-                if (shouldGetParentAccounts) {
-                    resultSet.addAll(
-                            orgOwnedAdmin.getParentActiveAdmin()
-                                    .accountTypesWithManagementDisabled);
-                }
+            if (disabled != null && disabled) {
+                resultSet.add(accountType);
             }
         }
         return resultSet.toArray(new String[resultSet.size()]);
@@ -14332,46 +13712,19 @@
             boolean uninstallBlocked) {
         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
 
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
-                    who,
-                    new String[]{
-                            MANAGE_DEVICE_POLICY_APPS_CONTROL,
-                            MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL
-                    },
-                    caller.getPackageName(),
-                    caller.getUserId());
-            mDevicePolicyEngine.setLocalPolicy(
-                    PolicyDefinition.PACKAGE_UNINSTALL_BLOCKED(packageName),
-                    enforcingAdmin,
-                    new BooleanPolicyValue(uninstallBlocked),
-                    caller.getUserId());
-        } else {
-            Preconditions.checkCallAuthorization((caller.hasAdminComponent()
-                    && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)
-                    || isFinancedDeviceOwner(caller)))
-                    || (caller.hasPackage()
-                    && isCallerDelegate(caller, DELEGATION_BLOCK_UNINSTALL)));
-            final int userId = caller.getUserId();
-            synchronized (getLockObject()) {
-                long id = mInjector.binderClearCallingIdentity();
-                try {
-                    mIPackageManager.setBlockUninstallForUser(
-                            packageName, uninstallBlocked, userId);
-                } catch (RemoteException re) {
-                    // Shouldn't happen.
-                    Slogf.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
-                } finally {
-                    mInjector.binderRestoreCallingIdentity(id);
-                }
-            }
-            if (uninstallBlocked) {
-                final PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
-                pmi.removeNonSystemPackageSuspensions(packageName, userId);
-                pmi.removeDistractingPackageRestrictions(packageName, userId);
-                pmi.flushPackageRestrictions(userId);
-            }
-        }
+        EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
+                who,
+                new String[]{
+                        MANAGE_DEVICE_POLICY_APPS_CONTROL,
+                        MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL
+                },
+                caller.getPackageName(),
+                caller.getUserId());
+        mDevicePolicyEngine.setLocalPolicy(
+                PolicyDefinition.PACKAGE_UNINSTALL_BLOCKED(packageName),
+                enforcingAdmin,
+                new BooleanPolicyValue(uninstallBlocked),
+                caller.getUserId());
 
         DevicePolicyEventLogger
                 .createEvent(DevicePolicyEnums.SET_UNINSTALL_BLOCKED)
@@ -14898,49 +14251,35 @@
             enforceMaxPackageNameLength(pkg);
         }
 
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_PACKAGES);
 
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            EnforcingAdmin enforcingAdmin;
-            synchronized (getLockObject()) {
-                enforcingAdmin = enforceCanCallLockTaskLocked(who, caller.getPackageName());
-            }
-            LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
+        EnforcingAdmin enforcingAdmin;
+        synchronized (getLockObject()) {
+            enforcingAdmin = enforceCanCallLockTaskLocked(who, caller.getPackageName());
+        }
+        LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
+                PolicyDefinition.LOCK_TASK,
+                enforcingAdmin,
+                caller.getUserId());
+        LockTaskPolicy policy;
+        if (currentPolicy == null) {
+            policy = new LockTaskPolicy(Set.of(packages));
+        } else {
+            policy = new LockTaskPolicy(currentPolicy);
+            policy.setPackages(Set.of(packages));
+        }
+        if (policy.getPackages().isEmpty()) {
+            mDevicePolicyEngine.removeLocalPolicy(
                     PolicyDefinition.LOCK_TASK,
                     enforcingAdmin,
                     caller.getUserId());
-            LockTaskPolicy policy;
-            if (currentPolicy == null) {
-                policy = new LockTaskPolicy(Set.of(packages));
-            } else {
-                policy = new LockTaskPolicy(currentPolicy);
-                policy.setPackages(Set.of(packages));
-            }
-            if (policy.getPackages().isEmpty()) {
-                mDevicePolicyEngine.removeLocalPolicy(
-                        PolicyDefinition.LOCK_TASK,
-                        enforcingAdmin,
-                        caller.getUserId());
-            } else {
-                mDevicePolicyEngine.setLocalPolicy(
-                        PolicyDefinition.LOCK_TASK,
-                        enforcingAdmin,
-                        policy,
-                        caller.getUserId());
-            }
         } else {
-            Objects.requireNonNull(who, "ComponentName is null");
-            synchronized (getLockObject()) {
-                enforceCanCallLockTaskLocked(caller);
-                final int userHandle = caller.getUserId();
-                setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
-            }
+            mDevicePolicyEngine.setLocalPolicy(
+                    PolicyDefinition.LOCK_TASK,
+                    enforcingAdmin,
+                    policy,
+                    caller.getUserId());
         }
     }
 
@@ -14955,32 +14294,18 @@
 
     @Override
     public String[] getLockTaskPackages(ComponentName who, String callerPackageName) {
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
         final int userHandle = caller.getUserId();
 
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            synchronized (getLockObject()) {
-                enforceCanQueryLockTaskLocked(who, caller.getPackageName());
-            }
-            LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
-                    PolicyDefinition.LOCK_TASK, userHandle);
-            if (policy == null) {
-                return new String[0];
-            } else {
-                return policy.getPackages().toArray(new String[policy.getPackages().size()]);
-            }
+        synchronized (getLockObject()) {
+            enforceCanQueryLockTaskLocked(who, caller.getPackageName());
+        }
+        LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
+                PolicyDefinition.LOCK_TASK, userHandle);
+        if (policy == null) {
+            return new String[0];
         } else {
-            Objects.requireNonNull(who, "ComponentName is null");
-            synchronized (getLockObject()) {
-                enforceCanCallLockTaskLocked(caller);
-                final List<String> packages = getUserData(userHandle).mLockTaskPackages;
-                return packages.toArray(new String[packages.size()]);
-            }
+            return policy.getPackages().toArray(new String[policy.getPackages().size()]);
         }
     }
 
@@ -14996,18 +14321,12 @@
         }
 
         final int userId = mInjector.userHandleGetCallingUserId();
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
-                    PolicyDefinition.LOCK_TASK, userId);
-            if (policy == null) {
-                return false;
-            }
-            return policy.getPackages().contains(pkg);
-        } else {
-            synchronized (getLockObject()) {
-                return getUserData(userId).mLockTaskPackages.contains(pkg);
-            }
+        LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
+                PolicyDefinition.LOCK_TASK, userId);
+        if (policy == null) {
+            return false;
         }
+        return policy.getPackages().contains(pkg);
     }
 
     @Override
@@ -15021,54 +14340,40 @@
         Preconditions.checkArgument(hasHome || !hasNotification,
             "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME");
 
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
         final int userHandle = caller.getUserId();
         synchronized (getLockObject()) {
             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_FEATURES);
         }
 
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            EnforcingAdmin enforcingAdmin;
-            synchronized (getLockObject()) {
-                enforcingAdmin = enforceCanCallLockTaskLocked(who, caller.getPackageName());
-                enforceCanSetLockTaskFeaturesOnFinancedDevice(caller, flags);
-            }
-            LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
+        EnforcingAdmin enforcingAdmin;
+        synchronized (getLockObject()) {
+            enforcingAdmin = enforceCanCallLockTaskLocked(who, caller.getPackageName());
+            enforceCanSetLockTaskFeaturesOnFinancedDevice(caller, flags);
+        }
+        LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
+                PolicyDefinition.LOCK_TASK,
+                enforcingAdmin,
+                caller.getUserId());
+        LockTaskPolicy policy;
+        if (currentPolicy == null) {
+            policy = new LockTaskPolicy(flags);
+        } else {
+            policy = new LockTaskPolicy(currentPolicy);
+            policy.setFlags(flags);
+        }
+        if (policy.getPackages().isEmpty()
+                && policy.getFlags() == DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
+            mDevicePolicyEngine.removeLocalPolicy(
                     PolicyDefinition.LOCK_TASK,
                     enforcingAdmin,
                     caller.getUserId());
-            LockTaskPolicy policy;
-            if (currentPolicy == null) {
-                policy = new LockTaskPolicy(flags);
-            } else {
-                policy = new LockTaskPolicy(currentPolicy);
-                policy.setFlags(flags);
-            }
-            if (policy.getPackages().isEmpty()
-                    && policy.getFlags() == DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
-                mDevicePolicyEngine.removeLocalPolicy(
-                        PolicyDefinition.LOCK_TASK,
-                        enforcingAdmin,
-                        caller.getUserId());
-            } else {
-                mDevicePolicyEngine.setLocalPolicy(
-                        PolicyDefinition.LOCK_TASK,
-                        enforcingAdmin,
-                        policy,
-                        caller.getUserId());
-            }
         } else {
-            Objects.requireNonNull(who, "ComponentName is null");
-            synchronized (getLockObject()) {
-                enforceCanCallLockTaskLocked(caller);
-                enforceCanSetLockTaskFeaturesOnFinancedDevice(caller, flags);
-                setLockTaskFeaturesLocked(userHandle, flags);
-            }
+            mDevicePolicyEngine.setLocalPolicy(
+                    PolicyDefinition.LOCK_TASK,
+                    enforcingAdmin,
+                    policy,
+                    caller.getUserId());
         }
     }
 
@@ -15081,33 +14386,20 @@
 
     @Override
     public int getLockTaskFeatures(ComponentName who, String callerPackageName) {
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
         final int userHandle = caller.getUserId();
 
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            synchronized (getLockObject()) {
-                enforceCanQueryLockTaskLocked(who, caller.getPackageName());
-            }
-            LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
-                    PolicyDefinition.LOCK_TASK, userHandle);
-            if (policy == null) {
-                // We default on the power button menu, in order to be consistent with pre-P
-                // behaviour.
-                return DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
-            }
-            return policy.getFlags();
-        } else {
-            Objects.requireNonNull(who, "ComponentName is null");
-            synchronized (getLockObject()) {
-                enforceCanCallLockTaskLocked(caller);
-                return getUserData(userHandle).mLockTaskFeatures;
-            }
+        synchronized (getLockObject()) {
+            enforceCanQueryLockTaskLocked(who, caller.getPackageName());
         }
+        LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
+                PolicyDefinition.LOCK_TASK, userHandle);
+        if (policy == null) {
+            // We default on the power button menu, in order to be consistent with pre-P
+            // behaviour.
+            return DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
+        }
+        return policy.getFlags();
     }
 
     private void maybeClearLockTaskPolicyLocked() {
@@ -15118,34 +14410,14 @@
                 if (canDPCManagedUserUseLockTaskLocked(userId)) {
                     continue;
                 }
-
-                if (isPolicyEngineForFinanceFlagEnabled()) {
-                    Map<EnforcingAdmin, PolicyValue<LockTaskPolicy>> policies =
-                            mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
-                                    PolicyDefinition.LOCK_TASK, userId);
-                    Set<EnforcingAdmin> admins = new HashSet<>(policies.keySet());
-                    for (EnforcingAdmin admin : admins) {
-                        if (admin.hasAuthority(EnforcingAdmin.DPC_AUTHORITY)) {
-                            mDevicePolicyEngine.removeLocalPolicy(
-                                    PolicyDefinition.LOCK_TASK, admin, userId);
-                        }
-                    }
-                } else {
-                    final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
-                    // TODO(b/278438525): handle in the policy engine
-                    if (!lockTaskPackages.isEmpty()) {
-                        Slogf.d(LOG_TAG,
-                                "User id " + userId
-                                        + " not affiliated. Clearing lock task packages");
-                        setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
-                    }
-                    final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures;
-                    if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
-                        Slogf.d(LOG_TAG,
-                                "User id " + userId
-                                        + " not affiliated. Clearing lock task features");
-                        setLockTaskFeaturesLocked(userId,
-                                DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
+                Map<EnforcingAdmin, PolicyValue<LockTaskPolicy>> policies =
+                        mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
+                                PolicyDefinition.LOCK_TASK, userId);
+                Set<EnforcingAdmin> admins = new HashSet<>(policies.keySet());
+                for (EnforcingAdmin admin : admins) {
+                    if (admin.hasAuthority(EnforcingAdmin.DPC_AUTHORITY)) {
+                        mDevicePolicyEngine.removeLocalPolicy(
+                                PolicyDefinition.LOCK_TASK, admin, userId);
                     }
                 }
             }
@@ -16442,69 +15714,22 @@
                 return result;
             }
         } else if (DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
-            if (isPolicyEngineForFinanceFlagEnabled()) {
-                Boolean value = mDevicePolicyEngine.getResolvedPolicy(
-                        PolicyDefinition.SCREEN_CAPTURE_DISABLED, userId);
-                if (value != null && value) {
-                    result = new Bundle();
-                    result.putInt(Intent.EXTRA_USER_ID, userId);
-                    return result;
-                }
-            } else {
-                synchronized (getLockObject()) {
-                    final DevicePolicyData policy = getUserData(userId);
-                    final int N = policy.mAdminList.size();
-                    for (int i = 0; i < N; i++) {
-                        final ActiveAdmin admin = policy.mAdminList.get(i);
-                        if (admin.disableScreenCapture) {
-                            result = new Bundle();
-                            result.putInt(Intent.EXTRA_USER_ID, userId);
-                            result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
-                                    admin.info.getComponent());
-                            return result;
-                        }
-                    }
-                }
+            Boolean value = mDevicePolicyEngine.getResolvedPolicy(
+                    PolicyDefinition.SCREEN_CAPTURE_DISABLED, userId);
+            if (value != null && value) {
+                result = new Bundle();
+                result.putInt(Intent.EXTRA_USER_ID, userId);
+                return result;
             }
         } else if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
-            if (isPolicyEngineForFinanceFlagEnabled()) {
-                PolicyDefinition<Boolean> policyDefinition =
-                        PolicyDefinition.getPolicyDefinitionForUserRestriction(
-                                UserManager.DISALLOW_CAMERA);
-                Boolean value = mDevicePolicyEngine.getResolvedPolicy(policyDefinition, userId);
-                if (value != null && value) {
-                    result = new Bundle();
-                    result.putInt(Intent.EXTRA_USER_ID, userId);
-                    return result;
-                }
-            } else {
-                synchronized (getLockObject()) {
-                    final DevicePolicyData policy = getUserData(userId);
-                    final int N = policy.mAdminList.size();
-                    for (int i = 0; i < N; i++) {
-                        final ActiveAdmin admin = policy.mAdminList.get(i);
-                        if (admin.disableCamera) {
-                            result = new Bundle();
-                            result.putInt(Intent.EXTRA_USER_ID, userId);
-                            result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
-                                    admin.info.getComponent());
-                            return result;
-                        }
-                    }
-                    // For the camera, a device owner on a different user can disable it globally,
-                    // so we need an additional check.
-                    if (result == null
-                            && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
-                        final ActiveAdmin admin = getDeviceOwnerAdminLocked();
-                        if (admin != null && admin.disableCamera) {
-                            result = new Bundle();
-                            result.putInt(Intent.EXTRA_USER_ID, mOwners.getDeviceOwnerUserId());
-                            result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
-                                    admin.info.getComponent());
-                            return result;
-                        }
-                    }
-                }
+            PolicyDefinition<Boolean> policyDefinition =
+                    PolicyDefinition.getPolicyDefinitionForUserRestriction(
+                            UserManager.DISALLOW_CAMERA);
+            Boolean value = mDevicePolicyEngine.getResolvedPolicy(policyDefinition, userId);
+            if (value != null && value) {
+                result = new Bundle();
+                result.putInt(Intent.EXTRA_USER_ID, userId);
+                return result;
             }
         } else {
             long ident = mInjector.binderClearCallingIdentity();
@@ -18564,14 +17789,9 @@
             Slogf.d(LOG_TAG, "Current state of DevicePolicyData#mRemovingAdmins for user "
                     + userHandle + ": " + policy.mRemovingAdmins);
 
-            pushScreenCapturePolicy(userHandle);
-
             Slogf.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
         }
         pushMeteredDisabledPackages(userHandle);
-        // The removed admin might have disabled camera, so update user
-        // restrictions.
-        pushUserRestrictions(userHandle);
     }
 
     @Override
@@ -20483,20 +19703,13 @@
     }
 
     private boolean isLockTaskFeatureEnabled(int lockTaskFeature) throws RemoteException {
-        int lockTaskFeatures = 0;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
-                    PolicyDefinition.LOCK_TASK, getCurrentForegroundUserId());
-            lockTaskFeatures = policy == null
-                    // We default on the power button menu, in order to be consistent with pre-P
-                    // behaviour.
-                    ? DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS
-                    : policy.getFlags();
-        } else {
-            //TODO(b/175285301): Explicitly get the user's identity to check.
-            lockTaskFeatures =
-                    getUserData(getCurrentForegroundUserId()).mLockTaskFeatures;
-        }
+        LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
+                PolicyDefinition.LOCK_TASK, getCurrentForegroundUserId());
+        int lockTaskFeatures = policy == null
+                // We default on the power button menu, in order to be consistent with pre-P
+                // behaviour.
+                ? DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS
+                : policy.getFlags();
         return (lockTaskFeatures & lockTaskFeature) == lockTaskFeature;
     }
 
@@ -20680,41 +19893,22 @@
     public void setUserControlDisabledPackages(ComponentName who, String callerPackageName,
             List<String> packages) {
         Objects.requireNonNull(packages, "packages is null");
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
         checkCanExecuteOrThrowUnsafe(
                 DevicePolicyManager.OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES);
 
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
-                    who,
-                    MANAGE_DEVICE_POLICY_APPS_CONTROL,
-                    caller.getPackageName(),
-                    caller.getUserId());
-            Binder.withCleanCallingIdentity(() -> {
-                if (packages.isEmpty()) {
-                    removeUserControlDisabledPackages(caller, enforcingAdmin);
-                } else {
-                    addUserControlDisabledPackages(caller, enforcingAdmin, new HashSet<>(packages));
-                }
-            });
-        } else {
-            Objects.requireNonNull(who, "ComponentName is null");
-            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
-                    || isProfileOwner(caller) || isFinancedDeviceOwner(caller));
-            synchronized (getLockObject()) {
-                ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(caller.getUserId());
-                if (!Objects.equals(admin.protectedPackages, packages)) {
-                    admin.protectedPackages = packages.isEmpty() ? null : packages;
-                    saveSettingsLocked(caller.getUserId());
-                    pushUserControlDisabledPackagesLocked(caller.getUserId());
-                }
+        EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
+                who,
+                MANAGE_DEVICE_POLICY_APPS_CONTROL,
+                caller.getPackageName(),
+                caller.getUserId());
+        Binder.withCleanCallingIdentity(() -> {
+            if (packages.isEmpty()) {
+                removeUserControlDisabledPackages(caller, enforcingAdmin);
+            } else {
+                addUserControlDisabledPackages(caller, enforcingAdmin, new HashSet<>(packages));
             }
-        }
+        });
 
         DevicePolicyEventLogger
                 .createEvent(DevicePolicyEnums.SET_USER_CONTROL_DISABLED_PACKAGES)
@@ -20756,34 +19950,17 @@
     @Override
     public List<String> getUserControlDisabledPackages(ComponentName who,
             String callerPackageName) {
-        CallerIdentity caller;
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            caller = getCallerIdentity(who, callerPackageName);
-        } else {
-            caller = getCallerIdentity(who);
-        }
-
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            enforceCanQuery(
-                    MANAGE_DEVICE_POLICY_APPS_CONTROL,
-                    caller.getPackageName(),
-                    caller.getUserId());
-            // This retrieves the policy for the calling user only, DOs for example can't know
-            // what's enforced globally or on another user.
-            Set<String> packages = mDevicePolicyEngine.getResolvedPolicy(
-                    PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
-                    caller.getUserId());
-            return packages == null ? Collections.emptyList() : packages.stream().toList();
-        } else {
-            Objects.requireNonNull(who, "ComponentName is null");
-            Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
-                    || isProfileOwner(caller) || isFinancedDeviceOwner(caller));
-            synchronized (getLockObject()) {
-                ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(caller.getUserId());
-                return admin.protectedPackages != null
-                        ? admin.protectedPackages : Collections.emptyList();
-            }
-        }
+        CallerIdentity caller = getCallerIdentity(who, callerPackageName);
+        enforceCanQuery(
+                MANAGE_DEVICE_POLICY_APPS_CONTROL,
+                caller.getPackageName(),
+                caller.getUserId());
+        // This retrieves the policy for the calling user only, DOs for example can't know
+        // what's enforced globally or on another user.
+        Set<String> packages = mDevicePolicyEngine.getResolvedPolicy(
+                PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
+                caller.getUserId());
+        return packages == null ? Collections.emptyList() : packages.stream().toList();
     }
 
     @Override
@@ -21066,27 +20243,18 @@
         Slogf.i(LOG_TAG, "%s personal apps for user %d", suspended ? "Suspending" : "Unsuspending",
                 parentUserId);
 
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            // TODO(b/280602237): migrate properly
-            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
-            if (profileOwner != null) {
-                EnforcingAdmin admin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
-                        profileOwner.info.getComponent(),
-                        profileUserId,
-                        profileOwner);
-                mDevicePolicyEngine.setLocalPolicy(
-                        PolicyDefinition.PERSONAL_APPS_SUSPENDED,
-                        admin,
-                        new BooleanPolicyValue(suspended),
-                        parentUserId);
-            }
-        } else {
-            if (suspended) {
-                suspendPersonalAppsInPackageManager(parentUserId);
-            } else {
-                mInjector.getPackageManagerInternal().unsuspendForSuspendingPackage(
-                        PLATFORM_PACKAGE_NAME, parentUserId);
-            }
+        // TODO(b/280602237): migrate properly
+        ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
+        if (profileOwner != null) {
+            EnforcingAdmin admin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
+                    profileOwner.info.getComponent(),
+                    profileUserId,
+                    profileOwner);
+            mDevicePolicyEngine.setLocalPolicy(
+                    PolicyDefinition.PERSONAL_APPS_SUSPENDED,
+                    admin,
+                    new BooleanPolicyValue(suspended),
+                    parentUserId);
         }
 
         synchronized (getLockObject()) {
@@ -22373,35 +21541,18 @@
     public void setUsbDataSignalingEnabled(String packageName, boolean enabled) {
         Objects.requireNonNull(packageName, "Admin package name must be provided");
         final CallerIdentity caller = getCallerIdentity(packageName);
-        if (!isPolicyEngineForFinanceFlagEnabled()) {
-            Preconditions.checkCallAuthorization(
-                    isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
-                    "USB data signaling can only be controlled by a device owner or "
-                            + "a profile owner on an organization-owned device.");
-            Preconditions.checkState(canUsbDataSignalingBeDisabled(),
-                    "USB data signaling cannot be disabled.");
-        }
 
         synchronized (getLockObject()) {
-            if (isPolicyEngineForFinanceFlagEnabled()) {
-                EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
-                        /* admin= */ null, MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING,
-                        caller.getPackageName(),
-                        caller.getUserId());
-                Preconditions.checkState(canUsbDataSignalingBeDisabled(),
-                        "USB data signaling cannot be disabled.");
-                mDevicePolicyEngine.setGlobalPolicy(
-                        PolicyDefinition.USB_DATA_SIGNALING,
-                        enforcingAdmin,
-                        new BooleanPolicyValue(enabled));
-            } else {
-                ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
-                if (admin.mUsbDataSignalingEnabled != enabled) {
-                    admin.mUsbDataSignalingEnabled = enabled;
-                    saveSettingsLocked(caller.getUserId());
-                    updateUsbDataSignal(mContext, isUsbDataSignalingEnabledInternalLocked());
-                }
-            }
+            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
+                    /* admin= */ null, MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING,
+                    caller.getPackageName(),
+                    caller.getUserId());
+            Preconditions.checkState(canUsbDataSignalingBeDisabled(),
+                    "USB data signaling cannot be disabled.");
+            mDevicePolicyEngine.setGlobalPolicy(
+                    PolicyDefinition.USB_DATA_SIGNALING,
+                    enforcingAdmin,
+                    new BooleanPolicyValue(enabled));
         }
         DevicePolicyEventLogger
                 .createEvent(DevicePolicyEnums.SET_USB_DATA_SIGNALING)
@@ -22423,24 +21574,10 @@
     @Override
     public boolean isUsbDataSignalingEnabled(String packageName) {
         final CallerIdentity caller = getCallerIdentity(packageName);
-        if (isPolicyEngineForFinanceFlagEnabled()) {
-            Boolean enabled = mDevicePolicyEngine.getResolvedPolicy(
-                    PolicyDefinition.USB_DATA_SIGNALING,
-                    caller.getUserId());
-            return enabled == null || enabled;
-        } else {
-            synchronized (getLockObject()) {
-                // If the caller is an admin, return the policy set by itself. Otherwise
-                // return the device-wide policy.
-                if (isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(
-                        caller)) {
-                    return getProfileOwnerOrDeviceOwnerLocked(
-                            caller.getUserId()).mUsbDataSignalingEnabled;
-                } else {
-                    return isUsbDataSignalingEnabledInternalLocked();
-                }
-            }
-        }
+        Boolean enabled = mDevicePolicyEngine.getResolvedPolicy(
+                PolicyDefinition.USB_DATA_SIGNALING,
+                caller.getUserId());
+        return enabled == null || enabled;
     }
 
     private boolean isUsbDataSignalingEnabledInternalLocked() {
@@ -22849,9 +21986,6 @@
         }
 
         private void handleFinancedDeviceKioskRoleChange() {
-            if (!isPolicyEngineForFinanceFlagEnabled()) {
-                return;
-            }
             Slog.i(LOG_TAG, "Handling action " + ACTION_DEVICE_FINANCING_STATE_CHANGED);
             Intent intent = new Intent(ACTION_DEVICE_FINANCING_STATE_CHANGED);
             mInjector.binderWithCleanCallingIdentity(() -> {
@@ -23842,13 +22976,6 @@
                 DEFAULT_VALUE_PERMISSION_BASED_ACCESS_FLAG);
     }
 
-    static boolean isPolicyEngineForFinanceFlagEnabled() {
-        return DeviceConfig.getBoolean(
-                NAMESPACE_DEVICE_POLICY_MANAGER,
-                ENABLE_DEVICE_POLICY_ENGINE_FOR_FINANCE_FLAG,
-                DEFAULT_ENABLE_DEVICE_POLICY_ENGINE_FOR_FINANCE_FLAG);
-    }
-
     private static boolean isKeepProfilesRunningFlagEnabled() {
         return DeviceConfig.getBoolean(
                 NAMESPACE_DEVICE_POLICY_MANAGER,
@@ -24200,9 +23327,7 @@
     }
 
     private boolean shouldMigrateToDevicePolicyEngine() {
-        return mInjector.binderWithCleanCallingIdentity(() ->
-                (isPermissionCheckFlagEnabled() || isPolicyEngineForFinanceFlagEnabled())
-                        && !mOwners.isMigratedToPolicyEngine());
+        return mInjector.binderWithCleanCallingIdentity(() -> !mOwners.isMigratedToPolicyEngine());
     }
 
     /**
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index caa4343..57fa12d 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -354,8 +354,6 @@
             "com.android.server.contentcapture.ContentCaptureManagerService";
     private static final String TRANSLATION_MANAGER_SERVICE_CLASS =
             "com.android.server.translation.TranslationManagerService";
-    private static final String SELECTION_TOOLBAR_MANAGER_SERVICE_CLASS =
-            "com.android.server.selectiontoolbar.SelectionToolbarManagerService";
     private static final String MUSIC_RECOGNITION_MANAGER_SERVICE_CLASS =
             "com.android.server.musicrecognition.MusicRecognitionManagerService";
     private static final String AMBIENT_CONTEXT_MANAGER_SERVICE_CLASS =
@@ -2738,13 +2736,6 @@
             Slog.d(TAG, "TranslationService not defined by OEM");
         }
 
-        if (!isTv) {
-            // Selection toolbar service
-            t.traceBegin("StartSelectionToolbarManagerService");
-            mSystemServiceManager.startService(SELECTION_TOOLBAR_MANAGER_SERVICE_CLASS);
-            t.traceEnd();
-        }
-
         // NOTE: ClipboardService depends on ContentCapture and Autofill
         t.traceBegin("StartClipboardService");
         mSystemServiceManager.startService(ClipboardService.class);
diff --git a/services/people/java/com/android/server/people/prediction/ShareTargetPredictor.java b/services/people/java/com/android/server/people/prediction/ShareTargetPredictor.java
index b620407..f5360eb 100644
--- a/services/people/java/com/android/server/people/prediction/ShareTargetPredictor.java
+++ b/services/people/java/com/android/server/people/prediction/ShareTargetPredictor.java
@@ -30,6 +30,7 @@
 import android.app.prediction.AppTarget;
 import android.app.prediction.AppTargetEvent;
 import android.app.prediction.AppTargetId;
+import android.content.ComponentName;
 import android.content.Context;
 import android.content.IntentFilter;
 import android.content.pm.ShortcutInfo;
@@ -39,6 +40,7 @@
 import android.util.Log;
 import android.util.Slog;
 
+import com.android.internal.R;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.app.ChooserActivity;
 import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
@@ -63,6 +65,7 @@
     private static final String REMOTE_APP_PREDICTOR_KEY = "remote_app_predictor";
     private final IntentFilter mIntentFilter;
     private final AppPredictor mRemoteAppPredictor;
+    @Nullable private final String mChooserActivity;
 
     ShareTargetPredictor(@NonNull AppPredictionContext predictionContext,
             @NonNull Consumer<List<AppTarget>> updatePredictionsMethod,
@@ -81,6 +84,9 @@
         } else {
             mRemoteAppPredictor = null;
         }
+        ComponentName component = ComponentName.unflattenFromString(
+                context.getResources().getString(R.string.config_chooserActivity));
+        mChooserActivity = (component == null) ? null : component.getShortClassName();
     }
 
     /** Reports chosen history of direct/app share targets. */
@@ -138,7 +144,7 @@
         SharesheetModelScorer.computeScoreForAppShare(shareTargets,
                 getShareEventType(mIntentFilter), getPredictionContext().getPredictedTargetCount(),
                 System.currentTimeMillis(), getDataManager(),
-                mCallingUserId);
+                mCallingUserId, mChooserActivity);
         Collections.sort(shareTargets, (t1, t2) -> -Float.compare(t1.getScore(), t2.getScore()));
         List<AppTarget> appTargetList = new ArrayList<>();
         for (ShareTarget shareTarget : shareTargets) {
diff --git a/services/people/java/com/android/server/people/prediction/SharesheetModelScorer.java b/services/people/java/com/android/server/people/prediction/SharesheetModelScorer.java
index c77843c..b2f1e21 100644
--- a/services/people/java/com/android/server/people/prediction/SharesheetModelScorer.java
+++ b/services/people/java/com/android/server/people/prediction/SharesheetModelScorer.java
@@ -26,7 +26,6 @@
 import android.util.Slog;
 
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.app.ChooserActivity;
 import com.android.server.people.data.AppUsageStatsData;
 import com.android.server.people.data.DataManager;
 import com.android.server.people.data.Event;
@@ -55,8 +54,6 @@
     private static final float FREQUENTLY_USED_APP_SCORE_INITIAL_DECAY = 0.3F;
     @VisibleForTesting
     static final float FOREGROUND_APP_WEIGHT = 0F;
-    @VisibleForTesting
-    static final String CHOOSER_ACTIVITY = ChooserActivity.class.getSimpleName();
 
     // Keep constructor private to avoid class being instantiated.
     private SharesheetModelScorer() {
@@ -169,13 +166,14 @@
      */
     static void computeScoreForAppShare(List<ShareTargetPredictor.ShareTarget> shareTargets,
             int shareEventType, int targetsLimit, long now, @NonNull DataManager dataManager,
-            @UserIdInt int callingUserId) {
+            @UserIdInt int callingUserId, @Nullable String chooserActivity) {
         computeScore(shareTargets, shareEventType, now);
-        postProcess(shareTargets, targetsLimit, dataManager, callingUserId);
+        postProcess(shareTargets, targetsLimit, dataManager, callingUserId, chooserActivity);
     }
 
     private static void postProcess(List<ShareTargetPredictor.ShareTarget> shareTargets,
-            int targetsLimit, @NonNull DataManager dataManager, @UserIdInt int callingUserId) {
+            int targetsLimit, @NonNull DataManager dataManager, @UserIdInt int callingUserId,
+            @Nullable String chooserActivity) {
         // Populates a map which key is package name and value is list of shareTargets descended
         // on total score.
         Map<String, List<ShareTargetPredictor.ShareTarget>> shareTargetMap = new ArrayMap<>();
@@ -192,7 +190,7 @@
             }
             targetsList.add(index, shareTarget);
         }
-        promoteForegroundApp(shareTargetMap, dataManager, callingUserId);
+        promoteForegroundApp(shareTargetMap, dataManager, callingUserId, chooserActivity);
         promoteMostChosenAndFrequentlyUsedApps(shareTargetMap, targetsLimit, dataManager,
                 callingUserId);
     }
@@ -272,9 +270,10 @@
      */
     private static void promoteForegroundApp(
             Map<String, List<ShareTargetPredictor.ShareTarget>> shareTargetMap,
-            @NonNull DataManager dataManager, @UserIdInt int callingUserId) {
+            @NonNull DataManager dataManager, @UserIdInt int callingUserId,
+            @Nullable String chooserActivity) {
         String sharingForegroundApp = findSharingForegroundApp(shareTargetMap, dataManager,
-                callingUserId);
+                callingUserId, chooserActivity);
         if (sharingForegroundApp != null) {
             ShareTargetPredictor.ShareTarget target = shareTargetMap.get(sharingForegroundApp).get(
                     0);
@@ -297,7 +296,8 @@
     @Nullable
     private static String findSharingForegroundApp(
             Map<String, List<ShareTargetPredictor.ShareTarget>> shareTargetMap,
-            @NonNull DataManager dataManager, @UserIdInt int callingUserId) {
+            @NonNull DataManager dataManager, @UserIdInt int callingUserId,
+            @Nullable String chooserActivity) {
         String sharingForegroundApp = null;
         long now = System.currentTimeMillis();
         List<UsageEvents.Event> events = dataManager.queryAppMovingToForegroundEvents(
@@ -306,8 +306,8 @@
         for (int i = events.size() - 1; i >= 0; i--) {
             String className = events.get(i).getClassName();
             String packageName = events.get(i).getPackageName();
-            if (packageName == null || (className != null && className.contains(CHOOSER_ACTIVITY))
-                    || packageName.contains(CHOOSER_ACTIVITY)) {
+            if (packageName == null || (className != null && chooserActivity != null
+                    && className.contains(chooserActivity))) {
                 continue;
             }
             if (sourceApp == null) {
diff --git a/services/permission/java/com/android/server/permission/access/AccessPolicy.kt b/services/permission/java/com/android/server/permission/access/AccessPolicy.kt
index 6a349e2..17474fb 100644
--- a/services/permission/java/com/android/server/permission/access/AccessPolicy.kt
+++ b/services/permission/java/com/android/server/permission/access/AccessPolicy.kt
@@ -26,7 +26,6 @@
 import com.android.server.permission.access.immutable.* // ktlint-disable no-wildcard-imports
 import com.android.server.permission.access.immutable.IndexedMap
 import com.android.server.permission.access.permission.AppIdPermissionPolicy
-import com.android.server.permission.access.permission.DevicePermissionPolicy
 import com.android.server.permission.access.util.attributeInt
 import com.android.server.permission.access.util.attributeInterned
 import com.android.server.permission.access.util.forEachTag
@@ -47,7 +46,6 @@
                 getOrPut(policy.subjectScheme) { MutableIndexedMap() }[policy.objectScheme] = policy
             }
             addPolicy(AppIdPermissionPolicy())
-            addPolicy(DevicePermissionPolicy())
             addPolicy(AppIdAppOpPolicy())
             addPolicy(PackageAppOpPolicy())
         } as IndexedMap<String, IndexedMap<String, SchemePolicy>>
diff --git a/services/permission/java/com/android/server/permission/access/AccessState.kt b/services/permission/java/com/android/server/permission/access/AccessState.kt
index 94c878a..4ec32ea 100644
--- a/services/permission/java/com/android/server/permission/access/AccessState.kt
+++ b/services/permission/java/com/android/server/permission/access/AccessState.kt
@@ -329,18 +329,6 @@
 private typealias AppIdPermissionFlagsReference =
     MutableReference<AppIdPermissionFlags, MutableAppIdPermissionFlags>
 
-
-typealias DevicePermissionFlags =
-    IndexedReferenceMap<String, IndexedMap<String, Int>, MutableIndexedMap<String, Int>>
-typealias MutableDevicePermissionFlags =
-    MutableIndexedReferenceMap<String, IndexedMap<String, Int>, MutableIndexedMap<String, Int>>
-typealias AppIdDevicePermissionFlags =
-    IntReferenceMap<DevicePermissionFlags, MutableDevicePermissionFlags>
-typealias MutableAppIdDevicePermissionFlags =
-    MutableIntReferenceMap<DevicePermissionFlags, MutableDevicePermissionFlags>
-private typealias AppIdDevicePermissionFlagsReference =
-    MutableReference<AppIdDevicePermissionFlags, MutableAppIdDevicePermissionFlags>
-
 typealias AppIdAppOpModes =
     IntReferenceMap<IndexedMap<String, Int>, MutableIndexedMap<String, Int>>
 typealias MutableAppIdAppOpModes =
@@ -358,7 +346,6 @@
 sealed class UserState(
     internal val packageVersionsReference: PackageVersionsReference,
     internal val appIdPermissionFlagsReference: AppIdPermissionFlagsReference,
-    internal val appIdDevicePermissionFlagsReference: AppIdDevicePermissionFlagsReference,
     internal val appIdAppOpModesReference: AppIdAppOpModesReference,
     internal val packageAppOpModesReference: PackageAppOpModesReference,
     defaultPermissionGrantFingerprint: String?,
@@ -370,9 +357,6 @@
     val appIdPermissionFlags: AppIdPermissionFlags
         get() = appIdPermissionFlagsReference.get()
 
-    val appIdDevicePermissionFlags: AppIdDevicePermissionFlags
-        get() = appIdDevicePermissionFlagsReference.get()
-
     val appIdAppOpModes: AppIdAppOpModes
         get() = appIdAppOpModesReference.get()
 
@@ -391,7 +375,6 @@
 class MutableUserState private constructor(
     packageVersionsReference: PackageVersionsReference,
     appIdPermissionFlagsReference: AppIdPermissionFlagsReference,
-    appIdDevicePermissionFlagsReference: AppIdDevicePermissionFlagsReference,
     appIdAppOpModesReference: AppIdAppOpModesReference,
     packageAppOpModesReference: PackageAppOpModesReference,
     defaultPermissionGrantFingerprint: String?,
@@ -399,7 +382,6 @@
 ) : UserState(
     packageVersionsReference,
     appIdPermissionFlagsReference,
-    appIdDevicePermissionFlagsReference,
     appIdAppOpModesReference,
     packageAppOpModesReference,
     defaultPermissionGrantFingerprint,
@@ -408,7 +390,6 @@
     constructor() : this(
         PackageVersionsReference(MutableIndexedMap<String, Int>()),
         AppIdPermissionFlagsReference(MutableAppIdPermissionFlags()),
-        AppIdDevicePermissionFlagsReference(MutableAppIdDevicePermissionFlags()),
         AppIdAppOpModesReference(MutableAppIdAppOpModes()),
         PackageAppOpModesReference(MutablePackageAppOpModes()),
         null,
@@ -418,7 +399,6 @@
     internal constructor(userState: UserState) : this(
         userState.packageVersionsReference.toImmutable(),
         userState.appIdPermissionFlagsReference.toImmutable(),
-        userState.appIdDevicePermissionFlagsReference.toImmutable(),
         userState.appIdAppOpModesReference.toImmutable(),
         userState.packageAppOpModesReference.toImmutable(),
         userState.defaultPermissionGrantFingerprint,
@@ -430,9 +410,6 @@
     fun mutateAppIdPermissionFlags(): MutableAppIdPermissionFlags =
         appIdPermissionFlagsReference.mutate()
 
-    fun mutateAppIdDevicePermissionFlags(): MutableAppIdDevicePermissionFlags =
-        appIdDevicePermissionFlagsReference.mutate()
-
     fun mutateAppIdAppOpModes(): MutableAppIdAppOpModes = appIdAppOpModesReference.mutate()
 
     fun mutatePackageAppOpModes(): MutablePackageAppOpModes = packageAppOpModesReference.mutate()
diff --git a/services/permission/java/com/android/server/permission/access/AccessUri.kt b/services/permission/java/com/android/server/permission/access/AccessUri.kt
index 1d46ca7..d1abc04 100644
--- a/services/permission/java/com/android/server/permission/access/AccessUri.kt
+++ b/services/permission/java/com/android/server/permission/access/AccessUri.kt
@@ -65,17 +65,6 @@
     }
 }
 
-data class DevicePermissionUri(
-    val permissionName: String,
-    val deviceId: Int
-) : AccessUri(SCHEME) {
-    override fun toString(): String = "$scheme:///$permissionName/$deviceId"
-
-    companion object {
-        const val SCHEME = "device-permission"
-    }
-}
-
 data class UidUri(
     val uid: Int
 ) : AccessUri(SCHEME) {
diff --git a/services/permission/java/com/android/server/permission/access/immutable/IntMapExtensions.kt b/services/permission/java/com/android/server/permission/access/immutable/IntMapExtensions.kt
index ed7f0af..9aa0a41 100644
--- a/services/permission/java/com/android/server/permission/access/immutable/IntMapExtensions.kt
+++ b/services/permission/java/com/android/server/permission/access/immutable/IntMapExtensions.kt
@@ -77,7 +77,7 @@
 }
 
 operator fun <T> MutableIntMap<T>.minusAssign(key: Int) {
-    array.remove(key)
+    array.remove(key).also { array.gc() }
 }
 
 fun <T> MutableIntMap<T>.putWithDefault(key: Int, value: T, defaultValue: T): T {
diff --git a/services/permission/java/com/android/server/permission/access/immutable/IntReferenceMapExtensions.kt b/services/permission/java/com/android/server/permission/access/immutable/IntReferenceMapExtensions.kt
index b4de5d1..1ed4f8a 100644
--- a/services/permission/java/com/android/server/permission/access/immutable/IntReferenceMapExtensions.kt
+++ b/services/permission/java/com/android/server/permission/access/immutable/IntReferenceMapExtensions.kt
@@ -77,7 +77,7 @@
 }
 
 operator fun <I : Immutable<M>, M : I> MutableIntReferenceMap<I, M>.minusAssign(key: Int) {
-    array.remove(key)
+    array.remove(key).also { array.gc() }
 }
 
 operator fun <I : Immutable<M>, M : I> MutableIntReferenceMap<I, M>.set(key: Int, value: M) {
diff --git a/services/permission/java/com/android/server/permission/access/permission/DevicePermissionPersistence.kt b/services/permission/java/com/android/server/permission/access/permission/DevicePermissionPersistence.kt
deleted file mode 100644
index 37a4a90..0000000
--- a/services/permission/java/com/android/server/permission/access/permission/DevicePermissionPersistence.kt
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.permission.access.permission
-
-import android.util.Slog
-import com.android.modules.utils.BinaryXmlPullParser
-import com.android.modules.utils.BinaryXmlSerializer
-import com.android.server.permission.access.AccessState
-import com.android.server.permission.access.DevicePermissionFlags
-import com.android.server.permission.access.MutableAccessState
-import com.android.server.permission.access.MutableAppIdDevicePermissionFlags
-import com.android.server.permission.access.MutableDevicePermissionFlags
-import com.android.server.permission.access.WriteMode
-import com.android.server.permission.access.immutable.IndexedMap
-import com.android.server.permission.access.immutable.MutableIndexedMap
-import com.android.server.permission.access.immutable.forEachIndexed
-import com.android.server.permission.access.immutable.forEachReversedIndexed
-import com.android.server.permission.access.immutable.set
-import com.android.server.permission.access.util.andInv
-import com.android.server.permission.access.util.attributeInt
-import com.android.server.permission.access.util.attributeInterned
-import com.android.server.permission.access.util.forEachTag
-import com.android.server.permission.access.util.getAttributeIntOrThrow
-import com.android.server.permission.access.util.getAttributeValueOrThrow
-import com.android.server.permission.access.util.hasBits
-import com.android.server.permission.access.util.tag
-import com.android.server.permission.access.util.tagName
-
-class DevicePermissionPersistence {
-    fun BinaryXmlPullParser.parseUserState(state: MutableAccessState, userId: Int) {
-        when (tagName) {
-            TAG_APP_ID_DEVICE_PERMISSIONS -> parseAppIdDevicePermissions(state, userId)
-            else -> {}
-        }
-    }
-
-    private fun BinaryXmlPullParser.parseAppIdDevicePermissions(
-        state: MutableAccessState,
-        userId: Int
-    ) {
-        val userState = state.mutateUserState(userId, WriteMode.NONE)!!
-        val appIdDevicePermissionFlags = userState.mutateAppIdDevicePermissionFlags()
-        forEachTag {
-            when (tagName) {
-                TAG_APP_ID -> parseAppId(appIdDevicePermissionFlags)
-                else -> Slog.w(LOG_TAG, "Ignoring unknown tag $name when parsing permission state")
-            }
-        }
-
-        appIdDevicePermissionFlags.forEachReversedIndexed { appIdIndex, appId, _ ->
-            if (appId !in state.externalState.appIdPackageNames) {
-                Slog.w(LOG_TAG, "Dropping unknown app ID $appId when parsing permission state")
-                appIdDevicePermissionFlags.removeAt(appIdIndex)
-                userState.requestWriteMode(WriteMode.ASYNCHRONOUS)
-            }
-        }
-    }
-
-    private fun BinaryXmlPullParser.parseAppId(
-        appIdPermissionFlags: MutableAppIdDevicePermissionFlags
-    ) {
-        val appId = getAttributeIntOrThrow(ATTR_ID)
-        val devicePermissionFlags = MutableDevicePermissionFlags()
-        appIdPermissionFlags[appId] = devicePermissionFlags
-        forEachTag {
-            when (tagName) {
-                TAG_DEVICE -> parseDevice(devicePermissionFlags)
-                else -> {
-                    Slog.w(LOG_TAG, "Ignoring unknown tag $name when parsing permission state")
-                }
-            }
-        }
-    }
-
-    private fun BinaryXmlPullParser.parseDevice(
-        deviceIdPermissionFlags: MutableDevicePermissionFlags
-    ) {
-        val deviceId = getAttributeValueOrThrow(ATTR_ID)
-        val permissionFlags = MutableIndexedMap<String, Int>()
-        deviceIdPermissionFlags.put(deviceId, permissionFlags)
-        forEachTag {
-            when (tagName) {
-                TAG_PERMISSION -> parsePermission(permissionFlags)
-                else -> Slog.w(LOG_TAG, "Ignoring unknown tag $name when parsing permission state")
-            }
-        }
-    }
-
-    private fun BinaryXmlPullParser.parsePermission(
-        permissionFlags: MutableIndexedMap<String, Int>
-    ) {
-        val name = getAttributeValueOrThrow(ATTR_NAME).intern()
-        val flags = getAttributeIntOrThrow(ATTR_FLAGS)
-        permissionFlags[name] = flags
-    }
-
-    fun BinaryXmlSerializer.serializeUserState(state: AccessState, userId: Int) {
-        val appIdDevicePermissionFlags = state.userStates[userId]!!.appIdDevicePermissionFlags
-        tag(TAG_APP_ID_DEVICE_PERMISSIONS) {
-            appIdDevicePermissionFlags.forEachIndexed { _, appId, devicePermissionFlags ->
-                serializeAppId(appId, devicePermissionFlags)
-            }
-        }
-    }
-
-    private fun BinaryXmlSerializer.serializeAppId(
-        appId: Int,
-        devicePermissionFlags: DevicePermissionFlags
-    ) {
-        tag(TAG_APP_ID) {
-            attributeInt(ATTR_ID, appId)
-            devicePermissionFlags.forEachIndexed { _, deviceId, permissionFlags ->
-                serializeDevice(deviceId, permissionFlags)
-            }
-        }
-    }
-
-    private fun BinaryXmlSerializer.serializeDevice(
-        deviceId: String,
-        permissionFlags: IndexedMap<String, Int>
-    ) {
-        tag(TAG_DEVICE) {
-            attributeInterned(ATTR_ID, deviceId)
-            permissionFlags.forEachIndexed { _, name, flags ->
-                serializePermission(name, flags)
-            }
-        }
-    }
-
-    private fun BinaryXmlSerializer.serializePermission(name: String, flags: Int) {
-        tag(TAG_PERMISSION) {
-            attributeInterned(ATTR_NAME, name)
-            // Never serialize one-time permissions as granted.
-            val serializedFlags = if (flags.hasBits(PermissionFlags.ONE_TIME)) {
-                flags andInv PermissionFlags.RUNTIME_GRANTED
-            } else {
-                flags
-            }
-            attributeInt(ATTR_FLAGS, serializedFlags)
-        }
-    }
-
-    companion object {
-        private val LOG_TAG = DevicePermissionPersistence::class.java.simpleName
-
-        private const val TAG_APP_ID_DEVICE_PERMISSIONS = "app-id-device-permissions"
-        private const val TAG_APP_ID = "app-id"
-        private const val TAG_DEVICE = "device"
-        private const val TAG_PERMISSION = "permission"
-
-        private const val ATTR_ID = "id"
-        private const val ATTR_NAME = "name"
-        private const val ATTR_FLAGS = "flags"
-    }
-}
\ No newline at end of file
diff --git a/services/permission/java/com/android/server/permission/access/permission/DevicePermissionPolicy.kt b/services/permission/java/com/android/server/permission/access/permission/DevicePermissionPolicy.kt
deleted file mode 100644
index c0d7546..0000000
--- a/services/permission/java/com/android/server/permission/access/permission/DevicePermissionPolicy.kt
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * Copyright (C) 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.permission.access.permission
-
-import android.util.Slog
-import com.android.modules.utils.BinaryXmlPullParser
-import com.android.modules.utils.BinaryXmlSerializer
-import com.android.server.permission.access.AccessState
-import com.android.server.permission.access.DevicePermissionUri
-import com.android.server.permission.access.GetStateScope
-import com.android.server.permission.access.MutableAccessState
-import com.android.server.permission.access.MutateStateScope
-import com.android.server.permission.access.SchemePolicy
-import com.android.server.permission.access.UidUri
-import com.android.server.permission.access.collection.* // ktlint-disable no-wildcard-imports
-import com.android.server.permission.access.immutable.* // ktlint-disable no-wildcard-imports
-import com.android.server.permission.access.util.andInv
-import com.android.server.pm.pkg.PackageState
-
-class DevicePermissionPolicy : SchemePolicy() {
-    private val persistence = DevicePermissionPersistence()
-
-    @Volatile
-    private var listeners: IndexedListSet<OnDevicePermissionFlagsChangedListener> =
-        MutableIndexedListSet()
-    private val listenersLock = Any()
-
-    override val subjectScheme: String
-        get() = UidUri.SCHEME
-
-    override val objectScheme: String
-        get() = DevicePermissionUri.SCHEME
-
-    override fun GetStateScope.onStateMutated() {
-        listeners.forEachIndexed { _, it -> it.onStateMutated() }
-    }
-
-    override fun MutateStateScope.onAppIdRemoved(appId: Int) {
-        newState.userStates.forEachIndexed { userStateIndex, _, userState ->
-            if (appId in userState.appIdDevicePermissionFlags) {
-                newState.mutateUserStateAt(userStateIndex)
-                    .mutateAppIdDevicePermissionFlags() -= appId
-            }
-        }
-    }
-
-    override fun MutateStateScope.onStorageVolumeMounted(
-        volumeUuid: String?,
-        packageNames: List<String>,
-        isSystemUpdated: Boolean
-    ) {
-        packageNames.forEachIndexed { _, packageName ->
-            val packageState = newState.externalState.packageStates[packageName]!!
-            trimPermissionStates(packageState.appId)
-        }
-    }
-
-    override fun MutateStateScope.onPackageAdded(packageState: PackageState) {
-        trimPermissionStates(packageState.appId)
-    }
-
-    override fun MutateStateScope.onPackageRemoved(packageName: String, appId: Int) {
-        if (appId in newState.externalState.appIdPackageNames) {
-            trimPermissionStates(appId)
-        }
-    }
-
-    override fun MutateStateScope.onPackageUninstalled(
-        packageName: String,
-        appId: Int,
-        userId: Int
-    ) {
-        resetPermissionStates(packageName, userId)
-    }
-
-    private fun MutateStateScope.resetPermissionStates(packageName: String, userId: Int) {
-        // It's okay to skip resetting permissions for packages that are removed,
-        // because their states will be trimmed in onPackageRemoved()/onAppIdRemoved()
-        val packageState = newState.externalState.packageStates[packageName] ?: return
-        val androidPackage = packageState.androidPackage ?: return
-        val appId = packageState.appId
-        val appIdPermissionFlags = newState.userStates[userId]!!.appIdDevicePermissionFlags
-        androidPackage.requestedPermissions.forEach { permissionName ->
-            val isRequestedByOtherPackages = anyPackageInAppId(appId) {
-                it.packageName != packageName &&
-                    permissionName in it.androidPackage!!.requestedPermissions
-            }
-            if (isRequestedByOtherPackages) {
-                return@forEach
-            }
-            appIdPermissionFlags[appId]?.forEachIndexed { _, deviceId, _ ->
-                setPermissionFlags(appId, deviceId, userId, permissionName, 0)
-            }
-        }
-    }
-
-    private fun MutateStateScope.trimPermissionStates(appId: Int) {
-        val requestedPermissions = MutableIndexedSet<String>()
-        forEachPackageInAppId(appId) {
-            requestedPermissions += it.androidPackage!!.requestedPermissions
-        }
-        newState.userStates.forEachIndexed { _, userId, userState ->
-            userState.appIdDevicePermissionFlags[appId]?.forEachReversedIndexed {
-                    _, deviceId, permissionFlags ->
-                permissionFlags.forEachReversedIndexed { _, permissionName, _ ->
-                    if (permissionName !in requestedPermissions) {
-                        setPermissionFlags(appId, deviceId, userId, permissionName, 0)
-                    }
-                }
-            }
-        }
-    }
-
-    private inline fun MutateStateScope.anyPackageInAppId(
-        appId: Int,
-        state: AccessState = newState,
-        predicate: (PackageState) -> Boolean
-    ): Boolean {
-        val packageNames = state.externalState.appIdPackageNames[appId]!!
-        return packageNames.anyIndexed { _, packageName ->
-            val packageState = state.externalState.packageStates[packageName]!!
-            packageState.androidPackage != null && predicate(packageState)
-        }
-    }
-
-    private inline fun MutateStateScope.forEachPackageInAppId(
-        appId: Int,
-        state: AccessState = newState,
-        action: (PackageState) -> Unit
-    ) {
-        val packageNames = state.externalState.appIdPackageNames[appId]!!
-        packageNames.forEachIndexed { _, packageName ->
-            val packageState = state.externalState.packageStates[packageName]!!
-            if (packageState.androidPackage != null) {
-                action(packageState)
-            }
-        }
-    }
-
-    override fun BinaryXmlPullParser.parseUserState(state: MutableAccessState, userId: Int) {
-        with(persistence) { this@parseUserState.parseUserState(state, userId) }
-    }
-
-    override fun BinaryXmlSerializer.serializeUserState(state: AccessState, userId: Int) {
-        with(persistence) { this@serializeUserState.serializeUserState(state, userId) }
-    }
-
-    fun GetStateScope.getPermissionFlags(
-        appId: Int,
-        deviceId: String,
-        userId: Int,
-        permissionName: String
-    ): Int =
-        state.userStates[userId]?.appIdDevicePermissionFlags?.get(appId)?.get(deviceId)
-            ?.getWithDefault(permissionName, 0) ?: 0
-
-    fun MutateStateScope.setPermissionFlags(
-        appId: Int,
-        deviceId: String,
-        userId: Int,
-        permissionName: String,
-        flags: Int
-    ): Boolean =
-        updatePermissionFlags(
-            appId, deviceId, userId, permissionName, PermissionFlags.MASK_ALL, flags
-        )
-
-    private fun MutateStateScope.updatePermissionFlags(
-        appId: Int,
-        deviceId: String,
-        userId: Int,
-        permissionName: String,
-        flagMask: Int,
-        flagValues: Int
-    ): Boolean {
-        if (!isDeviceAwarePermission(permissionName)) {
-            Slog.w(LOG_TAG, "$permissionName is not a device aware permission.")
-            return false
-        }
-        val oldFlags = newState.userStates[userId]!!.appIdDevicePermissionFlags[appId]
-            ?.get(deviceId).getWithDefault(permissionName, 0)
-        val newFlags = (oldFlags andInv flagMask) or (flagValues and flagMask)
-        if (oldFlags == newFlags) {
-            return false
-        }
-        val appIdDevicePermissionFlags =
-            newState.mutateUserState(userId)!!.mutateAppIdDevicePermissionFlags()
-        val devicePermissionFlags = appIdDevicePermissionFlags.mutateOrPut(appId) {
-            MutableIndexedReferenceMap()
-        }
-        val permissionFlags = devicePermissionFlags.mutateOrPut(deviceId) { MutableIndexedMap() }
-        permissionFlags.putWithDefault(permissionName, newFlags, 0)
-        if (permissionFlags.isEmpty()) {
-            devicePermissionFlags -= deviceId
-            if (devicePermissionFlags.isEmpty()) {
-                appIdDevicePermissionFlags -= appId
-            }
-        }
-        listeners.forEachIndexed { _, it ->
-            it.onDevicePermissionFlagsChanged(
-                appId, userId, deviceId, permissionName, oldFlags, newFlags
-            )
-        }
-        return true
-    }
-
-    fun addOnPermissionFlagsChangedListener(listener: OnDevicePermissionFlagsChangedListener) {
-        synchronized(listenersLock) {
-            listeners = listeners + listener
-        }
-    }
-
-    fun removeOnPermissionFlagsChangedListener(listener: OnDevicePermissionFlagsChangedListener) {
-        synchronized(listenersLock) {
-            listeners = listeners - listener
-        }
-    }
-
-    private fun isDeviceAwarePermission(permissionName: String): Boolean =
-        DEVICE_SUPPORTED_PERMISSIONS.contains(permissionName)
-
-    companion object {
-        private val LOG_TAG = DevicePermissionPolicy::class.java.simpleName
-
-        /**
-         * These permissions are supported for virtual devices.
-         */
-        private val DEVICE_SUPPORTED_PERMISSIONS = indexedSetOf(
-            android.Manifest.permission.CAMERA,
-            android.Manifest.permission.RECORD_AUDIO
-        )
-    }
-
-    /**
-     * TODO: b/289355341 - implement listener for permission changes
-     * Listener for permission flags changes.
-     */
-    abstract class OnDevicePermissionFlagsChangedListener {
-        /**
-         * Called when a permission flags change has been made to the upcoming new state.
-         *
-         * Implementations should keep this method fast to avoid stalling the locked state mutation,
-         * and only call external code after [onStateMutated] when the new state has actually become
-         * the current state visible to external code.
-         */
-        abstract fun onDevicePermissionFlagsChanged(
-            appId: Int,
-            userId: Int,
-            deviceId: String,
-            permissionName: String,
-            oldFlags: Int,
-            newFlags: Int
-        )
-
-        /**
-         * Called when the upcoming new state has become the current state.
-         *
-         * Implementations should keep this method fast to avoid stalling the locked state mutation.
-         */
-        abstract fun onStateMutated()
-    }
-}
\ No newline at end of file
diff --git a/services/permission/java/com/android/server/permission/access/permission/PermissionService.kt b/services/permission/java/com/android/server/permission/access/permission/PermissionService.kt
index d9f179a..edacf188 100644
--- a/services/permission/java/com/android/server/permission/access/permission/PermissionService.kt
+++ b/services/permission/java/com/android/server/permission/access/permission/PermissionService.kt
@@ -64,11 +64,9 @@
 import com.android.server.PermissionThread
 import com.android.server.ServiceThread
 import com.android.server.SystemConfig
-import com.android.server.companion.virtual.VirtualDeviceManagerInternal
 import com.android.server.permission.access.AccessCheckingService
 import com.android.server.permission.access.AccessState
 import com.android.server.permission.access.AppOpUri
-import com.android.server.permission.access.DevicePermissionUri
 import com.android.server.permission.access.GetStateScope
 import com.android.server.permission.access.MutateStateScope
 import com.android.server.permission.access.PermissionUri
@@ -112,9 +110,6 @@
     private val policy =
         service.getSchemePolicy(UidUri.SCHEME, PermissionUri.SCHEME) as AppIdPermissionPolicy
 
-    private val devicePolicy =
-        service.getSchemePolicy(UidUri.SCHEME, DevicePermissionUri.SCHEME) as DevicePermissionPolicy
-
     private val context = service.context
     private lateinit var metricsLogger: MetricsLogger
     private lateinit var packageManagerInternal: PackageManagerInternal
@@ -137,8 +132,6 @@
 
     private lateinit var permissionControllerManager: PermissionControllerManager
 
-    private lateinit var virtualDeviceManagerInternal: VirtualDeviceManagerInternal
-
     /**
      * A permission backup might contain apps that are not installed. In this case we delay the
      * restoration until the app is installed.
@@ -159,8 +152,6 @@
         systemConfig = SystemConfig.getInstance()
         userManagerInternal = LocalServices.getService(UserManagerInternal::class.java)
         userManagerService = UserManagerService.getInstance()
-        virtualDeviceManagerInternal =
-            LocalServices.getService(VirtualDeviceManagerInternal::class.java)
 
         // The package info cache is the cache for package and permission information.
         // Disable the package info and package permission caches locally but leave the
@@ -469,7 +460,7 @@
         return size
     }
 
-    override fun checkUidPermission(uid: Int, permissionName: String, deviceId: Int): Int {
+    override fun checkUidPermission(uid: Int, permissionName: String): Int {
         val userId = UserHandle.getUserId(uid)
         if (!userManagerInternal.exists(userId)) {
             return PackageManager.PERMISSION_DENIED
@@ -491,7 +482,7 @@
                 return PackageManager.PERMISSION_DENIED
             }
             val isPermissionGranted = service.getState {
-                isPermissionGranted(packageState, userId, permissionName, deviceId)
+                isPermissionGranted(packageState, userId, permissionName)
             }
             return if (isPermissionGranted) {
                 PackageManager.PERMISSION_GRANTED
@@ -524,12 +515,7 @@
         return false
     }
 
-    override fun checkPermission(
-        packageName: String,
-        permissionName: String,
-        deviceId: Int,
-        userId: Int
-    ): Int {
+    override fun checkPermission(packageName: String, permissionName: String, userId: Int): Int {
         if (!userManagerInternal.exists(userId)) {
             return PackageManager.PERMISSION_DENIED
         }
@@ -538,7 +524,7 @@
             .use { it.getPackageState(packageName) } ?: return PackageManager.PERMISSION_DENIED
 
         val isPermissionGranted = service.getState {
-            isPermissionGranted(packageState, userId, permissionName, deviceId)
+            isPermissionGranted(packageState, userId, permissionName)
         }
         return if (isPermissionGranted) {
             PackageManager.PERMISSION_GRANTED
@@ -556,21 +542,19 @@
     private fun GetStateScope.isPermissionGranted(
         packageState: PackageState,
         userId: Int,
-        permissionName: String,
-        deviceId: Int
+        permissionName: String
     ): Boolean {
         val appId = packageState.appId
         // Note that instant apps can't have shared UIDs, so we only need to check the current
         // package state.
         val isInstantApp = packageState.getUserStateOrDefault(userId).isInstantApp
-        if (isSinglePermissionGranted(appId, userId, isInstantApp, permissionName, deviceId)) {
+        if (isSinglePermissionGranted(appId, userId, isInstantApp, permissionName)) {
             return true
         }
 
         val fullerPermissionName = FULLER_PERMISSIONS[permissionName]
         if (fullerPermissionName != null &&
-            isSinglePermissionGranted(appId, userId, isInstantApp, fullerPermissionName, deviceId)
-        ) {
+            isSinglePermissionGranted(appId, userId, isInstantApp, fullerPermissionName)) {
             return true
         }
 
@@ -584,10 +568,9 @@
         appId: Int,
         userId: Int,
         isInstantApp: Boolean,
-        permissionName: String,
-        deviceId: Int,
+        permissionName: String
     ): Boolean {
-        val flags = getPermissionFlagsWithPolicy(appId, userId, permissionName, deviceId)
+        val flags = with(policy) { getPermissionFlags(appId, userId, permissionName) }
         if (!PermissionFlags.isPermissionGranted(flags)) {
             return false
         }
@@ -618,8 +601,7 @@
                 ?: return emptySet()
 
             return permissionFlags.mapNotNullIndexedTo(ArraySet()) { _, permissionName, _ ->
-                if (isPermissionGranted(
-                        packageState, userId, permissionName, Context.DEVICE_ID_DEFAULT)) {
+                if (isPermissionGranted(packageState, userId, permissionName)) {
                     permissionName
                 } else {
                     null
@@ -658,26 +640,18 @@
         }
     }
 
-    override fun grantRuntimePermission(
-        packageName: String,
-        permissionName: String,
-        deviceId: Int,
-        userId: Int
-    ) {
-        setRuntimePermissionGranted(
-            packageName, userId, permissionName, deviceId, isGranted = true
-        )
+    override fun grantRuntimePermission(packageName: String, permissionName: String, userId: Int) {
+        setRuntimePermissionGranted(packageName, userId, permissionName, isGranted = true)
     }
 
     override fun revokeRuntimePermission(
         packageName: String,
         permissionName: String,
-        deviceId: Int,
         userId: Int,
         reason: String?
     ) {
         setRuntimePermissionGranted(
-            packageName, userId, permissionName, deviceId, isGranted = false, revokeReason = reason
+            packageName, userId, permissionName, isGranted = false, revokeReason = reason
         )
     }
 
@@ -686,8 +660,8 @@
         userId: Int
     ) {
         setRuntimePermissionGranted(
-            packageName, userId, Manifest.permission.POST_NOTIFICATIONS, Context.DEVICE_ID_DEFAULT,
-            isGranted = false, skipKillUid = true
+            packageName, userId, Manifest.permission.POST_NOTIFICATIONS, isGranted = false,
+            skipKillUid = true
         )
     }
 
@@ -699,7 +673,6 @@
         packageName: String,
         userId: Int,
         permissionName: String,
-        deviceId: Int,
         isGranted: Boolean,
         skipKillUid: Boolean = false,
         revokeReason: String? = null
@@ -775,7 +748,7 @@
             }
 
             setRuntimePermissionGranted(
-                packageState, userId, permissionName, deviceId, isGranted, canManageRolePermission,
+                packageState, userId, permissionName, isGranted, canManageRolePermission,
                 overridePolicyFixed, reportError = true, methodName
             )
         }
@@ -809,16 +782,14 @@
                         if (permissionState ==
                             PackageInstaller.SessionParams.PERMISSION_STATE_GRANTED) {
                             setRuntimePermissionGranted(
-                                packageState, userId, permissionName, Context.DEVICE_ID_DEFAULT,
-                                isGranted = true, canManageRolePermission = false,
-                                overridePolicyFixed = false, reportError = false,
-                                "setRequestedPermissionStates"
+                                packageState, userId, permissionName, isGranted = true,
+                                canManageRolePermission = false, overridePolicyFixed = false,
+                                reportError = false, "setRequestedPermissionStates"
                             )
                             updatePermissionFlags(
                                 packageState.appId, userId, permissionName,
-                                Context.DEVICE_ID_DEFAULT,
                                 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED or
-                                PackageManager.FLAG_PERMISSION_REVOKED_COMPAT, 0,
+                                    PackageManager.FLAG_PERMISSION_REVOKED_COMPAT, 0,
                                 canUpdateSystemFlags = false,
                                 reportErrorForUnknownPermission = false,
                                 isPermissionRequested = true, "setRequestedPermissionStates",
@@ -845,7 +816,6 @@
         packageState: PackageState,
         userId: Int,
         permissionName: String,
-        deviceId: Int,
         isGranted: Boolean,
         canManageRolePermission: Boolean,
         overridePolicyFixed: Boolean,
@@ -901,7 +871,7 @@
         }
 
         val appId = packageState.appId
-        val oldFlags = getPermissionFlagsWithPolicy(appId, userId, permissionName, deviceId)
+        val oldFlags = with(policy) { getPermissionFlags(appId, userId, permissionName) }
 
         if (permissionName !in androidPackage.requestedPermissions && oldFlags == 0) {
             if (reportError) {
@@ -964,7 +934,7 @@
             return
         }
 
-        setPermissionFlagsWithPolicy(appId, userId, permissionName, deviceId, newFlags)
+        with(policy) { setPermissionFlags(appId, userId, permissionName, newFlags) }
 
         if (permission.isRuntime) {
             val action = if (isGranted) {
@@ -993,12 +963,7 @@
         with(appOpPolicy) { setAppOpMode(packageState.appId, userId, appOpName, mode) }
     }
 
-    override fun getPermissionFlags(
-        packageName: String,
-        permissionName: String,
-        deviceId: Int,
-        userId: Int,
-    ): Int {
+    override fun getPermissionFlags(packageName: String, permissionName: String, userId: Int): Int {
         if (!userManagerInternal.exists(userId)) {
             Slog.w(LOG_TAG, "getPermissionFlags: Unknown user $userId")
             return 0
@@ -1029,8 +994,7 @@
             }
 
             val flags =
-                getPermissionFlagsWithPolicy(packageState.appId, userId, permissionName, deviceId)
-
+                with(policy) { getPermissionFlags(packageState.appId, userId, permissionName) }
             return PermissionFlags.toApiFlags(flags)
         }
     }
@@ -1038,7 +1002,6 @@
     override fun isPermissionRevokedByPolicy(
         packageName: String,
         permissionName: String,
-        deviceId: Int,
         userId: Int
     ): Boolean {
         if (!userManagerInternal.exists(userId)) {
@@ -1055,13 +1018,13 @@
             .use { it.getPackageState(packageName) } ?: return false
 
         service.getState {
-            if (isPermissionGranted(packageState, userId, permissionName, deviceId)) {
+            if (isPermissionGranted(packageState, userId, permissionName)) {
                 return false
             }
 
-            val flags =
-                getPermissionFlagsWithPolicy(packageState.appId, userId, permissionName, deviceId)
-
+            val flags = with(policy) {
+                getPermissionFlags(packageState.appId, userId, permissionName)
+            }
             return flags.hasBits(PermissionFlags.POLICY_FIXED)
         }
     }
@@ -1083,8 +1046,7 @@
     override fun shouldShowRequestPermissionRationale(
         packageName: String,
         permissionName: String,
-        deviceId: Int,
-        userId: Int,
+        userId: Int
     ): Boolean {
         if (!userManagerInternal.exists(userId)) {
             Slog.w(LOG_TAG, "shouldShowRequestPermissionRationale: Unknown user $userId")
@@ -1106,11 +1068,11 @@
 
         val flags: Int
         service.getState {
-            if (isPermissionGranted(packageState, userId, permissionName, deviceId)) {
+            if (isPermissionGranted(packageState, userId, permissionName)) {
                 return false
             }
 
-            flags = getPermissionFlagsWithPolicy(appId, userId, permissionName, deviceId)
+            flags = with(policy) { getPermissionFlags(appId, userId, permissionName) }
         }
         if (flags.hasAnyBit(UNREQUESTABLE_MASK)) {
             return false
@@ -1142,7 +1104,6 @@
         flagMask: Int,
         flagValues: Int,
         enforceAdjustPolicyPermission: Boolean,
-        deviceId: Int,
         userId: Int
     ) {
         val callingUid = Binder.getCallingUid()
@@ -1238,7 +1199,7 @@
         val appId = packageState.appId
         service.mutateState {
             updatePermissionFlags(
-                appId, userId, permissionName, deviceId, flagMask, flagValues, canUpdateSystemFlags,
+                appId, userId, permissionName, flagMask, flagValues, canUpdateSystemFlags,
                 reportErrorForUnknownPermission = true, isPermissionRequested,
                 "updatePermissionFlags", packageName
             )
@@ -1287,9 +1248,8 @@
                 val androidPackage = packageState.androidPackage ?: return@forEach
                 androidPackage.requestedPermissions.forEach { permissionName ->
                     updatePermissionFlags(
-                        packageState.appId, userId, permissionName, Context.DEVICE_ID_DEFAULT,
-                        flagMask, flagValues, canUpdateSystemFlags,
-                        reportErrorForUnknownPermission = false,
+                        packageState.appId, userId, permissionName, flagMask, flagValues,
+                        canUpdateSystemFlags, reportErrorForUnknownPermission = false,
                         isPermissionRequested = true, "updatePermissionFlagsForAllApps", packageName
                     )
                 }
@@ -1304,7 +1264,6 @@
         appId: Int,
         userId: Int,
         permissionName: String,
-        deviceId: Int,
         flagMask: Int,
         flagValues: Int,
         canUpdateSystemFlags: Boolean,
@@ -1339,7 +1298,7 @@
             return
         }
 
-        val oldFlags = getPermissionFlagsWithPolicy(appId, userId, permissionName, deviceId)
+        val oldFlags = with(policy) { getPermissionFlags(appId, userId, permissionName) }
         if (!isPermissionRequested && oldFlags == 0) {
             Slog.w(
                 LOG_TAG, "$methodName: Permission $permissionName isn't requested by package" +
@@ -1349,7 +1308,7 @@
         }
 
         val newFlags = PermissionFlags.updateFlags(permission, oldFlags, flagMask, flagValues)
-        setPermissionFlagsWithPolicy(appId, userId, permissionName, deviceId, newFlags)
+        with(policy) { setPermissionFlags(appId, userId, permissionName, newFlags) }
     }
 
     override fun getAllowlistedRestrictedPermissions(
@@ -1406,49 +1365,6 @@
         )
     }
 
-    private fun GetStateScope.getPermissionFlagsWithPolicy(
-        appId: Int,
-        userId: Int,
-        permissionName: String,
-        deviceId: Int,
-    ): Int =
-        if (deviceId == Context.DEVICE_ID_DEFAULT) {
-            with(policy) { getPermissionFlags(appId, userId, permissionName) }
-        } else {
-            val persistentDeviceId = virtualDeviceManagerInternal.getPersistentIdForDevice(deviceId)
-            if (persistentDeviceId != null) {
-                with(devicePolicy) {
-                    getPermissionFlags(appId, persistentDeviceId, userId, permissionName)
-                }
-            } else {
-                Slog.e(LOG_TAG, "Invalid deviceId $deviceId, no persistent device ID found.")
-                0
-            }
-        }
-
-    private fun MutateStateScope.setPermissionFlagsWithPolicy(
-        appId: Int,
-        userId: Int,
-        permissionName: String,
-        deviceId: Int,
-        flags: Int
-    ): Boolean =
-        if (deviceId == Context.DEVICE_ID_DEFAULT) {
-            with(policy) {
-                setPermissionFlags(appId, userId, permissionName, flags)
-            }
-        } else {
-            val persistentDeviceId = virtualDeviceManagerInternal.getPersistentIdForDevice(deviceId)
-            if (persistentDeviceId != null) {
-                with(devicePolicy) {
-                    setPermissionFlags(appId, persistentDeviceId, userId, permissionName, flags)
-                }
-            } else {
-                Slog.e(LOG_TAG, "Invalid deviceId $deviceId, no cdm association found.")
-                false
-            }
-        }
-
     /**
      * This method does not enforce checks on the caller, should only be called after
      * required checks.
@@ -1623,7 +1539,8 @@
     ) {
         service.mutateState {
             with(policy) {
-                val permissionsFlags = getUidPermissionFlags(appId, userId) ?: return@mutateState
+                val permissionsFlags =
+                    getUidPermissionFlags(appId, userId) ?: return@mutateState
 
                 val permissions = getPermissions()
                 androidPackage.requestedPermissions.forEachIndexed { _, requestedPermission ->
@@ -1744,6 +1661,8 @@
         )
     }
 
+
+
     override fun getAppOpPermissionPackages(permissionName: String): Array<String> {
         requireNotNull(permissionName) { "permissionName cannot be null" }
         val packageNames = ArraySet<String>()
@@ -1960,7 +1879,7 @@
                     println("Permissions:")
                     withIndent {
                         userState.appIdPermissionFlags[appId]?.forEachIndexed {
-                            _, permissionName, flags ->
+                                _, permissionName, flags ->
                             val isGranted = PermissionFlags.isPermissionGranted(flags)
                             println(
                                 "$permissionName: granted=$isGranted, flags=" +
@@ -1969,20 +1888,6 @@
                         }
                     }
 
-                    userState.appIdDevicePermissionFlags[appId]?.forEachIndexed {
-                            _, deviceId, devicePermissionFlags ->
-                        println("Permissions (Device $deviceId):")
-                        withIndent {
-                            devicePermissionFlags.forEachIndexed { _, permissionName, flags ->
-                                val isGranted = PermissionFlags.isPermissionGranted(flags)
-                                println(
-                                    "$permissionName: granted=$isGranted, flags=" +
-                                        PermissionFlags.toString(flags)
-                                )
-                            }
-                        }
-                    }
-
                     println("App ops:")
                     withIndent {
                         userState.appIdAppOpModes[appId]?.forEachIndexed {_, appOpName, appOpMode ->
@@ -2507,7 +2412,7 @@
         }
 
         private fun isAppBackupAndRestoreRunning(uid: Int): Boolean {
-            if (checkUidPermission(uid, Manifest.permission.BACKUP, Context.DEVICE_ID_DEFAULT) !=
+            if (checkUidPermission(uid, Manifest.permission.BACKUP) !=
                 PackageManager.PERMISSION_GRANTED) {
                 return false
             }
diff --git a/services/selectiontoolbar/Android.bp b/services/selectiontoolbar/Android.bp
deleted file mode 100644
index cc6405f..0000000
--- a/services/selectiontoolbar/Android.bp
+++ /dev/null
@@ -1,22 +0,0 @@
-package {
-    // See: http://go/android-license-faq
-    // A large-scale-change added 'default_applicable_licenses' to import
-    // all of the 'license_kinds' from "frameworks_base_license"
-    // to get the below license kinds:
-    //   SPDX-license-identifier-Apache-2.0
-    default_applicable_licenses: ["frameworks_base_license"],
-}
-
-filegroup {
-    name: "services.selectiontoolbar-sources",
-    srcs: ["java/**/*.java"],
-    path: "java",
-    visibility: ["//frameworks/base/services"],
-}
-
-java_library_static {
-    name: "services.selectiontoolbar",
-    defaults: ["platform_service_defaults"],
-    srcs: [":services.selectiontoolbar-sources"],
-    libs: ["services.core"],
-}
diff --git a/services/selectiontoolbar/OWNERS b/services/selectiontoolbar/OWNERS
deleted file mode 100644
index ed9425c..0000000
--- a/services/selectiontoolbar/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-include /core/java/android/view/selectiontoolbar/OWNERS
diff --git a/services/selectiontoolbar/java/com/android/server/selectiontoolbar/RemoteSelectionToolbarRenderService.java b/services/selectiontoolbar/java/com/android/server/selectiontoolbar/RemoteSelectionToolbarRenderService.java
deleted file mode 100644
index ae4227b..0000000
--- a/services/selectiontoolbar/java/com/android/server/selectiontoolbar/RemoteSelectionToolbarRenderService.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.selectiontoolbar;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.os.IBinder;
-import android.service.selectiontoolbar.ISelectionToolbarRenderService;
-import android.service.selectiontoolbar.SelectionToolbarRenderService;
-import android.util.Slog;
-import android.view.selectiontoolbar.ISelectionToolbarCallback;
-import android.view.selectiontoolbar.ShowInfo;
-
-import com.android.internal.infra.AbstractRemoteService;
-import com.android.internal.infra.ServiceConnector;
-
-final class RemoteSelectionToolbarRenderService extends
-        ServiceConnector.Impl<ISelectionToolbarRenderService> {
-    private static final String TAG = "RemoteSelectionToolbarRenderService";
-
-    private static final long TIMEOUT_IDLE_UNBIND_MS =
-            AbstractRemoteService.PERMANENT_BOUND_TIMEOUT_MS;
-
-    private final ComponentName mComponentName;
-    private final IBinder mRemoteCallback;
-
-    RemoteSelectionToolbarRenderService(Context context, ComponentName serviceName, int userId,
-            IBinder callback) {
-        super(context, new Intent(SelectionToolbarRenderService.SERVICE_INTERFACE).setComponent(
-                serviceName), 0, userId, ISelectionToolbarRenderService.Stub::asInterface);
-        mComponentName = serviceName;
-        mRemoteCallback = callback;
-        // Bind right away.
-        connect();
-    }
-
-    @Override // from AbstractRemoteService
-    protected long getAutoDisconnectTimeoutMs() {
-        return TIMEOUT_IDLE_UNBIND_MS;
-    }
-
-    @Override // from ServiceConnector.Impl
-    protected void onServiceConnectionStatusChanged(ISelectionToolbarRenderService service,
-            boolean connected) {
-        try {
-            if (connected) {
-                service.onConnected(mRemoteCallback);
-            }
-        } catch (Exception e) {
-            Slog.w(TAG, "Exception calling onConnected().", e);
-        }
-    }
-
-    public ComponentName getComponentName() {
-        return mComponentName;
-    }
-
-    public void onShow(int callingUid, ShowInfo showInfo, ISelectionToolbarCallback callback) {
-        run((s) -> s.onShow(callingUid, showInfo, callback));
-    }
-
-    public void onHide(long widgetToken) {
-        run((s) -> s.onHide(widgetToken));
-    }
-
-    public void onDismiss(int callingUid, long widgetToken) {
-        run((s) -> s.onDismiss(callingUid, widgetToken));
-    }
-}
diff --git a/services/selectiontoolbar/java/com/android/server/selectiontoolbar/SelectionToolbarManagerService.java b/services/selectiontoolbar/java/com/android/server/selectiontoolbar/SelectionToolbarManagerService.java
deleted file mode 100644
index 3bdf55c..0000000
--- a/services/selectiontoolbar/java/com/android/server/selectiontoolbar/SelectionToolbarManagerService.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.selectiontoolbar;
-
-import android.content.Context;
-import android.util.Slog;
-import android.view.selectiontoolbar.ISelectionToolbarCallback;
-import android.view.selectiontoolbar.ISelectionToolbarManager;
-import android.view.selectiontoolbar.ShowInfo;
-
-import com.android.internal.util.DumpUtils;
-import com.android.server.infra.AbstractMasterSystemService;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-
-/**
- * Entry point service for selection toolbar management.
- */
-public final class SelectionToolbarManagerService extends
-        AbstractMasterSystemService<SelectionToolbarManagerService,
-                SelectionToolbarManagerServiceImpl> {
-
-    private static final String TAG = "SelectionToolbarManagerService";
-
-    @Override
-    public void onStart() {
-        publishBinderService(Context.SELECTION_TOOLBAR_SERVICE,
-                new SelectionToolbarManagerService.SelectionToolbarManagerServiceStub());
-    }
-
-    public SelectionToolbarManagerService(Context context) {
-        super(context, new SelectionToolbarServiceNameResolver(), /* disallowProperty= */
-                null, PACKAGE_UPDATE_POLICY_REFRESH_EAGER);
-    }
-
-    @Override
-    protected SelectionToolbarManagerServiceImpl newServiceLocked(int resolvedUserId,
-            boolean disabled) {
-        return new SelectionToolbarManagerServiceImpl(this, mLock, resolvedUserId);
-    }
-
-    final class SelectionToolbarManagerServiceStub extends ISelectionToolbarManager.Stub {
-
-        @Override
-        public void showToolbar(ShowInfo showInfo, ISelectionToolbarCallback callback, int userId) {
-            synchronized (mLock) {
-                SelectionToolbarManagerServiceImpl service = getServiceForUserLocked(userId);
-                if (service != null) {
-                    service.showToolbar(showInfo, callback);
-                } else {
-                    Slog.v(TAG, "showToolbar(): no service for " + userId);
-                }
-            }
-        }
-
-        @Override
-        public void hideToolbar(long widgetToken, int userId) {
-            synchronized (mLock) {
-                SelectionToolbarManagerServiceImpl service = getServiceForUserLocked(userId);
-                if (service != null) {
-                    service.hideToolbar(widgetToken);
-                } else {
-                    Slog.v(TAG, "hideToolbar(): no service for " + userId);
-                }
-            }
-        }
-
-        @Override
-        public void dismissToolbar(long widgetToken, int userId) {
-            synchronized (mLock) {
-                SelectionToolbarManagerServiceImpl service = getServiceForUserLocked(userId);
-                if (service != null) {
-                    service.dismissToolbar(widgetToken);
-                } else {
-                    Slog.v(TAG, "dismissToolbar(): no service for " + userId);
-                }
-            }
-        }
-
-        @Override
-        public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-            if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
-
-            synchronized (mLock) {
-                dumpLocked("", pw);
-            }
-        }
-    }
-}
diff --git a/services/selectiontoolbar/java/com/android/server/selectiontoolbar/SelectionToolbarManagerServiceImpl.java b/services/selectiontoolbar/java/com/android/server/selectiontoolbar/SelectionToolbarManagerServiceImpl.java
deleted file mode 100644
index c8d153a..0000000
--- a/services/selectiontoolbar/java/com/android/server/selectiontoolbar/SelectionToolbarManagerServiceImpl.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.selectiontoolbar;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.UserIdInt;
-import android.app.AppGlobals;
-import android.content.ComponentName;
-import android.content.pm.PackageManager;
-import android.content.pm.ServiceInfo;
-import android.os.Binder;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.service.selectiontoolbar.ISelectionToolbarRenderServiceCallback;
-import android.util.Slog;
-import android.view.selectiontoolbar.ISelectionToolbarCallback;
-import android.view.selectiontoolbar.ShowInfo;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.server.LocalServices;
-import com.android.server.infra.AbstractPerUserSystemService;
-import com.android.server.input.InputManagerInternal;
-
-final class SelectionToolbarManagerServiceImpl extends
-        AbstractPerUserSystemService<SelectionToolbarManagerServiceImpl,
-                SelectionToolbarManagerService> {
-
-    private static final String TAG = "SelectionToolbarManagerServiceImpl";
-
-    @GuardedBy("mLock")
-    @Nullable
-    private RemoteSelectionToolbarRenderService mRemoteService;
-
-    InputManagerInternal mInputManagerInternal;
-    private final SelectionToolbarRenderServiceRemoteCallback mRemoteServiceCallback =
-            new SelectionToolbarRenderServiceRemoteCallback();
-
-    protected SelectionToolbarManagerServiceImpl(@NonNull SelectionToolbarManagerService master,
-            @NonNull Object lock, int userId) {
-        super(master, lock, userId);
-        mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
-        updateRemoteServiceLocked();
-    }
-
-    @GuardedBy("mLock")
-    @Override // from PerUserSystemService
-    protected ServiceInfo newServiceInfoLocked(@NonNull ComponentName serviceComponent)
-            throws PackageManager.NameNotFoundException {
-        return getServiceInfoOrThrow(serviceComponent, mUserId);
-    }
-
-    @GuardedBy("mLock")
-    @Override // from PerUserSystemService
-    protected boolean updateLocked(boolean disabled) {
-        final boolean enabledChanged = super.updateLocked(disabled);
-        updateRemoteServiceLocked();
-        return enabledChanged;
-    }
-
-    /**
-     * Updates the reference to the remote service.
-     */
-    @GuardedBy("mLock")
-    private void updateRemoteServiceLocked() {
-        if (mRemoteService != null) {
-            Slog.d(TAG, "updateRemoteService(): destroying old remote service");
-            mRemoteService.unbind();
-            mRemoteService = null;
-        }
-    }
-
-    @GuardedBy("mLock")
-    void showToolbar(ShowInfo showInfo, ISelectionToolbarCallback callback) {
-        final RemoteSelectionToolbarRenderService remoteService = ensureRemoteServiceLocked();
-        if (remoteService != null) {
-            remoteService.onShow(Binder.getCallingUid(), showInfo, callback);
-        }
-    }
-
-    @GuardedBy("mLock")
-    void hideToolbar(long widgetToken) {
-        final RemoteSelectionToolbarRenderService remoteService = ensureRemoteServiceLocked();
-        if (remoteService != null) {
-            remoteService.onHide(widgetToken);
-        }
-    }
-
-    @GuardedBy("mLock")
-    void dismissToolbar(long widgetToken) {
-        final RemoteSelectionToolbarRenderService remoteService = ensureRemoteServiceLocked();
-        if (remoteService != null) {
-            remoteService.onDismiss(Binder.getCallingUid(), widgetToken);
-        }
-    }
-
-    @GuardedBy("mLock")
-    @Nullable
-    private RemoteSelectionToolbarRenderService ensureRemoteServiceLocked() {
-        if (mRemoteService == null) {
-            final String serviceName = getComponentNameLocked();
-            final ComponentName serviceComponent = ComponentName.unflattenFromString(serviceName);
-            mRemoteService = new RemoteSelectionToolbarRenderService(getContext(), serviceComponent,
-                    mUserId, mRemoteServiceCallback);
-        }
-        return mRemoteService;
-    }
-
-    private static ServiceInfo getServiceInfoOrThrow(ComponentName comp, @UserIdInt int userId)
-            throws PackageManager.NameNotFoundException {
-        int flags = PackageManager.GET_META_DATA;
-
-        ServiceInfo si = null;
-        try {
-            si = AppGlobals.getPackageManager().getServiceInfo(comp, flags, userId);
-        } catch (RemoteException e) {
-        }
-        if (si == null) {
-            throw new PackageManager.NameNotFoundException("Could not get serviceInfo for "
-                    + comp.flattenToShortString());
-        }
-        return si;
-    }
-
-    private void transferTouchFocus(IBinder source, IBinder target) {
-        mInputManagerInternal.transferTouchFocus(source, target);
-    }
-
-    private final class SelectionToolbarRenderServiceRemoteCallback extends
-            ISelectionToolbarRenderServiceCallback.Stub {
-
-        @Override
-        public void transferTouch(IBinder source, IBinder target) {
-            transferTouchFocus(source, target);
-        }
-    }
-}
diff --git a/services/selectiontoolbar/java/com/android/server/selectiontoolbar/SelectionToolbarServiceNameResolver.java b/services/selectiontoolbar/java/com/android/server/selectiontoolbar/SelectionToolbarServiceNameResolver.java
deleted file mode 100644
index 99b0f25..0000000
--- a/services/selectiontoolbar/java/com/android/server/selectiontoolbar/SelectionToolbarServiceNameResolver.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.selectiontoolbar;
-
-import android.service.selectiontoolbar.DefaultSelectionToolbarRenderService;
-
-import com.android.server.infra.ServiceNameResolver;
-
-import java.io.PrintWriter;
-
-final class SelectionToolbarServiceNameResolver implements ServiceNameResolver {
-
-    // TODO: move to SysUi or ExtServices
-    private static final String SELECTION_TOOLBAR_SERVICE_NAME =
-            "android/" + DefaultSelectionToolbarRenderService.class.getName();
-
-    @Override
-    public String getDefaultServiceName(int userId) {
-        return SELECTION_TOOLBAR_SERVICE_NAME;
-    }
-
-    @Override
-    public void dumpShort(PrintWriter pw) {
-        pw.print("service="); pw.print(SELECTION_TOOLBAR_SERVICE_NAME);
-    }
-
-    @Override
-    public void dumpShort(PrintWriter pw, int userId) {
-        pw.print("defaultService="); pw.print(getDefaultServiceName(userId));
-    }
-}
diff --git a/services/tests/PackageManagerServiceTests/server/src/com/android/server/pm/PackageManagerTests.java b/services/tests/PackageManagerServiceTests/server/src/com/android/server/pm/PackageManagerTests.java
index dc92376..7552800 100644
--- a/services/tests/PackageManagerServiceTests/server/src/com/android/server/pm/PackageManagerTests.java
+++ b/services/tests/PackageManagerServiceTests/server/src/com/android/server/pm/PackageManagerTests.java
@@ -56,7 +56,7 @@
 import android.os.RemoteException;
 import android.os.StatFs;
 import android.os.SystemClock;
-import android.platform.test.annotations.Presubmit;
+import android.platform.test.annotations.Postsubmit;
 import android.provider.DeviceConfig;
 import android.provider.Settings;
 import android.provider.Settings.SettingNotFoundException;
@@ -93,7 +93,7 @@
 import java.util.concurrent.SynchronousQueue;
 import java.util.concurrent.TimeUnit;
 
-@Presubmit
+@Postsubmit
 public class PackageManagerTests extends AndroidTestCase {
     private static final boolean localLOGV = true;
 
@@ -966,9 +966,11 @@
     }
 
     private static void assertUninstalled(ApplicationInfo info) throws Exception {
-        File nativeLibraryFile = new File(info.nativeLibraryDir);
-        assertFalse("Native library directory " + info.nativeLibraryDir
-                + " should be erased", nativeLibraryFile.exists());
+        if (info.nativeLibraryDir != null) {
+            File nativeLibraryFile = new File(info.nativeLibraryDir);
+            assertFalse("Native library directory " + info.nativeLibraryDir
+                    + " should be erased", nativeLibraryFile.exists());
+        }
     }
 
     public void deleteFromRawResource(int iFlags, int dFlags) throws Exception {
@@ -2883,14 +2885,15 @@
                     break;
                 }
             }
-            assertNotNull("activities should not be null", packageInfo.activities);
-            assertNotNull("configPreferences should not be null", packageInfo.configPreferences);
-            assertNotNull("instrumentation should not be null", packageInfo.instrumentation);
-            assertNotNull("permissions should not be null", packageInfo.permissions);
-            assertNotNull("providers should not be null", packageInfo.providers);
-            assertNotNull("receivers should not be null", packageInfo.receivers);
-            assertNotNull("services should not be null", packageInfo.services);
-            assertNotNull("signatures should not be null", packageInfo.signatures);
+            assertNotNull("applicationInfo should not be null", packageInfo.applicationInfo);
+            assertNull("activities should be null", packageInfo.activities);
+            assertNull("configPreferences should be null", packageInfo.configPreferences);
+            assertNull("instrumentation should be null", packageInfo.instrumentation);
+            assertNull("permissions should be null", packageInfo.permissions);
+            assertNull("providers should be null", packageInfo.providers);
+            assertNull("receivers should be null", packageInfo.receivers);
+            assertNull("services should be null", packageInfo.services);
+            assertNotNull("signingInfo should not be null", packageInfo.signingInfo);
         } finally {
             cleanUpInstall(ip);
         }
diff --git a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/pkg/PackageStateTest.kt b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/pkg/PackageStateTest.kt
index 5a733c7..d217d63 100644
--- a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/pkg/PackageStateTest.kt
+++ b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/pkg/PackageStateTest.kt
@@ -29,7 +29,6 @@
 import com.android.server.pm.parsing.pkg.PackageImpl
 import com.android.server.pm.pkg.AndroidPackage
 import com.android.server.pm.pkg.PackageState
-import com.android.server.pm.pkg.PackageStateImpl
 import com.android.server.pm.pkg.PackageUserState
 import com.android.server.pm.pkg.PackageUserStateImpl
 import com.android.server.pm.pkg.component.ParsedActivity
@@ -125,7 +124,7 @@
 
         fillMissingData(packageState, pkg as PackageImpl)
 
-        visitType(seenTypes, emptyList(), PackageStateImpl.copy(packageState),
+        visitType(seenTypes, emptyList(), PackageSetting(packageState, true),
             PackageState::class.starProjectedType)
         visitType(seenTypes, emptyList(), pkg, AndroidPackage::class.starProjectedType)
         visitType(seenTypes, emptyList(), packageState.getUserStateOrDefault(0),
diff --git a/services/tests/displayservicetests/src/com/android/server/display/DisplayDeviceConfigTest.java b/services/tests/displayservicetests/src/com/android/server/display/DisplayDeviceConfigTest.java
index da7a6a1..d9338a9 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/DisplayDeviceConfigTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/DisplayDeviceConfigTest.java
@@ -22,8 +22,10 @@
 
 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.assertTrue;
 import static org.mockito.ArgumentMatchers.anyFloat;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.Mockito.mock;
@@ -32,6 +34,7 @@
 import android.content.Context;
 import android.content.res.Resources;
 import android.content.res.TypedArray;
+import android.hardware.display.DisplayManagerInternal;
 import android.os.Temperature;
 import android.util.SparseArray;
 import android.util.Spline;
@@ -74,8 +77,7 @@
     private static final int[] HIGH_AMBIENT_THRESHOLD_OF_PEAK_REFRESH_RATE = new int[]{-1, 30000};
     private static final float[] NITS = {2, 500, 800};
     private static final float[] BRIGHTNESS = {0, 0.62f, 1};
-    private static final Spline NITS_TO_BRIGHTNESS_SPLINE =
-            Spline.createSpline(NITS, BRIGHTNESS);
+    private static final Spline NITS_TO_BRIGHTNESS_SPLINE = Spline.createSpline(NITS, BRIGHTNESS);
 
     private DisplayDeviceConfig mDisplayDeviceConfig;
     private static final float ZERO_DELTA = 0.0f;
@@ -178,40 +180,174 @@
         assertEquals(82, mDisplayDeviceConfig.getDefaultRefreshRateInHbmHdr());
         assertEquals(83, mDisplayDeviceConfig.getDefaultRefreshRateInHbmSunlight());
 
-        assertEquals("sensor_12345",
-                mDisplayDeviceConfig.getScreenOffBrightnessSensor().type);
-        assertEquals("Sensor 12345",
-                mDisplayDeviceConfig.getScreenOffBrightnessSensor().name);
+        assertNotNull(mDisplayDeviceConfig.getHostUsiVersion());
+        assertEquals(mDisplayDeviceConfig.getHostUsiVersion().getMajorVersion(), 2);
+        assertEquals(mDisplayDeviceConfig.getHostUsiVersion().getMinorVersion(), 0);
+    }
 
-        assertArrayEquals(new int[]{-1, 10, 20, 30, 40},
-                mDisplayDeviceConfig.getScreenOffBrightnessSensorValueToLux());
+    @Test
+    public void testConfigValuesFromConfigResource() {
+        setupDisplayDeviceConfigFromConfigResourceFile();
+        verifyConfigValuesFromConfigResource();
+    }
+
+    @Test
+    public void testThermalRefreshRateThrottlingFromDisplayConfig() throws IOException {
+        setupDisplayDeviceConfigFromDisplayConfigFile();
+
+        SparseArray<SurfaceControl.RefreshRateRange> defaultMap =
+                mDisplayDeviceConfig.getThermalRefreshRateThrottlingData(null);
+        assertNotNull(defaultMap);
+        assertEquals(2, defaultMap.size());
+        assertEquals(30, defaultMap.get(Temperature.THROTTLING_CRITICAL).min, SMALL_DELTA);
+        assertEquals(60, defaultMap.get(Temperature.THROTTLING_CRITICAL).max, SMALL_DELTA);
+        assertEquals(0, defaultMap.get(Temperature.THROTTLING_SHUTDOWN).min, SMALL_DELTA);
+        assertEquals(30, defaultMap.get(Temperature.THROTTLING_SHUTDOWN).max, SMALL_DELTA);
+
+        SparseArray<SurfaceControl.RefreshRateRange> testMap =
+                mDisplayDeviceConfig.getThermalRefreshRateThrottlingData("test");
+        assertNotNull(testMap);
+        assertEquals(1, testMap.size());
+        assertEquals(60, testMap.get(Temperature.THROTTLING_EMERGENCY).min, SMALL_DELTA);
+        assertEquals(90, testMap.get(Temperature.THROTTLING_EMERGENCY).max, SMALL_DELTA);
+    }
+
+    @Test
+    public void testValidLuxThrottling() throws Exception {
+        setupDisplayDeviceConfigFromDisplayConfigFile();
+
+        Map<DisplayDeviceConfig.BrightnessLimitMapType, Map<Float, Float>> luxThrottlingData =
+                mDisplayDeviceConfig.getLuxThrottlingData();
+        assertEquals(2, luxThrottlingData.size());
+
+        Map<Float, Float> adaptiveOnBrightnessPoints = luxThrottlingData.get(
+                DisplayDeviceConfig.BrightnessLimitMapType.ADAPTIVE);
+        assertEquals(2, adaptiveOnBrightnessPoints.size());
+        assertEquals(0.3f, adaptiveOnBrightnessPoints.get(1000f), SMALL_DELTA);
+        assertEquals(0.5f, adaptiveOnBrightnessPoints.get(5000f), SMALL_DELTA);
+
+        Map<Float, Float> adaptiveOffBrightnessPoints = luxThrottlingData.get(
+                DisplayDeviceConfig.BrightnessLimitMapType.DEFAULT);
+        assertEquals(2, adaptiveOffBrightnessPoints.size());
+        assertEquals(0.35f, adaptiveOffBrightnessPoints.get(1500f), SMALL_DELTA);
+        assertEquals(0.55f, adaptiveOffBrightnessPoints.get(5500f), SMALL_DELTA);
+    }
+
+    @Test
+    public void testInvalidLuxThrottling() throws Exception {
+        setupDisplayDeviceConfigFromDisplayConfigFile(
+                getContent(getInvalidLuxThrottling(), getValidProxSensor()));
+
+        Map<DisplayDeviceConfig.BrightnessLimitMapType, Map<Float, Float>> luxThrottlingData =
+                mDisplayDeviceConfig.getLuxThrottlingData();
+        assertEquals(1, luxThrottlingData.size());
+
+        Map<Float, Float> adaptiveOnBrightnessPoints = luxThrottlingData.get(
+                DisplayDeviceConfig.BrightnessLimitMapType.ADAPTIVE);
+        assertEquals(1, adaptiveOnBrightnessPoints.size());
+        assertEquals(0.3f, adaptiveOnBrightnessPoints.get(1000f), SMALL_DELTA);
+    }
+
+    @Test
+    public void testFallbackToConfigResource() throws IOException {
+        setupDisplayDeviceConfigFromConfigResourceFile();
+
+        // Empty display config file
+        setupDisplayDeviceConfigFromDisplayConfigFile(
+                "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n"
+                + "<displayConfiguration />\n");
+
+        // We should fall back to the config resource
+        verifyConfigValuesFromConfigResource();
+    }
+
+    @Test
+    public void testDensityMappingFromDisplayConfig() throws IOException {
+        setupDisplayDeviceConfigFromDisplayConfigFile();
+
+        assertEquals(120, mDisplayDeviceConfig.getDensityMapping()
+                .getDensityForResolution(720, 480));
+        assertEquals(213, mDisplayDeviceConfig.getDensityMapping()
+                .getDensityForResolution(1280, 720));
+        assertEquals(320, mDisplayDeviceConfig.getDensityMapping()
+                .getDensityForResolution(1920, 1080));
+        assertEquals(640, mDisplayDeviceConfig.getDensityMapping()
+                .getDensityForResolution(3840, 2160));
+    }
+
+    @Test
+    public void testHighBrightnessModeDataFromDisplayConfig() throws IOException {
+        setupDisplayDeviceConfigFromDisplayConfigFile();
+
+        DisplayDeviceConfig.HighBrightnessModeData hbmData =
+                mDisplayDeviceConfig.getHighBrightnessModeData();
+        assertNotNull(hbmData);
+        assertEquals(BRIGHTNESS[1], hbmData.transitionPoint, ZERO_DELTA);
+        assertEquals(10000, hbmData.minimumLux, ZERO_DELTA);
+        assertEquals(1800 * 1000, hbmData.timeWindowMillis);
+        assertEquals(300 * 1000, hbmData.timeMaxMillis);
+        assertEquals(60 * 1000, hbmData.timeMinMillis);
+        assertFalse(hbmData.allowInLowPowerMode);
+        assertEquals(0.6f, hbmData.minimumHdrPercentOfScreen, ZERO_DELTA);
+
+        List<DisplayManagerInternal.RefreshRateLimitation> refreshRateLimitations =
+                mDisplayDeviceConfig.getRefreshRateLimitations();
+        assertEquals(1, refreshRateLimitations.size());
+        assertEquals(DisplayManagerInternal.REFRESH_RATE_LIMIT_HIGH_BRIGHTNESS_MODE,
+                refreshRateLimitations.get(0).type);
+        assertEquals(120, refreshRateLimitations.get(0).range.min, ZERO_DELTA);
+        assertEquals(120, refreshRateLimitations.get(0).range.max, ZERO_DELTA);
+
+        // Max desired Hdr/SDR ratio upper-bounds the HDR brightness.
+        assertTrue(mDisplayDeviceConfig.hasSdrToHdrRatioSpline());
+        assertEquals(NITS_TO_BRIGHTNESS_SPLINE.interpolate(500 * 1.6f),
+                mDisplayDeviceConfig.getHdrBrightnessFromSdr(
+                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(500), Float.POSITIVE_INFINITY),
+                ZERO_DELTA);
+        assertEquals(NITS_TO_BRIGHTNESS_SPLINE.interpolate(500),
+                mDisplayDeviceConfig.getHdrBrightnessFromSdr(
+                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(500), 1.0f),
+                ZERO_DELTA);
+        assertEquals(NITS_TO_BRIGHTNESS_SPLINE.interpolate(500 * 1.25f),
+                mDisplayDeviceConfig.getHdrBrightnessFromSdr(
+                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(500), 1.25f),
+                SMALL_DELTA);
+        assertEquals(NITS_TO_BRIGHTNESS_SPLINE.interpolate(2 * 4),
+                mDisplayDeviceConfig.getHdrBrightnessFromSdr(
+                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(2), Float.POSITIVE_INFINITY),
+                SMALL_DELTA);
+    }
+
+    @Test
+    public void testThermalBrightnessThrottlingDataFromDisplayConfig() throws IOException {
+        setupDisplayDeviceConfigFromDisplayConfigFile();
 
         List<DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel>
                 defaultThrottlingLevels = new ArrayList<>();
         defaultThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.light), 0.4f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.light), 0.4f
+                ));
         defaultThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.moderate), 0.3f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.moderate), 0.3f
+                ));
         defaultThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.severe), 0.2f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.severe), 0.2f
+                ));
         defaultThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.critical), 0.1f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.critical), 0.1f
+                ));
         defaultThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.emergency), 0.05f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.emergency), 0.05f
+                ));
         defaultThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.shutdown), 0.025f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.shutdown), 0.025f
+                ));
 
         DisplayDeviceConfig.ThermalBrightnessThrottlingData defaultThrottlingData =
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData(defaultThrottlingLevels);
@@ -220,28 +356,28 @@
                 concurrentThrottlingLevels = new ArrayList<>();
         concurrentThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.light), 0.2f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.light), 0.2f
+                ));
         concurrentThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.moderate), 0.15f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.moderate), 0.15f
+                ));
         concurrentThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.severe), 0.1f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.severe), 0.1f
+                ));
         concurrentThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.critical), 0.05f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.critical), 0.05f
+                ));
         concurrentThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.emergency), 0.025f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.emergency), 0.025f
+                ));
         concurrentThrottlingLevels.add(
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData.ThrottlingLevel(
-                DisplayDeviceConfig.convertThermalStatus(ThermalStatus.shutdown), 0.0125f
-        ));
+                        DisplayDeviceConfig.convertThermalStatus(ThermalStatus.shutdown), 0.0125f
+                ));
         DisplayDeviceConfig.ThermalBrightnessThrottlingData concurrentThrottlingData =
                 new DisplayDeviceConfig.ThermalBrightnessThrottlingData(concurrentThrottlingLevels);
 
@@ -252,29 +388,87 @@
 
         assertEquals(throttlingDataMap,
                 mDisplayDeviceConfig.getThermalBrightnessThrottlingDataMapByThrottlingId());
-
-        assertNotNull(mDisplayDeviceConfig.getHostUsiVersion());
-        assertEquals(mDisplayDeviceConfig.getHostUsiVersion().getMajorVersion(), 2);
-        assertEquals(mDisplayDeviceConfig.getHostUsiVersion().getMinorVersion(), 0);
-
-        // Max desired Hdr/SDR ratio upper-bounds the HDR brightness.
-        assertEquals(1.0f,
-                mDisplayDeviceConfig.getHdrBrightnessFromSdr(0.62f, Float.POSITIVE_INFINITY),
-                ZERO_DELTA);
-        assertEquals(0.62f,
-                mDisplayDeviceConfig.getHdrBrightnessFromSdr(0.62f, 1.0f),
-                ZERO_DELTA);
-        assertEquals(0.77787f,
-                mDisplayDeviceConfig.getHdrBrightnessFromSdr(0.62f, 1.25f),
-                SMALL_DELTA);
-
-        // Todo: Add asserts for DensityMapping,
-        // HighBrightnessModeData AmbientLightSensor, RefreshRateLimitations and ProximitySensor.
     }
 
     @Test
-    public void testConfigValuesFromConfigResource() {
+    public void testAmbientLightSensorFromDisplayConfig() throws IOException {
+        setupDisplayDeviceConfigFromDisplayConfigFile();
+
+        assertEquals("test_light_sensor",
+                mDisplayDeviceConfig.getAmbientLightSensor().type);
+        assertEquals("Test Ambient Light Sensor",
+                mDisplayDeviceConfig.getAmbientLightSensor().name);
+        assertEquals(60, mDisplayDeviceConfig.getAmbientLightSensor().minRefreshRate, ZERO_DELTA);
+        assertEquals(120, mDisplayDeviceConfig.getAmbientLightSensor().maxRefreshRate, ZERO_DELTA);
+    }
+
+    @Test
+    public void testScreenOffBrightnessSensorFromDisplayConfig() throws IOException {
+        setupDisplayDeviceConfigFromDisplayConfigFile();
+
+        assertEquals("test_binned_brightness_sensor",
+                mDisplayDeviceConfig.getScreenOffBrightnessSensor().type);
+        assertEquals("Test Binned Brightness Sensor",
+                mDisplayDeviceConfig.getScreenOffBrightnessSensor().name);
+
+        assertArrayEquals(new int[]{ -1, 10, 20, 30, 40 },
+                mDisplayDeviceConfig.getScreenOffBrightnessSensorValueToLux());
+    }
+
+    @Test
+    public void testProximitySensorFromDisplayConfig() throws IOException {
+        setupDisplayDeviceConfigFromDisplayConfigFile();
+
+        assertEquals("test_proximity_sensor",
+                mDisplayDeviceConfig.getProximitySensor().type);
+        assertEquals("Test Proximity Sensor",
+                mDisplayDeviceConfig.getProximitySensor().name);
+    }
+
+    @Test
+    public void testProximitySensorWithEmptyValuesFromDisplayConfig() throws IOException {
+        setupDisplayDeviceConfigFromDisplayConfigFile(
+                getContent(getValidLuxThrottling(), getProxSensorWithEmptyValues()));
+        assertNull(mDisplayDeviceConfig.getProximitySensor());
+    }
+
+    @Test
+    public void testBlockingZoneThresholdsFromDisplayConfig() throws IOException {
+        setupDisplayDeviceConfigFromDisplayConfigFile();
+
+        assertArrayEquals(new float[]{ NITS_TO_BRIGHTNESS_SPLINE.interpolate(50),
+                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(300),
+                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(300), -1},
+                mDisplayDeviceConfig.getLowDisplayBrightnessThresholds(), SMALL_DELTA);
+        assertArrayEquals(new float[]{50, 60, -1, 60},
+                mDisplayDeviceConfig.getLowAmbientBrightnessThresholds(), ZERO_DELTA);
+        assertArrayEquals(new float[]{ NITS_TO_BRIGHTNESS_SPLINE.interpolate(80),
+                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(100),
+                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(100), -1},
+                mDisplayDeviceConfig.getHighDisplayBrightnessThresholds(), SMALL_DELTA);
+        assertArrayEquals(new float[]{70, 80, -1, 80},
+                mDisplayDeviceConfig.getHighAmbientBrightnessThresholds(), ZERO_DELTA);
+    }
+
+    @Test
+    public void testBlockingZoneThresholdsFromConfigResource() {
         setupDisplayDeviceConfigFromConfigResourceFile();
+
+        assertArrayEquals(displayBrightnessThresholdsIntToFloat(
+                        LOW_BRIGHTNESS_THRESHOLD_OF_PEAK_REFRESH_RATE),
+                mDisplayDeviceConfig.getLowDisplayBrightnessThresholds(), SMALL_DELTA);
+        assertArrayEquals(ambientBrightnessThresholdsIntToFloat(
+                        LOW_AMBIENT_THRESHOLD_OF_PEAK_REFRESH_RATE),
+                mDisplayDeviceConfig.getLowAmbientBrightnessThresholds(), ZERO_DELTA);
+        assertArrayEquals(displayBrightnessThresholdsIntToFloat(
+                        HIGH_BRIGHTNESS_THRESHOLD_OF_PEAK_REFRESH_RATE),
+                mDisplayDeviceConfig.getHighDisplayBrightnessThresholds(), SMALL_DELTA);
+        assertArrayEquals(ambientBrightnessThresholdsIntToFloat(
+                        HIGH_AMBIENT_THRESHOLD_OF_PEAK_REFRESH_RATE),
+                mDisplayDeviceConfig.getHighAmbientBrightnessThresholds(), ZERO_DELTA);
+    }
+
+    private void verifyConfigValuesFromConfigResource() {
         assertNull(mDisplayDeviceConfig.getName());
         assertArrayEquals(mDisplayDeviceConfig.getAutoBrightnessBrighteningLevelsNits(), new
                 float[]{2.0f, 200.0f, 600.0f}, ZERO_DELTA);
@@ -342,100 +536,8 @@
         assertEquals(mDisplayDeviceConfig.getDefaultRefreshRateInHbmHdr(),
                 DEFAULT_REFRESH_RATE_IN_HBM_HDR);
 
-        // Todo: Add asserts for ThermalBrightnessThrottlingData, DensityMapping,
-        // HighBrightnessModeData AmbientLightSensor, RefreshRateLimitations and ProximitySensor.
-    }
-
-    @Test
-    public void testThermalRefreshRateThrottlingFromDisplayConfig() throws IOException {
-        setupDisplayDeviceConfigFromDisplayConfigFile();
-
-        SparseArray<SurfaceControl.RefreshRateRange> defaultMap =
-                mDisplayDeviceConfig.getThermalRefreshRateThrottlingData(null);
-        assertNotNull(defaultMap);
-        assertEquals(2, defaultMap.size());
-        assertEquals(30, defaultMap.get(Temperature.THROTTLING_CRITICAL).min, SMALL_DELTA);
-        assertEquals(60, defaultMap.get(Temperature.THROTTLING_CRITICAL).max, SMALL_DELTA);
-        assertEquals(0, defaultMap.get(Temperature.THROTTLING_SHUTDOWN).min, SMALL_DELTA);
-        assertEquals(30, defaultMap.get(Temperature.THROTTLING_SHUTDOWN).max, SMALL_DELTA);
-
-        SparseArray<SurfaceControl.RefreshRateRange> testMap =
-                mDisplayDeviceConfig.getThermalRefreshRateThrottlingData("test");
-        assertNotNull(testMap);
-        assertEquals(1, testMap.size());
-        assertEquals(60, testMap.get(Temperature.THROTTLING_EMERGENCY).min, SMALL_DELTA);
-        assertEquals(90, testMap.get(Temperature.THROTTLING_EMERGENCY).max, SMALL_DELTA);
-    }
-
-    @Test
-    public void testValidLuxThrottling() throws Exception {
-        setupDisplayDeviceConfigFromDisplayConfigFile();
-
-        Map<DisplayDeviceConfig.BrightnessLimitMapType, Map<Float, Float>> luxThrottlingData =
-                mDisplayDeviceConfig.getLuxThrottlingData();
-        assertEquals(2, luxThrottlingData.size());
-
-        Map<Float, Float> adaptiveOnBrightnessPoints = luxThrottlingData.get(
-                DisplayDeviceConfig.BrightnessLimitMapType.ADAPTIVE);
-        assertEquals(2, adaptiveOnBrightnessPoints.size());
-        assertEquals(0.3f, adaptiveOnBrightnessPoints.get(1000f), SMALL_DELTA);
-        assertEquals(0.5f, adaptiveOnBrightnessPoints.get(5000f), SMALL_DELTA);
-
-        Map<Float, Float> adaptiveOffBrightnessPoints = luxThrottlingData.get(
-                DisplayDeviceConfig.BrightnessLimitMapType.DEFAULT);
-        assertEquals(2, adaptiveOffBrightnessPoints.size());
-        assertEquals(0.35f, adaptiveOffBrightnessPoints.get(1500f), SMALL_DELTA);
-        assertEquals(0.55f, adaptiveOffBrightnessPoints.get(5500f), SMALL_DELTA);
-    }
-
-    @Test
-    public void testInvalidLuxThrottling() throws Exception {
-        setupDisplayDeviceConfigFromDisplayConfigFile(getContent(getInvalidLuxThrottling()));
-
-        Map<DisplayDeviceConfig.BrightnessLimitMapType, Map<Float, Float>> luxThrottlingData =
-                mDisplayDeviceConfig.getLuxThrottlingData();
-        assertEquals(1, luxThrottlingData.size());
-
-        Map<Float, Float> adaptiveOnBrightnessPoints = luxThrottlingData.get(
-                DisplayDeviceConfig.BrightnessLimitMapType.ADAPTIVE);
-        assertEquals(1, adaptiveOnBrightnessPoints.size());
-        assertEquals(0.3f, adaptiveOnBrightnessPoints.get(1000f), SMALL_DELTA);
-    }
-
-    @Test
-    public void testBlockingZoneThresholdsFromDisplayConfig() throws IOException {
-        setupDisplayDeviceConfigFromDisplayConfigFile();
-
-        assertArrayEquals(new float[]{ NITS_TO_BRIGHTNESS_SPLINE.interpolate(50),
-                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(300),
-                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(300), -1},
-                mDisplayDeviceConfig.getLowDisplayBrightnessThresholds(), SMALL_DELTA);
-        assertArrayEquals(new float[]{50, 60, -1, 60},
-                mDisplayDeviceConfig.getLowAmbientBrightnessThresholds(), ZERO_DELTA);
-        assertArrayEquals(new float[]{ NITS_TO_BRIGHTNESS_SPLINE.interpolate(80),
-                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(100),
-                        NITS_TO_BRIGHTNESS_SPLINE.interpolate(100), -1},
-                mDisplayDeviceConfig.getHighDisplayBrightnessThresholds(), SMALL_DELTA);
-        assertArrayEquals(new float[]{70, 80, -1, 80},
-                mDisplayDeviceConfig.getHighAmbientBrightnessThresholds(), ZERO_DELTA);
-    }
-
-    @Test
-    public void testBlockingZoneThresholdsFromConfigResource() {
-        setupDisplayDeviceConfigFromConfigResourceFile();
-
-        assertArrayEquals(displayBrightnessThresholdsIntToFloat(
-                LOW_BRIGHTNESS_THRESHOLD_OF_PEAK_REFRESH_RATE),
-                mDisplayDeviceConfig.getLowDisplayBrightnessThresholds(), SMALL_DELTA);
-        assertArrayEquals(ambientBrightnessThresholdsIntToFloat(
-                LOW_AMBIENT_THRESHOLD_OF_PEAK_REFRESH_RATE),
-                mDisplayDeviceConfig.getLowAmbientBrightnessThresholds(), ZERO_DELTA);
-        assertArrayEquals(displayBrightnessThresholdsIntToFloat(
-                HIGH_BRIGHTNESS_THRESHOLD_OF_PEAK_REFRESH_RATE),
-                mDisplayDeviceConfig.getHighDisplayBrightnessThresholds(), SMALL_DELTA);
-        assertArrayEquals(ambientBrightnessThresholdsIntToFloat(
-                HIGH_AMBIENT_THRESHOLD_OF_PEAK_REFRESH_RATE),
-                mDisplayDeviceConfig.getHighAmbientBrightnessThresholds(), ZERO_DELTA);
+        assertEquals("test_light_sensor", mDisplayDeviceConfig.getAmbientLightSensor().type);
+        assertEquals("", mDisplayDeviceConfig.getAmbientLightSensor().name);
     }
 
     private String getValidLuxThrottling() {
@@ -541,14 +643,50 @@
                + "</refreshRateThrottlingMap>\n";
     }
 
-    private String getContent() {
-        return getContent(getValidLuxThrottling());
+    private String getValidProxSensor() {
+        return "<proxSensor>\n"
+                +   "<type>test_proximity_sensor</type>\n"
+                +   "<name>Test Proximity Sensor</name>\n"
+                + "</proxSensor>\n";
     }
 
-    private String getContent(String brightnessCapConfig) {
+    private String getProxSensorWithEmptyValues() {
+        return "<proxSensor>\n"
+                +   "<type></type>\n"
+                +   "<name></name>\n"
+                + "</proxSensor>\n";
+    }
+
+    private String getContent() {
+        return getContent(getValidLuxThrottling(), getValidProxSensor());
+    }
+
+    private String getContent(String brightnessCapConfig, String proxSensor) {
         return "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n"
                 + "<displayConfiguration>\n"
-                +   "<name>Example Display</name>"
+                +   "<name>Example Display</name>\n"
+                +   "<densityMapping>\n"
+                +       "<density>\n"
+                +           "<height>480</height>\n"
+                +           "<width>720</width>\n"
+                +           "<density>120</density>\n"
+                +       "</density>\n"
+                +       "<density>\n"
+                +           "<height>720</height>\n"
+                +           "<width>1280</width>\n"
+                +           "<density>213</density>\n"
+                +       "</density>\n"
+                +       "<density>\n"
+                +           "<height>1080</height>\n"
+                +           "<width>1920</width>\n"
+                +           "<density>320</density>\n"
+                +       "</density>\n"
+                +       "<density>\n"
+                +           "<height>2160</height>\n"
+                +           "<width>3840</width>\n"
+                +           "<density>640</density>\n"
+                +       "</density>\n"
+                +   "</densityMapping>\n"
                 +   "<screenBrightnessMap>\n"
                 +       "<point>\n"
                 +           "<value>" + BRIGHTNESS[0] + "</value>\n"
@@ -578,7 +716,7 @@
                 +       "</displayBrightnessMapping>\n"
                 +   "</autoBrightness>\n"
                 +   "<highBrightnessMode enabled=\"true\">\n"
-                +       "<transitionPoint>0.62</transitionPoint>\n"
+                +       "<transitionPoint>" + BRIGHTNESS[1] + "</transitionPoint>\n"
                 +       "<minimumLux>10000</minimumLux>\n"
                 +       "<timing>\n"
                 +           "<!-- allow for 5 minutes out of every 30 minutes -->\n"
@@ -590,8 +728,8 @@
                 +           "<minimum>120</minimum>\n"
                 +           "<maximum>120</maximum>\n"
                 +       "</refreshRate>\n"
-                +       "<thermalStatusLimit>light</thermalStatusLimit>\n"
                 +       "<allowInLowPowerMode>false</allowInLowPowerMode>\n"
+                +       "<minimumHdrPercentOfScreen>0.6</minimumHdrPercentOfScreen>\n"
                 +       "<sdrHdrRatioMap>\n"
                 +            "<point>\n"
                 +                "<sdrNits>2.000</sdrNits>\n"
@@ -604,10 +742,19 @@
                 +       "</sdrHdrRatioMap>\n"
                 +   "</highBrightnessMode>\n"
                 + brightnessCapConfig
+                +   "<lightSensor>\n"
+                +       "<type>test_light_sensor</type>\n"
+                +       "<name>Test Ambient Light Sensor</name>\n"
+                +       "<refreshRate>\n"
+                +           "<minimum>60</minimum>\n"
+                +           "<maximum>120</maximum>\n"
+                +       "</refreshRate>\n"
+                +   "</lightSensor>\n"
                 +   "<screenOffBrightnessSensor>\n"
-                +       "<type>sensor_12345</type>\n"
-                +       "<name>Sensor 12345</name>\n"
+                +       "<type>test_binned_brightness_sensor</type>\n"
+                +       "<name>Test Binned Brightness Sensor</name>\n"
                 +   "</screenOffBrightnessSensor>\n"
+                + proxSensor
                 +   "<ambientBrightnessChangeThresholds>\n"
                 +       "<brighteningThresholds>\n"
                 +           "<minimum>10</minimum>\n"
@@ -946,9 +1093,9 @@
         when(mResources.getInteger(R.integer.config_defaultRefreshRate))
                 .thenReturn(DEFAULT_REFRESH_RATE);
         when(mResources.getInteger(R.integer.config_fixedRefreshRateInHighZone))
-            .thenReturn(DEFAULT_HIGH_BLOCKING_ZONE_REFRESH_RATE);
+                .thenReturn(DEFAULT_HIGH_BLOCKING_ZONE_REFRESH_RATE);
         when(mResources.getInteger(R.integer.config_defaultRefreshRateInZone))
-            .thenReturn(DEFAULT_LOW_BLOCKING_ZONE_REFRESH_RATE);
+                .thenReturn(DEFAULT_LOW_BLOCKING_ZONE_REFRESH_RATE);
         when(mResources.getIntArray(R.array.config_brightnessThresholdsOfPeakRefreshRate))
                 .thenReturn(LOW_BRIGHTNESS_THRESHOLD_OF_PEAK_REFRESH_RATE);
         when(mResources.getIntArray(R.array.config_ambientThresholdsOfPeakRefreshRate))
@@ -960,11 +1107,14 @@
                 R.array.config_highAmbientBrightnessThresholdsOfFixedRefreshRate))
                 .thenReturn(HIGH_AMBIENT_THRESHOLD_OF_PEAK_REFRESH_RATE);
         when(mResources.getInteger(
-            R.integer.config_defaultRefreshRateInHbmHdr))
-            .thenReturn(DEFAULT_REFRESH_RATE_IN_HBM_HDR);
+                R.integer.config_defaultRefreshRateInHbmHdr))
+                .thenReturn(DEFAULT_REFRESH_RATE_IN_HBM_HDR);
         when(mResources.getInteger(
-            R.integer.config_defaultRefreshRateInHbmSunlight))
-            .thenReturn(DEFAULT_REFRESH_RATE_IN_HBM_SUNLIGHT);
+                R.integer.config_defaultRefreshRateInHbmSunlight))
+                .thenReturn(DEFAULT_REFRESH_RATE_IN_HBM_SUNLIGHT);
+
+        when(mResources.getString(com.android.internal.R.string.config_displayLightSensorType))
+                .thenReturn("test_light_sensor");
 
         mDisplayDeviceConfig = DisplayDeviceConfig.create(mContext, true);
     }
diff --git a/services/tests/displayservicetests/src/com/android/server/display/DisplayDeviceTest.java b/services/tests/displayservicetests/src/com/android/server/display/DisplayDeviceTest.java
new file mode 100644
index 0000000..4fd8f26
--- /dev/null
+++ b/services/tests/displayservicetests/src/com/android/server/display/DisplayDeviceTest.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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;
+
+import static android.view.Surface.ROTATION_0;
+import static android.view.Surface.ROTATION_180;
+import static android.view.Surface.ROTATION_270;
+import static android.view.Surface.ROTATION_90;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.platform.test.annotations.Presubmit;
+import android.view.SurfaceControl;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+/**
+ * Tests for the {@link DisplayDevice} class.
+ *
+ * Build/Install/Run:
+ * atest DisplayServicesTests:DisplayDeviceTest
+ */
+@SmallTest
+@Presubmit
+@RunWith(AndroidJUnit4.class)
+public class DisplayDeviceTest {
+    private final DisplayDeviceInfo mDisplayDeviceInfo = new DisplayDeviceInfo();
+    private static final int WIDTH = 500;
+    private static final int HEIGHT = 900;
+    private static final Point PORTRAIT_SIZE = new Point(WIDTH, HEIGHT);
+    private static final Point LANDSCAPE_SIZE = new Point(HEIGHT, WIDTH);
+
+    @Mock
+    private SurfaceControl.Transaction mMockTransaction;
+
+    @Before
+    public void setup() {
+        MockitoAnnotations.initMocks(this);
+        mDisplayDeviceInfo.width = WIDTH;
+        mDisplayDeviceInfo.height = HEIGHT;
+        mDisplayDeviceInfo.rotation = ROTATION_0;
+    }
+
+    @Test
+    public void testGetDisplaySurfaceDefaultSizeLocked_notRotated() {
+        DisplayDevice displayDevice = new FakeDisplayDevice(mDisplayDeviceInfo);
+        assertThat(displayDevice.getDisplaySurfaceDefaultSizeLocked()).isEqualTo(PORTRAIT_SIZE);
+    }
+
+    @Test
+    public void testGetDisplaySurfaceDefaultSizeLocked_rotation0() {
+        DisplayDevice displayDevice = new FakeDisplayDevice(mDisplayDeviceInfo);
+        displayDevice.setProjectionLocked(mMockTransaction, ROTATION_0, new Rect(), new Rect());
+        assertThat(displayDevice.getDisplaySurfaceDefaultSizeLocked()).isEqualTo(PORTRAIT_SIZE);
+    }
+
+    @Test
+    public void testGetDisplaySurfaceDefaultSizeLocked_rotation90() {
+        DisplayDevice displayDevice = new FakeDisplayDevice(mDisplayDeviceInfo);
+        displayDevice.setProjectionLocked(mMockTransaction, ROTATION_90, new Rect(), new Rect());
+        assertThat(displayDevice.getDisplaySurfaceDefaultSizeLocked()).isEqualTo(LANDSCAPE_SIZE);
+    }
+
+    @Test
+    public void testGetDisplaySurfaceDefaultSizeLocked_rotation180() {
+        DisplayDevice displayDevice = new FakeDisplayDevice(mDisplayDeviceInfo);
+        displayDevice.setProjectionLocked(mMockTransaction, ROTATION_180, new Rect(), new Rect());
+        assertThat(displayDevice.getDisplaySurfaceDefaultSizeLocked()).isEqualTo(PORTRAIT_SIZE);
+    }
+
+    @Test
+    public void testGetDisplaySurfaceDefaultSizeLocked_rotation270() {
+        DisplayDevice displayDevice = new FakeDisplayDevice(mDisplayDeviceInfo);
+        displayDevice.setProjectionLocked(mMockTransaction, ROTATION_270, new Rect(), new Rect());
+        assertThat(displayDevice.getDisplaySurfaceDefaultSizeLocked()).isEqualTo(LANDSCAPE_SIZE);
+    }
+
+    private static class FakeDisplayDevice extends DisplayDevice {
+        private final DisplayDeviceInfo mDisplayDeviceInfo;
+
+        FakeDisplayDevice(DisplayDeviceInfo displayDeviceInfo) {
+            super(null, null, "", InstrumentationRegistry.getInstrumentation().getContext());
+            mDisplayDeviceInfo = displayDeviceInfo;
+        }
+
+        @Override
+        public boolean hasStableUniqueId() {
+            return false;
+        }
+
+        @Override
+        public DisplayDeviceInfo getDisplayDeviceInfoLocked() {
+            return mDisplayDeviceInfo;
+        }
+    }
+}
diff --git a/services/tests/displayservicetests/src/com/android/server/display/DisplayManagerServiceTest.java b/services/tests/displayservicetests/src/com/android/server/display/DisplayManagerServiceTest.java
index bf23117..979676e 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/DisplayManagerServiceTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/DisplayManagerServiceTest.java
@@ -479,6 +479,41 @@
     }
 
     @Test
+    public void testCreateVirtualRotatesWithContent() throws RemoteException {
+        DisplayManagerService displayManager =
+                new DisplayManagerService(mContext, mBasicInjector);
+        registerDefaultDisplays(displayManager);
+
+        // This is effectively the DisplayManager service published to ServiceManager.
+        DisplayManagerService.BinderService bs = displayManager.new BinderService();
+
+        String uniqueId = "uniqueId --- Rotates with Content Test";
+        int width = 600;
+        int height = 800;
+        int dpi = 320;
+        int flags = DisplayManager.VIRTUAL_DISPLAY_FLAG_ROTATES_WITH_CONTENT;
+
+        when(mMockAppToken.asBinder()).thenReturn(mMockAppToken);
+        final VirtualDisplayConfig.Builder builder = new VirtualDisplayConfig.Builder(
+                VIRTUAL_DISPLAY_NAME, width, height, dpi);
+        builder.setFlags(flags);
+        builder.setUniqueId(uniqueId);
+        int displayId = bs.createVirtualDisplay(builder.build(), /* callback= */ mMockAppToken,
+                /* projection= */ null, PACKAGE_NAME);
+        verify(mMockProjectionService, never()).setContentRecordingSession(any(),
+                nullable(IMediaProjection.class));
+
+        displayManager.performTraversalInternal(mock(SurfaceControl.Transaction.class));
+
+        // flush the handler
+        displayManager.getDisplayHandler().runWithScissors(() -> {}, /* now= */ 0);
+
+        DisplayDeviceInfo ddi = displayManager.getDisplayDeviceInfoInternal(displayId);
+        assertNotNull(ddi);
+        assertTrue((ddi.flags & DisplayDeviceInfo.FLAG_ROTATES_WITH_CONTENT) != 0);
+    }
+
+    @Test
     public void testCreateVirtualDisplayOwnFocus() throws RemoteException {
         DisplayManagerService displayManager =
                 new DisplayManagerService(mContext, mBasicInjector);
diff --git a/services/tests/displayservicetests/src/com/android/server/display/LogicalDisplayTest.java b/services/tests/displayservicetests/src/com/android/server/display/LogicalDisplayTest.java
index 2065479..c0128ae 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/LogicalDisplayTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/LogicalDisplayTest.java
@@ -69,7 +69,6 @@
         mDisplayDeviceInfo.copyFrom(new DisplayDeviceInfo());
         mDisplayDeviceInfo.width = DISPLAY_WIDTH;
         mDisplayDeviceInfo.height = DISPLAY_HEIGHT;
-        mDisplayDeviceInfo.flags = DisplayDeviceInfo.FLAG_ROTATES_WITH_CONTENT;
         mDisplayDeviceInfo.touch = DisplayDeviceInfo.TOUCH_INTERNAL;
         mDisplayDeviceInfo.modeId = MODE_ID;
         mDisplayDeviceInfo.supportedModes = new Display.Mode[] {new Display.Mode(MODE_ID,
@@ -112,8 +111,18 @@
         mLogicalDisplay.configureDisplayLocked(t, mDisplayDevice, false);
         assertEquals(expectedPosition, mLogicalDisplay.getDisplayPosition());
 
-        expectedPosition.set(40, -20);
         DisplayInfo displayInfo = new DisplayInfo();
+        displayInfo.logicalWidth = DISPLAY_WIDTH;
+        displayInfo.logicalHeight = DISPLAY_HEIGHT;
+        // Rotation doesn't matter when the FLAG_ROTATES_WITH_CONTENT is absent.
+        displayInfo.rotation = Surface.ROTATION_90;
+        mLogicalDisplay.setDisplayInfoOverrideFromWindowManagerLocked(displayInfo);
+        mLogicalDisplay.configureDisplayLocked(t, mDisplayDevice, false);
+        assertEquals(expectedPosition, mLogicalDisplay.getDisplayPosition());
+
+        expectedPosition.set(40, -20);
+        mDisplayDeviceInfo.flags = DisplayDeviceInfo.FLAG_ROTATES_WITH_CONTENT;
+        mLogicalDisplay.updateLocked(mDeviceRepo);
         displayInfo.logicalWidth = DISPLAY_HEIGHT;
         displayInfo.logicalHeight = DISPLAY_WIDTH;
         displayInfo.rotation = Surface.ROTATION_90;
diff --git a/services/tests/displayservicetests/src/com/android/server/display/brightness/clamper/BrightnessLowPowerModeModifierTest.java b/services/tests/displayservicetests/src/com/android/server/display/brightness/clamper/BrightnessLowPowerModeModifierTest.java
new file mode 100644
index 0000000..0ff4724
--- /dev/null
+++ b/services/tests/displayservicetests/src/com/android/server/display/brightness/clamper/BrightnessLowPowerModeModifierTest.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.brightness.clamper;
+
+import static android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.server.display.DisplayBrightnessState;
+import com.android.server.display.brightness.BrightnessReason;
+
+import org.junit.Before;
+import org.junit.Test;
+
+@SmallTest
+public class BrightnessLowPowerModeModifierTest {
+    private static final float FLOAT_TOLERANCE = 0.001f;
+    private static final float DEFAULT_BRIGHTNESS = 0.5f;
+    private static final float LOW_POWER_BRIGHTNESS_FACTOR = 0.8f;
+    private static final float EXPECTED_LOW_POWER_BRIGHTNESS =
+            DEFAULT_BRIGHTNESS * LOW_POWER_BRIGHTNESS_FACTOR;
+    private final DisplayPowerRequest mRequest = new DisplayPowerRequest();
+    private final DisplayBrightnessState.Builder mBuilder = prepareBuilder();
+    private BrightnessLowPowerModeModifier mModifier;
+
+    @Before
+    public void setUp() {
+        mModifier = new BrightnessLowPowerModeModifier();
+        mRequest.screenLowPowerBrightnessFactor = LOW_POWER_BRIGHTNESS_FACTOR;
+        mRequest.lowPowerMode = true;
+    }
+
+    @Test
+    public void testApply_lowPowerModeOff() {
+        mRequest.lowPowerMode = false;
+
+        mModifier.apply(mRequest, mBuilder);
+
+        assertEquals(DEFAULT_BRIGHTNESS, mBuilder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(0, mBuilder.getBrightnessReason().getModifier());
+        assertTrue(mBuilder.isSlowChange());
+    }
+
+    @Test
+    public void testApply_lowPowerModeOn() {
+        mModifier.apply(mRequest, mBuilder);
+
+        assertEquals(EXPECTED_LOW_POWER_BRIGHTNESS, mBuilder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(BrightnessReason.MODIFIER_LOW_POWER,
+                mBuilder.getBrightnessReason().getModifier());
+        assertFalse(mBuilder.isSlowChange());
+    }
+
+    @Test
+    public void testApply_lowPowerModeOnAndLowPowerBrightnessFactorHigh() {
+        mRequest.screenLowPowerBrightnessFactor = 1.1f;
+
+        mModifier.apply(mRequest, mBuilder);
+
+        assertEquals(DEFAULT_BRIGHTNESS, mBuilder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(BrightnessReason.MODIFIER_LOW_POWER,
+                mBuilder.getBrightnessReason().getModifier());
+        assertFalse(mBuilder.isSlowChange());
+    }
+
+    @Test
+    public void testApply_lowPowerModeOnAndMinBrightness() {
+        mBuilder.setBrightness(0.0f);
+        mModifier.apply(mRequest, mBuilder);
+
+        assertEquals(0.0f, mBuilder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(0, mBuilder.getBrightnessReason().getModifier());
+        assertFalse(mBuilder.isSlowChange());
+    }
+
+    @Test
+    public void testApply_lowPowerModeOnAndLowPowerAlreadyApplied() {
+        mModifier.apply(mRequest, mBuilder);
+        DisplayBrightnessState.Builder builder = prepareBuilder();
+
+        mModifier.apply(mRequest, builder);
+
+        assertEquals(EXPECTED_LOW_POWER_BRIGHTNESS, builder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(BrightnessReason.MODIFIER_LOW_POWER,
+                builder.getBrightnessReason().getModifier());
+        assertTrue(builder.isSlowChange());
+    }
+
+    @Test
+    public void testApply_lowPowerModeOffAfterLowPowerOn() {
+        mModifier.apply(mRequest, mBuilder);
+        mRequest.lowPowerMode = false;
+        DisplayBrightnessState.Builder builder = prepareBuilder();
+
+        mModifier.apply(mRequest, builder);
+
+        assertEquals(DEFAULT_BRIGHTNESS, builder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(0, builder.getBrightnessReason().getModifier());
+        assertFalse(builder.isSlowChange());
+    }
+
+    private DisplayBrightnessState.Builder prepareBuilder() {
+        DisplayBrightnessState.Builder builder = DisplayBrightnessState.builder();
+        builder.setBrightness(DEFAULT_BRIGHTNESS);
+        builder.setIsSlowChange(true);
+        return builder;
+    }
+}
diff --git a/services/tests/displayservicetests/src/com/android/server/display/brightness/clamper/DisplayDimModifierTest.java b/services/tests/displayservicetests/src/com/android/server/display/brightness/clamper/DisplayDimModifierTest.java
new file mode 100644
index 0000000..be4e7c7
--- /dev/null
+++ b/services/tests/displayservicetests/src/com/android/server/display/brightness/clamper/DisplayDimModifierTest.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.brightness.clamper;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.hardware.display.DisplayManagerInternal;
+import android.os.PowerManager;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.internal.R;
+import com.android.server.display.DisplayBrightnessState;
+import com.android.server.display.brightness.BrightnessReason;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+public class DisplayDimModifierTest {
+    private static final float FLOAT_TOLERANCE = 0.001f;
+    private static final float DEFAULT_BRIGHTNESS = 0.5f;
+    private static final float MIN_DIM_AMOUNT = 0.05f;
+    private static final float DIM_CONFIG = 0.4f;
+
+    @Mock
+    private Context mMockContext;
+
+    @Mock
+    private PowerManager mMockPowerManager;
+
+    @Mock
+    private Resources mMockResources;
+
+    private final DisplayManagerInternal.DisplayPowerRequest
+            mRequest = new DisplayManagerInternal.DisplayPowerRequest();
+    private final DisplayBrightnessState.Builder mBuilder = prepareBuilder();
+    private DisplayDimModifier mModifier;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        when(mMockContext.getResources()).thenReturn(mMockResources);
+        when(mMockResources.getFloat(
+                R.dimen.config_screenBrightnessMinimumDimAmountFloat)).thenReturn(MIN_DIM_AMOUNT);
+        when(mMockContext.getSystemService(PowerManager.class)).thenReturn(mMockPowerManager);
+        when(mMockPowerManager.getBrightnessConstraint(
+                PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_DIM)).thenReturn(DIM_CONFIG);
+
+        mModifier = new DisplayDimModifier(mMockContext);
+        mRequest.policy = DisplayManagerInternal.DisplayPowerRequest.POLICY_DIM;
+    }
+
+    @Test
+    public void testApply_noDimPolicy() {
+        mRequest.policy = DisplayManagerInternal.DisplayPowerRequest.POLICY_OFF;
+        mModifier.apply(mRequest, mBuilder);
+
+        assertEquals(DEFAULT_BRIGHTNESS, mBuilder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(0, mBuilder.getBrightnessReason().getModifier());
+        assertTrue(mBuilder.isSlowChange());
+    }
+
+    @Test
+    public void testApply_dimPolicyFromResources() {
+        mBuilder.setBrightness(0.4f);
+        mModifier.apply(mRequest, mBuilder);
+
+        assertEquals(0.4f - MIN_DIM_AMOUNT, mBuilder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(BrightnessReason.MODIFIER_DIMMED,
+                mBuilder.getBrightnessReason().getModifier());
+        assertFalse(mBuilder.isSlowChange());
+    }
+
+    @Test
+    public void testApply_dimPolicyFromConfig() {
+        mModifier.apply(mRequest, mBuilder);
+
+        assertEquals(DIM_CONFIG, mBuilder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(BrightnessReason.MODIFIER_DIMMED,
+                mBuilder.getBrightnessReason().getModifier());
+        assertFalse(mBuilder.isSlowChange());
+    }
+
+    @Test
+    public void testApply_dimPolicyAndDimPolicyAlreadyApplied() {
+        mModifier.apply(mRequest, mBuilder);
+        DisplayBrightnessState.Builder builder = prepareBuilder();
+
+        mModifier.apply(mRequest, builder);
+
+        assertEquals(DIM_CONFIG, builder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(BrightnessReason.MODIFIER_DIMMED,
+                builder.getBrightnessReason().getModifier());
+        assertTrue(builder.isSlowChange());
+    }
+
+    @Test
+    public void testApply_dimPolicyAndMinBrightness() {
+        mBuilder.setBrightness(0.0f);
+        mModifier.apply(mRequest, mBuilder);
+
+        assertEquals(0.0f, mBuilder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(0, mBuilder.getBrightnessReason().getModifier());
+        assertFalse(mBuilder.isSlowChange());
+    }
+
+    @Test
+    public void testApply_dimPolicyOffAfterDimPolicyOn() {
+        mModifier.apply(mRequest, mBuilder);
+        mRequest.policy = DisplayManagerInternal.DisplayPowerRequest.POLICY_OFF;
+        DisplayBrightnessState.Builder builder = prepareBuilder();
+
+        mModifier.apply(mRequest, builder);
+
+        assertEquals(DEFAULT_BRIGHTNESS, builder.getBrightness(), FLOAT_TOLERANCE);
+        assertEquals(0, builder.getBrightnessReason().getModifier());
+        assertFalse(builder.isSlowChange());
+    }
+
+    private DisplayBrightnessState.Builder prepareBuilder() {
+        DisplayBrightnessState.Builder builder = DisplayBrightnessState.builder();
+        builder.setBrightness(DEFAULT_BRIGHTNESS);
+        builder.setIsSlowChange(true);
+        return builder;
+    }
+}
diff --git a/services/tests/displayservicetests/src/com/android/server/display/whitebalance/AmbientLuxTest.java b/services/tests/displayservicetests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
index f975b6f..183a84d 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
@@ -64,7 +64,9 @@
     private static final int AMBIENT_COLOR_TYPE = 20705;
     private static final String AMBIENT_COLOR_TYPE_STR = "colorSensoryDensoryDoc";
     private static final float LOW_LIGHT_AMBIENT_COLOR_TEMPERATURE = 5432.1f;
+    private static final float LOW_LIGHT_AMBIENT_COLOR_TEMPERATURE_STRONG = 5555.5f;
     private static final float HIGH_LIGHT_AMBIENT_COLOR_TEMPERATURE = 3456.7f;
+    private static final float HIGH_LIGHT_AMBIENT_COLOR_TEMPERATURE_STRONG = 3333.3f;
 
     private Handler mHandler = new Handler(Looper.getMainLooper());
     private Sensor mLightSensor;
@@ -78,6 +80,10 @@
     @Mock private TypedArray mBiases;
     @Mock private TypedArray mHighLightBrightnesses;
     @Mock private TypedArray mHighLightBiases;
+    @Mock private TypedArray mBrightnessesStrong;
+    @Mock private TypedArray mBiasesStrong;
+    @Mock private TypedArray mHighLightBrightnessesStrong;
+    @Mock private TypedArray mHighLightBiasesStrong;
     @Mock private TypedArray mAmbientColorTemperatures;
     @Mock private TypedArray mDisplayColorTemperatures;
     @Mock private TypedArray mStrongAmbientColorTemperatures;
@@ -108,6 +114,10 @@
                 LOW_LIGHT_AMBIENT_COLOR_TEMPERATURE);
         mockResourcesFloat(R.dimen.config_displayWhiteBalanceHighLightAmbientColorTemperature,
                 HIGH_LIGHT_AMBIENT_COLOR_TEMPERATURE);
+        mockResourcesFloat(R.dimen.config_displayWhiteBalanceLowLightAmbientColorTemperatureStrong,
+                LOW_LIGHT_AMBIENT_COLOR_TEMPERATURE_STRONG);
+        mockResourcesFloat(R.dimen.config_displayWhiteBalanceHighLightAmbientColorTemperatureStrong,
+                HIGH_LIGHT_AMBIENT_COLOR_TEMPERATURE_STRONG);
         when(mResourcesSpy.obtainTypedArray(
                 R.array.config_displayWhiteBalanceAmbientColorTemperatures))
                 .thenReturn(mAmbientColorTemperatures);
@@ -133,6 +143,18 @@
         when(mResourcesSpy.obtainTypedArray(
                 R.array.config_displayWhiteBalanceHighLightAmbientBiases))
                 .thenReturn(mHighLightBiases);
+        when(mResourcesSpy.obtainTypedArray(
+                R.array.config_displayWhiteBalanceLowLightAmbientBrightnessesStrong))
+                .thenReturn(mBrightnessesStrong);
+        when(mResourcesSpy.obtainTypedArray(
+                R.array.config_displayWhiteBalanceLowLightAmbientBiasesStrong))
+                .thenReturn(mBiasesStrong);
+        when(mResourcesSpy.obtainTypedArray(
+                R.array.config_displayWhiteBalanceHighLightAmbientBrightnessesStrong))
+                .thenReturn(mHighLightBrightnessesStrong);
+        when(mResourcesSpy.obtainTypedArray(
+                R.array.config_displayWhiteBalanceHighLightAmbientBiasesStrong))
+                .thenReturn(mHighLightBiasesStrong);
         mockThrottler();
         LocalServices.removeServiceForTest(ColorDisplayService.ColorDisplayServiceInternal.class);
         LocalServices.addService(ColorDisplayService.ColorDisplayServiceInternal.class,
@@ -388,8 +410,8 @@
     public void testStrongMode() {
         final float lowerBrightness = 10.0f;
         final float upperBrightness = 50.0f;
-        setBrightnesses(lowerBrightness, upperBrightness);
-        setBiases(0.0f, 1.0f);
+        setBrightnessesStrong(lowerBrightness, upperBrightness);
+        setBiasesStrong(0.0f, 1.0f);
         final int ambientColorTempLow = 6000;
         final int ambientColorTempHigh = 8000;
         final int displayColorTempLow = 6400;
@@ -413,7 +435,7 @@
                 setEstimatedBrightnessAndUpdate(controller,
                         mix(lowerBrightness, upperBrightness, brightnessFraction));
                 assertEquals(controller.mPendingAmbientColorTemperature,
-                        mix(LOW_LIGHT_AMBIENT_COLOR_TEMPERATURE,
+                        mix(LOW_LIGHT_AMBIENT_COLOR_TEMPERATURE_STRONG,
                                 mix(displayColorTempLow, displayColorTempHigh, ambientTempFraction),
                                 brightnessFraction),
                         ALLOWED_ERROR_DELTA);
@@ -458,7 +480,7 @@
         assertEquals(-1.0f, controller.mPendingAmbientColorTemperature, 0);
     }
 
-    void mockThrottler() {
+    private void mockThrottler() {
         when(mResourcesSpy.getInteger(
                 R.integer.config_displayWhiteBalanceDecreaseDebounce)).thenReturn(0);
         when(mResourcesSpy.getInteger(
@@ -513,10 +535,18 @@
         setFloatArrayResource(mBrightnesses, vals);
     }
 
+    private void setBrightnessesStrong(float... vals) {
+        setFloatArrayResource(mBrightnessesStrong, vals);
+    }
+
     private void setBiases(float... vals) {
         setFloatArrayResource(mBiases, vals);
     }
 
+    private void setBiasesStrong(float... vals) {
+        setFloatArrayResource(mBiasesStrong, vals);
+    }
+
     private void setHighLightBrightnesses(float... vals) {
         setFloatArrayResource(mHighLightBrightnesses, vals);
     }
diff --git a/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java
index 88f3b2e..525bfd7 100644
--- a/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java
@@ -48,7 +48,6 @@
 import static org.junit.Assert.assertTrue;
 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.ArgumentMatchers.anyLong;
 import static org.mockito.ArgumentMatchers.anyString;
@@ -83,6 +82,7 @@
 import android.os.PowerManagerInternal;
 import android.os.PowerSaveState;
 import android.os.SystemClock;
+import android.os.WearModeManagerInternal;
 import android.provider.DeviceConfig;
 import android.telephony.TelephonyCallback;
 import android.telephony.TelephonyManager;
@@ -147,6 +147,8 @@
     private TelephonyManager mTelephonyManager;
     @Mock
     private Sensor mOffBodySensor;
+    @Mock
+    private WearModeManagerInternal mWearModeManagerInternal;
 
     class InjectorForTest extends DeviceIdleController.Injector {
         ConnectivityManager connectivityManager;
@@ -348,6 +350,9 @@
         mAnyMotionDetector = new AnyMotionDetectorForTest();
         mInjector = new InjectorForTest(getContext());
 
+        doReturn(mWearModeManagerInternal)
+                .when(() -> LocalServices.getService(WearModeManagerInternal.class));
+
         setupDeviceIdleController();
     }
 
@@ -2413,22 +2418,20 @@
     }
 
     @Test
-    public void testLowLatencyBodyDetection_NoBodySensor() {
-        mConstants.USE_BODY_SENSOR = true;
-        doReturn(null).when(mSensorManager).getDefaultSensor(
-                eq(Sensor.TYPE_LOW_LATENCY_OFFBODY_DETECT), anyBoolean());
+    public void testModeManager_NoModeManagerLocalService_AddListenerNotCalled() {
+        mConstants.USE_MODE_MANAGER = true;
+        doReturn(null)
+                .when(() -> LocalServices.getService(WearModeManagerInternal.class));
         cleanupDeviceIdleController();
         setupDeviceIdleController();
-        verify(mSensorManager, never())
-                .registerListener(any(), any(), anyInt());
+        verify(mWearModeManagerInternal, never()).addActiveStateChangeListener(
+                eq(WearModeManagerInternal.QUICK_DOZE_REQUEST_IDENTIFIER), any(),
+                eq(mDeviceIdleController.mModeManagerQuickDozeRequestConsumer));
     }
 
     @Test
-    public void testLowLatencyBodyDetection_NoBatterySaver_QuickDoze() {
-        mConstants.USE_BODY_SENSOR = true;
-        doReturn(mOffBodySensor)
-                .when(mSensorManager)
-                .getDefaultSensor(eq(Sensor.TYPE_LOW_LATENCY_OFFBODY_DETECT), anyBoolean());
+    public void testModeManager_NoBatterySaver_QuickDoze() {
+        mConstants.USE_MODE_MANAGER = true;
         PowerSaveState powerSaveState = new PowerSaveState.Builder().setBatterySaverEnabled(
                 false).build();
         when(mPowerManagerInternal.getLowPowerState(anyInt()))
@@ -2436,32 +2439,19 @@
         cleanupDeviceIdleController();
         setupDeviceIdleController();
 
-        ArgumentCaptor<SensorEventListener> listenerCaptor =
-                ArgumentCaptor.forClass(SensorEventListener.class);
-        verify(mSensorManager)
-                .registerListener(listenerCaptor.capture(), eq(mOffBodySensor),
-                        eq(SensorManager.SENSOR_DELAY_NORMAL));
-        final SensorEventListener listener = listenerCaptor.getValue();
-        // Set the device as off body
-        float[] valsZero = {0.0f};
-        SensorEvent offbodyEvent = new SensorEvent(mOffBodySensor, 1, 1L, valsZero);
-        listener.onSensorChanged(offbodyEvent);
+        // Mode manager quick doze request: true.
+        mDeviceIdleController.mModeManagerQuickDozeRequestConsumer.accept(true);
         assertTrue(mDeviceIdleController.isQuickDozeEnabled());
 
-        // Set the device as on body
-        float[] valsNonZero = {1.0f};
-        SensorEvent onbodyEvent = new SensorEvent(mOffBodySensor, 1, 1L, valsNonZero);
-        listener.onSensorChanged(onbodyEvent);
+        // Mode manager quick doze request: false.
+        mDeviceIdleController.mModeManagerQuickDozeRequestConsumer.accept(false);
         assertFalse(mDeviceIdleController.isQuickDozeEnabled());
         verifyStateConditions(STATE_ACTIVE);
     }
 
     @Test
-    public void testLowLatencyBodyDetection_WithBatterySaver_QuickDoze() {
-        mConstants.USE_BODY_SENSOR = true;
-        doReturn(mOffBodySensor)
-                .when(mSensorManager)
-                .getDefaultSensor(eq(Sensor.TYPE_LOW_LATENCY_OFFBODY_DETECT), anyBoolean());
+    public void testModeManager_WithBatterySaver_QuickDoze() {
+        mConstants.USE_MODE_MANAGER = true;
         PowerSaveState powerSaveState = new PowerSaveState.Builder().setBatterySaverEnabled(
                 true).build();
         when(mPowerManagerInternal.getLowPowerState(anyInt()))
@@ -2469,22 +2459,13 @@
         cleanupDeviceIdleController();
         setupDeviceIdleController();
 
-        ArgumentCaptor<SensorEventListener> listenerCaptor =
-                ArgumentCaptor.forClass(SensorEventListener.class);
-        verify(mSensorManager)
-                .registerListener(listenerCaptor.capture(), eq(mOffBodySensor),
-                        eq(SensorManager.SENSOR_DELAY_NORMAL));
-        final SensorEventListener listener = listenerCaptor.getValue();
-        // Set the device as off body
-        float[] valsZero = {0.0f};
-        SensorEvent offbodyEvent = new SensorEvent(mOffBodySensor, 1, 1L, valsZero);
-        listener.onSensorChanged(offbodyEvent);
+        // Mode manager quick doze request: true.
+        mDeviceIdleController.mModeManagerQuickDozeRequestConsumer.accept(true);
         assertTrue(mDeviceIdleController.isQuickDozeEnabled());
 
-        // Set the device as on body. Quick doze should remain enabled because battery saver is on.
-        float[] valsNonZero = {1.0f};
-        SensorEvent onbodyEvent = new SensorEvent(mOffBodySensor, 1, 1L, valsNonZero);
-        listener.onSensorChanged(onbodyEvent);
+        // Mode manager quick doze request: false.
+        // Quick doze should remain enabled because battery saver is on.
+        mDeviceIdleController.mModeManagerQuickDozeRequestConsumer.accept(false);
         assertTrue(mDeviceIdleController.isQuickDozeEnabled());
     }
 
diff --git a/services/tests/mockingservicestests/src/com/android/server/backup/SystemBackupAgentTest.java b/services/tests/mockingservicestests/src/com/android/server/backup/SystemBackupAgentTest.java
index c6d8848..4095be7 100644
--- a/services/tests/mockingservicestests/src/com/android/server/backup/SystemBackupAgentTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/backup/SystemBackupAgentTest.java
@@ -83,7 +83,8 @@
                         "slices",
                         "people",
                         "app_locales",
-                        "app_gender");
+                        "app_gender",
+                        "companion");
     }
 
     @Test
@@ -106,7 +107,8 @@
                         "account_manager",
                         "people",
                         "app_locales",
-                        "app_gender");
+                        "app_gender",
+                        "companion");
     }
 
     @Test
@@ -121,7 +123,8 @@
                         "account_sync_settings",
                         "notifications",
                         "permissions",
-                        "app_locales");
+                        "app_locales",
+                        "companion");
     }
 
     @Test
@@ -140,7 +143,8 @@
                         "app_locales",
                         "account_manager",
                         "usage_stats",
-                        "shortcut_manager");
+                        "shortcut_manager",
+                        "companion");
     }
 
     private class TestableSystemBackupAgent extends SystemBackupAgent {
diff --git a/services/tests/mockingservicestests/src/com/android/server/location/gnss/hal/FakeGnssHal.java b/services/tests/mockingservicestests/src/com/android/server/location/gnss/hal/FakeGnssHal.java
index 2d962ac..1a8b12a 100644
--- a/services/tests/mockingservicestests/src/com/android/server/location/gnss/hal/FakeGnssHal.java
+++ b/services/tests/mockingservicestests/src/com/android/server/location/gnss/hal/FakeGnssHal.java
@@ -686,9 +686,6 @@
     }
 
     @Override
-    protected void sendNiResponse(int notificationId, int userResponse) {}
-
-    @Override
     protected void requestPowerStats() {
         Objects.requireNonNull(mGnssNative).reportGnssPowerStats(mState.mPowerStats);
     }
diff --git a/services/tests/mockingservicestests/src/com/android/server/pm/SuspendPackageHelperTest.kt b/services/tests/mockingservicestests/src/com/android/server/pm/SuspendPackageHelperTest.kt
index 5cca5fa..6797576 100644
--- a/services/tests/mockingservicestests/src/com/android/server/pm/SuspendPackageHelperTest.kt
+++ b/services/tests/mockingservicestests/src/com/android/server/pm/SuspendPackageHelperTest.kt
@@ -40,7 +40,7 @@
         val failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 targetPackages, true /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, null /* dialogInfo */, DEVICE_OWNER_PACKAGE,
-                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */)
+                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */, false /* quarantined */)
         testHandler.flush()
 
         verify(pms).scheduleWritePackageRestrictions(eq(TEST_USER_ID))
@@ -64,14 +64,14 @@
         var failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 null /* packageNames */, true /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, null /* dialogInfo */, DEVICE_OWNER_PACKAGE,
-                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */)
+                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */, false /* quarantined */)
 
         assertThat(failedNames).isNull()
 
         failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 arrayOfNulls(0), true /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, null /* dialogInfo */, DEVICE_OWNER_PACKAGE,
-                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */)
+                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */, false /* quarantined */)
 
         assertThat(failedNames).isEmpty()
     }
@@ -81,7 +81,7 @@
         val failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 arrayOf(TEST_PACKAGE_2), true /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, null /* dialogInfo */, TEST_PACKAGE_1, TEST_USER_ID,
-                Binder.getCallingUid(), false /* forQuietMode */)
+                Binder.getCallingUid(), false /* forQuietMode */, false /* quarantined */)
 
         assertThat(failedNames).asList().hasSize(1)
         assertThat(failedNames).asList().contains(TEST_PACKAGE_2)
@@ -92,7 +92,7 @@
         val failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 arrayOf(DEVICE_OWNER_PACKAGE), true /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, null /* dialogInfo */, DEVICE_OWNER_PACKAGE,
-                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */)
+                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */, false /* quarantined */)
 
         assertThat(failedNames).asList().hasSize(1)
         assertThat(failedNames).asList().contains(DEVICE_OWNER_PACKAGE)
@@ -103,7 +103,7 @@
         val failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 arrayOf(NONEXISTENT_PACKAGE), true /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, null /* dialogInfo */, DEVICE_OWNER_PACKAGE,
-                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */)
+                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */, false /* quarantined */)
 
         assertThat(failedNames).asList().hasSize(1)
         assertThat(failedNames).asList().contains(NONEXISTENT_PACKAGE)
@@ -116,7 +116,7 @@
         val failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 knownPackages, true /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, null /* dialogInfo */, DEVICE_OWNER_PACKAGE,
-                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */)!!
+                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */, false /* quarantined */)!!
 
         assertThat(failedNames.size).isEqualTo(knownPackages.size)
         for (pkg in knownPackages) {
@@ -132,7 +132,7 @@
         val failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 knownPackages, true /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, null /* dialogInfo */, DEVICE_OWNER_PACKAGE,
-                TEST_USER_ID, deviceOwnerUid, true /* forQuietMode */)!!
+                TEST_USER_ID, deviceOwnerUid, true /* forQuietMode */, false /* quarantined */)!!
 
         assertThat(failedNames.size).isEqualTo(1)
         assertThat(failedNames[0]).isEqualTo(MGMT_ROLE_HOLDER_PACKAGE)
@@ -144,13 +144,13 @@
         var failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 targetPackages, true /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, null /* dialogInfo */, DEVICE_OWNER_PACKAGE,
-                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */)
+                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */, false /* quarantined */)
         testHandler.flush()
         assertThat(failedNames).isEmpty()
         failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 targetPackages, false /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, null /* dialogInfo */, DEVICE_OWNER_PACKAGE,
-                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */)
+                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */, false /* quarantined */)
         testHandler.flush()
 
         verify(pms, times(2)).scheduleWritePackageRestrictions(eq(TEST_USER_ID))
@@ -202,7 +202,7 @@
         var failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 arrayOf(TEST_PACKAGE_1), true /* suspended */, appExtras, null /* launcherExtras */,
                 null /* dialogInfo */, DEVICE_OWNER_PACKAGE, TEST_USER_ID, deviceOwnerUid,
-                false /* forQuietMode */)
+                false /* forQuietMode */, false /* quarantined */)
         testHandler.flush()
         assertThat(failedNames).isEmpty()
 
@@ -220,7 +220,7 @@
         var failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 targetPackages, true /* suspended */, appExtras, null /* launcherExtras */,
                 null /* dialogInfo */, DEVICE_OWNER_PACKAGE, TEST_USER_ID, deviceOwnerUid,
-                false /* forQuietMode */)
+                false /* forQuietMode */, false /* quarantined */)
         testHandler.flush()
         assertThat(failedNames).isEmpty()
         assertThat(suspendPackageHelper.getSuspendingPackage(pms.snapshotComputer(),
@@ -265,7 +265,7 @@
         var failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 arrayOf(TEST_PACKAGE_2), true /* suspended */, null /* appExtras */, launcherExtras,
                 null /* dialogInfo */, DEVICE_OWNER_PACKAGE, TEST_USER_ID, deviceOwnerUid,
-                false /* forQuietMode */)
+                false /* forQuietMode */, false /* quarantined */)
         testHandler.flush()
         assertThat(failedNames).isEmpty()
 
@@ -280,7 +280,7 @@
         var failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 arrayOf(TEST_PACKAGE_1), true /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, null /* dialogInfo */, DEVICE_OWNER_PACKAGE,
-                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */)
+                TEST_USER_ID, deviceOwnerUid, false /* forQuietMode */, false /* quarantined */)
         testHandler.flush()
         assertThat(failedNames).isEmpty()
 
@@ -295,7 +295,7 @@
         var failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 arrayOf(TEST_PACKAGE_2), true /* suspended */, null /* appExtras */, launcherExtras,
                 null /* dialogInfo */, DEVICE_OWNER_PACKAGE, TEST_USER_ID, deviceOwnerUid,
-                false /* forQuietMode */)
+                false /* forQuietMode */, false /* quarantined */)
         testHandler.flush()
         assertThat(failedNames).isEmpty()
 
@@ -310,7 +310,7 @@
         var failedNames = suspendPackageHelper.setPackagesSuspended(pms.snapshotComputer(),
                 arrayOf(TEST_PACKAGE_1), true /* suspended */, null /* appExtras */,
                 null /* launcherExtras */, dialogInfo, DEVICE_OWNER_PACKAGE, TEST_USER_ID,
-                deviceOwnerUid, false /* forQuietMode */)
+                deviceOwnerUid, false /* forQuietMode */, false /* quarantined */)
         testHandler.flush()
         assertThat(failedNames).isEmpty()
 
@@ -324,7 +324,7 @@
     @Throws(Exception::class)
     fun sendPackagesSuspendedForUser() {
         suspendPackageHelper.sendPackagesSuspendedForUser(
-            Intent.ACTION_PACKAGES_SUSPENDED, packagesToChange, uidsToChange, TEST_USER_ID)
+            Intent.ACTION_PACKAGES_SUSPENDED, packagesToChange, uidsToChange, false, TEST_USER_ID)
         testHandler.flush()
         verify(broadcastHelper).sendPackageBroadcast(any(), nullable(), bundleCaptor.capture(),
                 anyInt(), nullable(), nullable(), any(), nullable(), nullable(), nullable(),
@@ -341,7 +341,7 @@
     @Throws(Exception::class)
     fun sendPackagesSuspendModifiedForUser() {
         suspendPackageHelper.sendPackagesSuspendedForUser(
-            Intent.ACTION_PACKAGES_SUSPENSION_CHANGED, packagesToChange, uidsToChange, TEST_USER_ID)
+            Intent.ACTION_PACKAGES_SUSPENSION_CHANGED, packagesToChange, uidsToChange, false, TEST_USER_ID)
         testHandler.flush()
         verify(broadcastHelper).sendPackageBroadcast(
                 eq(Intent.ACTION_PACKAGES_SUSPENSION_CHANGED), nullable(), bundleCaptor.capture(),
diff --git a/services/tests/mockingservicestests/src/com/android/server/pm/UserManagerServiceTest.java b/services/tests/mockingservicestests/src/com/android/server/pm/UserManagerServiceTest.java
index 0664ab8..bdbf4ec 100644
--- a/services/tests/mockingservicestests/src/com/android/server/pm/UserManagerServiceTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/pm/UserManagerServiceTest.java
@@ -15,7 +15,10 @@
  */
 package com.android.server.pm;
 
+import static android.os.UserManager.DISALLOW_OUTGOING_CALLS;
+import static android.os.UserManager.DISALLOW_SMS;
 import static android.os.UserManager.DISALLOW_USER_SWITCH;
+import static android.os.UserManager.USER_TYPE_FULL_SECONDARY;
 
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
@@ -60,6 +63,8 @@
 import org.junit.Test;
 import org.mockito.Mock;
 
+import java.io.File;
+
 /**
  * Run as {@code atest FrameworksMockingServicesTests:com.android.server.pm.UserManagerServiceTest}
  */
@@ -104,6 +109,8 @@
             .getTargetContext();
     private final SparseArray<UserData> mUsers = new SparseArray<>();
 
+    private File mTestDir;
+
     private Context mSpiedContext;
 
     private @Mock PackageManagerService mMockPms;
@@ -141,17 +148,23 @@
         doNothing().when(mSpiedContext).sendBroadcastAsUser(any(), any(), any());
 
         // Must construct UserManagerService in the UiThread
+        mTestDir = new File(mRealContext.getDataDir(), "umstest");
+        mTestDir.mkdirs();
         mUms = new UserManagerService(mSpiedContext, mMockPms, mMockUserDataPreparer,
-                mPackagesLock, mRealContext.getDataDir(), mUsers);
+                mPackagesLock, mTestDir, mUsers);
         mUmi = LocalServices.getService(UserManagerInternal.class);
         assertWithMessage("LocalServices.getService(UserManagerInternal.class)").that(mUmi)
                 .isNotNull();
     }
 
     @After
-    public void resetUserManagerInternal() {
+    public void tearDown() {
         // LocalServices follows the "Highlander rule" - There can be only one!
         LocalServices.removeServiceForTest(UserManagerInternal.class);
+
+        // Clean up test dir to remove persisted user files.
+        assertThat(deleteRecursive(mTestDir)).isTrue();
+        mUsers.clear();
     }
 
     @Test
@@ -328,6 +341,7 @@
     @Test
     public void testGetBootUser_Headless_ThrowsIfOnlySystemUserExists() throws Exception {
         setSystemUserHeadless(true);
+        removeNonSystemUsers();
 
         assertThrows(UserManager.CheckedUserOperationException.class,
                 () -> mUmi.getBootUser(/* waitUntilSet= */ false));
@@ -490,6 +504,33 @@
         assertThat(mUms.isUserSwitcherEnabled(USER_ID)).isTrue();
     }
 
+    @Test
+    public void testMainUser_hasNoCallsOrSMSRestrictionsByDefault() {
+        // Remove the main user so we can add another one
+        for (int i = 0; i < mUsers.size(); i++) {
+            UserData userData = mUsers.valueAt(i);
+            if (userData.info.isMain()) {
+                mUsers.delete(i);
+                break;
+            }
+        }
+        UserInfo mainUser = mUms.createUserWithThrow("main user", USER_TYPE_FULL_SECONDARY,
+                UserInfo.FLAG_FULL | UserInfo.FLAG_MAIN);
+
+        assertThat(mUms.hasUserRestriction(DISALLOW_OUTGOING_CALLS, mainUser.id))
+                .isFalse();
+        assertThat(mUms.hasUserRestriction(DISALLOW_SMS, mainUser.id))
+                .isFalse();
+    }
+
+    private void removeNonSystemUsers() {
+        for (UserInfo user : mUms.getUsers(true)) {
+            if (!user.getUserHandle().isSystem()) {
+                mUms.removeUserInfo(user.id);
+            }
+        }
+    }
+
     private void resetUserSwitcherEnabled() {
         mUms.putUserInfo(new UserInfo(USER_ID, "Test User", 0));
         mUms.setUserRestriction(DISALLOW_USER_SWITCH, false, USER_ID);
@@ -598,6 +639,18 @@
         userData.mLastEnteredForegroundTimeMillis = timeMillis;
     }
 
+    public boolean deleteRecursive(File file) {
+        if (file.isDirectory()) {
+            for (File item : file.listFiles()) {
+                boolean success = deleteRecursive(item);
+                if (!success) {
+                    return false;
+                }
+            }
+        }
+        return file.delete();
+    }
+
     private static final class TestUserData extends UserData {
 
         @SuppressWarnings("deprecation")
diff --git a/services/tests/powerservicetests/src/com/android/server/power/NotifierTest.java b/services/tests/powerservicetests/src/com/android/server/power/NotifierTest.java
index 58cdb1b..91d8ceb 100644
--- a/services/tests/powerservicetests/src/com/android/server/power/NotifierTest.java
+++ b/services/tests/powerservicetests/src/com/android/server/power/NotifierTest.java
@@ -50,9 +50,7 @@
 import com.android.internal.app.IBatteryStats;
 import com.android.server.LocalServices;
 import com.android.server.policy.WindowManagerPolicy;
-import com.android.server.power.batterysaver.BatterySaverController;
-import com.android.server.power.batterysaver.BatterySaverPolicy;
-import com.android.server.power.batterysaver.BatterySavingStats;
+import com.android.server.power.batterysaver.BatterySaverStateMachine;
 import com.android.server.statusbar.StatusBarManagerInternal;
 
 import org.junit.Before;
@@ -69,8 +67,7 @@
     private static final String SYSTEM_PROPERTY_QUIESCENT = "ro.boot.quiescent";
     private static final int USER_ID = 0;
 
-    @Mock private BatterySaverController mBatterySaverControllerMock;
-    @Mock private BatterySaverPolicy mBatterySaverPolicyMock;
+    @Mock private BatterySaverStateMachine mBatterySaverStateMachineMock;
     @Mock private PowerManagerService.NativeWrapper mNativeWrapperMock;
     @Mock private Notifier mNotifierMock;
     @Mock private WirelessChargerDetector mWirelessChargerDetectorMock;
@@ -263,16 +260,8 @@
         }
 
         @Override
-        BatterySaverPolicy createBatterySaverPolicy(
-                Object lock, Context context, BatterySavingStats batterySavingStats) {
-            return mBatterySaverPolicyMock;
-        }
-
-        @Override
-        BatterySaverController createBatterySaverController(
-                Object lock, Context context, BatterySaverPolicy batterySaverPolicy,
-                BatterySavingStats batterySavingStats) {
-            return mBatterySaverControllerMock;
+        BatterySaverStateMachine createBatterySaverStateMachine(Object lock, Context context) {
+            return mBatterySaverStateMachineMock;
         }
 
         @Override
diff --git a/services/tests/powerservicetests/src/com/android/server/power/PowerManagerServiceTest.java b/services/tests/powerservicetests/src/com/android/server/power/PowerManagerServiceTest.java
index 0b1e338..8e1d8ab 100644
--- a/services/tests/powerservicetests/src/com/android/server/power/PowerManagerServiceTest.java
+++ b/services/tests/powerservicetests/src/com/android/server/power/PowerManagerServiceTest.java
@@ -108,7 +108,6 @@
 import com.android.server.power.batterysaver.BatterySaverController;
 import com.android.server.power.batterysaver.BatterySaverPolicy;
 import com.android.server.power.batterysaver.BatterySaverStateMachine;
-import com.android.server.power.batterysaver.BatterySavingStats;
 import com.android.server.testutils.OffsettableClock;
 
 import com.google.testing.junit.testparameterinjector.TestParameter;
@@ -141,7 +140,7 @@
  * Tests for {@link com.android.server.power.PowerManagerService}.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:PowerManagerServiceTest
+ *  atest PowerServiceTests:PowerManagerServiceTest
  */
 @SuppressWarnings("GuardedBy")
 @RunWith(TestParameterInjector.class)
@@ -184,6 +183,7 @@
     private OffsettableClock mClock;
     private long mLastElapsedRealtime;
     private TestLooper mTestLooper;
+    private boolean mIsBatterySaverSupported = true;
 
     private static class IntentFilterMatcher implements ArgumentMatcher<IntentFilter> {
         private final IntentFilter mFilter;
@@ -215,6 +215,10 @@
                 .setBatterySaverEnabled(BATTERY_SAVER_ENABLED)
                 .setBrightnessFactor(BRIGHTNESS_FACTOR)
                 .build();
+        when(mBatterySaverStateMachineMock.getBatterySaverController()).thenReturn(
+                mBatterySaverControllerMock);
+        when(mBatterySaverStateMachineMock.getBatterySaverPolicy()).thenReturn(
+                mBatterySaverPolicyMock);
         when(mBatterySaverPolicyMock.getBatterySaverPolicy(
                 eq(PowerManager.ServiceType.SCREEN_BRIGHTNESS)))
                 .thenReturn(powerSaveState);
@@ -235,11 +239,16 @@
         mContextSpy = spy(new ContextWrapper(ApplicationProvider.getApplicationContext()));
         mResourcesSpy = spy(mContextSpy.getResources());
         when(mContextSpy.getResources()).thenReturn(mResourcesSpy);
+        setBatterySaverSupported();
 
         MockContentResolver cr = new MockContentResolver(mContextSpy);
         cr.addProvider(Settings.AUTHORITY, new FakeSettingsProvider());
         when(mContextSpy.getContentResolver()).thenReturn(cr);
 
+        when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_dreamsSupported))
+                .thenReturn(true);
+        when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_dreamsEnabledByDefault))
+                .thenReturn(true);
         Settings.Global.putInt(mContextSpy.getContentResolver(),
                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
         Settings.Secure.putInt(mContextSpy.getContentResolver(),
@@ -265,21 +274,7 @@
             }
 
             @Override
-            BatterySaverPolicy createBatterySaverPolicy(
-                    Object lock, Context context, BatterySavingStats batterySavingStats) {
-                return mBatterySaverPolicyMock;
-            }
-
-            @Override
-            BatterySaverController createBatterySaverController(
-                    Object lock, Context context, BatterySaverPolicy batterySaverPolicy,
-                    BatterySavingStats batterySavingStats) {
-                return mBatterySaverControllerMock;
-            }
-
-            @Override
-            BatterySaverStateMachine createBatterySaverStateMachine(Object lock, Context context,
-                    BatterySaverController batterySaverController) {
+            BatterySaverStateMachine createBatterySaverStateMachine(Object lock, Context context) {
                 return mBatterySaverStateMachineMock;
             }
 
@@ -476,6 +471,12 @@
         mTestLooper.dispatchAll();
     }
 
+    private void setBatterySaverSupported() {
+        when(mResourcesSpy.getBoolean(
+                com.android.internal.R.bool.config_batterySaverSupported)).thenReturn(
+                mIsBatterySaverSupported);
+    }
+
     @Test
     public void testCreateService_initializesNativeServiceAndSetsPowerModes() {
         PowerManagerService service = createService();
@@ -1084,13 +1085,9 @@
     @SuppressWarnings("GuardedBy")
     @Test
     public void testScreensaverActivateOnSleepEnabled_powered_afterTimeout_goesToDreaming() {
-        when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_dreamsSupported))
-                .thenReturn(true);
         when(mBatteryManagerInternalMock.isPowered(anyInt())).thenReturn(true);
         Settings.Secure.putInt(mContextSpy.getContentResolver(),
                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 1);
-        Settings.Secure.putInt(mContextSpy.getContentResolver(),
-                Settings.Secure.SCREENSAVER_ENABLED, 1);
 
         doAnswer(inv -> {
             when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
@@ -1112,8 +1109,6 @@
     public void testAmbientSuppression_disablesDreamingAndWakesDevice() {
         Settings.Secure.putInt(mContextSpy.getContentResolver(),
                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 1);
-        Settings.Secure.putInt(mContextSpy.getContentResolver(),
-                Settings.Secure.SCREENSAVER_ENABLED, 1);
 
         setDreamsDisabledByAmbientModeSuppressionConfig(true);
         setMinimumScreenOffTimeoutConfig(10000);
@@ -1141,8 +1136,6 @@
     public void testAmbientSuppressionDisabled_shouldNotWakeDevice() {
         Settings.Secure.putInt(mContextSpy.getContentResolver(),
                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 1);
-        Settings.Secure.putInt(mContextSpy.getContentResolver(),
-                Settings.Secure.SCREENSAVER_ENABLED, 1);
 
         setDreamsDisabledByAmbientModeSuppressionConfig(false);
         setMinimumScreenOffTimeoutConfig(10000);
@@ -1169,8 +1162,6 @@
     public void testAmbientSuppression_doesNotAffectDreamForcing() {
         Settings.Secure.putInt(mContextSpy.getContentResolver(),
                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 1);
-        Settings.Secure.putInt(mContextSpy.getContentResolver(),
-                Settings.Secure.SCREENSAVER_ENABLED, 1);
 
         setDreamsDisabledByAmbientModeSuppressionConfig(true);
         setMinimumScreenOffTimeoutConfig(10000);
@@ -1196,8 +1187,6 @@
     public void testBatteryDrainDuringDream() {
         Settings.Secure.putInt(mContextSpy.getContentResolver(),
                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 1);
-        Settings.Secure.putInt(mContextSpy.getContentResolver(),
-                Settings.Secure.SCREENSAVER_ENABLED, 1);
 
         setMinimumScreenOffTimeoutConfig(100);
         setDreamsBatteryLevelDrainConfig(5);
@@ -2551,6 +2540,19 @@
     }
 
     @Test
+    public void testGetFullPowerSavePolicy_whenNoBatterySaverSupported() {
+        mIsBatterySaverSupported = false;
+        setBatterySaverSupported();
+        createService();
+        BatterySaverPolicyConfig mockReturnConfig = new BatterySaverPolicyConfig.Builder().build();
+        assertFalse(mService.getBinderServiceInstance().setPowerSaveModeEnabled(true));
+        BatterySaverPolicyConfig policyConfig =
+                mService.getBinderServiceInstance().getFullPowerSavePolicy();
+        assertThat(mockReturnConfig.toString()).isEqualTo(policyConfig.toString());
+        verify(mBatterySaverStateMachineMock, never()).getFullBatterySaverPolicy();
+    }
+
+    @Test
     public void testSetFullPowerSavePolicy_callsStateMachine() {
         createService();
         startSystem();
diff --git a/services/tests/powerstatstests/Android.bp b/services/tests/powerstatstests/Android.bp
new file mode 100644
index 0000000..05acd9b
--- /dev/null
+++ b/services/tests/powerstatstests/Android.bp
@@ -0,0 +1,52 @@
+package {
+    // See: http://go/android-license-faq
+    default_applicable_licenses: ["frameworks_base_license"],
+}
+
+android_test {
+    name: "PowerStatsTests",
+
+    // Include all test java files.
+    srcs: [
+        "src/**/*.java",
+    ],
+
+    static_libs: [
+        "services.core",
+        "coretests-aidl",
+        "platformprotosnano",
+        "junit",
+        "truth-prebuilt",
+        "androidx.test.runner",
+        "androidx.test.ext.junit",
+        "androidx.test.ext.truth",
+        "androidx.test.uiautomator_uiautomator",
+        "mockito-target-minus-junit4",
+        "servicestests-utils",
+    ],
+
+    libs: [
+        "android.test.base",
+    ],
+
+    resource_dirs: ["res/"],
+
+    data: [
+        ":BstatsTestApp",
+    ],
+
+    test_suites: [
+        "automotive-tests",
+        "device-tests",
+    ],
+
+    platform_apis: true,
+
+    certificate: "platform",
+
+    dxflags: ["--multi-dex"],
+
+    optimize: {
+        enabled: false,
+    },
+}
diff --git a/services/tests/powerstatstests/AndroidManifest.xml b/services/tests/powerstatstests/AndroidManifest.xml
new file mode 100644
index 0000000..d3a88d2
--- /dev/null
+++ b/services/tests/powerstatstests/AndroidManifest.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2023 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT 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.frameworks.powerstatstests">
+
+    <uses-permission android:name="android.permission.BATTERY_STATS" />
+    <uses-permission android:name="android.permission.CHANGE_COMPONENT_ENABLED_STATE"/>
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL"/>
+    <uses-permission android:name="android.permission.MANAGE_USERS"/>
+
+    <queries>
+        <package android:name="com.android.coretests.apps.bstatstestapp" />
+    </queries>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+         android:targetPackage="com.android.frameworks.powerstatstests"
+         android:label="BatteryStats and PowerStats Services Tests"/>
+</manifest>
diff --git a/services/tests/powerstatstests/AndroidTest.xml b/services/tests/powerstatstests/AndroidTest.xml
new file mode 100644
index 0000000..79b07e8
--- /dev/null
+++ b/services/tests/powerstatstests/AndroidTest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2023 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT 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 Power Stats Tests.">
+    <option name="test-suite-tag" value="apct" />
+    <option name="test-suite-tag" value="apct-instrumentation" />
+
+    <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="PowerStatsTests.apk" />
+        <option name="test-file-name" value="BstatsTestApp.apk" />
+    </target_preparer>
+
+    <option name="test-tag" value="PowerStatsTests" />
+
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="com.android.frameworks.powerstatstests" />
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
+        <option name="hidden-api-checks" value="false"/>
+        <option name="exclude-annotation" value="androidx.test.filters.FlakyTest" />
+    </test>
+</configuration>
diff --git a/core/tests/coretests/BstatsTestApp/Android.bp b/services/tests/powerstatstests/BstatsTestApp/Android.bp
similarity index 100%
rename from core/tests/coretests/BstatsTestApp/Android.bp
rename to services/tests/powerstatstests/BstatsTestApp/Android.bp
diff --git a/core/tests/coretests/BstatsTestApp/AndroidManifest.xml b/services/tests/powerstatstests/BstatsTestApp/AndroidManifest.xml
similarity index 100%
rename from core/tests/coretests/BstatsTestApp/AndroidManifest.xml
rename to services/tests/powerstatstests/BstatsTestApp/AndroidManifest.xml
diff --git a/core/tests/coretests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/BaseCmdReceiver.java b/services/tests/powerstatstests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/BaseCmdReceiver.java
similarity index 100%
rename from core/tests/coretests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/BaseCmdReceiver.java
rename to services/tests/powerstatstests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/BaseCmdReceiver.java
diff --git a/core/tests/coretests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/Common.java b/services/tests/powerstatstests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/Common.java
similarity index 99%
rename from core/tests/coretests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/Common.java
rename to services/tests/powerstatstests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/Common.java
index d192fbd..c731e53 100644
--- a/core/tests/coretests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/Common.java
+++ b/services/tests/powerstatstests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/Common.java
@@ -15,8 +15,6 @@
  */
 package com.android.coretests.apps.bstatstestapp;
 
-import com.android.frameworks.coretests.aidl.ICmdCallback;
-
 import android.content.Intent;
 import android.os.Bundle;
 import android.os.IBinder;
@@ -24,6 +22,8 @@
 import android.os.SystemClock;
 import android.util.Log;
 
+import com.android.frameworks.coretests.aidl.ICmdCallback;
+
 public class Common {
     private static final String EXTRA_KEY_CMD_RECEIVER = "cmd_receiver";
 
diff --git a/core/tests/coretests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/IsolatedTestService.java b/services/tests/powerstatstests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/IsolatedTestService.java
similarity index 100%
rename from core/tests/coretests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/IsolatedTestService.java
rename to services/tests/powerstatstests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/IsolatedTestService.java
diff --git a/core/tests/coretests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/TestActivity.java b/services/tests/powerstatstests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/TestActivity.java
similarity index 100%
rename from core/tests/coretests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/TestActivity.java
rename to services/tests/powerstatstests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/TestActivity.java
diff --git a/core/tests/coretests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/TestService.java b/services/tests/powerstatstests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/TestService.java
similarity index 100%
rename from core/tests/coretests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/TestService.java
rename to services/tests/powerstatstests/BstatsTestApp/src/com/android/coretests/apps/bstatstestapp/TestService.java
diff --git a/services/tests/powerstatstests/OWNERS b/services/tests/powerstatstests/OWNERS
new file mode 100644
index 0000000..9ed0e05
--- /dev/null
+++ b/services/tests/powerstatstests/OWNERS
@@ -0,0 +1,4 @@
+# Bug component: 987260
+
+include /BATTERY_STATS_OWNERS
+include /services/core/java/com/android/server/powerstats/OWNERS
diff --git a/services/tests/powerstatstests/TEST_MAPPING b/services/tests/powerstatstests/TEST_MAPPING
new file mode 100644
index 0000000..e1eb1e4
--- /dev/null
+++ b/services/tests/powerstatstests/TEST_MAPPING
@@ -0,0 +1,22 @@
+{
+  "presubmit": [
+    {
+      "name": "PowerStatsTests",
+      "options": [
+        {"include-filter": "com.android.server.power.stats"},
+        {"exclude-annotation": "android.platform.test.annotations.FlakyTest"},
+        {"exclude-annotation": "androidx.test.filters.FlakyTest"},
+        {"exclude-annotation": "org.junit.Ignore"}
+      ]
+    }
+  ],
+  "postsubmit": [
+    {
+      "name": "PowerStatsTests",
+      "options": [
+        {"include-filter": "com.android.server.power.stats"},
+        {"exclude-annotation": "org.junit.Ignore"}
+      ]
+    }
+  ]
+}
diff --git a/services/tests/servicestests/res/xml/irq_device_map_1.xml b/services/tests/powerstatstests/res/xml/irq_device_map_1.xml
similarity index 100%
rename from services/tests/servicestests/res/xml/irq_device_map_1.xml
rename to services/tests/powerstatstests/res/xml/irq_device_map_1.xml
diff --git a/services/tests/servicestests/res/xml/irq_device_map_2.xml b/services/tests/powerstatstests/res/xml/irq_device_map_2.xml
similarity index 100%
rename from services/tests/servicestests/res/xml/irq_device_map_2.xml
rename to services/tests/powerstatstests/res/xml/irq_device_map_2.xml
diff --git a/services/tests/servicestests/res/xml/irq_device_map_3.xml b/services/tests/powerstatstests/res/xml/irq_device_map_3.xml
similarity index 100%
rename from services/tests/servicestests/res/xml/irq_device_map_3.xml
rename to services/tests/powerstatstests/res/xml/irq_device_map_3.xml
diff --git a/services/tests/servicestests/res/xml/power_profile_test_legacy_modem.xml b/services/tests/powerstatstests/res/xml/power_profile_test_legacy_modem.xml
similarity index 100%
rename from services/tests/servicestests/res/xml/power_profile_test_legacy_modem.xml
rename to services/tests/powerstatstests/res/xml/power_profile_test_legacy_modem.xml
diff --git a/services/tests/servicestests/res/xml/power_profile_test_modem_calculator.xml b/services/tests/powerstatstests/res/xml/power_profile_test_modem_calculator.xml
similarity index 100%
rename from services/tests/servicestests/res/xml/power_profile_test_modem_calculator.xml
rename to services/tests/powerstatstests/res/xml/power_profile_test_modem_calculator.xml
diff --git a/services/tests/servicestests/res/xml/power_profile_test_modem_calculator_multiactive.xml b/services/tests/powerstatstests/res/xml/power_profile_test_modem_calculator_multiactive.xml
similarity index 100%
rename from services/tests/servicestests/res/xml/power_profile_test_modem_calculator_multiactive.xml
rename to services/tests/powerstatstests/res/xml/power_profile_test_modem_calculator_multiactive.xml
diff --git a/services/tests/servicestests/res/xml/power_profile_test_modem_default.xml b/services/tests/powerstatstests/res/xml/power_profile_test_modem_default.xml
similarity index 100%
rename from services/tests/servicestests/res/xml/power_profile_test_modem_default.xml
rename to services/tests/powerstatstests/res/xml/power_profile_test_modem_default.xml
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/AmbientDisplayPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/AmbientDisplayPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/AmbientDisplayPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/AmbientDisplayPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/AudioPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/AudioPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/AudioPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/AudioPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryChargeCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryChargeCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryChargeCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryChargeCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryExternalStatsWorkerTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryExternalStatsWorkerTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryExternalStatsWorkerTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryExternalStatsWorkerTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsBackgroundStatsTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsBackgroundStatsTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsBackgroundStatsTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsBackgroundStatsTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsBinderCallStatsTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsBinderCallStatsTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsBinderCallStatsTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsBinderCallStatsTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsCounterTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsCounterTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsCounterTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsCounterTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsCpuTimesTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsCpuTimesTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsCpuTimesTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsCpuTimesTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsDualTimerTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsDualTimerTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsDualTimerTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsDualTimerTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsDurationTimerTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsDurationTimerTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsDurationTimerTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsDurationTimerTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsHistoryIteratorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsHistoryIteratorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsHistoryIteratorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsHistoryIteratorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsHistoryTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsHistoryTest.java
similarity index 85%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsHistoryTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsHistoryTest.java
index 48ba765..f2cbef6 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsHistoryTest.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsHistoryTest.java
@@ -38,7 +38,6 @@
 
 import com.android.internal.os.BatteryStatsHistory;
 import com.android.internal.os.BatteryStatsHistoryIterator;
-import com.android.internal.os.Clock;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -65,7 +64,7 @@
     private final Parcel mHistoryBuffer = Parcel.obtain();
     private File mSystemDir;
     private File mHistoryDir;
-    private final Clock mClock = new MockClock();
+    private final MockClock mClock = new MockClock();
     private BatteryStatsHistory mHistory;
     private BatteryStats.HistoryPrinter mHistoryPrinter;
     @Mock
@@ -486,10 +485,94 @@
                 NetworkRegistrationInfo.NR_STATE_NONE);
     }
 
+    @Test
+    public void largeTagPool() {
+        // Keep the preserved part of history short - we only need to capture the very tail of
+        // history.
+        mHistory = new BatteryStatsHistory(mHistoryBuffer, mSystemDir, 1, 6000,
+                mStepDetailsCalculator, mClock, mTracer);
+
+        mHistory.forceRecordAllHistory();
+
+        mClock.realtime = 2_000_000;
+        mClock.uptime = 1_000_000;
+        // More than 32k strings
+        final int tagCount = 0x7FFF + 20;
+        for (int tag = 0; tag < tagCount;) {
+            mClock.realtime += 10;
+            mClock.uptime += 10;
+            mHistory.recordEvent(mClock.realtime, mClock.uptime, HistoryItem.EVENT_ALARM_START,
+                    "a" + (tag++), 42);
+
+            mHistory.setBatteryState(true, BatteryManager.BATTERY_STATUS_CHARGING, tag % 50, 0);
+            mClock.realtime += 10;
+            mClock.uptime += 10;
+            mHistory.recordWakelockStartEvent(mClock.realtime, mClock.uptime, "w" + tag, 42);
+            mClock.realtime += 10;
+            mClock.uptime += 10;
+            mHistory.recordWakelockStopEvent(mClock.realtime, mClock.uptime, "w" + tag, 42);
+            tag++;
+
+            mHistory.recordWakeupEvent(mClock.realtime, mClock.uptime, "wr" + (tag++));
+        }
+
+        int eventTagsPooled = 0;
+        int eventTagsUnpooled = 0;
+        int wakelockTagsPooled = 0;
+        int wakelockTagsUnpooled = 0;
+        int wakeReasonTagsPooled = 0;
+        int wakeReasonTagsUnpooled = 0;
+        for (BatteryStatsHistoryIterator iterator = mHistory.iterate(); iterator.hasNext(); ) {
+            HistoryItem item  = iterator.next();
+            if (item.cmd != HistoryItem.CMD_UPDATE) {
+                continue;
+            }
+            String checkinDump = toString(item, true);
+            if (item.eventCode == HistoryItem.EVENT_ALARM_START) {
+                if (item.eventTag.poolIdx != BatteryStats.HistoryTag.HISTORY_TAG_POOL_OVERFLOW) {
+                    eventTagsPooled++;
+                    assertThat(checkinDump).contains("+Eal=" + item.eventTag.poolIdx);
+                } else {
+                    eventTagsUnpooled++;
+                    assertThat(checkinDump).contains("+Eal=42:\"" + item.eventTag.string + "\"");
+                }
+            }
+
+            if (item.wakelockTag != null) {
+                if (item.wakelockTag.poolIdx != BatteryStats.HistoryTag.HISTORY_TAG_POOL_OVERFLOW) {
+                    wakelockTagsPooled++;
+                    assertThat(checkinDump).contains("w=" + item.wakelockTag.poolIdx);
+                } else {
+                    wakelockTagsUnpooled++;
+                    assertThat(checkinDump).contains("w=42:\"" + item.wakelockTag.string + "\"");
+                }
+            }
+
+            if (item.wakeReasonTag != null) {
+                if (item.wakeReasonTag.poolIdx
+                        != BatteryStats.HistoryTag.HISTORY_TAG_POOL_OVERFLOW) {
+                    wakeReasonTagsPooled++;
+                    assertThat(checkinDump).contains("wr=" + item.wakeReasonTag.poolIdx);
+                } else {
+                    wakeReasonTagsUnpooled++;
+                    assertThat(checkinDump).contains("wr=0:\"" + item.wakeReasonTag.string + "\"");
+                }
+            }
+        }
+
+        // Self-check - ensure that we have all cases represented in the test
+        assertThat(eventTagsPooled).isGreaterThan(0);
+        assertThat(eventTagsUnpooled).isGreaterThan(0);
+        assertThat(wakelockTagsPooled).isGreaterThan(0);
+        assertThat(wakelockTagsUnpooled).isGreaterThan(0);
+        assertThat(wakeReasonTagsPooled).isGreaterThan(0);
+        assertThat(wakeReasonTagsUnpooled).isGreaterThan(0);
+    }
+
     private String toString(BatteryStats.HistoryItem item, boolean checkin) {
         StringWriter writer = new StringWriter();
         PrintWriter pw = new PrintWriter(writer);
-        mHistoryPrinter.printNextItem(pw, item, 0, checkin, /* verbose */ true);
+        mHistoryPrinter.printNextItem(pw, item, 0, checkin, /* verbose */ false);
         pw.flush();
         return writer.toString();
     }
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsImplTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsImplTest.java
similarity index 99%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsImplTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsImplTest.java
index f20f061..5ebc6ca 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsImplTest.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsImplTest.java
@@ -267,7 +267,7 @@
         final long[][] delta3 = {
                 {98545, 95768795, 76586, 548945, 57846},
                 {788876, 586, 578459, 8776984, 9578923},
-                {3049509483598l, 4597834, 377654, 94589035, 7854},
+                {3049509483598L, 4597834, 377654, 94589035, 7854},
                 {9493, 784, 99895, 8974893, 9879843}
         };
 
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsManagerTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsManagerTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsManagerTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsManagerTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsNoteTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsNoteTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsNoteTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsNoteTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsResetTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsResetTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsResetTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsResetTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsSamplingTimerTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsSamplingTimerTest.java
similarity index 96%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsSamplingTimerTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsSamplingTimerTest.java
index 784d673..ee68bf8 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsSamplingTimerTest.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsSamplingTimerTest.java
@@ -1,17 +1,17 @@
 /*
  * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.power.stats;
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsSensorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsSensorTest.java
similarity index 98%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsSensorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsSensorTest.java
index b8f0ce3..9c70f37 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsSensorTest.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsSensorTest.java
@@ -1,17 +1,17 @@
 /*
  * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.power.stats;
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsServTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsServTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsServTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsServTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsStopwatchTimerTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsStopwatchTimerTest.java
similarity index 94%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsStopwatchTimerTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsStopwatchTimerTest.java
index fcae42a..18a366c 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsStopwatchTimerTest.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsStopwatchTimerTest.java
@@ -1,17 +1,17 @@
 /*
  * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.power.stats;
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsTimeBaseTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsTimeBaseTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsTimeBaseTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsTimeBaseTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsTimerTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsTimerTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsTimerTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsTimerTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsUserLifecycleTests.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsUserLifecycleTests.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsUserLifecycleTests.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsUserLifecycleTests.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsRule.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsRule.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsRule.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsRule.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsStoreTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsStoreTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsStoreTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsStoreTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BluetoothPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BluetoothPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BluetoothPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BluetoothPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BstatsCpuTimesValidationTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BstatsCpuTimesValidationTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/BstatsCpuTimesValidationTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/BstatsCpuTimesValidationTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/CameraPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/CameraPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/CameraPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/CameraPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/CpuPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/CpuPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/CpuPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/CpuPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/CustomEnergyConsumerPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/CustomEnergyConsumerPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/CustomEnergyConsumerPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/CustomEnergyConsumerPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/EnergyConsumerSnapshotTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/EnergyConsumerSnapshotTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/EnergyConsumerSnapshotTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/EnergyConsumerSnapshotTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/FlashlightPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/FlashlightPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/FlashlightPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/FlashlightPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/GnssPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/GnssPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/GnssPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/GnssPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/IdlePowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/IdlePowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/IdlePowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/IdlePowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/KernelWakelockReaderTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/KernelWakelockReaderTest.java
similarity index 97%
rename from services/tests/servicestests/src/com/android/server/power/stats/KernelWakelockReaderTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/KernelWakelockReaderTest.java
index c0f3c77..2edfc8e 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/KernelWakelockReaderTest.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/KernelWakelockReaderTest.java
@@ -1,17 +1,17 @@
 /*
  * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.power.stats;
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/LongSamplingCounterArrayTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/LongSamplingCounterArrayTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/LongSamplingCounterArrayTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/LongSamplingCounterArrayTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/LongSamplingCounterTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/LongSamplingCounterTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/LongSamplingCounterTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/LongSamplingCounterTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/MemoryPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/MemoryPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/MemoryPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/MemoryPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/MobileRadioPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/MobileRadioPowerCalculatorTest.java
similarity index 99%
rename from services/tests/servicestests/src/com/android/server/power/stats/MobileRadioPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/MobileRadioPowerCalculatorTest.java
index d3ec0d7..888a168 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/MobileRadioPowerCalculatorTest.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/MobileRadioPowerCalculatorTest.java
@@ -46,7 +46,7 @@
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
 
-import com.android.frameworks.servicestests.R;
+import com.android.frameworks.powerstatstests.R;
 
 import com.google.common.collect.Range;
 
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/MockBatteryStatsImpl.java b/services/tests/powerstatstests/src/com/android/server/power/stats/MockBatteryStatsImpl.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/MockBatteryStatsImpl.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/MockBatteryStatsImpl.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/MockClock.java b/services/tests/powerstatstests/src/com/android/server/power/stats/MockClock.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/MockClock.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/MockClock.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/OWNERS b/services/tests/powerstatstests/src/com/android/server/power/stats/OWNERS
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/OWNERS
rename to services/tests/powerstatstests/src/com/android/server/power/stats/OWNERS
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/ScreenPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/ScreenPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/ScreenPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/ScreenPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/SensorPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/SensorPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/SensorPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/SensorPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/SystemServerCpuThreadReaderTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/SystemServerCpuThreadReaderTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/SystemServerCpuThreadReaderTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/SystemServerCpuThreadReaderTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/SystemServicePowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/SystemServicePowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/SystemServicePowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/SystemServicePowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/UserPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/UserPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/UserPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/UserPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/VideoPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/VideoPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/VideoPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/VideoPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/WakelockPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/WakelockPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/WakelockPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/WakelockPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/WifiPowerCalculatorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/WifiPowerCalculatorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/WifiPowerCalculatorTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/WifiPowerCalculatorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/wakeups/CpuWakeupStatsTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/wakeups/CpuWakeupStatsTest.java
similarity index 99%
rename from services/tests/servicestests/src/com/android/server/power/stats/wakeups/CpuWakeupStatsTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/wakeups/CpuWakeupStatsTest.java
index b81b776..0dc836b 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/wakeups/CpuWakeupStatsTest.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/wakeups/CpuWakeupStatsTest.java
@@ -34,7 +34,7 @@
 import androidx.test.InstrumentationRegistry;
 import androidx.test.ext.junit.runners.AndroidJUnit4;
 
-import com.android.frameworks.servicestests.R;
+import com.android.frameworks.powerstatstests.R;
 import com.android.server.power.stats.wakeups.CpuWakeupStats.Wakeup;
 
 import org.junit.Test;
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/wakeups/IrqDeviceMapTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/wakeups/IrqDeviceMapTest.java
similarity index 98%
rename from services/tests/servicestests/src/com/android/server/power/stats/wakeups/IrqDeviceMapTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/wakeups/IrqDeviceMapTest.java
index 47a8f49..9af2884 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/wakeups/IrqDeviceMapTest.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/wakeups/IrqDeviceMapTest.java
@@ -23,7 +23,7 @@
 import androidx.test.InstrumentationRegistry;
 import androidx.test.ext.junit.runners.AndroidJUnit4;
 
-import com.android.frameworks.servicestests.R;
+import com.android.frameworks.powerstatstests.R;
 import com.android.internal.util.CollectionUtils;
 
 import org.junit.Test;
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/wakeups/WakingActivityHistoryTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/wakeups/WakingActivityHistoryTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/power/stats/wakeups/WakingActivityHistoryTest.java
rename to services/tests/powerstatstests/src/com/android/server/power/stats/wakeups/WakingActivityHistoryTest.java
diff --git a/services/tests/servicestests/src/com/android/server/powerstats/IntervalRandomNoiseGeneratorTest.java b/services/tests/powerstatstests/src/com/android/server/powerstats/IntervalRandomNoiseGeneratorTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/powerstats/IntervalRandomNoiseGeneratorTest.java
rename to services/tests/powerstatstests/src/com/android/server/powerstats/IntervalRandomNoiseGeneratorTest.java
diff --git a/services/tests/servicestests/src/com/android/server/powerstats/PowerStatsServiceTest.java b/services/tests/powerstatstests/src/com/android/server/powerstats/PowerStatsServiceTest.java
similarity index 100%
rename from services/tests/servicestests/src/com/android/server/powerstats/PowerStatsServiceTest.java
rename to services/tests/powerstatstests/src/com/android/server/powerstats/PowerStatsServiceTest.java
diff --git a/services/tests/servicestests/Android.bp b/services/tests/servicestests/Android.bp
index 173c5f5..92ff7ab 100644
--- a/services/tests/servicestests/Android.bp
+++ b/services/tests/servicestests/Android.bp
@@ -112,7 +112,6 @@
     },
 
     data: [
-        ":BstatsTestApp",
         ":JobTestApp",
         ":SimpleServiceTestApp1",
         ":SimpleServiceTestApp2",
@@ -134,7 +133,6 @@
     name: "servicestests-core-utils",
     srcs: [
         "src/com/android/server/am/DeviceConfigSession.java",
-        "src/com/android/server/display/TestUtils.java",
         "src/com/android/server/pm/PackageSettingBuilder.java",
         "src/com/android/server/pm/parsing/TestPackageParser2.kt",
     ],
diff --git a/services/tests/servicestests/AndroidTest.xml b/services/tests/servicestests/AndroidTest.xml
index fbb0ca1..b1d5039 100644
--- a/services/tests/servicestests/AndroidTest.xml
+++ b/services/tests/servicestests/AndroidTest.xml
@@ -28,7 +28,6 @@
     <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="BstatsTestApp.apk" />
         <option name="test-file-name" value="FrameworksServicesTests.apk" />
         <option name="test-file-name" value="JobTestApp.apk" />
         <option name="test-file-name" value="SuspendTestApp.apk" />
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationGestureHandlerTest.java b/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationGestureHandlerTest.java
index 19fb2c9..0a8c570 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationGestureHandlerTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationGestureHandlerTest.java
@@ -51,7 +51,6 @@
 import android.os.UserHandle;
 import android.os.VibrationEffect;
 import android.os.Vibrator;
-import android.platform.test.annotations.FlakyTest;
 import android.provider.Settings;
 import android.testing.TestableContext;
 import android.util.DebugUtils;
@@ -59,6 +58,7 @@
 import android.view.MotionEvent;
 import android.view.ViewConfiguration;
 
+import androidx.test.filters.FlakyTest;
 import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.util.ConcurrentUtils;
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/AuthSessionTest.java b/services/tests/servicestests/src/com/android/server/biometrics/AuthSessionTest.java
index 0cfddd3..769be17 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/AuthSessionTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/AuthSessionTest.java
@@ -351,6 +351,8 @@
         assertEquals(startFingerprintNow ? BiometricSensor.STATE_AUTHENTICATING
                         : BiometricSensor.STATE_COOKIE_RETURNED,
                 session.mPreAuthInfo.eligibleSensors.get(fingerprintSensorId).getSensorState());
+        verify(mBiometricContext).updateContext((OperationContextExt) anyObject(),
+                eq(session.isCrypto()));
 
         // start fingerprint sensor if it was delayed
         if (!startFingerprintNow) {
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/AuthenticationStatsCollectorTest.java b/services/tests/servicestests/src/com/android/server/biometrics/AuthenticationStatsCollectorTest.java
new file mode 100644
index 0000000..746fb53
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/biometrics/AuthenticationStatsCollectorTest.java
@@ -0,0 +1,281 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.biometrics;
+
+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.anySet;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+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 static java.util.Collections.emptySet;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.content.pm.PackageManager;
+import android.content.res.Resources;
+import android.hardware.face.FaceManager;
+import android.hardware.fingerprint.FingerprintManager;
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.internal.R;
+import com.android.server.biometrics.sensors.BiometricNotification;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.io.File;
+
+@Presubmit
+@SmallTest
+public class AuthenticationStatsCollectorTest {
+
+    private AuthenticationStatsCollector mAuthenticationStatsCollector;
+    private static final float FRR_THRESHOLD = 0.2f;
+    private static final int USER_ID_1 = 1;
+
+    @Mock
+    private Context mContext;
+    @Mock
+    private Resources mResources;
+    @Mock
+    private PackageManager mPackageManager;
+    @Mock
+    private FingerprintManager mFingerprintManager;
+    @Mock
+    private FaceManager mFaceManager;
+    @Mock
+    private SharedPreferences mSharedPreferences;
+    @Mock
+    private BiometricNotification mBiometricNotification;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+
+        when(mContext.getResources()).thenReturn(mResources);
+        when(mResources.getFraction(eq(R.fraction.config_biometricNotificationFrrThreshold),
+                anyInt(), anyInt())).thenReturn(FRR_THRESHOLD);
+
+        when(mContext.getPackageManager()).thenReturn(mPackageManager);
+
+        when(mContext.getSystemServiceName(FingerprintManager.class))
+                .thenReturn(Context.FINGERPRINT_SERVICE);
+        when(mContext.getSystemService(Context.FINGERPRINT_SERVICE))
+                .thenReturn(mFingerprintManager);
+        when(mContext.getSystemServiceName(FaceManager.class)).thenReturn(Context.FACE_SERVICE);
+        when(mContext.getSystemService(Context.FACE_SERVICE)).thenReturn(mFaceManager);
+
+        when(mContext.getSharedPreferences(any(File.class), anyInt()))
+                .thenReturn(mSharedPreferences);
+        when(mSharedPreferences.getStringSet(anyString(), anySet())).thenReturn(emptySet());
+
+        mAuthenticationStatsCollector = new AuthenticationStatsCollector(mContext,
+                0 /* modality */, mBiometricNotification);
+    }
+
+
+    @Test
+    public void authenticate_authenticationSucceeded_mapShouldBeUpdated() {
+        // Assert that the user doesn't exist in the map initially.
+        assertThat(mAuthenticationStatsCollector.getAuthenticationStatsForUser(USER_ID_1)).isNull();
+
+        mAuthenticationStatsCollector.authenticate(USER_ID_1, true /* authenticated */);
+
+        AuthenticationStats authenticationStats =
+                mAuthenticationStatsCollector.getAuthenticationStatsForUser(USER_ID_1);
+        assertThat(authenticationStats.getUserId()).isEqualTo(USER_ID_1);
+        assertThat(authenticationStats.getTotalAttempts()).isEqualTo(1);
+        assertThat(authenticationStats.getRejectedAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getEnrollmentNotifications()).isEqualTo(0);
+    }
+
+    @Test
+    public void authenticate_authenticationFailed_mapShouldBeUpdated() {
+        // Assert that the user doesn't exist in the map initially.
+        assertThat(mAuthenticationStatsCollector.getAuthenticationStatsForUser(USER_ID_1)).isNull();
+
+        mAuthenticationStatsCollector.authenticate(USER_ID_1, false /* authenticated */);
+
+        AuthenticationStats authenticationStats =
+                mAuthenticationStatsCollector.getAuthenticationStatsForUser(USER_ID_1);
+
+        assertThat(authenticationStats.getUserId()).isEqualTo(USER_ID_1);
+        assertThat(authenticationStats.getTotalAttempts()).isEqualTo(1);
+        assertThat(authenticationStats.getRejectedAttempts()).isEqualTo(1);
+        assertThat(authenticationStats.getEnrollmentNotifications()).isEqualTo(0);
+    }
+
+    @Test
+    public void authenticate_frrNotExceeded_notificationNotExceeded_shouldNotSendNotification() {
+
+        mAuthenticationStatsCollector.setAuthenticationStatsForUser(USER_ID_1,
+                new AuthenticationStats(USER_ID_1, 500 /* totalAttempts */,
+                        40 /* rejectedAttempts */, 0 /* enrollmentNotifications */,
+                        0 /* modality */));
+
+        mAuthenticationStatsCollector.authenticate(USER_ID_1, false /* authenticated */);
+
+        // Assert that no notification should be sent.
+        verify(mBiometricNotification, never()).sendFaceEnrollNotification(any());
+        verify(mBiometricNotification, never()).sendFpEnrollNotification(any());
+        // Assert that data has been reset.
+        AuthenticationStats authenticationStats = mAuthenticationStatsCollector
+                .getAuthenticationStatsForUser(USER_ID_1);
+        assertThat(authenticationStats.getTotalAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getRejectedAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getFrr()).isWithin(0f).of(-1.0f);
+    }
+
+    @Test
+    public void authenticate_frrExceeded_notificationExceeded_shouldNotSendNotification() {
+
+        mAuthenticationStatsCollector.setAuthenticationStatsForUser(USER_ID_1,
+                new AuthenticationStats(USER_ID_1, 500 /* totalAttempts */,
+                        400 /* rejectedAttempts */, 2 /* enrollmentNotifications */,
+                        0 /* modality */));
+
+        mAuthenticationStatsCollector.authenticate(USER_ID_1, false /* authenticated */);
+
+        // Assert that no notification should be sent.
+        verify(mBiometricNotification, never()).sendFaceEnrollNotification(any());
+        verify(mBiometricNotification, never()).sendFpEnrollNotification(any());
+        // Assert that data has been reset.
+        AuthenticationStats authenticationStats = mAuthenticationStatsCollector
+                .getAuthenticationStatsForUser(USER_ID_1);
+        assertThat(authenticationStats.getTotalAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getRejectedAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getFrr()).isWithin(0f).of(-1.0f);
+    }
+
+    @Test
+    public void authenticate_frrExceeded_bothBiometricsEnrolled_shouldNotSendNotification() {
+
+        mAuthenticationStatsCollector.setAuthenticationStatsForUser(USER_ID_1,
+                new AuthenticationStats(USER_ID_1, 500 /* totalAttempts */,
+                        400 /* rejectedAttempts */, 0 /* enrollmentNotifications */,
+                        0 /* modality */));
+
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
+                .thenReturn(true);
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE)).thenReturn(true);
+        when(mFingerprintManager.hasEnrolledTemplates(anyInt())).thenReturn(true);
+        when(mFaceManager.hasEnrolledTemplates(anyInt())).thenReturn(true);
+
+        mAuthenticationStatsCollector.authenticate(USER_ID_1, false /* authenticated */);
+
+        // Assert that no notification should be sent.
+        verify(mBiometricNotification, never()).sendFaceEnrollNotification(any());
+        verify(mBiometricNotification, never()).sendFpEnrollNotification(any());
+        // Assert that data has been reset.
+        AuthenticationStats authenticationStats = mAuthenticationStatsCollector
+                .getAuthenticationStatsForUser(USER_ID_1);
+        assertThat(authenticationStats.getTotalAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getRejectedAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getFrr()).isWithin(0f).of(-1.0f);
+    }
+
+    @Test
+    public void authenticate_frrExceeded_singleModality_shouldNotSendNotification() {
+
+        mAuthenticationStatsCollector.setAuthenticationStatsForUser(USER_ID_1,
+                new AuthenticationStats(USER_ID_1, 500 /* totalAttempts */,
+                        400 /* rejectedAttempts */, 0 /* enrollmentNotifications */,
+                        0 /* modality */));
+
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
+                .thenReturn(true);
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE)).thenReturn(false);
+        when(mFingerprintManager.hasEnrolledTemplates(anyInt())).thenReturn(true);
+
+        mAuthenticationStatsCollector.authenticate(USER_ID_1, false /* authenticated */);
+
+        // Assert that no notification should be sent.
+        verify(mBiometricNotification, never()).sendFaceEnrollNotification(any());
+        verify(mBiometricNotification, never()).sendFpEnrollNotification(any());
+        // Assert that data has been reset.
+        AuthenticationStats authenticationStats = mAuthenticationStatsCollector
+                .getAuthenticationStatsForUser(USER_ID_1);
+        assertThat(authenticationStats.getTotalAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getRejectedAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getFrr()).isWithin(0f).of(-1.0f);
+    }
+
+    @Test
+    public void authenticate_frrExceeded_faceEnrolled_shouldSendFpNotification() {
+        mAuthenticationStatsCollector.setAuthenticationStatsForUser(USER_ID_1,
+                new AuthenticationStats(USER_ID_1, 500 /* totalAttempts */,
+                        400 /* rejectedAttempts */, 0 /* enrollmentNotifications */,
+                        0 /* modality */));
+
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
+                .thenReturn(true);
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE)).thenReturn(true);
+        when(mFingerprintManager.hasEnrolledTemplates(anyInt())).thenReturn(false);
+        when(mFaceManager.hasEnrolledTemplates(anyInt())).thenReturn(true);
+
+        mAuthenticationStatsCollector.authenticate(USER_ID_1, false /* authenticated */);
+
+        // Assert that fingerprint enrollment notification should be sent.
+        verify(mBiometricNotification, times(1))
+                .sendFpEnrollNotification(mContext);
+        verify(mBiometricNotification, never()).sendFaceEnrollNotification(any());
+        // Assert that data has been reset.
+        AuthenticationStats authenticationStats = mAuthenticationStatsCollector
+                .getAuthenticationStatsForUser(USER_ID_1);
+        assertThat(authenticationStats.getTotalAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getRejectedAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getFrr()).isWithin(0f).of(-1.0f);
+    }
+
+    @Test
+    public void authenticate_frrExceeded_fpEnrolled_shouldSendFaceNotification() {
+        mAuthenticationStatsCollector.setAuthenticationStatsForUser(USER_ID_1,
+                new AuthenticationStats(USER_ID_1, 500 /* totalAttempts */,
+                        400 /* rejectedAttempts */, 0 /* enrollmentNotifications */,
+                        0 /* modality */));
+
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
+                .thenReturn(true);
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE)).thenReturn(true);
+        when(mFingerprintManager.hasEnrolledTemplates(anyInt())).thenReturn(true);
+        when(mFaceManager.hasEnrolledTemplates(anyInt())).thenReturn(false);
+
+        mAuthenticationStatsCollector.authenticate(USER_ID_1, false /* authenticated */);
+
+        // Assert that fingerprint enrollment notification should be sent.
+        verify(mBiometricNotification, times(1))
+                .sendFaceEnrollNotification(mContext);
+        verify(mBiometricNotification, never()).sendFpEnrollNotification(any());
+        // Assert that data has been reset.
+        AuthenticationStats authenticationStats = mAuthenticationStatsCollector
+                .getAuthenticationStatsForUser(USER_ID_1);
+        assertThat(authenticationStats.getTotalAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getRejectedAttempts()).isEqualTo(0);
+        assertThat(authenticationStats.getFrr()).isWithin(0f).of(-1.0f);
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/AuthenticationStatsPersisterTest.java b/services/tests/servicestests/src/com/android/server/biometrics/AuthenticationStatsPersisterTest.java
new file mode 100644
index 0000000..dde2a3c
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/biometrics/AuthenticationStatsPersisterTest.java
@@ -0,0 +1,252 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.biometrics;
+
+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.anySet;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.hardware.biometrics.BiometricsProtoEnums;
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.filters.SmallTest;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoRule;
+
+import java.io.File;
+import java.util.List;
+import java.util.Set;
+
+@Presubmit
+@SmallTest
+public class AuthenticationStatsPersisterTest {
+
+    @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
+
+    private static final int USER_ID_1 = 1;
+    private static final int USER_ID_2 = 2;
+    private static final String USER_ID = "user_id";
+    private static final String FACE_ATTEMPTS = "face_attempts";
+    private static final String FACE_REJECTIONS = "face_rejections";
+    private static final String FINGERPRINT_ATTEMPTS = "fingerprint_attempts";
+    private static final String FINGERPRINT_REJECTIONS = "fingerprint_rejections";
+    private static final String ENROLLMENT_NOTIFICATIONS = "enrollment_notifications";
+    private static final String KEY = "frr_stats";
+
+    @Mock
+    private Context mContext;
+    @Mock
+    private SharedPreferences mSharedPreferences;
+    @Mock
+    private SharedPreferences.Editor mEditor;
+    private AuthenticationStatsPersister mAuthenticationStatsPersister;
+
+    @Captor
+    private ArgumentCaptor<Set<String>> mStringSetArgumentCaptor;
+
+    @Before
+    public void setUp() {
+        when(mContext.getSharedPreferences(any(File.class), anyInt()))
+                .thenReturn(mSharedPreferences);
+        when(mSharedPreferences.edit()).thenReturn(mEditor);
+        when(mEditor.putStringSet(anyString(), anySet())).thenReturn(mEditor);
+
+        mAuthenticationStatsPersister = new AuthenticationStatsPersister(mContext);
+    }
+
+    @Test
+    public void getAllFrrStats_face_shouldListAllFrrStats() throws JSONException {
+        AuthenticationStats stats1 = new AuthenticationStats(USER_ID_1,
+                300 /* totalAttempts */, 10 /* rejectedAttempts */,
+                0 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FACE);
+        AuthenticationStats stats2 = new AuthenticationStats(USER_ID_2,
+                200 /* totalAttempts */, 20 /* rejectedAttempts */,
+                0 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FINGERPRINT);
+        when(mSharedPreferences.getStringSet(eq(KEY), anySet())).thenReturn(
+                Set.of(buildFrrStats(stats1), buildFrrStats(stats2)));
+
+        List<AuthenticationStats> authenticationStatsList =
+                mAuthenticationStatsPersister.getAllFrrStats(BiometricsProtoEnums.MODALITY_FACE);
+
+        assertThat(authenticationStatsList.size()).isEqualTo(2);
+        AuthenticationStats expectedStats2 = new AuthenticationStats(USER_ID_2,
+                0 /* totalAttempts */, 0 /* rejectedAttempts */,
+                0 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FACE);
+        assertThat(authenticationStatsList).contains(stats1);
+        assertThat(authenticationStatsList).contains(expectedStats2);
+    }
+
+    @Test
+    public void getAllFrrStats_fingerprint_shouldListAllFrrStats() throws JSONException {
+        // User 1 with fingerprint authentication stats.
+        AuthenticationStats stats1 = new AuthenticationStats(USER_ID_1,
+                200 /* totalAttempts */, 20 /* rejectedAttempts */,
+                0 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FINGERPRINT);
+        // User 2 without fingerprint authentication stats.
+        AuthenticationStats stats2 = new AuthenticationStats(USER_ID_2,
+                300 /* totalAttempts */, 10 /* rejectedAttempts */,
+                0 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FACE);
+        when(mSharedPreferences.getStringSet(eq(KEY), anySet())).thenReturn(
+                Set.of(buildFrrStats(stats1), buildFrrStats(stats2)));
+
+        List<AuthenticationStats> authenticationStatsList =
+                mAuthenticationStatsPersister
+                        .getAllFrrStats(BiometricsProtoEnums.MODALITY_FINGERPRINT);
+
+        assertThat(authenticationStatsList.size()).isEqualTo(2);
+        AuthenticationStats expectedStats2 = new AuthenticationStats(USER_ID_2,
+                0 /* totalAttempts */, 0 /* rejectedAttempts */,
+                0 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FINGERPRINT);
+        assertThat(authenticationStatsList).contains(stats1);
+        assertThat(authenticationStatsList).contains(expectedStats2);
+    }
+
+    @Test
+    public void persistFrrStats_newUser_face_shouldSuccess() throws JSONException {
+        AuthenticationStats authenticationStats = new AuthenticationStats(USER_ID_1,
+                300 /* totalAttempts */, 10 /* rejectedAttempts */,
+                0 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FACE);
+
+        mAuthenticationStatsPersister.persistFrrStats(authenticationStats.getUserId(),
+                authenticationStats.getTotalAttempts(),
+                authenticationStats.getRejectedAttempts(),
+                authenticationStats.getEnrollmentNotifications(),
+                authenticationStats.getModality());
+
+        verify(mEditor).putStringSet(eq(KEY), mStringSetArgumentCaptor.capture());
+        assertThat(mStringSetArgumentCaptor.getValue())
+                .contains(buildFrrStats(authenticationStats));
+    }
+
+    @Test
+    public void persistFrrStats_newUser_fingerprint_shouldSuccess() throws JSONException {
+        AuthenticationStats authenticationStats = new AuthenticationStats(USER_ID_1,
+                300 /* totalAttempts */, 10 /* rejectedAttempts */,
+                0 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FINGERPRINT);
+
+        mAuthenticationStatsPersister.persistFrrStats(authenticationStats.getUserId(),
+                authenticationStats.getTotalAttempts(),
+                authenticationStats.getRejectedAttempts(),
+                authenticationStats.getEnrollmentNotifications(),
+                authenticationStats.getModality());
+
+        verify(mEditor).putStringSet(eq(KEY), mStringSetArgumentCaptor.capture());
+        assertThat(mStringSetArgumentCaptor.getValue())
+                .contains(buildFrrStats(authenticationStats));
+    }
+
+    @Test
+    public void persistFrrStats_existingUser_shouldUpdateRecord() throws JSONException {
+        AuthenticationStats authenticationStats = new AuthenticationStats(USER_ID_1,
+                300 /* totalAttempts */, 10 /* rejectedAttempts */,
+                0 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FACE);
+        AuthenticationStats newAuthenticationStats = new AuthenticationStats(USER_ID_1,
+                500 /* totalAttempts */, 30 /* rejectedAttempts */,
+                1 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FACE);
+        when(mSharedPreferences.getStringSet(eq(KEY), anySet())).thenReturn(
+                Set.of(buildFrrStats(authenticationStats)));
+
+        mAuthenticationStatsPersister.persistFrrStats(newAuthenticationStats.getUserId(),
+                newAuthenticationStats.getTotalAttempts(),
+                newAuthenticationStats.getRejectedAttempts(),
+                newAuthenticationStats.getEnrollmentNotifications(),
+                newAuthenticationStats.getModality());
+
+        verify(mEditor).putStringSet(eq(KEY), mStringSetArgumentCaptor.capture());
+        assertThat(mStringSetArgumentCaptor.getValue())
+                .contains(buildFrrStats(newAuthenticationStats));
+    }
+
+    @Test
+    public void persistFrrStats_existingUserWithFingerprint_faceAuthenticate_shouldUpdateRecord()
+            throws JSONException {
+        // User with fingerprint authentication stats.
+        AuthenticationStats authenticationStats = new AuthenticationStats(USER_ID_1,
+                200 /* totalAttempts */, 20 /* rejectedAttempts */,
+                0 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FINGERPRINT);
+        // The same user with face authentication stats.
+        AuthenticationStats newAuthenticationStats = new AuthenticationStats(USER_ID_1,
+                500 /* totalAttempts */, 30 /* rejectedAttempts */,
+                1 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FACE);
+        when(mSharedPreferences.getStringSet(eq(KEY), anySet())).thenReturn(
+                Set.of(buildFrrStats(authenticationStats)));
+
+        mAuthenticationStatsPersister.persistFrrStats(newAuthenticationStats.getUserId(),
+                newAuthenticationStats.getTotalAttempts(),
+                newAuthenticationStats.getRejectedAttempts(),
+                newAuthenticationStats.getEnrollmentNotifications(),
+                newAuthenticationStats.getModality());
+
+        String expectedFrrStats = new JSONObject(buildFrrStats(authenticationStats))
+                .put(ENROLLMENT_NOTIFICATIONS, newAuthenticationStats.getEnrollmentNotifications())
+                .put(FACE_ATTEMPTS, newAuthenticationStats.getTotalAttempts())
+                .put(FACE_REJECTIONS, newAuthenticationStats.getRejectedAttempts()).toString();
+        verify(mEditor).putStringSet(eq(KEY), mStringSetArgumentCaptor.capture());
+        assertThat(mStringSetArgumentCaptor.getValue()).contains(expectedFrrStats);
+    }
+
+    @Test
+    public void removeFrrStats_existingUser_shouldUpdateRecord() throws JSONException {
+        AuthenticationStats authenticationStats = new AuthenticationStats(USER_ID_1,
+                300 /* totalAttempts */, 10 /* rejectedAttempts */,
+                0 /* enrollmentNotifications */, BiometricsProtoEnums.MODALITY_FACE);
+        when(mSharedPreferences.getStringSet(eq(KEY), anySet())).thenReturn(
+                Set.of(buildFrrStats(authenticationStats)));
+
+        mAuthenticationStatsPersister.removeFrrStats(USER_ID_1);
+
+        verify(mEditor).putStringSet(eq(KEY), mStringSetArgumentCaptor.capture());
+        assertThat(mStringSetArgumentCaptor.getValue()).doesNotContain(authenticationStats);
+    }
+
+    private String buildFrrStats(AuthenticationStats authenticationStats)
+            throws JSONException {
+        if (authenticationStats.getModality() == BiometricsProtoEnums.MODALITY_FACE) {
+            return new JSONObject()
+                    .put(USER_ID, authenticationStats.getUserId())
+                    .put(FACE_ATTEMPTS, authenticationStats.getTotalAttempts())
+                    .put(FACE_REJECTIONS, authenticationStats.getRejectedAttempts())
+                    .put(ENROLLMENT_NOTIFICATIONS, authenticationStats.getEnrollmentNotifications())
+                    .toString();
+        } else if (authenticationStats.getModality() == BiometricsProtoEnums.MODALITY_FINGERPRINT) {
+            return new JSONObject()
+                    .put(USER_ID, authenticationStats.getUserId())
+                    .put(FINGERPRINT_ATTEMPTS, authenticationStats.getTotalAttempts())
+                    .put(FINGERPRINT_REJECTIONS, authenticationStats.getRejectedAttempts())
+                    .put(ENROLLMENT_NOTIFICATIONS, authenticationStats.getEnrollmentNotifications())
+                    .toString();
+        }
+        return "";
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/AuthenticationStatsTest.java b/services/tests/servicestests/src/com/android/server/biometrics/AuthenticationStatsTest.java
new file mode 100644
index 0000000..e8e72cb
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/biometrics/AuthenticationStatsTest.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.biometrics;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class AuthenticationStatsTest {
+
+    @Test
+    public void authenticate_statsShouldBeUpdated() {
+        AuthenticationStats authenticationStats =
+                new AuthenticationStats(1 /* userId */ , 0 /* totalAttempts */,
+                        0 /* rejectedAttempts */, 0 /* enrollmentNotifications */,
+                        0 /* modality */);
+
+        authenticationStats.authenticate(true /* authenticated */);
+
+        assertEquals(authenticationStats.getTotalAttempts(), 1);
+        assertEquals(authenticationStats.getRejectedAttempts(), 0);
+
+        authenticationStats.authenticate(false /* authenticated */);
+
+        assertEquals(authenticationStats.getTotalAttempts(), 2);
+        assertEquals(authenticationStats.getRejectedAttempts(), 1);
+    }
+}
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 fc62e75..e79ac09 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
@@ -16,6 +16,7 @@
 
 package com.android.server.biometrics;
 
+import static android.hardware.biometrics.BiometricAuthenticator.TYPE_CREDENTIAL;
 import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FACE;
 import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FINGERPRINT;
 import static android.hardware.biometrics.BiometricManager.Authenticators;
@@ -116,9 +117,9 @@
     private static final String ERROR_LOCKOUT = "error_lockout";
     private static final String FACE_SUBTITLE = "face_subtitle";
     private static final String FINGERPRINT_SUBTITLE = "fingerprint_subtitle";
+    private static final String CREDENTIAL_SUBTITLE = "credential_subtitle";
     private static final String DEFAULT_SUBTITLE = "default_subtitle";
 
-
     private static final String FINGERPRINT_ACQUIRED_SENSOR_DIRTY = "sensor_dirty";
 
     private static final int SENSOR_ID_FINGERPRINT = 0;
@@ -143,6 +144,8 @@
     @Mock
     IBiometricAuthenticator mFaceAuthenticator;
     @Mock
+    IBiometricAuthenticator mCredentialAuthenticator;
+    @Mock
     ITrustManager mTrustManager;
     @Mock
     DevicePolicyManager mDevicePolicyManager;
@@ -196,10 +199,12 @@
                 .thenReturn(ERROR_NOT_RECOGNIZED);
         when(mResources.getString(R.string.biometric_error_user_canceled))
                 .thenReturn(ERROR_USER_CANCELED);
-        when(mContext.getString(R.string.biometric_dialog_face_subtitle))
+        when(mContext.getString(R.string.face_dialog_default_subtitle))
                 .thenReturn(FACE_SUBTITLE);
-        when(mContext.getString(R.string.biometric_dialog_fingerprint_subtitle))
+        when(mContext.getString(R.string.fingerprint_dialog_default_subtitle))
                 .thenReturn(FINGERPRINT_SUBTITLE);
+        when(mContext.getString(R.string.screen_lock_dialog_default_subtitle))
+                .thenReturn(CREDENTIAL_SUBTITLE);
         when(mContext.getString(R.string.biometric_dialog_default_subtitle))
                 .thenReturn(DEFAULT_SUBTITLE);
 
@@ -292,7 +297,8 @@
         mBiometricService.onStart();
 
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
-                Authenticators.DEVICE_CREDENTIAL);
+                Authenticators.DEVICE_CREDENTIAL, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
         verify(mReceiver1).onError(
                 eq(BiometricAuthenticator.TYPE_CREDENTIAL),
@@ -312,7 +318,8 @@
         mBiometricService.onStart();
 
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
-                Authenticators.DEVICE_CREDENTIAL);
+                Authenticators.DEVICE_CREDENTIAL, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
 
         assertNotNull(mBiometricService.mAuthSession);
@@ -338,7 +345,8 @@
         mBiometricService.onStart();
 
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
-                null /* authenticators */);
+                null /* authenticators */, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
         verify(mReceiver1).onError(
                 eq(BiometricAuthenticator.TYPE_NONE),
@@ -357,7 +365,8 @@
                 mFingerprintAuthenticator);
 
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
-                null /* authenticators */);
+                null /* authenticators */, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
         verify(mReceiver1).onError(
                 eq(TYPE_FINGERPRINT),
@@ -370,7 +379,8 @@
         setupAuthForOnly(TYPE_FINGERPRINT, Authenticators.BIOMETRIC_WEAK);
 
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
-                Authenticators.BIOMETRIC_STRONG);
+                Authenticators.BIOMETRIC_STRONG, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
         verify(mReceiver1).onError(
                 eq(BiometricAuthenticator.TYPE_NONE),
@@ -429,7 +439,8 @@
                 mFingerprintAuthenticator);
 
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
-                null /* authenticators */);
+                null /* authenticators */, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
         verify(mReceiver1).onError(
                 eq(TYPE_FINGERPRINT),
@@ -441,9 +452,9 @@
     public void testAuthenticateFace_shouldShowSubtitleForFace() throws Exception {
         setupAuthForOnly(TYPE_FACE, Authenticators.BIOMETRIC_STRONG);
 
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */,
-                null);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                null /* authenticators */, true /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
 
         assertEquals(FACE_SUBTITLE, mBiometricService.mAuthSession.mPromptInfo.getSubtitle());
@@ -453,9 +464,9 @@
     public void testAuthenticateFingerprint_shouldShowSubtitleForFingerprint() throws Exception {
         setupAuthForOnly(TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
 
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */,
-                null);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                null /* authenticators */, true /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
 
         assertEquals(FINGERPRINT_SUBTITLE,
@@ -463,6 +474,19 @@
     }
 
     @Test
+    public void testAuthenticateFingerprint_shouldShowSubtitleForCredential() throws Exception {
+        setupAuthForOnly(TYPE_CREDENTIAL, Authenticators.DEVICE_CREDENTIAL);
+
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                null /* authenticators */, true /* useDefaultSubtitle */,
+                true /* deviceCredentialAllowed */);
+        waitForIdle();
+
+        assertEquals(CREDENTIAL_SUBTITLE,
+                mBiometricService.mAuthSession.mPromptInfo.getSubtitle());
+    }
+
+    @Test
     public void testAuthenticateBothFpAndFace_shouldShowDefaultSubtitle() throws Exception {
         final int[] modalities = new int[] {
                 TYPE_FINGERPRINT,
@@ -476,9 +500,9 @@
 
         setupAuthForMultiple(modalities, strengths);
 
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */,
-                null);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                null /* authenticators */, true /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
 
         assertEquals(DEFAULT_SUBTITLE, mBiometricService.mAuthSession.mPromptInfo.getSubtitle());
@@ -492,7 +516,8 @@
         // Disabled in user settings receives onError
         when(mBiometricService.mSettingObserver.getEnabledForApps(anyInt())).thenReturn(false);
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
-                null /* authenticators */);
+                null /* authenticators */, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
         verify(mReceiver1).onError(
                 eq(BiometricAuthenticator.TYPE_NONE),
@@ -506,7 +531,8 @@
                 anyInt() /* modality */, anyInt() /* userId */))
                 .thenReturn(true);
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
-                null /* authenticators */);
+                null /* authenticators */, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
         verify(mReceiver1, never()).onError(anyInt(), anyInt(), anyInt());
         final byte[] HAT = generateRandomHAT();
@@ -524,7 +550,8 @@
                 anyInt() /* modality */, anyInt() /* userId */))
                 .thenReturn(false);
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
-                null /* authenticators */);
+                null /* authenticators */, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
         mBiometricService.mAuthSession.mSensorReceiver.onAuthenticationSucceeded(
                 SENSOR_ID_FACE,
@@ -552,7 +579,8 @@
             throws Exception {
         // Start testing the happy path
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
-                null /* authenticators */);
+                null /* authenticators */, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
 
         // Creates a pending auth session with the correct initial states
@@ -632,7 +660,8 @@
                 .thenReturn(true);
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
                 true /* requireConfirmation */,
-                Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK);
+                Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK,
+                false /* useDefaultSubtitle*/, false /* deviceCredentialAllowed */);
         waitForIdle();
 
         assertEquals(STATE_SHOWING_DEVICE_CREDENTIAL,
@@ -702,7 +731,8 @@
 
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
                 true /* requireConfirmation */,
-                Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_STRONG);
+                Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_STRONG,
+                false /* useDefaultSubtitle */, false /* deviceCredentialAllowed */);
         waitForIdle();
 
         verify(mReceiver1).onError(anyInt() /* modality */,
@@ -754,7 +784,8 @@
                 false /* requireConfirmation */, null /* authenticators */);
 
         invokeAuthenticate(mBiometricService.mImpl, mReceiver2, false /* requireConfirmation */,
-                null /* authenticators */);
+                null /* authenticators */, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
 
         verify(mReceiver1).onError(
@@ -887,7 +918,8 @@
         setupAuthForOnly(TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
                 false /* requireConfirmation */,
-                Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK);
+                Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK,
+                false /* useDefaultSubtitle */, false /* deviceCredentialAllowed */);
         waitForIdle();
 
         assertEquals(STATE_AUTH_CALLED, mBiometricService.mAuthSession.getState());
@@ -920,8 +952,9 @@
     public void testErrorFromHal_whilePreparingAuthentication_credentialNotAllowed()
             throws Exception {
         setupAuthForOnly(TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */, null /* authenticators */);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                null /* authenticators */, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
 
         mBiometricService.mAuthSession.mSensorReceiver.onError(
@@ -957,8 +990,9 @@
         setupAuthForOnly(TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
         when(mFingerprintAuthenticator.getLockoutModeForUser(anyInt()))
                 .thenReturn(lockoutMode);
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */, null /* authenticators */);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                null /* authenticators */, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
 
         // Modality and error are sent
@@ -996,8 +1030,9 @@
         when(mFingerprintAuthenticator.getLockoutModeForUser(anyInt()))
                 .thenReturn(lockoutMode);
         when(mFaceAuthenticator.hasEnrolledTemplates(anyInt(), any())).thenReturn(false);
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */, null /* authenticators */);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                null /* authenticators */, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
 
         // The lockout error should be sent, instead of ERROR_NONE_ENROLLED. See b/286923477.
@@ -1014,7 +1049,8 @@
                 .thenReturn(LockoutTracker.LOCKOUT_PERMANENT);
         invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
                 false /* requireConfirmation */,
-                Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_STRONG);
+                Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_STRONG,
+                false /* useDefaultSubtitle */, false /* deviceCredentialAllowed */);
         waitForIdle();
 
         verify(mReceiver1, never()).onError(anyInt(), anyInt(), anyInt());
@@ -1503,7 +1539,8 @@
         assertEquals(BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED,
                 invokeCanAuthenticate(mBiometricService, authenticators));
         long requestId = invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */, authenticators);
+                false /* requireConfirmation */, authenticators, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
         verify(mReceiver1).onError(
                 eq(TYPE_FINGERPRINT),
@@ -1539,7 +1576,8 @@
                 invokeCanAuthenticate(mBiometricService, authenticators));
         requestId = invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
                 false /* requireConfirmation */,
-                authenticators);
+                authenticators, false /* useDefaultSubtitle */,
+                false /* deviceCredentialAllowed */);
         waitForIdle();
         assertTrue(Utils.isCredentialRequested(mBiometricService.mAuthSession.mPromptInfo));
         verify(mBiometricService.mStatusBarService).showAuthenticationDialog(
@@ -1749,6 +1787,11 @@
             mBiometricService.mImpl.registerAuthenticator(SENSOR_ID_FACE, modality, strength,
                     mFaceAuthenticator);
         }
+
+        if ((modality & TYPE_CREDENTIAL) != 0) {
+            when(mTrustManager.isDeviceSecure(anyInt(), anyInt()))
+                    .thenReturn(true);
+        }
     }
 
     // TODO: Reduce duplicated code, currently we cannot start the BiometricService in setUp() for
@@ -1799,7 +1842,8 @@
             Integer authenticators) throws Exception {
         // Request auth, creates a pending session
         final long requestId = invokeAuthenticate(
-                service, receiver, requireConfirmation, authenticators);
+                service, receiver, requireConfirmation, authenticators,
+                false /* useDefaultSubtitle */, false /* deviceCredentialAllowed */);
         waitForIdle();
 
         startPendingAuthSession(mBiometricService);
@@ -1827,7 +1871,8 @@
 
     private static long invokeAuthenticate(IBiometricService.Stub service,
             IBiometricServiceReceiver receiver, boolean requireConfirmation,
-            Integer authenticators) throws Exception {
+            Integer authenticators, boolean useDefaultSubtitle,
+            boolean deviceCredentialAllowed) throws Exception {
         return service.authenticate(
                 new Binder() /* token */,
                 0 /* operationId */,
@@ -1835,7 +1880,8 @@
                 receiver,
                 TEST_PACKAGE_NAME /* packageName */,
                 createTestPromptInfo(requireConfirmation, authenticators,
-                        false /* checkDevicePolicy */));
+                        false /* checkDevicePolicy */, useDefaultSubtitle,
+                        deviceCredentialAllowed));
     }
 
     private static long invokeAuthenticateForWorkApp(IBiometricService.Stub service,
@@ -1847,16 +1893,19 @@
                 receiver,
                 TEST_PACKAGE_NAME /* packageName */,
                 createTestPromptInfo(false /* requireConfirmation */, authenticators,
-                        true /* checkDevicePolicy */));
+                        true /* checkDevicePolicy */, false /* useDefaultSubtitle */,
+                        false /* deviceCredentialAllowed */));
     }
 
     private static PromptInfo createTestPromptInfo(
             boolean requireConfirmation,
             Integer authenticators,
-            boolean checkDevicePolicy) {
+            boolean checkDevicePolicy,
+            boolean useDefaultSubtitle,
+            boolean deviceCredentialAllowed) {
         final PromptInfo promptInfo = new PromptInfo();
         promptInfo.setConfirmationRequested(requireConfirmation);
-        promptInfo.setUseDefaultSubtitle(true);
+        promptInfo.setUseDefaultSubtitle(useDefaultSubtitle);
 
         if (authenticators != null) {
             promptInfo.setAuthenticators(authenticators);
@@ -1864,6 +1913,7 @@
         if (checkDevicePolicy) {
             promptInfo.setDisallowBiometricsIfPolicyExists(checkDevicePolicy);
         }
+        promptInfo.setDeviceCredentialAllowed(deviceCredentialAllowed);
         return promptInfo;
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/log/BiometricLoggerTest.java b/services/tests/servicestests/src/com/android/server/biometrics/log/BiometricLoggerTest.java
index 612f717..a508718 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/log/BiometricLoggerTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/log/BiometricLoggerTest.java
@@ -39,6 +39,7 @@
 import androidx.test.filters.SmallTest;
 import androidx.test.platform.app.InstrumentationRegistry;
 
+import com.android.server.biometrics.AuthenticationStatsCollector;
 import com.android.server.biometrics.sensors.BaseClientMonitor;
 
 import org.junit.Before;
@@ -65,6 +66,8 @@
     @Mock
     private BiometricFrameworkStatsLogger mSink;
     @Mock
+    private AuthenticationStatsCollector mAuthenticationStatsCollector;
+    @Mock
     private SensorManager mSensorManager;
     @Mock
     private BaseClientMonitor mClient;
@@ -87,7 +90,8 @@
     }
 
     private BiometricLogger createLogger(int statsModality, int statsAction, int statsClient) {
-        return new BiometricLogger(statsModality, statsAction, statsClient, mSink, mSensorManager);
+        return new BiometricLogger(statsModality, statsAction, statsClient, mSink,
+                mAuthenticationStatsCollector, mSensorManager);
     }
 
     @Test
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceProviderTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceProviderTest.java
index d1d6e9d..f43120d 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceProviderTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/aidl/FaceProviderTest.java
@@ -27,6 +27,7 @@
 import static org.mockito.Mockito.when;
 
 import android.content.Context;
+import android.content.res.Resources;
 import android.hardware.biometrics.common.CommonProps;
 import android.hardware.biometrics.face.IFace;
 import android.hardware.biometrics.face.ISession;
@@ -39,6 +40,7 @@
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.SmallTest;
 
+import com.android.internal.R;
 import com.android.server.biometrics.log.BiometricContext;
 import com.android.server.biometrics.sensors.BaseClientMonitor;
 import com.android.server.biometrics.sensors.BiometricScheduler;
@@ -59,11 +61,15 @@
 
     private static final String TAG = "FaceProviderTest";
 
+    private static final float FRR_THRESHOLD = 0.2f;
+
     @Mock
     private Context mContext;
     @Mock
     private UserManager mUserManager;
     @Mock
+    private Resources mResources;
+    @Mock
     private IFace mDaemon;
     @Mock
     private BiometricContext mBiometricContext;
@@ -86,6 +92,10 @@
         when(mUserManager.getAliveUsers()).thenReturn(new ArrayList<>());
         when(mDaemon.createSession(anyInt(), anyInt(), any())).thenReturn(mock(ISession.class));
 
+        when(mContext.getResources()).thenReturn(mResources);
+        when(mResources.getFraction(R.fraction.config_biometricNotificationFrrThreshold, 1, 1))
+                .thenReturn(FRR_THRESHOLD);
+
         final SensorProps sensor1 = new SensorProps();
         sensor1.commonProps = new CommonProps();
         sensor1.commonProps.sensorId = 0;
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/Face10Test.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/Face10Test.java
index d174533..e558c4d 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/Face10Test.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/face/hidl/Face10Test.java
@@ -26,6 +26,7 @@
 import static org.mockito.Mockito.when;
 
 import android.content.Context;
+import android.content.res.Resources;
 import android.hardware.biometrics.ComponentInfoInternal;
 import android.hardware.biometrics.SensorProperties;
 import android.hardware.face.FaceSensorProperties;
@@ -41,6 +42,7 @@
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.SmallTest;
 
+import com.android.internal.R;
 import com.android.server.biometrics.log.BiometricContext;
 import com.android.server.biometrics.sensors.BiometricScheduler;
 import com.android.server.biometrics.sensors.BiometricStateCallback;
@@ -65,12 +67,15 @@
     private static final String TAG = "Face10Test";
     private static final int SENSOR_ID = 1;
     private static final int USER_ID = 20;
+    private static final float FRR_THRESHOLD = 0.2f;
 
     @Mock
     private Context mContext;
     @Mock
     private UserManager mUserManager;
     @Mock
+    private Resources mResources;
+    @Mock
     private BiometricScheduler mScheduler;
     @Mock
     private BiometricContext mBiometricContext;
@@ -93,6 +98,10 @@
         when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
         when(mUserManager.getAliveUsers()).thenReturn(new ArrayList<>());
 
+        when(mContext.getResources()).thenReturn(mResources);
+        when(mResources.getFraction(R.fraction.config_biometricNotificationFrrThreshold, 1, 1))
+                .thenReturn(FRR_THRESHOLD);
+
         mLockoutResetDispatcher = new LockoutResetDispatcher(mContext);
 
         final int maxEnrollmentsPerUser = 1;
diff --git a/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java
index 4512cc02..908afc8 100644
--- a/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java
@@ -61,6 +61,7 @@
 import android.companion.virtual.sensor.VirtualSensor;
 import android.companion.virtual.sensor.VirtualSensorCallback;
 import android.companion.virtual.sensor.VirtualSensorConfig;
+import android.content.AttributionSource;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.ContextWrapper;
@@ -363,7 +364,8 @@
                 new CameraAccessController(mContext, mLocalService, mCameraAccessBlockedCallback);
 
         mAssociationInfo = new AssociationInfo(/* associationId= */ 1, 0, null,
-                MacAddress.BROADCAST_ADDRESS, "", null, null, true, false, false, 0, 0, -1);
+                null, MacAddress.BROADCAST_ADDRESS, "", null, null, true, false, false,
+                0, 0, -1);
 
         mVdms = new VirtualDeviceManagerService(mContext);
         mLocalService = mVdms.getLocalServiceInstance();
@@ -1728,7 +1730,9 @@
     private VirtualDeviceImpl createVirtualDevice(int virtualDeviceId, int ownerUid,
             VirtualDeviceParams params) {
         VirtualDeviceImpl virtualDeviceImpl = new VirtualDeviceImpl(mContext,
-                mAssociationInfo, mVdms, new Binder(), ownerUid, virtualDeviceId,
+                mAssociationInfo, mVdms, new Binder(),
+                new AttributionSource(ownerUid, "com.android.virtualdevice.test", "virtualdevice"),
+                virtualDeviceId,
                 mInputController, mCameraAccessController,
                 mPendingTrampolineCallback, mActivityListener, mSoundEffectListener,
                 mRunningAppsChangedCallback, params, new DisplayManagerGlobal(mIDisplayManager));
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceMigrationTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceMigrationTest.java
index b539a76..943a9c47 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceMigrationTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceMigrationTest.java
@@ -236,7 +236,7 @@
         verify(getServices().packageManagerInternal, never())
                 .unsuspendForSuspendingPackage(PLATFORM_PACKAGE_NAME, USER_SYSTEM);
         verify(getServices().ipackageManager, never()).setPackagesSuspendedAsUser(
-                any(), anyBoolean(), any(), any(), any(), any(), anyInt());
+                any(), anyBoolean(), any(), any(), any(), anyInt(), any(), anyInt());
 
         final DpmMockContext poContext = new DpmMockContext(getServices(), mRealTestContext);
         poContext.binder.callingUid = UserHandle.getUid(COPE_PROFILE_USER_ID, COPE_ADMIN1_APP_ID);
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 74787781..f408ef0 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
@@ -7527,7 +7527,7 @@
                 .cancel(eq(SystemMessageProto.SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED));
         // Verify that the apps are NOT unsuspeded.
         verify(getServices().ipackageManager, never()).setPackagesSuspendedAsUser(
-                any(), eq(false), any(), any(), any(), any(), anyInt());
+                any(), eq(false), any(), any(), any(), anyInt(), any(), anyInt());
         // Verify that DPC is invoked to check policy compliance.
         verify(mContext.spiedContext).startActivityAsUser(
                 MockUtils.checkIntentAction(ACTION_CHECK_POLICY_COMPLIANCE),
diff --git a/services/tests/servicestests/src/com/android/server/display/TestUtils.java b/services/tests/servicestests/src/com/android/server/display/TestUtils.java
deleted file mode 100644
index 8b45145..0000000
--- a/services/tests/servicestests/src/com/android/server/display/TestUtils.java
+++ /dev/null
@@ -1,94 +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;
-
-import android.hardware.Sensor;
-import android.hardware.SensorEvent;
-import android.hardware.input.InputSensorInfo;
-import android.os.Parcel;
-import android.os.SystemClock;
-import android.view.DisplayAddress;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-
-public final class TestUtils {
-
-    public static SensorEvent createSensorEvent(Sensor sensor, int value) throws Exception {
-        final Constructor<SensorEvent> constructor =
-                SensorEvent.class.getDeclaredConstructor(int.class);
-        constructor.setAccessible(true);
-        final SensorEvent event = constructor.newInstance(1);
-        event.sensor = sensor;
-        event.values[0] = value;
-        event.timestamp = SystemClock.elapsedRealtimeNanos();
-        return event;
-    }
-
-
-    public static void setSensorType(Sensor sensor, int type, String strType) throws Exception {
-        Method setter = Sensor.class.getDeclaredMethod("setType", Integer.TYPE);
-        setter.setAccessible(true);
-        setter.invoke(sensor, type);
-        if (strType != null) {
-            Field f = sensor.getClass().getDeclaredField("mStringType");
-            f.setAccessible(true);
-            f.set(sensor, strType);
-        }
-    }
-
-    public static void setMaximumRange(Sensor sensor, float maximumRange) throws Exception {
-        Method setter = Sensor.class.getDeclaredMethod("setRange", Float.TYPE, Float.TYPE);
-        setter.setAccessible(true);
-        setter.invoke(sensor, maximumRange, 1);
-    }
-
-    public static Sensor createSensor(int type, String strType) throws Exception {
-        Constructor<Sensor> constr = Sensor.class.getDeclaredConstructor();
-        constr.setAccessible(true);
-        Sensor sensor = constr.newInstance();
-        setSensorType(sensor, type, strType);
-        return sensor;
-    }
-
-    public static Sensor createSensor(int type, String strType, float maximumRange)
-            throws Exception {
-        Constructor<Sensor> constr = Sensor.class.getDeclaredConstructor();
-        constr.setAccessible(true);
-        Sensor sensor = constr.newInstance();
-        setSensorType(sensor, type, strType);
-        setMaximumRange(sensor, maximumRange);
-        return sensor;
-    }
-
-    public static Sensor createSensor(String type, String name) {
-        return new Sensor(new InputSensorInfo(
-                name, "vendor", 0, 0, 0, 1f, 1f, 1, 1, 1, 1,
-                type, "", 0, 0, 0));
-    }
-
-    /**
-     * Create a custom {@link DisplayAddress} to ensure we're not relying on any specific
-     * display-address implementation in our code. Intentionally uses default object (reference)
-     * equality rules.
-     */
-    public static class TestDisplayAddress extends DisplayAddress {
-        @Override
-        public void writeToParcel(Parcel out, int flags) { }
-    }
-}
diff --git a/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java b/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java
index e9a7d85..0376376 100644
--- a/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java
+++ b/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java
@@ -67,6 +67,8 @@
 @RunWith(AndroidJUnit4.class)
 public final class UpdatableFontDirTest {
 
+    private static final String LEGACY_FONTS_XML = "/system/etc/fonts.xml";
+
     /**
      * A {@link UpdatableFontDir.FontFileParser} for testing. Instead of using real font files,
      * this test uses fake font files. A fake font file has its PostScript naem and revision as the
@@ -140,7 +142,7 @@
     private List<File> mPreinstalledFontDirs;
     private final Supplier<Long> mCurrentTimeSupplier = () -> CURRENT_TIME;
     private final Function<Map<String, File>, FontConfig> mConfigSupplier =
-            (map) -> SystemFonts.getSystemFontConfig(map, 0, 0);
+            (map) -> SystemFonts.getSystemFontConfigForTesting(LEGACY_FONTS_XML, map, 0, 0);
     private FakeFontFileParser mParser;
     private FakeFsverityUtil mFakeFsverityUtil;
 
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/BaseAbsoluteVolumeBehaviorTest.java b/services/tests/servicestests/src/com/android/server/hdmi/BaseAbsoluteVolumeBehaviorTest.java
index 399655ffa..e6d326a 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/BaseAbsoluteVolumeBehaviorTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/BaseAbsoluteVolumeBehaviorTest.java
@@ -92,11 +92,11 @@
 
     // Default Audio Status given by the System Audio device in its initial <Report Audio Status>
     // that triggers AVB being enabled
-    private static final AudioStatus INITIAL_SYSTEM_AUDIO_DEVICE_STATUS =
+    protected static final AudioStatus INITIAL_SYSTEM_AUDIO_DEVICE_STATUS =
             new AudioStatus(50, false);
 
     // VolumeInfo passed to AudioDeviceVolumeManager#setDeviceAbsoluteVolumeBehavior to enable AVB
-    private static final VolumeInfo ENABLE_AVB_VOLUME_INFO =
+    protected static final VolumeInfo ENABLE_AVB_VOLUME_INFO =
             new VolumeInfo.Builder(AudioManager.STREAM_MUSIC)
                     .setMuted(INITIAL_SYSTEM_AUDIO_DEVICE_STATUS.getMute())
                     .setVolumeIndex(INITIAL_SYSTEM_AUDIO_DEVICE_STATUS.getVolume())
@@ -106,6 +106,8 @@
 
     private static final int EMPTY_FLAGS = 0;
 
+    protected static final int STREAM_MUSIC_MAX_VOLUME = 25;
+
     protected abstract HdmiCecLocalDevice createLocalDevice(HdmiControlService hdmiControlService);
 
     protected abstract int getPhysicalAddress();
@@ -201,7 +203,7 @@
                 Collections.singletonList(getAudioOutputDevice()));
 
         // Max volume of STREAM_MUSIC
-        mAudioFramework.setStreamMaxVolume(AudioManager.STREAM_MUSIC, 25);
+        mAudioFramework.setStreamMaxVolume(AudioManager.STREAM_MUSIC, STREAM_MUSIC_MAX_VOLUME);
 
         // Receive messages from devices to make sure they're registered in HdmiCecNetwork
         mNativeWrapper.onCecMessage(HdmiCecMessageBuilder.buildGiveDevicePowerStatus(
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecAtomLoggingTest.java b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecAtomLoggingTest.java
index ffe088c..a621055 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecAtomLoggingTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecAtomLoggingTest.java
@@ -19,14 +19,17 @@
 import static com.android.server.hdmi.Constants.ADDR_PLAYBACK_1;
 import static com.android.server.hdmi.Constants.ADDR_TV;
 import static com.android.server.hdmi.Constants.PATH_RELATIONSHIP_ANCESTOR;
+import static com.android.server.hdmi.HdmiControlService.WAKE_UP_SCREEN_ON;
 
 import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
@@ -307,4 +310,60 @@
                         HdmiCecAtomWriter.FEATURE_ABORT_OPCODE_UNKNOWN,
                         HdmiStatsEnums.FEATURE_ABORT_REASON_UNKNOWN);
     }
+
+    @Test
+    public void testDsmStatusChanged_toggleDsmStatus_ArcSupported_writesAtom() {
+        doReturn(true).when(mHdmiControlServiceSpy).isArcSupported();
+        mHdmiControlServiceSpy.setSoundbarMode(HdmiControlManager.SOUNDBAR_MODE_ENABLED);
+        mTestLooper.dispatchAll();
+
+        verify(mHdmiCecAtomWriterSpy, times(1))
+                .dsmStatusChanged(eq(true), eq(true),
+                        eq(HdmiStatsEnums.LOG_REASON_DSM_SETTING_TOGGLED));
+    }
+
+    @Test
+    public void testDsmStatusChanged_toggleDsmStatus_ArcNotSupported_writesAtom() {
+        doReturn(false).when(mHdmiControlServiceSpy).isArcSupported();
+        mHdmiControlServiceSpy.setSoundbarMode(HdmiControlManager.SOUNDBAR_MODE_ENABLED);
+        mTestLooper.dispatchAll();
+
+        verify(mHdmiCecAtomWriterSpy, times(1))
+                .dsmStatusChanged(eq(false), eq(true),
+                        eq(HdmiStatsEnums.LOG_REASON_DSM_SETTING_TOGGLED));
+    }
+
+    @Test
+    public void testDsmStatusChanged_onWakeUp_ArcSupported_writesAtom_logReasonWake() {
+        mHdmiControlServiceSpy.setSoundbarMode(HdmiControlManager.SOUNDBAR_MODE_DISABLED);
+        Mockito.clearInvocations(mHdmiCecAtomWriterSpy);
+
+        doReturn(true).when(mHdmiControlServiceSpy).isArcSupported();
+        mHdmiControlServiceSpy.onWakeUp(WAKE_UP_SCREEN_ON);
+        mTestLooper.dispatchAll();
+
+        verify(mHdmiCecAtomWriterSpy, times(1))
+                .dsmStatusChanged(eq(true), eq(false),
+                        eq(HdmiStatsEnums.LOG_REASON_DSM_WAKE));
+        verify(mHdmiCecAtomWriterSpy, never())
+                .dsmStatusChanged(anyBoolean(), anyBoolean(),
+                        eq(HdmiStatsEnums.LOG_REASON_DSM_SETTING_TOGGLED));
+    }
+
+    @Test
+    public void testDsmStatusChanged_onWakeUp_ArcNotSupported_writesAtom_logReasonWake() {
+        mHdmiControlServiceSpy.setSoundbarMode(HdmiControlManager.SOUNDBAR_MODE_DISABLED);
+        Mockito.clearInvocations(mHdmiCecAtomWriterSpy);
+
+        doReturn(false).when(mHdmiControlServiceSpy).isArcSupported();
+        mHdmiControlServiceSpy.onWakeUp(WAKE_UP_SCREEN_ON);
+        mTestLooper.dispatchAll();
+
+        verify(mHdmiCecAtomWriterSpy, times(1))
+                .dsmStatusChanged(eq(false), eq(false),
+                        eq(HdmiStatsEnums.LOG_REASON_DSM_WAKE));
+        verify(mHdmiCecAtomWriterSpy, never())
+                .dsmStatusChanged(anyBoolean(), anyBoolean(),
+                        eq(HdmiStatsEnums.LOG_REASON_DSM_SETTING_TOGGLED));
+    }
 }
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 40c762c..dec89d9 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java
@@ -383,6 +383,47 @@
     }
 
     @Test
+    public void handleRoutingChange_toSwitchInActivePath_noStandby() {
+        int newPlaybackPhysicalAddress = 0x2100;
+        int switchPhysicalAddress = 0x2000;
+        mNativeWrapper.setPhysicalAddress(newPlaybackPhysicalAddress);
+        mHdmiControlService.allocateLogicalAddress(mLocalDevices, INITIATED_BY_ENABLE_CEC);
+
+        mHdmiCecLocalDevicePlayback.mService.getHdmiCecConfig().setStringValue(
+                HdmiControlManager.CEC_SETTING_NAME_POWER_STATE_CHANGE_ON_ACTIVE_SOURCE_LOST,
+                HdmiControlManager.POWER_STATE_CHANGE_ON_ACTIVE_SOURCE_LOST_STANDBY_NOW);
+        mHdmiCecLocalDevicePlayback.setActiveSource(mPlaybackLogicalAddress,
+                newPlaybackPhysicalAddress, "HdmiCecLocalDevicePlaybackTest");
+        mTestLooper.dispatchAll();
+
+        HdmiCecMessage message =
+                HdmiCecMessageBuilder.buildRoutingChange(ADDR_TV, newPlaybackPhysicalAddress,
+                        switchPhysicalAddress);
+        assertThat(mHdmiCecLocalDevicePlayback.handleRoutingChange(message))
+                .isEqualTo(Constants.HANDLED);
+        assertThat(mHdmiCecLocalDevicePlayback.isActiveSource()).isTrue();
+        assertThat(mPowerManager.isInteractive()).isTrue();
+    }
+
+    @Test
+    public void handleRoutingChange_toTv_StandbyNow() {
+        mHdmiCecLocalDevicePlayback.mService.getHdmiCecConfig().setStringValue(
+                HdmiControlManager.CEC_SETTING_NAME_POWER_STATE_CHANGE_ON_ACTIVE_SOURCE_LOST,
+                HdmiControlManager.POWER_STATE_CHANGE_ON_ACTIVE_SOURCE_LOST_STANDBY_NOW);
+        mHdmiCecLocalDevicePlayback.setActiveSource(mPlaybackLogicalAddress,
+                mPlaybackPhysicalAddress, "HdmiCecLocalDevicePlaybackTest");
+        mTestLooper.dispatchAll();
+
+        HdmiCecMessage message =
+                HdmiCecMessageBuilder.buildRoutingChange(ADDR_TV, mPlaybackPhysicalAddress,
+                        Constants.TV_PHYSICAL_ADDRESS);
+        assertThat(mHdmiCecLocalDevicePlayback.handleRoutingChange(message))
+                .isEqualTo(Constants.HANDLED);
+        assertThat(mHdmiCecLocalDevicePlayback.isActiveSource()).isFalse();
+        assertThat(mPowerManager.isInteractive()).isFalse();
+    }
+
+    @Test
     public void handleRoutingChange_otherDevice_StandbyNow_InactiveSource() {
         mHdmiCecLocalDevicePlayback.mService.getHdmiCecConfig().setStringValue(
                 HdmiControlManager.CEC_SETTING_NAME_POWER_STATE_CHANGE_ON_ACTIVE_SOURCE_LOST,
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java
index 55e5dbd..c632727f 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java
@@ -174,6 +174,20 @@
                     protected boolean earcBlocksArcConnection() {
                         return mEarcBlocksArc;
                     }
+
+                    /**
+                     * Override displayOsd to prevent it from broadcasting an intent, which
+                     * can trigger a SecurityException.
+                    */
+                    @Override
+                    void displayOsd(int messageId) {
+                        // do nothing
+                    }
+
+                    @Override
+                    void displayOsd(int messageId, int extra) {
+                        // do nothing
+                    }
                 };
 
         mHdmiControlService.setIoLooper(mMyLooper);
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/TvToAudioSystemAvbTest.java b/services/tests/servicestests/src/com/android/server/hdmi/TvToAudioSystemAvbTest.java
index 024e36d..86647fc 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/TvToAudioSystemAvbTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/TvToAudioSystemAvbTest.java
@@ -321,4 +321,98 @@
                         getLogicalAddress(), getSystemAudioDeviceLogicalAddress(),
                         Constants.AUDIO_VOLUME_STATUS_UNKNOWN));
     }
+
+    /**
+     * Tests that a volume adjustment command with direction ADJUST_SAME causes HdmiControlService
+     * to request the System Audio device's audio status, and notify AudioService of the
+     * audio status.
+     */
+    @Test
+    public void avbEnabled_audioDeviceVolumeAdjusted_adjustSame_updatesAudioService() {
+        enableAbsoluteVolumeBehavior();
+        mNativeWrapper.clearResultMessages();
+
+        // HdmiControlService receives a volume adjustment with direction ADJUST_SAME
+        mHdmiControlService.getAbsoluteVolumeChangedListener().onAudioDeviceVolumeAdjusted(
+                getAudioOutputDevice(),
+                ENABLE_AVB_VOLUME_INFO,
+                AudioManager.ADJUST_SAME,
+                AudioDeviceVolumeManager.ADJUST_MODE_NORMAL
+        );
+        mTestLooper.dispatchAll();
+
+        // Device sends <Give Audio Status>
+        assertThat(mNativeWrapper.getResultMessages()).contains(
+                HdmiCecMessageBuilder.buildGiveAudioStatus(getLogicalAddress(),
+                        getSystemAudioDeviceLogicalAddress()));
+
+        clearInvocations(mAudioManager);
+
+        // Device receives <Report Audio Status> with a new volume and mute state
+        mNativeWrapper.onCecMessage(HdmiCecMessageBuilder.buildReportAudioStatus(
+                getSystemAudioDeviceLogicalAddress(),
+                getLogicalAddress(),
+                80,
+                true));
+        mTestLooper.dispatchAll();
+
+        // HdmiControlService calls setStreamVolume and adjustStreamVolume to trigger volume UI
+        verify(mAudioManager).setStreamVolume(
+                eq(AudioManager.STREAM_MUSIC),
+                // Volume level is rescaled to the max volume of STREAM_MUSIC
+                eq(80 * STREAM_MUSIC_MAX_VOLUME / AudioStatus.MAX_VOLUME),
+                eq(AudioManager.FLAG_ABSOLUTE_VOLUME | AudioManager.FLAG_SHOW_UI));
+        verify(mAudioManager).adjustStreamVolume(
+                eq(AudioManager.STREAM_MUSIC),
+                eq(AudioManager.ADJUST_MUTE),
+                eq(AudioManager.FLAG_ABSOLUTE_VOLUME | AudioManager.FLAG_SHOW_UI));
+    }
+
+    /**
+     * Tests that a volume adjustment command with direction ADJUST_SAME causes HdmiControlService
+     * to request the System Audio device's audio status, and notify AudioService of the
+     * audio status, even if it's unchanged from the previous one.
+     */
+    @Test
+    public void avbEnabled_audioDeviceVolumeAdjusted_adjustSame_noChange_updatesAudioService() {
+        enableAbsoluteVolumeBehavior();
+        mNativeWrapper.clearResultMessages();
+
+        // HdmiControlService receives a volume adjustment with direction ADJUST_SAME
+        mHdmiControlService.getAbsoluteVolumeChangedListener().onAudioDeviceVolumeAdjusted(
+                getAudioOutputDevice(),
+                ENABLE_AVB_VOLUME_INFO,
+                AudioManager.ADJUST_SAME,
+                AudioDeviceVolumeManager.ADJUST_MODE_NORMAL
+        );
+        mTestLooper.dispatchAll();
+
+        // Device sends <Give Audio Status>
+        assertThat(mNativeWrapper.getResultMessages()).contains(
+                HdmiCecMessageBuilder.buildGiveAudioStatus(getLogicalAddress(),
+                        getSystemAudioDeviceLogicalAddress()));
+
+        clearInvocations(mAudioManager);
+
+        // Device receives <Report Audio Status> with the same volume level and mute state that
+        // as when AVB was enabled
+        mNativeWrapper.onCecMessage(HdmiCecMessageBuilder.buildReportAudioStatus(
+                getSystemAudioDeviceLogicalAddress(),
+                getLogicalAddress(),
+                INITIAL_SYSTEM_AUDIO_DEVICE_STATUS.getVolume(),
+                INITIAL_SYSTEM_AUDIO_DEVICE_STATUS.getMute()));
+        mTestLooper.dispatchAll();
+
+        // HdmiControlService calls setStreamVolume and adjustStreamVolume to trigger volume UI
+        verify(mAudioManager).setStreamVolume(
+                eq(AudioManager.STREAM_MUSIC),
+                // Volume level is rescaled to the max volume of STREAM_MUSIC
+                eq(INITIAL_SYSTEM_AUDIO_DEVICE_STATUS.getVolume()
+                        * STREAM_MUSIC_MAX_VOLUME / AudioStatus.MAX_VOLUME),
+                eq(AudioManager.FLAG_ABSOLUTE_VOLUME | AudioManager.FLAG_SHOW_UI));
+        verify(mAudioManager).adjustStreamVolume(
+                eq(AudioManager.STREAM_MUSIC),
+                eq(AudioManager.ADJUST_UNMUTE),
+                eq(AudioManager.FLAG_ABSOLUTE_VOLUME | AudioManager.FLAG_SHOW_UI));
+    }
 }
diff --git a/services/tests/servicestests/src/com/android/server/os/BugreportManagerServiceImplTest.java b/services/tests/servicestests/src/com/android/server/os/BugreportManagerServiceImplTest.java
index 24029b1..fc27edc 100644
--- a/services/tests/servicestests/src/com/android/server/os/BugreportManagerServiceImplTest.java
+++ b/services/tests/servicestests/src/com/android/server/os/BugreportManagerServiceImplTest.java
@@ -35,6 +35,7 @@
 import androidx.test.platform.app.InstrumentationRegistry;
 import androidx.test.runner.AndroidJUnit4;
 
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -68,6 +69,27 @@
         mBugreportFileManager = new BugreportManagerServiceImpl.BugreportFileManager();
     }
 
+    @After
+    public void tearDown() throws Exception {
+        // Changes to RoleManager persist between tests, so we need to clear out any funny
+        // business we did in previous tests.
+        RoleManager roleManager = mContext.getSystemService(RoleManager.class);
+        CallbackFuture future = new CallbackFuture();
+        runWithShellPermissionIdentity(
+                () -> {
+                    roleManager.setBypassingRoleQualification(false);
+                    roleManager.removeRoleHolderAsUser(
+                            "android.app.role.SYSTEM_AUTOMOTIVE_PROJECTION",
+                            mContext.getPackageName(),
+                            /* flags= */ 0,
+                            Process.myUserHandle(),
+                            mContext.getMainExecutor(),
+                            future);
+                });
+
+        assertThat(future.get()).isEqualTo(true);
+    }
+
     @Test
     public void testBugreportFileManagerFileExists() {
         Pair<Integer, String> callingInfo = new Pair<>(mCallingUid, mCallingPackage);
@@ -131,14 +153,17 @@
                 new BugreportManagerServiceImpl.Injector(mContext, new ArraySet<>()));
         RoleManager roleManager = mContext.getSystemService(RoleManager.class);
         CallbackFuture future = new CallbackFuture();
-        runWithShellPermissionIdentity(() -> roleManager.setBypassingRoleQualification(true));
-        runWithShellPermissionIdentity(() -> roleManager.addRoleHolderAsUser(
-                "android.app.role.SYSTEM_AUTOMOTIVE_PROJECTION",
-                mContext.getPackageName(),
-                /* flags= */ 0,
-                Process.myUserHandle(),
-                mContext.getMainExecutor(),
-                future));
+        runWithShellPermissionIdentity(
+                () -> {
+                    roleManager.setBypassingRoleQualification(true);
+                    roleManager.addRoleHolderAsUser(
+                            "android.app.role.SYSTEM_AUTOMOTIVE_PROJECTION",
+                            mContext.getPackageName(),
+                            /* flags= */ 0,
+                            Process.myUserHandle(),
+                            mContext.getMainExecutor(),
+                            future);
+                });
 
         assertThat(future.get()).isEqualTo(true);
         mService.cancelBugreport(Binder.getCallingUid(), mContext.getPackageName());
diff --git a/services/tests/servicestests/src/com/android/server/people/prediction/SharesheetModelScorerTest.java b/services/tests/servicestests/src/com/android/server/people/prediction/SharesheetModelScorerTest.java
index 45fff48..2cd9198 100644
--- a/services/tests/servicestests/src/com/android/server/people/prediction/SharesheetModelScorerTest.java
+++ b/services/tests/servicestests/src/com/android/server/people/prediction/SharesheetModelScorerTest.java
@@ -57,6 +57,7 @@
     private static final String PACKAGE_3 = "pkg3";
     private static final String CLASS_1 = "cls1";
     private static final String CLASS_2 = "cls2";
+    private static final String CHOOSER_ACTIVITY = "ChooserActivity";
     private static final double DELTA = 1e-6;
     private static final long NOW = System.currentTimeMillis();
     private static final Range<Long> WITHIN_ONE_DAY = new Range(
@@ -246,7 +247,7 @@
         SharesheetModelScorer.computeScoreForAppShare(
                 List.of(mShareTarget1, mShareTarget2, mShareTarget3, mShareTarget4, mShareTarget5,
                         mShareTarget6),
-                Event.TYPE_SHARE_TEXT, 20, NOW, mDataManager, USER_ID);
+                Event.TYPE_SHARE_TEXT, 20, NOW, mDataManager, USER_ID, CHOOSER_ACTIVITY);
 
         // Verification
         assertEquals(0.514f, mShareTarget1.getScore(), DELTA);
@@ -278,7 +279,7 @@
         SharesheetModelScorer.computeScoreForAppShare(
                 List.of(mShareTarget1, mShareTarget2, mShareTarget3, mShareTarget4, mShareTarget5,
                         mShareTarget6),
-                Event.TYPE_SHARE_TEXT, 20, NOW, mDataManager, USER_ID);
+                Event.TYPE_SHARE_TEXT, 20, NOW, mDataManager, USER_ID, CHOOSER_ACTIVITY);
 
         verify(mDataManager, times(1)).queryAppUsageStats(anyInt(), anyLong(), anyLong(),
                 anySet());
@@ -311,7 +312,7 @@
         SharesheetModelScorer.computeScoreForAppShare(
                 List.of(mShareTarget1, mShareTarget2, mShareTarget3, mShareTarget4, mShareTarget5,
                         mShareTarget6),
-                Event.TYPE_SHARE_TEXT, 20, NOW, mDataManager, USER_ID);
+                Event.TYPE_SHARE_TEXT, 20, NOW, mDataManager, USER_ID, CHOOSER_ACTIVITY);
 
         verify(mDataManager, times(1)).queryAppUsageStats(anyInt(), anyLong(), anyLong(),
                 anySet());
@@ -349,7 +350,7 @@
         SharesheetModelScorer.computeScoreForAppShare(
                 List.of(mShareTarget1, mShareTarget2, mShareTarget3, mShareTarget4, mShareTarget5,
                         mShareTarget6),
-                Event.TYPE_SHARE_TEXT, 4, NOW, mDataManager, USER_ID);
+                Event.TYPE_SHARE_TEXT, 4, NOW, mDataManager, USER_ID, CHOOSER_ACTIVITY);
 
         verify(mDataManager, never()).queryAppUsageStats(anyInt(), anyLong(), anyLong(),
                 anySet());
@@ -377,7 +378,7 @@
                 anyLong())).thenReturn(
                 List.of(createUsageEvent(PACKAGE_2),
                         createUsageEvent(PACKAGE_3),
-                        createUsageEvent(SharesheetModelScorer.CHOOSER_ACTIVITY),
+                        createUsageEvent(CHOOSER_ACTIVITY),
                         createUsageEvent(PACKAGE_3),
                         createUsageEvent(PACKAGE_3))
         );
@@ -385,7 +386,7 @@
         SharesheetModelScorer.computeScoreForAppShare(
                 List.of(mShareTarget1, mShareTarget2, mShareTarget3, mShareTarget4, mShareTarget5,
                         mShareTarget6),
-                Event.TYPE_SHARE_TEXT, 20, NOW, mDataManager, USER_ID);
+                Event.TYPE_SHARE_TEXT, 20, NOW, mDataManager, USER_ID, CHOOSER_ACTIVITY);
 
         verify(mDataManager, times(1)).queryAppMovingToForegroundEvents(anyInt(), anyLong(),
                 anyLong());
@@ -413,7 +414,7 @@
                 anyLong())).thenReturn(
                 List.of(createUsageEvent(PACKAGE_3),
                         createUsageEvent(PACKAGE_3),
-                        createUsageEvent(SharesheetModelScorer.CHOOSER_ACTIVITY),
+                        createUsageEvent(CHOOSER_ACTIVITY),
                         createUsageEvent(PACKAGE_3),
                         createUsageEvent(PACKAGE_3))
         );
@@ -421,7 +422,7 @@
         SharesheetModelScorer.computeScoreForAppShare(
                 List.of(mShareTarget1, mShareTarget2, mShareTarget3, mShareTarget4, mShareTarget5,
                         mShareTarget6),
-                Event.TYPE_SHARE_TEXT, 20, NOW, mDataManager, USER_ID);
+                Event.TYPE_SHARE_TEXT, 20, NOW, mDataManager, USER_ID, CHOOSER_ACTIVITY);
 
         verify(mDataManager, times(1)).queryAppMovingToForegroundEvents(anyInt(), anyLong(),
                 anyLong());
diff --git a/services/tests/servicestests/src/com/android/server/pm/UserManagerTest.java b/services/tests/servicestests/src/com/android/server/pm/UserManagerTest.java
index dd681aa..ecd35a5 100644
--- a/services/tests/servicestests/src/com/android/server/pm/UserManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/UserManagerTest.java
@@ -130,7 +130,8 @@
             // Keep system and current user
             if (user.id != UserHandle.USER_SYSTEM &&
                     user.id != currentUser &&
-                    user.id != communalProfileId) {
+                    user.id != communalProfileId &&
+                    !user.isMain()) {
                 removeUser(user.id);
             }
         }
@@ -325,6 +326,24 @@
         assertThat(hasUser(user2.id)).isTrue();
     }
 
+
+    @MediumTest
+    @Test
+    public void testGetFullUserCount() throws Exception {
+        assertThat(mUserManager.getFullUserCount()).isEqualTo(1);
+        UserInfo user1 = createUser("User 1", UserInfo.FLAG_FULL);
+        UserInfo user2 = createUser("User 2", UserInfo.FLAG_ADMIN);
+
+        assertThat(user1).isNotNull();
+        assertThat(user2).isNotNull();
+
+        assertThat(mUserManager.getFullUserCount()).isEqualTo(3);
+        removeUser(user1.id);
+        assertThat(mUserManager.getFullUserCount()).isEqualTo(2);
+        removeUser(user2.id);
+        assertThat(mUserManager.getFullUserCount()).isEqualTo(1);
+    }
+
     /**
      * Tests that UserManager knows how many users can be created.
      *
@@ -1105,16 +1124,16 @@
     public void testCreateProfileForUser_disallowAddManagedProfile() throws Exception {
         assumeManagedUsersSupported();
         final int mainUserId = mUserManager.getMainUser().getIdentifier();
-        final UserHandle mainUserHandle = asHandle(mainUserId);
+        final UserHandle currentUserHandle = asHandle(ActivityManager.getCurrentUser());
         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
-                mainUserHandle);
+                currentUserHandle);
         try {
             UserInfo userInfo = createProfileForUser("Managed",
                     UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
             assertThat(userInfo).isNull();
         } finally {
             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, false,
-                    mainUserHandle);
+                    currentUserHandle);
         }
     }
 
@@ -1190,6 +1209,7 @@
     @Test
     public void testGetManagedProfileCreationTime() throws Exception {
         assumeManagedUsersSupported();
+        assumeTrue("User does not have access to creation time", mUserManager.isMainUser());
         final int mainUserId = mUserManager.getMainUser().getIdentifier();
         final long startTime = System.currentTimeMillis();
         UserInfo profile = createProfileForUser("Managed 1",
@@ -1545,6 +1565,25 @@
         assertThat(userInfo.name).isEqualTo(newName);
     }
 
+    @Test
+    public void testCannotCreateAdditionalMainUser() {
+        UserHandle mainUser = mUserManager.getMainUser();
+        assumeTrue("There is no main user", mainUser != null);
+
+        // Users with FLAG_MAIN can't be removed, so no point using the local createUser method.
+        UserInfo newMainUser = mUserManager.createUser("test", UserInfo.FLAG_MAIN);
+        assertThat(newMainUser).isNull();
+
+        List<UserInfo> users = mUserManager.getUsers();
+        int mainUserCount = 0;
+        for (UserInfo user : users) {
+            if (user.isMain()) {
+                mainUserCount++;
+            }
+        }
+        assertThat(mainUserCount).isEqualTo(1);
+    }
+
     private boolean isPackageInstalledForUser(String packageName, int userId) {
         try {
             return mPackageManager.getPackageInfoAsUser(packageName, 0, userId) != null;
diff --git a/services/tests/servicestests/src/com/android/server/pm/parsing/AndroidPackageParsingValidationTest.kt b/services/tests/servicestests/src/com/android/server/pm/parsing/AndroidPackageParsingValidationTest.kt
index f834cb2..560a919 100644
--- a/services/tests/servicestests/src/com/android/server/pm/parsing/AndroidPackageParsingValidationTest.kt
+++ b/services/tests/servicestests/src/com/android/server/pm/parsing/AndroidPackageParsingValidationTest.kt
@@ -138,6 +138,17 @@
             R.styleable.AndroidManifestApplication_taskAffinity,
             1024
         )
+        validateTagAttr(
+            tag,
+            "zygotePreloadName",
+            R.styleable.AndroidManifestApplication_zygotePreloadName,
+            1024
+        )
+        validateTagAttrComponentName(
+            tag,
+            "zygotePreloadName",
+            R.styleable.AndroidManifestApplication_zygotePreloadName
+        )
         validateTagCount("profileable", 100, tag)
         validateTagCount("uses-native-library", 100, tag)
         validateTagCount("receiver", 1000, tag)
@@ -507,8 +518,26 @@
             }
         }
 
-        val failNames = arrayOf("com.android.TestClass:", "-TestClass", "TestClass.", ".", "..")
-        for (name in failNames) {
+        val badNames = arrayOf(
+            ";",
+            ",",
+            "[",
+            "]",
+            "(",
+            ")",
+            "{",
+            "}",
+            ":",
+            "?",
+            "-",
+            "%",
+            "^",
+            "*",
+            "|",
+            "/",
+            "\\"
+        )
+        for (name in badNames) {
             val xml = "<$tag $attr=\"$name\" />"
             pullParser.setInput(ByteArrayInputStream(xml.toByteArray()), null)
             val validator = Validator()
diff --git a/services/tests/servicestests/src/com/android/server/power/hint/HintManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/power/hint/HintManagerServiceTest.java
index 726a4e2..9fca513 100644
--- a/services/tests/servicestests/src/com/android/server/power/hint/HintManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/power/hint/HintManagerServiceTest.java
@@ -27,10 +27,11 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyBoolean;
+import static org.mockito.Mockito.anyInt;
 import static org.mockito.Mockito.anyLong;
+import static org.mockito.Mockito.eq;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.times;
@@ -73,6 +74,7 @@
     private static final int TGID = Process.getThreadGroupLeader(TID);
     private static final int[] SESSION_TIDS_A = new int[] {TID};
     private static final int[] SESSION_TIDS_B = new int[] {TID};
+    private static final int[] SESSION_TIDS_C = new int[] {TID};
     private static final long[] DURATIONS_THREE = new long[] {1L, 100L, 1000L};
     private static final long[] TIMESTAMPS_THREE = new long[] {1L, 2L, 3L};
     private static final long[] DURATIONS_ZERO = new long[] {};
@@ -94,6 +96,8 @@
               eq(DEFAULT_TARGET_DURATION))).thenReturn(1L);
         when(mNativeWrapperMock.halCreateHintSession(eq(TGID), eq(UID), eq(SESSION_TIDS_B),
               eq(DEFAULT_TARGET_DURATION))).thenReturn(2L);
+        when(mNativeWrapperMock.halCreateHintSession(eq(TGID), eq(UID), eq(SESSION_TIDS_C),
+              eq(0L))).thenReturn(1L);
         when(mAmInternalMock.getIsolatedProcesses(anyInt())).thenReturn(null);
         LocalServices.removeServiceForTest(ActivityManagerInternal.class);
         LocalServices.addService(ActivityManagerInternal.class, mAmInternalMock);
@@ -138,6 +142,10 @@
         IHintSession b = service.getBinderServiceInstance().createHintSession(token,
                 SESSION_TIDS_B, DEFAULT_TARGET_DURATION);
         assertNotEquals(a, b);
+
+        IHintSession c = service.getBinderServiceInstance().createHintSession(token,
+                SESSION_TIDS_C, 0L);
+        assertNotNull(c);
     }
 
     @Test
@@ -338,4 +346,35 @@
         a.setThreads(SESSION_TIDS_A);
         verify(mNativeWrapperMock, never()).halSetThreads(anyLong(), any());
     }
+
+    @Test
+    public void testSetMode() throws Exception {
+        HintManagerService service = createService();
+        IBinder token = new Binder();
+
+        AppHintSession a = (AppHintSession) service.getBinderServiceInstance()
+                .createHintSession(token, SESSION_TIDS_A, DEFAULT_TARGET_DURATION);
+
+        a.setMode(0, true);
+        verify(mNativeWrapperMock, times(1)).halSetMode(anyLong(),
+                eq(0), eq(true));
+
+        a.setMode(0, false);
+        verify(mNativeWrapperMock, times(1)).halSetMode(anyLong(),
+                eq(0), eq(false));
+
+        assertThrows(IllegalArgumentException.class, () -> {
+            a.setMode(-1, true);
+        });
+
+        reset(mNativeWrapperMock);
+        // Set session to background, then the duration would not be updated.
+        service.mUidObserver.onUidStateChanged(
+                a.mUid, ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND, 0, 0);
+        FgThread.getHandler().runWithScissors(() -> { }, 500);
+        assertFalse(a.updateHintAllowed());
+        a.setMode(0, true);
+        verify(mNativeWrapperMock, never()).halSetMode(anyLong(), anyInt(), anyBoolean());
+    }
+
 }
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsTests.java b/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsTests.java
deleted file mode 100644
index 48290e5..0000000
--- a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsTests.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.power.stats;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
-        AmbientDisplayPowerCalculatorTest.class,
-        AudioPowerCalculatorTest.class,
-        BatteryChargeCalculatorTest.class,
-        BatteryExternalStatsWorkerTest.class,
-        BatteryStatsCpuTimesTest.class,
-        BatteryStatsBackgroundStatsTest.class,
-        BatteryStatsBinderCallStatsTest.class,
-        BatteryStatsCounterTest.class,
-        BatteryStatsDualTimerTest.class,
-        BatteryStatsDurationTimerTest.class,
-        BatteryStatsHistoryIteratorTest.class,
-        BatteryStatsHistoryTest.class,
-        BatteryStatsImplTest.class,
-        BatteryStatsManagerTest.class,
-        BatteryStatsNoteTest.class,
-        BatteryStatsSamplingTimerTest.class,
-        BatteryStatsSensorTest.class,
-        BatteryStatsServTest.class,
-        BatteryStatsStopwatchTimerTest.class,
-        BatteryStatsTimeBaseTest.class,
-        BatteryStatsTimerTest.class,
-        BatteryUsageStatsProviderTest.class,
-        BatteryUsageStatsTest.class,
-        BatteryUsageStatsStoreTest.class,
-        BatteryStatsUserLifecycleTests.class,
-        BluetoothPowerCalculatorTest.class,
-        BstatsCpuTimesValidationTest.class,
-        CameraPowerCalculatorTest.class,
-        CpuPowerCalculatorTest.class,
-        CustomEnergyConsumerPowerCalculatorTest.class,
-        FlashlightPowerCalculatorTest.class,
-        GnssPowerCalculatorTest.class,
-        IdlePowerCalculatorTest.class,
-        KernelWakelockReaderTest.class,
-        LongSamplingCounterTest.class,
-        LongSamplingCounterArrayTest.class,
-        EnergyConsumerSnapshotTest.class,
-        MobileRadioPowerCalculatorTest.class,
-        ScreenPowerCalculatorTest.class,
-        SensorPowerCalculatorTest.class,
-        SystemServerCpuThreadReaderTest.class,
-        SystemServicePowerCalculatorTest.class,
-        UserPowerCalculatorTest.class,
-        VideoPowerCalculatorTest.class,
-        WakelockPowerCalculatorTest.class,
-        WifiPowerCalculatorTest.class,
-})
-public class BatteryStatsTests {
-}
diff --git a/services/tests/servicestests/src/com/android/server/powerstats/OWNERS b/services/tests/servicestests/src/com/android/server/powerstats/OWNERS
deleted file mode 100644
index 12f13ea..0000000
--- a/services/tests/servicestests/src/com/android/server/powerstats/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-include /services/core/java/com/android/server/powerstats/OWNERS
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ConditionProvidersTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ConditionProvidersTest.java
index b94ed01..d04c518 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ConditionProvidersTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ConditionProvidersTest.java
@@ -18,10 +18,14 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertTrue;
+
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
 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.ServiceConnection;
@@ -51,6 +55,7 @@
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
+        mContext.ensureTestableResources();
 
         mProviders = new ConditionProviders(mContext, mUserProfiles, mIpm);
         mProviders.setCallback(mCallback);
@@ -131,4 +136,21 @@
         verify(mCallback).onConditionChanged(eq(Uri.parse("b")), eq(conditionsToNotify[3]));
         verifyNoMoreInteractions(mCallback);
     }
+
+    @Test
+    public void testRemoveDefaultFromConfig() {
+        final int userId = 0;
+        ComponentName oldDefaultComponent = ComponentName.unflattenFromString("package/Component1");
+
+        when(mContext.getResources().getString(
+                com.android.internal.R.string.config_defaultDndDeniedPackages))
+                .thenReturn("package");
+        mProviders.setPackageOrComponentEnabled(oldDefaultComponent.flattenToString(),
+                userId, true, true /*enabled*/, false /*userSet*/);
+        assertEquals("package", mProviders.getApproved(userId, true));
+
+        mProviders.removeDefaultFromConfig(userId);
+
+        assertTrue(mProviders.getApproved(userId, true).isEmpty());
+    }
 }
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java
index 95fae07..7b16500 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java
@@ -15,17 +15,20 @@
  */
 package com.android.server.notification;
 
-import static com.android.internal.config.sysui.SystemUiSystemPropertiesFlags.NotificationFlags.NO_SORT_BY_INTERRUPTIVENESS;
+import static android.telecom.TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME;
 
 import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
 
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
 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.app.Notification;
@@ -33,8 +36,10 @@
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.Person;
+import android.content.BroadcastReceiver;
 import android.content.ContentResolver;
 import android.content.Context;
+import android.content.Intent;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.content.res.Resources;
@@ -47,6 +52,8 @@
 import android.telecom.TelecomManager;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.internal.config.sysui.SystemUiSystemPropertiesFlags;
 import com.android.server.UiServiceTestCase;
 
@@ -54,16 +61,17 @@
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
+import java.util.concurrent.CountDownLatch;
 
 @SmallTest
-@RunWith(Parameterized.class)
+@RunWith(AndroidJUnit4.class)
 public class NotificationComparatorTest extends UiServiceTestCase {
     @Mock Context mMockContext;
     @Mock TelecomManager mTm;
@@ -97,24 +105,9 @@
     private NotificationRecord mRecordColorized;
     private NotificationRecord mRecordColorizedCall;
 
-    @Parameterized.Parameters(name = "sortByInterruptiveness={0}")
-    public static Boolean[] getSortByInterruptiveness() {
-        return new Boolean[] { true, false };
-    }
-
-    @Parameterized.Parameter
-    public boolean mSortByInterruptiveness;
-
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
-        SystemUiSystemPropertiesFlags.TEST_RESOLVER = flag -> {
-            if (flag.mSysPropKey.equals(NO_SORT_BY_INTERRUPTIVENESS.mSysPropKey)) {
-                return !mSortByInterruptiveness;
-            }
-            return new SystemUiSystemPropertiesFlags.DebugResolver().isEnabled(flag);
-        };
-
         int userId = UserHandle.myUserId();
 
         final Resources res = mContext.getResources();
@@ -309,13 +302,8 @@
         expected.add(mNoMediaSessionMedia);
         expected.add(mRecordCheater);
         expected.add(mRecordCheaterColorized);
-        if (mSortByInterruptiveness) {
-            expected.add(mRecordMinCall);
-            expected.add(mRecordMinCallNonInterruptive);
-        } else {
-            expected.add(mRecordMinCallNonInterruptive);
-            expected.add(mRecordMinCall);
-        }
+        expected.add(mRecordMinCallNonInterruptive);
+        expected.add(mRecordMinCall);
 
         List<NotificationRecord> actual = new ArrayList<>();
         actual.addAll(expected);
@@ -330,11 +318,7 @@
     public void testRankingScoreOverrides() {
         NotificationComparator comp = new NotificationComparator(mMockContext);
         NotificationRecord recordMinCallNonInterruptive = spy(mRecordMinCallNonInterruptive);
-        if (mSortByInterruptiveness) {
-            assertTrue(comp.compare(mRecordMinCall, recordMinCallNonInterruptive) < 0);
-        } else {
-            assertTrue(comp.compare(mRecordMinCall, recordMinCallNonInterruptive) > 0);
-        }
+        assertTrue(comp.compare(mRecordMinCall, recordMinCallNonInterruptive) > 0);
 
         when(recordMinCallNonInterruptive.getRankingScore()).thenReturn(1f);
         assertTrue(comp.compare(mRecordMinCall, recordMinCallNonInterruptive) > 0);
@@ -360,6 +344,73 @@
         assertTrue(comp.isImportantPeople(mRecordContact));
     }
 
+    @Test
+    public void testChangeDialerPackageWhileSorting() throws InterruptedException {
+        final int halfList = 100;
+        int userId = UserHandle.myUserId();
+        when(mTm.getDefaultDialerPackage()).thenReturn("B");
+
+        ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor = ArgumentCaptor.forClass(
+                BroadcastReceiver.class);
+        NotificationComparator comparator = new NotificationComparator(mMockContext);
+        verify(mMockContext).registerReceiver(broadcastReceiverCaptor.capture(), any());
+        BroadcastReceiver dialerChangedBroadcastReceiver = broadcastReceiverCaptor.getValue();
+
+        ArrayList<NotificationRecord> records = new ArrayList<>();
+        for (int i = 0; i < halfList; i++) {
+            Notification notifCallFromPkgA = new Notification.Builder(mMockContext, TEST_CHANNEL_ID)
+                    .setCategory(Notification.CATEGORY_CALL)
+                    .setFlag(Notification.FLAG_FOREGROUND_SERVICE, true)
+                    .build();
+            records.add(new NotificationRecord(mMockContext,
+                    new StatusBarNotification("A", "A", 2 * i, "callA", callUid, callUid,
+                            notifCallFromPkgA, new UserHandle(userId), "", 0),
+                    getDefaultChannel()));
+
+            Notification notifCallFromPkgB = new Notification.Builder(mMockContext, TEST_CHANNEL_ID)
+                    .setCategory(Notification.CATEGORY_CALL)
+                    .setFlag(Notification.FLAG_FOREGROUND_SERVICE, true)
+                    .build();
+            records.add(new NotificationRecord(mMockContext,
+                    new StatusBarNotification("B", "B", 2 * i + 1, "callB", callUid, callUid,
+                            notifCallFromPkgB, new UserHandle(userId), "", 0),
+                    getDefaultChannel()));
+        }
+
+        CountDownLatch allDone = new CountDownLatch(2);
+        new Thread(() -> {
+            // The lock prevents the other thread from changing the dialer package mid-sort, so:
+            // 1) Results should be "all B before all A" (asserted below).
+            // 2) No "IllegalArgumentException: Comparison method violates its general contract!"
+            synchronized (comparator.mStateLock) {
+                records.sort(comparator);
+                allDone.countDown();
+            }
+        }).start();
+
+        new Thread(() -> {
+            String nextDialer = "A";
+            while (allDone.getCount() == 2) {
+                Intent dialerChangedIntent = new Intent();
+                dialerChangedIntent.putExtra(EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, nextDialer);
+                dialerChangedBroadcastReceiver.onReceive(mMockContext, dialerChangedIntent);
+                nextDialer = nextDialer.equals("A") ? "B" : "A";
+            }
+            allDone.countDown();
+        }).start();
+
+        allDone.await();
+
+        for (int i = 0; i < halfList; i++) {
+            assertWithMessage("Wrong element in position #" + i)
+                    .that(records.get(i).getSbn().getPackageName()).isEqualTo("B");
+        }
+        for (int i = halfList; i < 2 * halfList; i++) {
+            assertWithMessage("Wrong element in position #" + i)
+                    .that(records.get(i).getSbn().getPackageName()).isEqualTo("A");
+        }
+    }
+
     private NotificationChannel getDefaultChannel() {
         return new NotificationChannel(NotificationChannel.DEFAULT_CHANNEL_ID, "name",
                 NotificationManager.IMPORTANCE_LOW);
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
index bdee99b..57aa0b9 100755
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -117,6 +117,7 @@
 import static org.mockito.Mockito.clearInvocations;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.inOrder;
 import static org.mockito.Mockito.mock;
@@ -7752,7 +7753,8 @@
     public void testOnNotificationActionClick() {
         final int actionIndex = 2;
         final Notification.Action action =
-                new Notification.Action.Builder(null, "text", null).build();
+                new Notification.Action.Builder(null, "text", PendingIntent.getActivity(
+                        mContext, 0, new Intent(), PendingIntent.FLAG_IMMUTABLE)).build();
         final boolean generatedByAssistant = false;
 
         NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
@@ -7776,7 +7778,8 @@
     public void testOnAssistantNotificationActionClick() {
         final int actionIndex = 1;
         final Notification.Action action =
-                new Notification.Action.Builder(null, "text", null).build();
+                new Notification.Action.Builder(null, "text", PendingIntent.getActivity(
+                        mContext, 0, new Intent(), PendingIntent.FLAG_IMMUTABLE)).build();
         final boolean generatedByAssistant = true;
 
         NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
@@ -12431,6 +12434,21 @@
         verify(mDevicePolicyManager).isActiveDeviceOwner(uid);
     }
 
+    @Test
+    public void testResetDefaultDnd() {
+        TestableNotificationManagerService service = spy(mService);
+        UserInfo user = new UserInfo(0, "owner", 0);
+        when(mUm.getAliveUsers()).thenReturn(List.of(user));
+        doReturn(false).when(service).isDNDMigrationDone(anyInt());
+
+        service.resetDefaultDndIfNecessary();
+
+        verify(mConditionProviders, times(1)).removeDefaultFromConfig(user.id);
+        verify(mConditionProviders, times(1)).resetDefaultFromConfig();
+        verify(service, times(1)).allowDndPackages(user.id);
+        verify(service, times(1)).setDNDMigrationDone(user.id);
+    }
+
     private static <T extends Parcelable> T parcelAndUnparcel(T source,
             Parcelable.Creator<T> creator) {
         Parcel parcel = Parcel.obtain();
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java
index fae92d9..f83a1df 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java
@@ -36,7 +36,7 @@
 import static junit.framework.Assert.assertTrue;
 
 import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.fail;
+import static org.junit.Assert.assertThrows;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.eq;
@@ -44,7 +44,6 @@
 import static org.mockito.Mockito.when;
 
 import android.app.ActivityManager;
-import android.app.IActivityManager;
 import android.app.Notification;
 import android.app.Notification.Builder;
 import android.app.NotificationChannel;
@@ -76,6 +75,7 @@
 
 import com.android.internal.R;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.server.LocalServices;
 import com.android.server.UiServiceTestCase;
 import com.android.server.uri.UriGrantsManagerInternal;
 
@@ -850,84 +850,78 @@
 
     @Test
     public void testCalculateGrantableUris_PappProvided() {
-        IActivityManager am = mock(IActivityManager.class);
         UriGrantsManagerInternal ugm = mock(UriGrantsManagerInternal.class);
         when(ugm.checkGrantUriPermission(anyInt(), eq(null), any(Uri.class),
                 anyInt(), anyInt())).thenThrow(new SecurityException());
 
+        LocalServices.removeServiceForTest(UriGrantsManagerInternal.class);
+        LocalServices.addService(UriGrantsManagerInternal.class, ugm);
+
         channel.setSound(null, null);
         Notification n = new Notification.Builder(mContext, channel.getId())
                 .setSmallIcon(Icon.createWithContentUri(Uri.parse("content://something")))
                 .build();
         StatusBarNotification sbn =
                 new StatusBarNotification(PKG_P, PKG_P, id1, tag1, uid, uid, n, mUser, null, uid);
-        NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
-        record.mAm = am;
-        record.mUgmInternal = ugm;
 
-        try {
-            record.calculateGrantableUris();
-            fail("App provided uri for p targeting app should throw exception");
-        } catch (SecurityException e) {
-            // expected
-        }
+        assertThrows("App provided uri for p targeting app should throw exception",
+                SecurityException.class,
+                () -> new NotificationRecord(mMockContext, sbn, channel));
     }
 
     @Test
     public void testCalculateGrantableUris_PappProvided_invalidSound() {
-        IActivityManager am = mock(IActivityManager.class);
         UriGrantsManagerInternal ugm = mock(UriGrantsManagerInternal.class);
         when(ugm.checkGrantUriPermission(anyInt(), eq(null), any(Uri.class),
                 anyInt(), anyInt())).thenThrow(new SecurityException());
 
+        LocalServices.removeServiceForTest(UriGrantsManagerInternal.class);
+        LocalServices.addService(UriGrantsManagerInternal.class, ugm);
+
         channel.setSound(Uri.parse("content://something"), mock(AudioAttributes.class));
 
         Notification n = mock(Notification.class);
         when(n.getChannelId()).thenReturn(channel.getId());
         StatusBarNotification sbn =
                 new StatusBarNotification(PKG_P, PKG_P, id1, tag1, uid, uid, n, mUser, null, uid);
-        NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
-        record.mAm = am;
-        record.mUgmInternal = ugm;
 
-        record.calculateGrantableUris();
+        NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
         assertEquals(Settings.System.DEFAULT_NOTIFICATION_URI, record.getSound());
     }
 
     @Test
     public void testCalculateGrantableUris_PuserOverridden() {
-        IActivityManager am = mock(IActivityManager.class);
         UriGrantsManagerInternal ugm = mock(UriGrantsManagerInternal.class);
         when(ugm.checkGrantUriPermission(anyInt(), eq(null), any(Uri.class),
                 anyInt(), anyInt())).thenThrow(new SecurityException());
 
+        LocalServices.removeServiceForTest(UriGrantsManagerInternal.class);
+        LocalServices.addService(UriGrantsManagerInternal.class, ugm);
+
         channel.lockFields(NotificationChannel.USER_LOCKED_SOUND);
         Notification n = mock(Notification.class);
         when(n.getChannelId()).thenReturn(channel.getId());
         StatusBarNotification sbn =
                 new StatusBarNotification(PKG_P, PKG_P, id1, tag1, uid, uid, n, mUser, null, uid);
-        NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
-        record.mAm = am;
 
-        record.calculateGrantableUris();
+        new NotificationRecord(mMockContext, sbn, channel); // should not throw
     }
 
     @Test
     public void testCalculateGrantableUris_prePappProvided() {
-        IActivityManager am = mock(IActivityManager.class);
         UriGrantsManagerInternal ugm = mock(UriGrantsManagerInternal.class);
         when(ugm.checkGrantUriPermission(anyInt(), eq(null), any(Uri.class),
                 anyInt(), anyInt())).thenThrow(new SecurityException());
 
+        LocalServices.removeServiceForTest(UriGrantsManagerInternal.class);
+        LocalServices.addService(UriGrantsManagerInternal.class, ugm);
+
         Notification n = mock(Notification.class);
         when(n.getChannelId()).thenReturn(channel.getId());
         StatusBarNotification sbn =
                 new StatusBarNotification(PKG_O, PKG_O, id1, tag1, uid, uid, n, mUser, null, uid);
-        NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
-        record.mAm = am;
 
-        record.calculateGrantableUris();
-        // should not throw
+        new NotificationRecord(mMockContext, sbn, channel); // should not throw
     }
 
     @Test
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
index c242554..81d939f 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
@@ -600,7 +600,7 @@
         NotificationChannel channel2 =
                 new NotificationChannel("id2", "name2", IMPORTANCE_LOW);
         channel2.setDescription("descriptions for all");
-        channel2.setSound(SOUND_URI, mAudioAttributes);
+        channel2.setSound(CANONICAL_SOUND_URI, mAudioAttributes);
         channel2.enableLights(true);
         channel2.setBypassDnd(true);
         channel2.setLockscreenVisibility(VISIBILITY_SECRET);
@@ -1374,6 +1374,8 @@
                 .when(mTestIContentProvider).uncanonicalize(any(), eq(CANONICAL_SOUND_URI));
         doReturn(localUri)
                 .when(mTestIContentProvider).uncanonicalize(any(), eq(canonicalBasedOnLocal));
+        doReturn(canonicalBasedOnLocal)
+                .when(mTestIContentProvider).canonicalize(any(), eq(localUri));
 
         NotificationChannel channel =
                 new NotificationChannel("id", "name", IMPORTANCE_LOW);
@@ -1387,7 +1389,7 @@
 
         NotificationChannel actualChannel = mHelper.getNotificationChannel(
                 PKG_N_MR1, UID_N_MR1, channel.getId(), false);
-        assertEquals(localUri, actualChannel.getSound());
+        assertEquals(canonicalBasedOnLocal, actualChannel.getSound());
     }
 
     @Test
diff --git a/services/tests/vibrator/TEST_MAPPING b/services/tests/vibrator/TEST_MAPPING
index f0a7e47..39bd238 100644
--- a/services/tests/vibrator/TEST_MAPPING
+++ b/services/tests/vibrator/TEST_MAPPING
@@ -3,9 +3,8 @@
     {
       "name": "FrameworksVibratorServicesTests",
       "options": [
-        {"exclude-annotation": "android.platform.test.annotations.LargeTest"},
-        {"exclude-annotation": "android.platform.test.annotations.FlakyTest"},
         {"exclude-annotation": "androidx.test.filters.FlakyTest"},
+        {"exclude-annotation": "androidx.test.filters.LargeTest"},
         {"exclude-annotation": "org.junit.Ignore"}
       ]
     }
diff --git a/services/tests/vibrator/src/com/android/server/vibrator/VibrationThreadTest.java b/services/tests/vibrator/src/com/android/server/vibrator/VibrationThreadTest.java
index edc5df2..44cf333 100644
--- a/services/tests/vibrator/src/com/android/server/vibrator/VibrationThreadTest.java
+++ b/services/tests/vibrator/src/com/android/server/vibrator/VibrationThreadTest.java
@@ -60,11 +60,11 @@
 import android.os.vibrator.StepSegment;
 import android.os.vibrator.VibrationConfig;
 import android.os.vibrator.VibrationEffectSegment;
-import android.platform.test.annotations.FlakyTest;
-import android.platform.test.annotations.LargeTest;
 import android.util.SparseArray;
 
 import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.FlakyTest;
+import androidx.test.filters.LargeTest;
 
 import com.android.server.LocalServices;
 
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 3db53eb..302ad7f 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -2719,6 +2719,9 @@
         assertEquals(Configuration.ORIENTATION_PORTRAIT, displayConfig.orientation);
         assertEquals(Configuration.ORIENTATION_PORTRAIT, activityConfig.orientation);
 
+        // Unblock the rotation animation, so the further orientation updates won't be ignored.
+        unblockDisplayRotation(activity.mDisplayContent);
+
         final ActivityRecord topActivity = createActivityRecord(activity.getTask());
         topActivity.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
 
@@ -2939,6 +2942,9 @@
         // transform to activity1.
         int rotation = (mDisplayContent.getRotation() + 1) % 4;
         mDisplayContent.setFixedRotationLaunchingApp(activity, rotation);
+        // The configuration with rotation change should not trigger task-association.
+        assertNotNull(activity.mStartingData);
+        assertNull(activity.mStartingData.mAssociatedTask);
         doReturn(rotation).when(mDisplayContent)
                 .rotationForActivityInDifferentOrientation(topActivity);
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivitySnapshotControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivitySnapshotControllerTests.java
index 0eca8c9..98f1843 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivitySnapshotControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivitySnapshotControllerTests.java
@@ -18,6 +18,9 @@
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
 
+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 android.platform.test.annotations.Presubmit;
@@ -28,6 +31,8 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.ArrayList;
+
 /**
  * Test class for {@link ActivitySnapshotController}.
  *
@@ -42,13 +47,13 @@
     private ActivitySnapshotController mActivitySnapshotController;
     @Before
     public void setUp() throws Exception {
+        spyOn(mWm.mSnapshotController.mActivitySnapshotController);
         mActivitySnapshotController = mWm.mSnapshotController.mActivitySnapshotController;
+        doReturn(false).when(mActivitySnapshotController).shouldDisableSnapshots();
         mActivitySnapshotController.resetTmpFields();
     }
     @Test
     public void testOpenActivityTransition() {
-        final SnapshotController.TransitionState transitionState =
-                new SnapshotController.TransitionState();
         final Task task = createTask(mDisplayContent);
         // note for createAppWindow: the new child is added at index 0
         final WindowState openingWindow = createAppWindow(task,
@@ -59,14 +64,12 @@
                 "closingWindow");
         closingWindow.mActivityRecord.commitVisibility(
                 false /* visible */, true /* performLayout */);
-        transitionState.addParticipant(closingWindow.mActivityRecord, false);
-        transitionState.addParticipant(openingWindow.mActivityRecord, true);
-        mActivitySnapshotController.handleOpenActivityTransition(transitionState);
+        final ArrayList<WindowContainer> windows = new ArrayList<>();
+        windows.add(openingWindow.mActivityRecord);
+        windows.add(closingWindow.mActivityRecord);
+        mActivitySnapshotController.handleTransitionFinish(windows);
 
-        assertEquals(1, mActivitySnapshotController.mPendingCaptureActivity.size());
         assertEquals(0, mActivitySnapshotController.mPendingRemoveActivity.size());
-        assertEquals(closingWindow.mActivityRecord,
-                mActivitySnapshotController.mPendingCaptureActivity.valueAt(0));
         mActivitySnapshotController.resetTmpFields();
 
         // simulate three activity
@@ -74,19 +77,15 @@
                 "belowClose");
         belowClose.mActivityRecord.commitVisibility(
                 false /* visible */, true /* performLayout */);
-        mActivitySnapshotController.handleOpenActivityTransition(transitionState);
-        assertEquals(1, mActivitySnapshotController.mPendingCaptureActivity.size());
+        windows.add(belowClose.mActivityRecord);
+        mActivitySnapshotController.handleTransitionFinish(windows);
         assertEquals(1, mActivitySnapshotController.mPendingRemoveActivity.size());
-        assertEquals(closingWindow.mActivityRecord,
-                mActivitySnapshotController.mPendingCaptureActivity.valueAt(0));
         assertEquals(belowClose.mActivityRecord,
                 mActivitySnapshotController.mPendingRemoveActivity.valueAt(0));
     }
 
     @Test
     public void testCloseActivityTransition() {
-        final SnapshotController.TransitionState transitionState =
-                new SnapshotController.TransitionState();
         final Task task = createTask(mDisplayContent);
         // note for createAppWindow: the new child is added at index 0
         final WindowState closingWindow = createAppWindow(task, ACTIVITY_TYPE_STANDARD,
@@ -97,10 +96,10 @@
                 ACTIVITY_TYPE_STANDARD, "openingWindow");
         openingWindow.mActivityRecord.commitVisibility(
                 true /* visible */, true /* performLayout */);
-        transitionState.addParticipant(closingWindow.mActivityRecord, false);
-        transitionState.addParticipant(openingWindow.mActivityRecord, true);
-        mActivitySnapshotController.handleCloseActivityTransition(transitionState);
-        assertEquals(0, mActivitySnapshotController.mPendingCaptureActivity.size());
+        final ArrayList<WindowContainer> windows = new ArrayList<>();
+        windows.add(openingWindow.mActivityRecord);
+        windows.add(closingWindow.mActivityRecord);
+        mActivitySnapshotController.handleTransitionFinish(windows);
         assertEquals(1, mActivitySnapshotController.mPendingDeleteActivity.size());
         assertEquals(openingWindow.mActivityRecord,
                 mActivitySnapshotController.mPendingDeleteActivity.valueAt(0));
@@ -111,8 +110,8 @@
                 "belowOpen");
         belowOpen.mActivityRecord.commitVisibility(
                 false /* visible */, true /* performLayout */);
-        mActivitySnapshotController.handleCloseActivityTransition(transitionState);
-        assertEquals(0, mActivitySnapshotController.mPendingCaptureActivity.size());
+        windows.add(belowOpen.mActivityRecord);
+        mActivitySnapshotController.handleTransitionFinish(windows);
         assertEquals(1, mActivitySnapshotController.mPendingDeleteActivity.size());
         assertEquals(1, mActivitySnapshotController.mPendingLoadActivity.size());
         assertEquals(openingWindow.mActivityRecord,
@@ -123,10 +122,6 @@
 
     @Test
     public void testTaskTransition() {
-        final SnapshotController.TransitionState taskCloseTransition =
-                new SnapshotController.TransitionState();
-        final SnapshotController.TransitionState taskOpenTransition =
-                new SnapshotController.TransitionState();
         final Task closeTask = createTask(mDisplayContent);
         // note for createAppWindow: the new child is added at index 0
         final WindowState closingWindow = createAppWindow(closeTask, ACTIVITY_TYPE_STANDARD,
@@ -147,10 +142,10 @@
                 "openingWindowBelow");
         openingWindowBelow.mActivityRecord.commitVisibility(
                 false /* visible */, true /* performLayout */);
-        taskCloseTransition.addParticipant(closeTask, false);
-        taskOpenTransition.addParticipant(openTask, true);
-        mActivitySnapshotController.handleCloseTaskTransition(taskCloseTransition);
-        mActivitySnapshotController.handleOpenTaskTransition(taskOpenTransition);
+        final ArrayList<WindowContainer> windows = new ArrayList<>();
+        windows.add(closeTask);
+        windows.add(openTask);
+        mActivitySnapshotController.handleTransitionFinish(windows);
 
         assertEquals(1, mActivitySnapshotController.mPendingRemoveActivity.size());
         assertEquals(closingWindowBelow.mActivityRecord,
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 4290f4b..d169a58 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java
@@ -490,6 +490,11 @@
                 .build();
         final Task task = activity.getTask();
         final TaskDisplayArea tda = task.getDisplayArea();
+        // Ensure the display is not a large screen
+        if (tda.getConfiguration().smallestScreenWidthDp
+                >= WindowManager.LARGE_SCREEN_SMALLEST_SCREEN_WIDTH_DP) {
+            resizeDisplay(activity.mDisplayContent, 500, 800);
+        }
 
         // Ignore the activity min width/height for determine multi window eligibility.
         mAtm.mRespectsActivityMinWidthHeightMultiWindow = -1;
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppSnapshotControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/AppSnapshotControllerTests.java
deleted file mode 100644
index 83af1814..0000000
--- a/services/tests/wmtests/src/com/android/server/wm/AppSnapshotControllerTests.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS 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.ACTIVITY_TYPE_STANDARD;
-
-import static com.android.server.wm.SnapshotController.ACTIVITY_CLOSE;
-import static com.android.server.wm.SnapshotController.ACTIVITY_OPEN;
-import static com.android.server.wm.SnapshotController.TASK_CLOSE;
-import static com.android.server.wm.SnapshotController.TASK_OPEN;
-
-import static org.junit.Assert.assertTrue;
-
-import android.platform.test.annotations.Presubmit;
-import android.util.ArraySet;
-
-import androidx.test.filters.SmallTest;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-
-/**
- * Test class for {@link SnapshotController}.
- *
- * Build/Install/Run:
- *  *  atest WmTests:AppSnapshotControllerTests
- */
-@SmallTest
-@Presubmit
-@RunWith(WindowTestRunner.class)
-public class AppSnapshotControllerTests extends WindowTestsBase {
-    final ArraySet<ActivityRecord> mClosingApps = new ArraySet<>();
-    final ArraySet<ActivityRecord> mOpeningApps = new ArraySet<>();
-
-    final TransitionMonitor mOpenActivityMonitor = new TransitionMonitor();
-    final TransitionMonitor mCloseActivityMonitor = new TransitionMonitor();
-    final TransitionMonitor mOpenTaskMonitor = new TransitionMonitor();
-    final TransitionMonitor mCloseTaskMonitor = new TransitionMonitor();
-
-    @Before
-    public void setUp() throws Exception {
-        resetStatus();
-        mWm.mSnapshotController.registerTransitionStateConsumer(
-                ACTIVITY_CLOSE, mCloseActivityMonitor::handleTransition);
-        mWm.mSnapshotController.registerTransitionStateConsumer(
-                ACTIVITY_OPEN, mOpenActivityMonitor::handleTransition);
-        mWm.mSnapshotController.registerTransitionStateConsumer(
-                TASK_CLOSE, mCloseTaskMonitor::handleTransition);
-        mWm.mSnapshotController.registerTransitionStateConsumer(
-                TASK_OPEN, mOpenTaskMonitor::handleTransition);
-    }
-
-    @After
-    public void tearDown() throws Exception {
-        mWm.mSnapshotController.unregisterTransitionStateConsumer(
-                ACTIVITY_CLOSE, mCloseActivityMonitor::handleTransition);
-        mWm.mSnapshotController.unregisterTransitionStateConsumer(
-                ACTIVITY_OPEN, mOpenActivityMonitor::handleTransition);
-        mWm.mSnapshotController.unregisterTransitionStateConsumer(
-                TASK_CLOSE, mCloseTaskMonitor::handleTransition);
-        mWm.mSnapshotController.unregisterTransitionStateConsumer(
-                TASK_OPEN, mOpenTaskMonitor::handleTransition);
-    }
-
-    private static class TransitionMonitor {
-        private final ArraySet<WindowContainer> mOpenParticipant = new ArraySet<>();
-        private final ArraySet<WindowContainer> mCloseParticipant = new ArraySet<>();
-        void handleTransition(SnapshotController.TransitionState<ActivityRecord> state) {
-            mOpenParticipant.addAll(state.getParticipant(true /* open */));
-            mCloseParticipant.addAll(state.getParticipant(false /* close */));
-        }
-        void reset() {
-            mOpenParticipant.clear();
-            mCloseParticipant.clear();
-        }
-    }
-
-    private void resetStatus() {
-        mClosingApps.clear();
-        mOpeningApps.clear();
-        mOpenActivityMonitor.reset();
-        mCloseActivityMonitor.reset();
-        mOpenTaskMonitor.reset();
-        mCloseTaskMonitor.reset();
-    }
-
-    @Test
-    public void testHandleAppTransition_openActivityTransition() {
-        final Task task = createTask(mDisplayContent);
-        // note for createAppWindow: the new child is added at index 0
-        final WindowState openingWindow = createAppWindow(task,
-                ACTIVITY_TYPE_STANDARD, "openingWindow");
-        openingWindow.mActivityRecord.commitVisibility(
-                true /* visible */, true /* performLayout */);
-        final WindowState closingWindow = createAppWindow(task, ACTIVITY_TYPE_STANDARD,
-                "closingWindow");
-        closingWindow.mActivityRecord.commitVisibility(
-                false /* visible */, true /* performLayout */);
-        mClosingApps.add(closingWindow.mActivityRecord);
-        mOpeningApps.add(openingWindow.mActivityRecord);
-        mWm.mSnapshotController.handleAppTransition(mClosingApps, mOpeningApps);
-        assertTrue(mOpenActivityMonitor.mCloseParticipant.contains(closingWindow.mActivityRecord));
-        assertTrue(mOpenActivityMonitor.mOpenParticipant.contains(openingWindow.mActivityRecord));
-    }
-
-    @Test
-    public void testHandleAppTransition_closeActivityTransition() {
-        final Task task = createTask(mDisplayContent);
-        // note for createAppWindow: the new child is added at index 0
-        final WindowState closingWindow = createAppWindow(task, ACTIVITY_TYPE_STANDARD,
-                "closingWindow");
-        closingWindow.mActivityRecord.commitVisibility(
-                false /* visible */, true /* performLayout */);
-        final WindowState openingWindow = createAppWindow(task,
-                ACTIVITY_TYPE_STANDARD, "openingWindow");
-        openingWindow.mActivityRecord.commitVisibility(
-                true /* visible */, true /* performLayout */);
-        mClosingApps.add(closingWindow.mActivityRecord);
-        mOpeningApps.add(openingWindow.mActivityRecord);
-        mWm.mSnapshotController.handleAppTransition(mClosingApps, mOpeningApps);
-        assertTrue(mCloseActivityMonitor.mCloseParticipant.contains(closingWindow.mActivityRecord));
-        assertTrue(mCloseActivityMonitor.mOpenParticipant.contains(openingWindow.mActivityRecord));
-    }
-
-    @Test
-    public void testHandleAppTransition_TaskTransition() {
-        final Task closeTask = createTask(mDisplayContent);
-        // note for createAppWindow: the new child is added at index 0
-        final WindowState closingWindow = createAppWindow(closeTask, ACTIVITY_TYPE_STANDARD,
-                "closingWindow");
-        closingWindow.mActivityRecord.commitVisibility(
-                false /* visible */, true /* performLayout */);
-        final WindowState closingWindowBelow = createAppWindow(closeTask, ACTIVITY_TYPE_STANDARD,
-                "closingWindowBelow");
-        closingWindowBelow.mActivityRecord.commitVisibility(
-                false /* visible */, true /* performLayout */);
-
-        final Task openTask = createTask(mDisplayContent);
-        final WindowState openingWindow = createAppWindow(openTask, ACTIVITY_TYPE_STANDARD,
-                "openingWindow");
-        openingWindow.mActivityRecord.commitVisibility(
-                true /* visible */, true /* performLayout */);
-        final WindowState openingWindowBelow = createAppWindow(openTask, ACTIVITY_TYPE_STANDARD,
-                "openingWindowBelow");
-        openingWindowBelow.mActivityRecord.commitVisibility(
-                false /* visible */, true /* performLayout */);
-
-        mClosingApps.add(closingWindow.mActivityRecord);
-        mOpeningApps.add(openingWindow.mActivityRecord);
-        mWm.mSnapshotController.handleAppTransition(mClosingApps, mOpeningApps);
-        assertTrue(mCloseTaskMonitor.mCloseParticipant.contains(closeTask));
-        assertTrue(mOpenTaskMonitor.mOpenParticipant.contains(openTask));
-    }
-}
diff --git a/services/tests/wmtests/src/com/android/server/wm/ContentRecorderTests.java b/services/tests/wmtests/src/com/android/server/wm/ContentRecorderTests.java
index 41c0caae..c84eab3 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ContentRecorderTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ContentRecorderTests.java
@@ -36,6 +36,7 @@
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.atLeast;
 import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.clearInvocations;
 import static org.mockito.Mockito.never;
 
 import android.app.WindowConfiguration;
@@ -507,6 +508,7 @@
         // Return the default display as the value to mirror to ensure the VD with flag mirroring
         // creates a ContentRecordingSession automatically.
         doReturn(DEFAULT_DISPLAY).when(mWm.mDisplayManagerInternal).getDisplayIdToMirror(anyInt());
+        clearInvocations(virtualDisplay);
         virtualDisplay.updateRecording();
 
         // THEN mirroring is initiated for the default display's DisplayArea.
diff --git a/services/tests/wmtests/src/com/android/server/wm/ContentRecordingControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/ContentRecordingControllerTests.java
index 52226c2..4473a31 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ContentRecordingControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ContentRecordingControllerTests.java
@@ -123,6 +123,7 @@
         controller.setContentRecordingSessionLocked(mWaitingDisplaySession, mWm);
         verify(mVirtualDisplayContent, atLeastOnce()).setContentRecordingSession(
                 mWaitingDisplaySession);
+        verify(mVirtualDisplayContent).updateRecording();
 
         // WHEN updating the session on the same display, so no longer waiting to record.
         ContentRecordingSession sessionUpdate = ContentRecordingSession.createTaskSession(
@@ -135,7 +136,7 @@
         // THEN the session was accepted.
         assertThat(resultingSession).isEqualTo(sessionUpdate);
         verify(mVirtualDisplayContent, atLeastOnce()).setContentRecordingSession(sessionUpdate);
-        verify(mVirtualDisplayContent).updateRecording();
+        verify(mVirtualDisplayContent, atLeastOnce()).updateRecording();
     }
 
     @Test
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayAreaGroupTest.java b/services/tests/wmtests/src/com/android/server/wm/DisplayAreaGroupTest.java
index f536cd0..87dbca5 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayAreaGroupTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayAreaGroupTest.java
@@ -114,8 +114,9 @@
 
     @Test
     public void testResolveOverrideConfiguration_reverseOrientationWhenDifferentFromParentRoot() {
-        mDisplayContent.setBounds(0, 0, 600, 900);
-        mDisplayContent.updateOrientation();
+        // Rotate the display to portrait.
+        final DisplayRotation displayRotation = mDisplayContent.getDisplayRotation();
+        displayRotation.setRotation(displayRotation.getPortraitRotation());
         mDisplayContent.sendNewConfiguration();
 
         // DAG fills Display
@@ -128,7 +129,7 @@
         assertThat(mDisplayAreaGroup.getConfiguration().orientation)
                 .isEqualTo(ORIENTATION_LANDSCAPE);
 
-        // DisplayAreaGroup is portriat, same as Display
+        // DisplayAreaGroup is portrait, same as Display
         mDisplayAreaGroup.setBounds(0, 0, 300, 450);
 
         assertThat(mDisplayAreaGroup.getConfiguration().orientation)
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 d015ca3..a2b7da3 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
@@ -1819,7 +1819,7 @@
 
         final ActivityRecord activity = createActivityRecord(mDisplayContent);
         final ActivityRecord recentsActivity = createActivityRecord(mDisplayContent);
-        recentsActivity.setRequestedOrientation(SCREEN_ORIENTATION_PORTRAIT);
+        recentsActivity.setRequestedOrientation(SCREEN_ORIENTATION_NOSENSOR);
         doReturn(mock(RecentsAnimationController.class)).when(mWm).getRecentsAnimationController();
 
         // Do not rotate if the recents animation is animating on top.
@@ -2049,6 +2049,17 @@
         assertNotEquals(testPlayer.mLastReady.getChange(dcToken).getEndRotation(),
                 testPlayer.mLastReady.getChange(dcToken).getStartRotation());
         testPlayer.finish();
+
+        // The AsyncRotationController should only exist if there is an ongoing rotation change.
+        dc.finishAsyncRotationIfPossible();
+        dc.setLastHasContent();
+        doReturn(dr.getRotation() + 1).when(dr).rotationForOrientation(anyInt(), anyInt());
+        dr.updateRotationUnchecked(true /* forceUpdate */);
+        assertNotNull(dc.getAsyncRotationController());
+        doReturn(dr.getRotation() - 1).when(dr).rotationForOrientation(anyInt(), anyInt());
+        dr.updateRotationUnchecked(true /* forceUpdate */);
+        assertNull("Cancel AsyncRotationController for the intermediate rotation changes 0->1->0",
+                dc.getAsyncRotationController());
     }
 
     @Test
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 939ff97..c4302db 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayRotationTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayRotationTests.java
@@ -1194,6 +1194,15 @@
     }
 
     @Test
+    public void testIsFixedToUserRotation_displayContentOrientationFixed() throws Exception {
+        mBuilder.build();
+        when(mMockDisplayContent.isDisplayOrientationFixed()).thenReturn(true);
+
+        assertFalse("Display rotation should respect app requested orientation if"
+                + " the display has fixed orientation.", mTarget.isFixedToUserRotation());
+    }
+
+    @Test
     public void testIsFixedToUserRotation_FixedToUserRotationIfNoAutoRotation() throws Exception {
         mBuilder.build();
         mTarget.setFixedToUserRotation(FIXED_TO_USER_ROTATION_IF_NO_AUTO_ROTATION);
diff --git a/services/tests/wmtests/src/com/android/server/wm/LetterboxUiControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/LetterboxUiControllerTest.java
index 72ab18d..2ad9fa0 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LetterboxUiControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LetterboxUiControllerTest.java
@@ -37,6 +37,8 @@
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER;
+import static android.content.pm.PackageManager.USER_MIN_ASPECT_RATIO_3_2;
+import static android.content.pm.PackageManager.USER_MIN_ASPECT_RATIO_FULLSCREEN;
 import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
 import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
 import static android.view.InsetsSource.FLAG_INSETS_ROUNDED_CORNER;
@@ -48,6 +50,8 @@
 import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_MIN_ASPECT_RATIO_OVERRIDE;
 import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE;
 import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_RESIZEABLE_ACTIVITY_OVERRIDES;
+import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_FULLSCREEN_OVERRIDE;
+import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_OVERRIDE;
 import static android.view.WindowManager.PROPERTY_COMPAT_ENABLE_FAKE_FOCUS;
 import static android.view.WindowManager.PROPERTY_COMPAT_IGNORE_REQUESTED_ORIENTATION;
 
@@ -807,6 +811,108 @@
                 /* candidate */ SCREEN_ORIENTATION_PORTRAIT), SCREEN_ORIENTATION_PORTRAIT);
     }
 
+    // shouldApplyUser...Override
+    @Test
+    public void testShouldApplyUserFullscreenOverride_trueProperty_returnsFalse() throws Exception {
+        mockThatProperty(PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_FULLSCREEN_OVERRIDE,
+                /* value */ true);
+
+        mController = new LetterboxUiController(mWm, mActivity);
+        doReturn(false).when(mLetterboxConfiguration).isUserAppAspectRatioFullscreenEnabled();
+
+        assertFalse(mController.shouldApplyUserFullscreenOverride());
+    }
+
+    @Test
+    public void testShouldApplyUserFullscreenOverride_falseFullscreenProperty_returnsFalse()
+            throws Exception {
+        prepareActivityThatShouldApplyUserFullscreenOverride();
+        mockThatProperty(PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_FULLSCREEN_OVERRIDE,
+                /* value */ false);
+
+        mController = new LetterboxUiController(mWm, mActivity);
+
+        assertFalse(mController.shouldApplyUserFullscreenOverride());
+    }
+
+    @Test
+    public void testShouldApplyUserFullscreenOverride_falseSettingsProperty_returnsFalse()
+            throws Exception {
+        prepareActivityThatShouldApplyUserFullscreenOverride();
+        mockThatProperty(PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_OVERRIDE, /* value */ false);
+
+        mController = new LetterboxUiController(mWm, mActivity);
+
+        assertFalse(mController.shouldApplyUserFullscreenOverride());
+    }
+
+    @Test
+    public void testShouldApplyUserFullscreenOverride_disabledIgnoreOrientationRequest() {
+        prepareActivityThatShouldApplyUserFullscreenOverride();
+        mDisplayContent.setIgnoreOrientationRequest(false);
+
+        assertFalse(mController.shouldApplyUserFullscreenOverride());
+    }
+
+    @Test
+    public void testShouldApplyUserFullscreenOverride_returnsTrue() {
+        prepareActivityThatShouldApplyUserFullscreenOverride();
+
+        assertTrue(mController.shouldApplyUserFullscreenOverride());
+    }
+
+    @Test
+    public void testShouldApplyUserMinAspectRatioOverride_falseProperty_returnsFalse()
+            throws Exception {
+        prepareActivityThatShouldApplyUserMinAspectRatioOverride();
+        mockThatProperty(PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_OVERRIDE, /* value */ false);
+
+        mController = new LetterboxUiController(mWm, mActivity);
+
+        assertFalse(mController.shouldApplyUserMinAspectRatioOverride());
+    }
+
+    @Test
+    public void testShouldApplyUserMinAspectRatioOverride_trueProperty_returnsFalse()
+            throws Exception {
+        doReturn(false).when(mLetterboxConfiguration).isUserAppAspectRatioSettingsEnabled();
+        mockThatProperty(PROPERTY_COMPAT_ALLOW_USER_ASPECT_RATIO_OVERRIDE, /* value */ true);
+
+        mController = new LetterboxUiController(mWm, mActivity);
+
+        assertFalse(mController.shouldApplyUserMinAspectRatioOverride());
+    }
+
+    @Test
+    public void testShouldApplyUserMinAspectRatioOverride_disabledIgnoreOrientationRequest() {
+        prepareActivityThatShouldApplyUserMinAspectRatioOverride();
+        mDisplayContent.setIgnoreOrientationRequest(false);
+
+        assertFalse(mController.shouldApplyUserMinAspectRatioOverride());
+    }
+
+    @Test
+    public void testShouldApplyUserMinAspectRatioOverride_returnsTrue() {
+        prepareActivityThatShouldApplyUserMinAspectRatioOverride();
+
+        assertTrue(mController.shouldApplyUserMinAspectRatioOverride());
+    }
+
+    private void prepareActivityThatShouldApplyUserMinAspectRatioOverride() {
+        spyOn(mController);
+        doReturn(true).when(mLetterboxConfiguration).isUserAppAspectRatioSettingsEnabled();
+        mDisplayContent.setIgnoreOrientationRequest(true);
+        doReturn(USER_MIN_ASPECT_RATIO_3_2).when(mController).getUserMinAspectRatioOverrideCode();
+    }
+
+    private void prepareActivityThatShouldApplyUserFullscreenOverride() {
+        spyOn(mController);
+        doReturn(true).when(mLetterboxConfiguration).isUserAppAspectRatioFullscreenEnabled();
+        mDisplayContent.setIgnoreOrientationRequest(true);
+        doReturn(USER_MIN_ASPECT_RATIO_FULLSCREEN).when(mController)
+                .getUserMinAspectRatioOverrideCode();
+    }
+
     // shouldUseDisplayLandscapeNaturalOrientation
 
     @Test
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 6e52af1..c1be5ca 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
@@ -353,6 +353,7 @@
 
     @Test
     public void testRecentViewInFixedPortraitWhenTopAppInLandscape() {
+        makeDisplayPortrait(mDefaultDisplay);
         unblockDisplayRotation(mDefaultDisplay);
         mWm.setRecentsAnimationController(mController);
 
@@ -488,6 +489,7 @@
 
     @Test
     public void testWallpaperHasFixedRotationApplied() {
+        makeDisplayPortrait(mDefaultDisplay);
         unblockDisplayRotation(mDefaultDisplay);
         mWm.setRecentsAnimationController(mController);
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
index d5afe3b..0cdd9b8 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
@@ -1880,6 +1880,11 @@
         final int dh = 2500;
         final int notchHeight = 200;
         setUpApp(new TestDisplayContent.Builder(mAtm, dw, dh).setNotch(notchHeight).build());
+        // The test assumes the notch will be at left side when the orientation is landscape.
+        if (mContext.getResources().getBoolean(
+                com.android.internal.R.bool.config_reverseDefaultRotation)) {
+            setReverseDefaultRotation(mActivity.mDisplayContent, false);
+        }
         addStatusBar(mActivity.mDisplayContent);
 
         mActivity.setVisible(false);
diff --git a/services/tests/wmtests/src/com/android/server/wm/SurfaceControlTests.java b/services/tests/wmtests/src/com/android/server/wm/SurfaceControlTests.java
index 9a93746..e3f8e8c 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SurfaceControlTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SurfaceControlTests.java
@@ -125,6 +125,7 @@
 
     @Test
     public void testSurfaceChangedOnRotation() {
+        CommonUtils.dismissKeyguard();
         final Instrumentation instrumentation = getInstrumentation();
         final Context context = instrumentation.getContext();
         final Intent intent = new Intent().setComponent(
@@ -137,6 +138,8 @@
         instrumentation.runOnMainSync(() -> activity.setContentView(sv));
         sv.getHolder().addCallback(new SurfaceHolder.Callback() {
             int mInitialTransformHint = -1;
+            int mInitialW;
+            int mInitialH;
 
             @Override
             public void surfaceCreated(@NonNull SurfaceHolder holder) {
@@ -148,7 +151,10 @@
                         sv.getViewRootImpl().getSurfaceControl().getTransformHint();
                 if (mInitialTransformHint == -1) {
                     mInitialTransformHint = transformHint;
-                } else if (mInitialTransformHint == transformHint) {
+                    mInitialW = width;
+                    mInitialH = height;
+                } else if (mInitialTransformHint == transformHint
+                        && (width > height) != (mInitialW > mInitialH)) {
                     // For example, the initial hint is from portrait, so the later changes from
                     // landscape should not receive the same hint.
                     unexpectedTransformHint[0] = true;
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 be436bf..7634d9f 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
@@ -384,7 +384,16 @@
     }
 
     private void tearDown() {
-        mWmService.mRoot.forAllDisplayPolicies(DisplayPolicy::release);
+        for (int i = mWmService.mRoot.getChildCount() - 1; i >= 0; i--) {
+            final DisplayContent dc = mWmService.mRoot.getChildAt(i);
+            // Unregister SettingsObserver.
+            dc.getDisplayPolicy().release();
+            // Unregister SensorEventListener (foldable device may register for hinge angle).
+            dc.getDisplayRotation().onDisplayRemoved();
+            if (dc.mDisplayRotationCompatPolicy != null) {
+                dc.mDisplayRotationCompatPolicy.dispose();
+            }
+        }
 
         // Unregister display listener from root to avoid issues with subsequent tests.
         mContext.getSystemService(DisplayManager.class)
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java
index 54b9351..bfa279d 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java
@@ -143,6 +143,7 @@
     @Before
     public void setup() throws RemoteException {
         MockitoAnnotations.initMocks(this);
+        removeGlobalMinSizeRestriction();
         mWindowOrganizerController = mAtm.mWindowOrganizerController;
         mTransitionController = mWindowOrganizerController.mTransitionController;
         mController = mWindowOrganizerController.mTaskFragmentOrganizerController;
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskStackChangedListenerTest.java b/services/tests/wmtests/src/com/android/server/wm/TaskStackChangedListenerTest.java
index 16c38ac..08438c8 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskStackChangedListenerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskStackChangedListenerTest.java
@@ -354,25 +354,37 @@
             }
         });
 
-        final LandscapeActivity activity =
-                (LandscapeActivity) startTestActivity(LandscapeActivity.class);
+        final boolean isIgnoringOrientationRequest =
+                CommonUtils.getIgnoreOrientationRequest(Display.DEFAULT_DISPLAY);
+        if (isIgnoringOrientationRequest) {
+            CommonUtils.setIgnoreOrientationRequest(Display.DEFAULT_DISPLAY, false);
+        }
 
-        int[] taskIdAndOrientation = waitForResult(taskIdAndOrientationQueue,
-                candidate -> candidate[0] == activity.getTaskId());
-        assertNotNull(taskIdAndOrientation);
-        assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, taskIdAndOrientation[1]);
+        try {
+            final LandscapeActivity activity =
+                    (LandscapeActivity) startTestActivity(LandscapeActivity.class);
 
-        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
-        taskIdAndOrientation = waitForResult(taskIdAndOrientationQueue,
-                candidate -> candidate[0] == activity.getTaskId());
-        assertNotNull(taskIdAndOrientation);
-        assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT, taskIdAndOrientation[1]);
+            int[] taskIdAndOrientation = waitForResult(taskIdAndOrientationQueue,
+                    candidate -> candidate[0] == activity.getTaskId());
+            assertNotNull(taskIdAndOrientation);
+            assertEquals(
+                    ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, taskIdAndOrientation[1]);
 
-        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
-        taskIdAndOrientation = waitForResult(taskIdAndOrientationQueue,
-                candidate -> candidate[0] == activity.getTaskId());
-        assertNotNull(taskIdAndOrientation);
-        assertEquals(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED, taskIdAndOrientation[1]);
+            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
+            taskIdAndOrientation = waitForResult(taskIdAndOrientationQueue,
+                    candidate -> candidate[0] == activity.getTaskId());
+            assertNotNull(taskIdAndOrientation);
+            assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT, taskIdAndOrientation[1]);
+
+            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
+            taskIdAndOrientation = waitForResult(taskIdAndOrientationQueue,
+                    candidate -> candidate[0] == activity.getTaskId());
+            assertNotNull(taskIdAndOrientation);
+            assertEquals(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED, taskIdAndOrientation[1]);
+        } finally {
+            CommonUtils.setIgnoreOrientationRequest(
+                    Display.DEFAULT_DISPLAY, isIgnoringOrientationRequest);
+        }
     }
 
     /**
diff --git a/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java b/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
index 40b1521..07cdfaf 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
@@ -46,7 +46,6 @@
 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 com.android.server.wm.SnapshotController.TASK_CLOSE;
 import static com.android.server.wm.WindowContainer.POSITION_TOP;
 
 import static org.junit.Assert.assertEquals;
@@ -1387,8 +1386,6 @@
     @Test
     public void testTransientLaunch() {
         spyOn(mWm.mSnapshotController.mTaskSnapshotController);
-        mWm.mSnapshotController.registerTransitionStateConsumer(TASK_CLOSE,
-                mWm.mSnapshotController.mTaskSnapshotController::handleTaskClose);
         final ArrayList<ActivityRecord> enteringAnimReports = new ArrayList<>();
         final TransitionController controller = new TestTransitionController(mAtm) {
             @Override
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 6305bb6..6216acb 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WallpaperControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WallpaperControllerTests.java
@@ -116,10 +116,7 @@
     public void testWallpaperSizeWithFixedTransform() {
         // No wallpaper
         final DisplayContent dc = mDisplayContent;
-        if (dc.mBaseDisplayHeight == dc.mBaseDisplayWidth) {
-            // Make sure the size is different when changing orientation.
-            resizeDisplay(dc, 500, 1000);
-        }
+        makeDisplayPortrait(dc);
 
         // No wallpaper WSA Surface
         final WindowState wallpaperWindow = createWallpaperWindow(dc);
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowContextListenerControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowContextListenerControllerTests.java
index 55dc375..d85d9b5 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowContextListenerControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowContextListenerControllerTests.java
@@ -41,19 +41,16 @@
 import static org.mockito.MockitoAnnotations.initMocks;
 
 import android.app.ClientTransactionHandler;
-import android.app.IWindowToken;
 import android.app.servertransaction.ClientTransactionItem;
 import android.app.servertransaction.WindowContextInfoChangeItem;
 import android.content.res.Configuration;
 import android.graphics.Rect;
-import android.os.Binder;
 import android.os.Bundle;
-import android.os.IBinder;
 import android.platform.test.annotations.Presubmit;
-import android.util.ArrayMap;
 import android.view.Display;
 import android.view.DisplayInfo;
 import android.window.WindowContextInfo;
+import android.window.WindowTokenClient;
 
 import androidx.test.filters.SmallTest;
 
@@ -78,11 +75,11 @@
 
     @Mock
     private ClientTransactionHandler mHandler;
+    @Mock
+    private WindowTokenClient mClientToken;
 
     private WindowProcessController mWpc;
-    private final IBinder mClientToken = new Binder();
     private WindowContainer<?> mContainer;
-    private ArrayMap<IBinder, TestWindowTokenClient> mWindowTokenClientMap;
 
     @Before
     public void setUp() {
@@ -92,7 +89,6 @@
         // Make display on to verify configuration propagation.
         mDefaultDisplay.getDisplayInfo().state = STATE_ON;
         mDisplayContent.getDisplayInfo().state = STATE_ON;
-        mWindowTokenClientMap = new ArrayMap<>();
 
         mWpc = mSystemServicesTestRule.addProcess(
                 DEFAULT_COMPONENT_PACKAGE_NAME, DEFAULT_COMPONENT_PACKAGE_NAME, 0 /* pid */,
@@ -102,13 +98,9 @@
         doAnswer(invocation -> {
             // Mock ActivityThread
             final Object[] args = invocation.getArguments();
-            final IBinder clientToken = (IBinder) args[0];
+            final WindowTokenClient clientToken = (WindowTokenClient) args[0];
             final WindowContextInfo info = (WindowContextInfo) args[1];
-            final TestWindowTokenClient client = mWindowTokenClientMap.get(clientToken);
-            if (client != null) {
-                // Can be null for mock client.
-                client.onConfigurationChanged(info.getConfiguration(), info.getDisplayId());
-            }
+            clientToken.onConfigurationChanged(info.getConfiguration(), info.getDisplayId());
             return null;
         }).when(mHandler).handleWindowContextInfoChanged(any(), any());
         doAnswer(invocation -> {
@@ -131,7 +123,7 @@
 
         assertEquals(1, mController.mListeners.size());
 
-        final IBinder clientToken = mock(IBinder.class);
+        final WindowTokenClient clientToken = mock(WindowTokenClient.class);
         mController.registerWindowContainerListener(mWpc, clientToken, mContainer,
                 TYPE_APPLICATION_OVERLAY, null /* options */);
 
@@ -344,15 +336,11 @@
         assertThat(clientToken.mDisplayId).isEqualTo(mDisplayContent.mDisplayId);
     }
 
-    private class TestWindowTokenClient extends IWindowToken.Stub {
+    private static class TestWindowTokenClient extends WindowTokenClient {
         private Configuration mConfiguration;
         private int mDisplayId;
         private boolean mRemoved;
 
-        TestWindowTokenClient() {
-            mWindowTokenClientMap.put(asBinder(), this);
-        }
-
         @Override
         public void onConfigurationChanged(Configuration configuration, int displayId) {
             mConfiguration = configuration;
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowManagerServiceTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowManagerServiceTests.java
index 55fda05..76576f7 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowManagerServiceTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowManagerServiceTests.java
@@ -107,6 +107,8 @@
 import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
 
+import java.util.ArrayList;
+
 /**
  * Build/Install/Run:
  * atest WmTests:WindowManagerServiceTests
@@ -975,6 +977,28 @@
         verify(window, times(2)).requestAppKeyboardShortcuts(receiver, 0);
     }
 
+    @Test
+    public void testReportSystemGestureExclusionChanged_invalidWindow() {
+        final Session session = mock(Session.class);
+        final IWindow window = mock(IWindow.class);
+        final IBinder binder = mock(IBinder.class);
+        doReturn(binder).when(window).asBinder();
+
+        // No exception even if the window doesn't exist
+        mWm.reportSystemGestureExclusionChanged(session, window, new ArrayList<>());
+    }
+
+    @Test
+    public void testReportKeepClearAreasChanged_invalidWindow() {
+        final Session session = mock(Session.class);
+        final IWindow window = mock(IWindow.class);
+        final IBinder binder = mock(IBinder.class);
+        doReturn(binder).when(window).asBinder();
+
+        // No exception even if the window doesn't exist
+        mWm.reportKeepClearAreasChanged(session, window, new ArrayList<>(), new ArrayList<>());
+    }
+
     class TestResultReceiver implements IResultReceiver {
         public android.os.Bundle resultData;
         private final IBinder mBinder = mock(IBinder.class);
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 cf83981..ebe40b0 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
@@ -170,9 +170,13 @@
     }
 
     @Test
-    public void testSetRunningRecentsAnimation() {
-        mWpc.setRunningRecentsAnimation(true);
-        mWpc.setRunningRecentsAnimation(false);
+    public void testSetAnimatingReason() {
+        mWpc.addAnimatingReason(WindowProcessController.ANIMATING_REASON_REMOTE_ANIMATION);
+        assertTrue(mWpc.isRunningRemoteTransition());
+        mWpc.addAnimatingReason(WindowProcessController.ANIMATING_REASON_WAKEFULNESS_CHANGE);
+        mWpc.removeAnimatingReason(WindowProcessController.ANIMATING_REASON_REMOTE_ANIMATION);
+        assertFalse(mWpc.isRunningRemoteTransition());
+        mWpc.removeAnimatingReason(WindowProcessController.ANIMATING_REASON_WAKEFULNESS_CHANGE);
         waitHandlerIdle(mAtm.mH);
 
         InOrder orderVerifier = Mockito.inOrder(mMockListener);
@@ -201,7 +205,7 @@
         waitHandlerIdle(mAtm.mH);
 
         InOrder orderVerifier = Mockito.inOrder(mMockListener);
-        orderVerifier.verify(mMockListener, times(3)).setRunningRemoteAnimation(eq(true));
+        orderVerifier.verify(mMockListener, times(1)).setRunningRemoteAnimation(eq(true));
         orderVerifier.verify(mMockListener, times(1)).setRunningRemoteAnimation(eq(false));
         orderVerifier.verifyNoMoreInteractions();
     }
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 62de67a..99688da 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
@@ -48,6 +48,7 @@
 
 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.doNothing;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
@@ -59,6 +60,7 @@
 import static org.junit.Assert.assertFalse;
 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 android.annotation.IntDef;
@@ -956,6 +958,38 @@
         return testPlayer;
     }
 
+    /** Overrides the behavior of config_reverseDefaultRotation for the given display. */
+    void setReverseDefaultRotation(DisplayContent dc, boolean reverse) {
+        final DisplayRotation displayRotation = dc.getDisplayRotation();
+        if (!Mockito.mockingDetails(displayRotation).isSpy()) {
+            spyOn(displayRotation);
+        }
+        doAnswer(invocation -> {
+            invocation.callRealMethod();
+            final int w = invocation.getArgument(0);
+            final int h = invocation.getArgument(1);
+            if (w > h) {
+                if (reverse) {
+                    displayRotation.mPortraitRotation = Surface.ROTATION_90;
+                    displayRotation.mUpsideDownRotation = Surface.ROTATION_270;
+                } else {
+                    displayRotation.mPortraitRotation = Surface.ROTATION_270;
+                    displayRotation.mUpsideDownRotation = Surface.ROTATION_90;
+                }
+            } else {
+                if (reverse) {
+                    displayRotation.mLandscapeRotation = Surface.ROTATION_270;
+                    displayRotation.mSeascapeRotation = Surface.ROTATION_90;
+                } else {
+                    displayRotation.mLandscapeRotation = Surface.ROTATION_90;
+                    displayRotation.mSeascapeRotation = Surface.ROTATION_270;
+                }
+            }
+            return null;
+        }).when(displayRotation).configure(anyInt(), anyInt());
+        displayRotation.configure(dc.mBaseDisplayWidth, dc.mBaseDisplayHeight);
+    }
+
     /**
      * Avoids rotating screen disturbed by some conditions. It is usually used for the default
      * display that is not the instance of {@link TestDisplayContent} (it bypasses the conditions).
@@ -963,6 +997,8 @@
      * @see DisplayRotation#updateRotationUnchecked
      */
     void unblockDisplayRotation(DisplayContent dc) {
+        dc.mOpeningApps.clear();
+        mWm.mAppsFreezingScreen = 0;
         mWm.stopFreezingDisplayLocked();
         // The rotation animation won't actually play, it needs to be cleared manually.
         dc.setRotationAnimation(null);
@@ -971,11 +1007,19 @@
     static void resizeDisplay(DisplayContent displayContent, int width, int height) {
         displayContent.updateBaseDisplayMetrics(width, height, displayContent.mBaseDisplayDensity,
                 displayContent.mBaseDisplayPhysicalXDpi, displayContent.mBaseDisplayPhysicalYDpi);
+        displayContent.getDisplayRotation().configure(width, height);
         final Configuration c = new Configuration();
         displayContent.computeScreenConfiguration(c);
         displayContent.onRequestedOverrideConfigurationChanged(c);
     }
 
+    /** Used for the tests that assume the display is portrait by default. */
+    static void makeDisplayPortrait(DisplayContent displayContent) {
+        if (displayContent.mBaseDisplayHeight <= displayContent.mBaseDisplayWidth) {
+            resizeDisplay(displayContent, 500, 1000);
+        }
+    }
+
     // The window definition for UseTestDisplay#addWindows. The test can declare to add only
     // necessary windows, that avoids adding unnecessary overhead of unused windows.
     static final int W_NOTIFICATION_SHADE = TYPE_NOTIFICATION_SHADE;
diff --git a/services/tests/wmtests/src/com/android/server/wm/utils/CommonUtils.java b/services/tests/wmtests/src/com/android/server/wm/utils/CommonUtils.java
index ed23296..bfbba5f 100644
--- a/services/tests/wmtests/src/com/android/server/wm/utils/CommonUtils.java
+++ b/services/tests/wmtests/src/com/android/server/wm/utils/CommonUtils.java
@@ -21,9 +21,12 @@
 import android.app.Activity;
 import android.app.KeyguardManager;
 import android.app.UiAutomation;
+import android.os.RemoteException;
 import android.os.SystemClock;
 import android.util.Log;
+import android.view.IWindowManager;
 import android.view.KeyEvent;
+import android.view.WindowManagerGlobal;
 
 import androidx.test.uiautomator.UiDevice;
 
@@ -48,6 +51,37 @@
         }
     }
 
+    public static boolean getIgnoreOrientationRequest(int displayId) {
+        final UiDevice uiDevice = UiDevice.getInstance(getInstrumentation());
+        final String result;
+        try {
+            result = uiDevice.executeShellCommand("cmd window get-ignore-orientation-request -d "
+                    + displayId);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+
+        final String[] tokens = result.split(" ");
+        if (tokens.length != 4) {
+            throw new RuntimeException("Expecting a result with 4 tokens, but got " + result);
+        }
+
+        // The output looks like "ignoreOrientationRequest true for displayId=0"
+        return Boolean.parseBoolean(tokens[1]);
+    }
+
+    public static void setIgnoreOrientationRequest(
+            int displayId, boolean ignoreOrientationRequest) {
+        runWithShellPermissionIdentity(() -> {
+            final IWindowManager wm = WindowManagerGlobal.getWindowManagerService();
+            try {
+                wm.setIgnoreOrientationRequest(displayId, ignoreOrientationRequest);
+            } catch (RemoteException e) {
+                e.rethrowFromSystemServer();
+            }
+        });
+    }
+
     /** Dismisses the Keyguard if it is locked. */
     public static void dismissKeyguard() {
         final KeyguardManager keyguardManager = getInstrumentation().getContext().getSystemService(
diff --git a/services/usage/java/com/android/server/usage/StorageStatsService.java b/services/usage/java/com/android/server/usage/StorageStatsService.java
index 0d88a0d..befc4a0 100644
--- a/services/usage/java/com/android/server/usage/StorageStatsService.java
+++ b/services/usage/java/com/android/server/usage/StorageStatsService.java
@@ -364,8 +364,10 @@
             if (appInfo.isSystemApp() && !appInfo.isUpdatedSystemApp()) {
                 // We don't count code baked into system image
             } else {
-                codePaths = ArrayUtils.appendElement(String.class, codePaths,
+                if (appInfo.getCodePath() != null) {
+                    codePaths = ArrayUtils.appendElement(String.class, codePaths,
                         appInfo.getCodePath());
+                }
             }
 
             final PackageStats stats = new PackageStats(TAG);
@@ -418,8 +420,10 @@
                 if (appInfo.isSystemApp() && !appInfo.isUpdatedSystemApp()) {
                     // We don't count code baked into system image
                 } else {
-                    codePaths = ArrayUtils.appendElement(String.class, codePaths,
-                            appInfo.getCodePath());
+                    if (appInfo.getCodePath() != null) {
+                        codePaths = ArrayUtils.appendElement(String.class, codePaths,
+                                appInfo.getCodePath());
+                    }
                 }
             } catch (NameNotFoundException e) {
                 throw new ParcelableException(e);
diff --git a/services/usage/java/com/android/server/usage/TEST_MAPPING b/services/usage/java/com/android/server/usage/TEST_MAPPING
index a3fe6f2..6e84543 100644
--- a/services/usage/java/com/android/server/usage/TEST_MAPPING
+++ b/services/usage/java/com/android/server/usage/TEST_MAPPING
@@ -20,22 +20,13 @@
       ]
     },
     {
-      "name": "CtsUsageStatsTestCases",
+      "name": "CtsBRSTestCases",
       "options": [
         {
-          "include-filter": "android.app.usage.cts.BroadcastResponseStatsTest"
-        },
-        {
           "exclude-annotation": "androidx.test.filters.FlakyTest"
         },
         {
-          "exclude-annotation": "android.platform.test.annotations.FlakyTest"
-        },
-        {
-          "exclude-annotation": "androidx.test.filters.MediumTest"
-        },
-        {
-          "exclude-annotation": "androidx.test.filters.LargeTest"
+          "exclude-annotation": "org.junit.Ignore"
         }
       ]
     }
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
index ccc4ac2..3d78a1d 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
@@ -54,6 +54,7 @@
 import android.service.voice.HotwordDetectionService;
 import android.service.voice.HotwordDetectionServiceFailure;
 import android.service.voice.HotwordDetector;
+import android.service.voice.IDetectorSessionStorageService;
 import android.service.voice.IMicrophoneHotwordDetectionVoiceInteractionCallback;
 import android.service.voice.ISandboxedDetectionService;
 import android.service.voice.IVisualQueryDetectionVoiceInteractionCallback;
@@ -69,6 +70,7 @@
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.app.IHotwordRecognitionStatusCallback;
 import com.android.internal.app.IVisualQueryDetectionAttentionListener;
+import com.android.internal.infra.AndroidFuture;
 import com.android.internal.infra.ServiceConnector;
 import com.android.server.LocalServices;
 import com.android.server.pm.permission.PermissionManagerServiceInternal;
@@ -157,6 +159,8 @@
     @NonNull private ServiceConnection mRemoteVisualQueryDetectionService;
     @GuardedBy("mLock")
     @Nullable private IBinder mAudioFlinger;
+
+    @Nullable private IHotwordRecognitionStatusCallback mHotwordRecognitionCallback;
     @GuardedBy("mLock")
     private boolean mDebugHotwordLogging = false;
 
@@ -368,29 +372,29 @@
     /**
      * This method is only used by VisualQueryDetector.
      */
-    void startPerceivingLocked(IVisualQueryDetectionVoiceInteractionCallback callback) {
+    boolean startPerceivingLocked(IVisualQueryDetectionVoiceInteractionCallback callback) {
         if (DEBUG) {
             Slog.d(TAG, "startPerceivingLocked");
         }
         final VisualQueryDetectorSession session = getVisualQueryDetectorSessionLocked();
         if (session == null) {
-            return;
+            return false;
         }
-        session.startPerceivingLocked(callback);
+        return session.startPerceivingLocked(callback);
     }
 
     /**
      * This method is only used by VisaulQueryDetector.
      */
-    void stopPerceivingLocked() {
+    boolean stopPerceivingLocked() {
         if (DEBUG) {
             Slog.d(TAG, "stopPerceivingLocked");
         }
         final VisualQueryDetectorSession session = getVisualQueryDetectorSessionLocked();
         if (session == null) {
-            return;
+            return false;
         }
-        session.stopPerceivingLocked();
+        return session.stopPerceivingLocked();
     }
 
     public void startListeningFromExternalSourceLocked(
@@ -694,6 +698,7 @@
             updateContentCaptureManager(connection);
             updateSpeechService(connection);
             updateServiceIdentity(connection);
+            updateStorageService(connection);
             return connection;
         }
     }
@@ -910,6 +915,7 @@
                     mVoiceInteractionServiceUid, mVoiceInteractorIdentity,
                     mScheduledExecutorService, mDebugHotwordLogging, mRemoteExceptionListener);
         }
+        mHotwordRecognitionCallback = callback;
         mDetectorSessions.put(detectorType, session);
         session.initialize(options, sharedMemory);
     }
@@ -1035,6 +1041,23 @@
         }));
     }
 
+    private void updateStorageService(ServiceConnection connection) {
+        connection.run(service -> {
+            service.registerRemoteStorageService(new IDetectorSessionStorageService.Stub() {
+                @Override
+                public void openFile(String filename, AndroidFuture future)
+                        throws RemoteException {
+                    Slog.v(TAG, "BinderCallback#onFileOpen");
+                    try {
+                        mHotwordRecognitionCallback.onOpenFile(filename, future);
+                    } catch (RemoteException e) {
+                        e.rethrowFromSystemServer();
+                    }
+                }
+            });
+        });
+    }
+
     private void addServiceUidForAudioPolicy(int uid) {
         mScheduledExecutorService.execute(() -> {
             AudioManagerInternal audioManager =
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VisualQueryDetectorSession.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VisualQueryDetectorSession.java
index 2e05e20..4720d27 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VisualQueryDetectorSession.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VisualQueryDetectorSession.java
@@ -95,7 +95,7 @@
     }
 
     @SuppressWarnings("GuardedBy")
-    void startPerceivingLocked(IVisualQueryDetectionVoiceInteractionCallback callback) {
+    boolean startPerceivingLocked(IVisualQueryDetectionVoiceInteractionCallback callback) {
         if (DEBUG) {
             Slog.d(TAG, "startPerceivingLocked");
         }
@@ -198,15 +198,16 @@
                 mQueryStreaming = false;
             }
         };
-        mRemoteDetectionService.run(service -> service.detectWithVisualSignals(internalCallback));
+        return mRemoteDetectionService.run(
+                service -> service.detectWithVisualSignals(internalCallback));
     }
 
     @SuppressWarnings("GuardedBy")
-    void stopPerceivingLocked() {
+    boolean stopPerceivingLocked() {
         if (DEBUG) {
             Slog.d(TAG, "stopPerceivingLocked");
         }
-        mRemoteDetectionService.run(ISandboxedDetectionService::stopDetection);
+        return mRemoteDetectionService.run(ISandboxedDetectionService::stopDetection);
     }
 
     @Override
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
index 3502a3f..98cc1da 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
@@ -23,7 +23,6 @@
 import android.annotation.UserIdInt;
 import android.app.ActivityManager;
 import android.app.ActivityManagerInternal;
-import android.app.ActivityThread;
 import android.app.AppGlobals;
 import android.app.role.OnRoleHoldersChangedListener;
 import android.app.role.RoleManager;
@@ -51,7 +50,6 @@
 import android.hardware.soundtrigger.SoundTrigger.RecognitionConfig;
 import android.media.AudioFormat;
 import android.media.permission.Identity;
-import android.media.permission.IdentityContext;
 import android.media.permission.PermissionUtil;
 import android.media.permission.SafeCloseable;
 import android.os.Binder;
@@ -61,7 +59,6 @@
 import android.os.Parcel;
 import android.os.ParcelFileDescriptor;
 import android.os.PersistableBundle;
-import android.os.Process;
 import android.os.RemoteCallback;
 import android.os.RemoteCallbackList;
 import android.os.RemoteException;
@@ -88,6 +85,7 @@
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.app.IHotwordRecognitionStatusCallback;
 import com.android.internal.app.IVisualQueryDetectionAttentionListener;
+import com.android.internal.app.IVisualQueryRecognitionStatusListener;
 import com.android.internal.app.IVoiceActionCheckCallback;
 import com.android.internal.app.IVoiceInteractionManagerService;
 import com.android.internal.app.IVoiceInteractionSessionListener;
@@ -139,6 +137,7 @@
 
     private final RemoteCallbackList<IVoiceInteractionSessionListener>
             mVoiceInteractionSessionListeners = new RemoteCallbackList<>();
+    private IVisualQueryRecognitionStatusListener mVisualQueryRecognitionStatusListener;
 
     public VoiceInteractionManagerService(Context context) {
         super(context);
@@ -1346,6 +1345,17 @@
         @android.annotation.EnforcePermission(
                 android.Manifest.permission.ACCESS_VOICE_INTERACTION_SERVICE)
         @Override
+        public void subscribeVisualQueryRecognitionStatus(IVisualQueryRecognitionStatusListener
+                listener) {
+            super.subscribeVisualQueryRecognitionStatus_enforcePermission();
+            synchronized (this) {
+                mVisualQueryRecognitionStatusListener = listener;
+            }
+        }
+
+        @android.annotation.EnforcePermission(
+                android.Manifest.permission.ACCESS_VOICE_INTERACTION_SERVICE)
+        @Override
         public void enableVisualQueryDetection(
                 IVisualQueryDetectionAttentionListener listener) {
             super.enableVisualQueryDetection_enforcePermission();
@@ -1391,7 +1401,10 @@
                 }
                 final long caller = Binder.clearCallingIdentity();
                 try {
-                    mImpl.startPerceivingLocked(callback);
+                    boolean success = mImpl.startPerceivingLocked(callback);
+                    if (success && mVisualQueryRecognitionStatusListener != null) {
+                        mVisualQueryRecognitionStatusListener.onStartPerceiving();
+                    }
                 } finally {
                     Binder.restoreCallingIdentity(caller);
                 }
@@ -1409,7 +1422,10 @@
                 }
                 final long caller = Binder.clearCallingIdentity();
                 try {
-                    mImpl.stopPerceivingLocked();
+                    boolean success = mImpl.stopPerceivingLocked();
+                    if (success && mVisualQueryRecognitionStatusListener != null) {
+                        mVisualQueryRecognitionStatusListener.onStopPerceiving();
+                    }
                 } finally {
                     Binder.restoreCallingIdentity(caller);
                 }
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java
index 5d88a65..471acc1 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java
@@ -784,30 +784,30 @@
         mHotwordDetectionConnection.setVisualQueryDetectionAttentionListenerLocked(listener);
     }
 
-    public void startPerceivingLocked(IVisualQueryDetectionVoiceInteractionCallback callback) {
+    public boolean startPerceivingLocked(IVisualQueryDetectionVoiceInteractionCallback callback) {
         if (DEBUG) {
             Slog.d(TAG, "startPerceivingLocked");
         }
 
         if (mHotwordDetectionConnection == null) {
             // TODO: callback.onError();
-            return;
+            return false;
         }
 
-        mHotwordDetectionConnection.startPerceivingLocked(callback);
+        return mHotwordDetectionConnection.startPerceivingLocked(callback);
     }
 
-    public void stopPerceivingLocked() {
+    public boolean stopPerceivingLocked() {
         if (DEBUG) {
             Slog.d(TAG, "stopPerceivingLocked");
         }
 
         if (mHotwordDetectionConnection == null) {
             Slog.w(TAG, "stopPerceivingLocked() called but connection isn't established");
-            return;
+            return false;
         }
 
-        mHotwordDetectionConnection.stopPerceivingLocked();
+        return mHotwordDetectionConnection.stopPerceivingLocked();
     }
 
     public void startListeningFromMicLocked(
diff --git a/telecomm/OWNERS b/telecomm/OWNERS
index dcaf858..b57b7c7 100644
--- a/telecomm/OWNERS
+++ b/telecomm/OWNERS
@@ -4,7 +4,6 @@
 tgunn@google.com
 xiaotonj@google.com
 rgreenwalt@google.com
-chinmayd@google.com
 grantmenke@google.com
 pmadapurmath@google.com
 tjstuart@google.com
\ No newline at end of file
diff --git a/telecomm/java/android/telecom/Call.java b/telecomm/java/android/telecom/Call.java
index 78b86d3..5bdcdf4 100644
--- a/telecomm/java/android/telecom/Call.java
+++ b/telecomm/java/android/telecom/Call.java
@@ -2661,7 +2661,9 @@
         // remove ourselves from the Phone. Note that we do this after completing all state updates
         // so a client can cleanly transition all their UI to the state appropriate for a
         // DISCONNECTED Call while still relying on the existence of that Call in the Phone's list.
-        if (mState == STATE_DISCONNECTED) {
+        // Check if the original state is already disconnected, otherwise onCallRemoved will be
+        // triggered before onCallAdded.
+        if (mState == STATE_DISCONNECTED && stateChanged) {
             fireCallDestroyed();
         }
     }
diff --git a/telecomm/java/android/telecom/Connection.java b/telecomm/java/android/telecom/Connection.java
index 943d8d6..4a541da 100644
--- a/telecomm/java/android/telecom/Connection.java
+++ b/telecomm/java/android/telecom/Connection.java
@@ -3388,7 +3388,11 @@
     public void onAbort() {}
 
     /**
-     * Notifies this Connection of a request to hold.
+     * Notifies this Connection of a request to hold. {@link Connection#setOnHold} should be within
+     * the onHold() body in order to transition the call state to {@link Connection#STATE_HOLDING}.
+     * <p>
+     * Note: If the Connection does not transition to  {@link Connection#STATE_HOLDING} within 2
+     * seconds, the call will be disconnected.
      */
     public void onHold() {}
 
diff --git a/telecomm/java/android/telecom/Phone.java b/telecomm/java/android/telecom/Phone.java
index 95a8e16..61e829e7 100644
--- a/telecomm/java/android/telecom/Phone.java
+++ b/telecomm/java/android/telecom/Phone.java
@@ -174,6 +174,9 @@
             checkCallTree(parcelableCall);
             call.internalUpdate(parcelableCall, mCallByTelecomCallId);
             fireCallAdded(call);
+            if (call.getState() == Call.STATE_DISCONNECTED) {
+                internalRemoveCall(call);
+            }
         } else {
             Log.w(this, "Call %s added, but it was already present", call.internalGetCallId());
             checkCallTree(parcelableCall);
diff --git a/telecomm/java/android/telecom/RemoteConnectionManager.java b/telecomm/java/android/telecom/RemoteConnectionManager.java
index fbbfefd..fbf8eef 100644
--- a/telecomm/java/android/telecom/RemoteConnectionManager.java
+++ b/telecomm/java/android/telecom/RemoteConnectionManager.java
@@ -39,18 +39,21 @@
     void addConnectionService(
             ComponentName componentName,
             IConnectionService outgoingConnectionServiceRpc) {
-        if (!mRemoteConnectionServices.containsKey(componentName)) {
-            try {
-                RemoteConnectionService remoteConnectionService = new RemoteConnectionService(
-                        outgoingConnectionServiceRpc,
-                        mOurConnectionServiceImpl);
-                mRemoteConnectionServices.put(componentName, remoteConnectionService);
-            } catch (RemoteException e) {
-                Log.w(RemoteConnectionManager.this,
-                        "error when addConnectionService of %s: %s", componentName,
-                        e.toString());
-            }
-        }
+        mRemoteConnectionServices.computeIfAbsent(
+                componentName,
+                key -> {
+                    try {
+                        return new RemoteConnectionService(
+                                outgoingConnectionServiceRpc, mOurConnectionServiceImpl);
+                    } catch (RemoteException e) {
+                        Log.w(
+                                RemoteConnectionManager.this,
+                                "error when addConnectionService of %s: %s",
+                                componentName,
+                                e.toString());
+                        return null;
+                    }
+                });
     }
 
     public RemoteConnection createRemoteConnection(
@@ -63,17 +66,14 @@
         }
 
         ComponentName componentName = request.getAccountHandle().getComponentName();
-        if (!mRemoteConnectionServices.containsKey(componentName)) {
+        RemoteConnectionService remoteService = mRemoteConnectionServices.get(componentName);
+        if (remoteService == null) {
             throw new UnsupportedOperationException("accountHandle not supported: "
                     + componentName);
         }
 
-        RemoteConnectionService remoteService = mRemoteConnectionServices.get(componentName);
-        if (remoteService != null) {
-            return remoteService.createRemoteConnection(
-                    connectionManagerPhoneAccount, request, isIncoming);
-        }
-        return null;
+        return remoteService.createRemoteConnection(
+                connectionManagerPhoneAccount, request, isIncoming);
     }
 
     /**
@@ -94,17 +94,14 @@
         }
 
         ComponentName componentName = request.getAccountHandle().getComponentName();
-        if (!mRemoteConnectionServices.containsKey(componentName)) {
+        RemoteConnectionService remoteService = mRemoteConnectionServices.get(componentName);
+        if (remoteService == null) {
             throw new UnsupportedOperationException("accountHandle not supported: "
                     + componentName);
         }
 
-        RemoteConnectionService remoteService = mRemoteConnectionServices.get(componentName);
-        if (remoteService != null) {
-            return remoteService.createRemoteConference(
-                    connectionManagerPhoneAccount, request, isIncoming);
-        }
-        return null;
+        return remoteService.createRemoteConference(
+                connectionManagerPhoneAccount, request, isIncoming);
     }
 
     public void conferenceRemoteConnections(RemoteConnection a, RemoteConnection b) {
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index 314150b..4907134 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -9418,6 +9418,7 @@
      * <li>3 = {@link android.telephony.NetworkRegistrationInfo#SERVICE_TYPE_SMS}</li>
      * <li>4 = {@link android.telephony.NetworkRegistrationInfo#SERVICE_TYPE_VIDEO}</li>
      * <li>5 = {@link android.telephony.NetworkRegistrationInfo#SERVICE_TYPE_EMERGENCY}</li>
+     * <li>6 = {@link android.telephony.NetworkRegistrationInfo#SERVICE_TYPE_MMS}</li>
      * </ul>
      * <p>
      * An example config for two PLMNs "123411" and "123412":
diff --git a/telephony/java/android/telephony/NetworkRegistrationInfo.java b/telephony/java/android/telephony/NetworkRegistrationInfo.java
index 6258b9c..631013f 100644
--- a/telephony/java/android/telephony/NetworkRegistrationInfo.java
+++ b/telephony/java/android/telephony/NetworkRegistrationInfo.java
@@ -170,7 +170,7 @@
     @Retention(RetentionPolicy.SOURCE)
     @IntDef(prefix = "SERVICE_TYPE_",
             value = {SERVICE_TYPE_UNKNOWN, SERVICE_TYPE_VOICE, SERVICE_TYPE_DATA, SERVICE_TYPE_SMS,
-                    SERVICE_TYPE_VIDEO, SERVICE_TYPE_EMERGENCY})
+                    SERVICE_TYPE_VIDEO, SERVICE_TYPE_EMERGENCY, SERVICE_TYPE_MMS})
     public @interface ServiceType {}
 
     /**
@@ -203,11 +203,16 @@
      */
     public static final int SERVICE_TYPE_EMERGENCY  = 5;
 
+    /**
+     * MMS service
+     */
+    public static final int SERVICE_TYPE_MMS = 6;
+
     /** @hide  */
     public static final int FIRST_SERVICE_TYPE = SERVICE_TYPE_VOICE;
 
     /** @hide  */
-    public static final int LAST_SERVICE_TYPE = SERVICE_TYPE_EMERGENCY;
+    public static final int LAST_SERVICE_TYPE = SERVICE_TYPE_MMS;
 
     @Domain
     private final int mDomain;
@@ -739,6 +744,7 @@
             case SERVICE_TYPE_SMS: return "SMS";
             case SERVICE_TYPE_VIDEO: return "VIDEO";
             case SERVICE_TYPE_EMERGENCY: return "EMERGENCY";
+            case SERVICE_TYPE_MMS: return "MMS";
         }
         return "Unknown service type " + serviceType;
     }
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index 040c5b0..baacb57 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -85,11 +85,11 @@
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.Objects;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.Executor;
 import java.util.function.Consumer;
 import java.util.stream.Collectors;
@@ -1107,6 +1107,16 @@
      */
     public static final String SATELLITE_ENABLED = SimInfo.COLUMN_SATELLITE_ENABLED;
 
+    /**
+     * TelephonyProvider column name for satellite attach enabled for carrier. The value of this
+     * column is set based on user settings.
+     * By default, it's disabled.
+     * <P>Type: INTEGER (int)</P>
+     * @hide
+     */
+    public static final String SATELLITE_ATTACH_ENABLED_FOR_CARRIER =
+            SimInfo.COLUMN_SATELLITE_ATTACH_ENABLED_FOR_CARRIER;
+
     /** @hide */
     @Retention(RetentionPolicy.SOURCE)
     @IntDef(prefix = {"USAGE_SETTING_"},
@@ -1318,10 +1328,24 @@
 
     private final Context mContext;
 
-    // Cache of Resource that has been created in getResourcesForSubId. Key is a Pair containing
-    // the Context and subId.
-    private static final Map<Pair<Context, Integer>, Resources> sResourcesCache =
-            new ConcurrentHashMap<>();
+    /**
+     * In order to prevent the overflow of the heap size due to an indiscriminate increase in the
+     * cache, the heap size of the resource cache is set sufficiently large.
+     */
+    private static final int MAX_RESOURCE_CACHE_ENTRY_COUNT = 10_000;
+
+    /**
+     * Cache of Resources that has been created in getResourcesForSubId. Key contains package name,
+     * and Configuration of Resources. If more than the maximum number of resources are stored in
+     * this cache, the least recently used Resources will be removed to maintain the maximum size.
+     */
+    private static final Map<Pair<String, Configuration>, Resources> sResourcesCache =
+            Collections.synchronizedMap(new LinkedHashMap<>(16, 0.75f, true) {
+                @Override
+                protected boolean removeEldestEntry(Entry eldest) {
+                    return size() > MAX_RESOURCE_CACHE_ENTRY_COUNT;
+                }
+            });
 
     /**
      * A listener class for monitoring changes to {@link SubscriptionInfo} records.
@@ -2807,14 +2831,20 @@
     @NonNull
     public static Resources getResourcesForSubId(Context context, int subId,
             boolean useRootLocale) {
-        // Check if resources for this context and subId already exist in the resource cache.
-        // Resources that use the root locale are not cached.
-        Pair<Context, Integer> cacheKey = null;
-        if (isValidSubscriptionId(subId) && !useRootLocale) {
-            cacheKey = Pair.create(context, subId);
-            if (sResourcesCache.containsKey(cacheKey)) {
+        // Check if the Resources already exists in the cache based on the given context. Find a
+        // Resource that match Configuration.
+        Pair<String, Configuration> cacheKey = null;
+        if (isValidSubscriptionId(subId)) {
+            Configuration configurationKey =
+                    new Configuration(context.getResources().getConfiguration());
+            if (useRootLocale) {
+                configurationKey.setLocale(Locale.ROOT);
+            }
+            cacheKey = Pair.create(context.getPackageName(), configurationKey);
+            Resources cached = sResourcesCache.get(cacheKey);
+            if (cached != null) {
                 // Cache hit. Use cached Resources.
-                return sResourcesCache.get(cacheKey);
+                return cached;
             }
         }
 
diff --git a/telephony/java/android/telephony/satellite/ISatelliteTransmissionUpdateCallback.aidl b/telephony/java/android/telephony/satellite/ISatelliteTransmissionUpdateCallback.aidl
index a81444d..06fc3c6 100644
--- a/telephony/java/android/telephony/satellite/ISatelliteTransmissionUpdateCallback.aidl
+++ b/telephony/java/android/telephony/satellite/ISatelliteTransmissionUpdateCallback.aidl
@@ -45,6 +45,7 @@
      * Called when the satellite position changed.
      *
      * @param pointingInfo The pointing info containing the satellite location.
+     *                     Satellite location is based on magnetic north direction.
      */
     void onSatellitePositionChanged(in PointingInfo pointingInfo);
 }
diff --git a/telephony/java/android/telephony/satellite/PointingInfo.java b/telephony/java/android/telephony/satellite/PointingInfo.java
index 47dbdaf..dc4d38b 100644
--- a/telephony/java/android/telephony/satellite/PointingInfo.java
+++ b/telephony/java/android/telephony/satellite/PointingInfo.java
@@ -26,7 +26,7 @@
 /**
  * PointingInfo is used to store the position of satellite received from satellite modem.
  * The position of satellite is represented by azimuth and elevation angles
- * with degrees as unit of measurement.
+ * with degrees as unit of measurement. Satellite position is based on magnetic north direction.
  * @hide
  */
 @SystemApi
diff --git a/tests/AttestationVerificationTest/src/android/security/attestationverification/PeerDeviceSystemAttestationVerificationTest.kt b/tests/AttestationVerificationTest/src/android/security/attestationverification/PeerDeviceSystemAttestationVerificationTest.kt
index 32c2230..ad95fbc 100644
--- a/tests/AttestationVerificationTest/src/android/security/attestationverification/PeerDeviceSystemAttestationVerificationTest.kt
+++ b/tests/AttestationVerificationTest/src/android/security/attestationverification/PeerDeviceSystemAttestationVerificationTest.kt
@@ -39,7 +39,7 @@
     @Before
     fun setup() {
         rule.getScenario().onActivity {
-            avm = it.getSystemService(AttestationVerificationManager::class.java)
+            avm = it.getSystemService(AttestationVerificationManager::class.java)!!
             activity = it
         }
         invalidAttestationByteArray = TEST_ATTESTATION_CERT_FILENAME.fromPEMFileToByteArray()
diff --git a/tests/AttestationVerificationTest/src/android/security/attestationverification/SystemAttestationVerificationTest.kt b/tests/AttestationVerificationTest/src/android/security/attestationverification/SystemAttestationVerificationTest.kt
index 169effa..8f06b4a2 100644
--- a/tests/AttestationVerificationTest/src/android/security/attestationverification/SystemAttestationVerificationTest.kt
+++ b/tests/AttestationVerificationTest/src/android/security/attestationverification/SystemAttestationVerificationTest.kt
@@ -43,7 +43,7 @@
     @Before
     fun setup() {
         rule.getScenario().onActivity {
-            avm = it.getSystemService(AttestationVerificationManager::class.java)
+            avm = it.getSystemService(AttestationVerificationManager::class.java)!!
             activity = it
             androidKeystore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
         }
diff --git a/tests/BinaryTransparencyHostTest/Android.bp b/tests/BinaryTransparencyHostTest/Android.bp
index dc6bdff..615990f 100644
--- a/tests/BinaryTransparencyHostTest/Android.bp
+++ b/tests/BinaryTransparencyHostTest/Android.bp
@@ -35,6 +35,8 @@
     data: [
         ":BinaryTransparencyTestApp",
         ":EasterEgg",
+        ":FeatureSplitBase",
+        ":FeatureSplit1",
         ":com.android.apex.cts.shim.v2_rebootless_prebuilt",
     ],
     test_suites: [
diff --git a/tests/BinaryTransparencyHostTest/src/android/transparency/test/BinaryTransparencyHostTest.java b/tests/BinaryTransparencyHostTest/src/android/transparency/test/BinaryTransparencyHostTest.java
index 346622f..6e5f08a 100644
--- a/tests/BinaryTransparencyHostTest/src/android/transparency/test/BinaryTransparencyHostTest.java
+++ b/tests/BinaryTransparencyHostTest/src/android/transparency/test/BinaryTransparencyHostTest.java
@@ -91,20 +91,20 @@
     public void testCollectAllSilentInstalledMbaInfo() throws Exception {
         try {
             new InstallMultiple()
-                .addFile("ApkVerityTestApp.apk")
-                .addFile("ApkVerityTestAppSplit.apk")
+                .addFile("FeatureSplitBase.apk")
+                .addFile("FeatureSplit1.apk")
                 .run();
             updatePreloadApp();
-            assertNotNull(getDevice().getAppPackageInfo("com.android.apkverity"));
+            assertNotNull(getDevice().getAppPackageInfo("com.android.test.split.feature"));
             assertNotNull(getDevice().getAppPackageInfo("com.android.egg"));
 
             assertTrue(getDevice().setProperty("debug.transparency.bg-install-apps",
-                        "com.android.apkverity,com.android.egg"));
+                        "com.android.test.split.feature,com.android.egg"));
             runDeviceTest("testCollectAllSilentInstalledMbaInfo");
         } finally {
             // No need to wait until job complete, since we can't verifying very meaningfully.
             cancelPendingJob();
-            uninstallPackage("com.android.apkverity");
+            uninstallPackage("com.android.test.split.feature");
             uninstallPackage("com.android.egg");
         }
     }
diff --git a/tests/BinaryTransparencyHostTest/test-app/src/android/transparency/test/app/BinaryTransparencyTest.java b/tests/BinaryTransparencyHostTest/test-app/src/android/transparency/test/app/BinaryTransparencyTest.java
index c087a85..2bc056e 100644
--- a/tests/BinaryTransparencyHostTest/test-app/src/android/transparency/test/app/BinaryTransparencyTest.java
+++ b/tests/BinaryTransparencyHostTest/test-app/src/android/transparency/test/app/BinaryTransparencyTest.java
@@ -121,7 +121,7 @@
         // Verify
         assertThat(appInfoList).isNotEmpty();  // because we just installed from the host side
 
-        var expectedAppNames = Set.of("com.android.apkverity", "com.android.egg");
+        var expectedAppNames = Set.of("com.android.test.split.feature", "com.android.egg");
         var actualAppNames = appInfoList.stream().map((appInfo) -> appInfo.packageName)
                 .collect(Collectors.toList());
         assertThat(actualAppNames).containsAtLeastElementsIn(expectedAppNames);
@@ -141,6 +141,6 @@
                 }
             }
         }
-        assertThat(actualSplitNames).containsExactly("feature_x");  // Name of ApkVerityTestAppSplit
+        assertThat(actualSplitNames).containsExactly("feature1");  // Name of FeatureSplit1
     }
 }
diff --git a/tests/CompanionDeviceMultiDeviceTests/host/Android.bp b/tests/CompanionDeviceMultiDeviceTests/host/Android.bp
index 1167a3e..03335c7 100644
--- a/tests/CompanionDeviceMultiDeviceTests/host/Android.bp
+++ b/tests/CompanionDeviceMultiDeviceTests/host/Android.bp
@@ -37,7 +37,6 @@
     },
     data: [
         ":cdm_snippet",
-        "requirements.txt",
     ],
     version: {
         py2: {
diff --git a/tests/CompanionDeviceMultiDeviceTests/host/cdm_transport_test.py b/tests/CompanionDeviceMultiDeviceTests/host/cdm_transport_test.py
index 9cb2d10..5516c0f 100644
--- a/tests/CompanionDeviceMultiDeviceTests/host/cdm_transport_test.py
+++ b/tests/CompanionDeviceMultiDeviceTests/host/cdm_transport_test.py
@@ -25,12 +25,4 @@
 
 
 if __name__ == '__main__':
-    try:
-        # Take test args and remove standalone '--' from the list
-        index = sys.argv.index('--')
-        sys.argv = sys.argv[:1] + sys.argv[index + 1:]
-    except ValueError:
-        # Ignore if '--' is not in args
-        pass
-
     test_runner.main()
\ No newline at end of file
diff --git a/tests/CompanionDeviceMultiDeviceTests/host/requirements.txt b/tests/CompanionDeviceMultiDeviceTests/host/requirements.txt
deleted file mode 100644
index 86a11aa..0000000
--- a/tests/CompanionDeviceMultiDeviceTests/host/requirements.txt
+++ /dev/null
@@ -1 +0,0 @@
-mobly==1.12.1
diff --git a/tests/FlickerTests/Android.bp b/tests/FlickerTests/Android.bp
index 3e67286..2ccc0fa 100644
--- a/tests/FlickerTests/Android.bp
+++ b/tests/FlickerTests/Android.bp
@@ -39,7 +39,11 @@
         "src/**/activityembedding/*.kt",
         "src/**/activityembedding/open/*.kt",
         "src/**/activityembedding/close/*.kt",
+        "src/**/activityembedding/layoutchange/*.kt",
+        "src/**/activityembedding/pip/*.kt",
         "src/**/activityembedding/rotation/*.kt",
+        "src/**/activityembedding/rtl/*.kt",
+        "src/**/activityembedding/splitscreen/*.kt",
     ],
 }
 
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/close/CloseSecondaryActivityInSplitTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/close/CloseSecondaryActivityInSplitTest.kt
index 4530ef3..0c36c59 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/close/CloseSecondaryActivityInSplitTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/close/CloseSecondaryActivityInSplitTest.kt
@@ -38,7 +38,7 @@
  * Setup: Launch A|B in split with B being the secondary activity. Transitions: Finish B and expect
  * A to become fullscreen.
  *
- * To run this test: `atest FlickerTests:CloseSecondaryActivityInSplitTest`
+ * To run this test: `atest FlickerTestsOther:CloseSecondaryActivityInSplitTest`
  */
 @RequiresDevice
 @RunWith(Parameterized::class)
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/layoutchange/HorizontalSplitChangeRatioTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/layoutchange/HorizontalSplitChangeRatioTest.kt
index c3529ba..adff579 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/layoutchange/HorizontalSplitChangeRatioTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/layoutchange/HorizontalSplitChangeRatioTest.kt
@@ -14,17 +14,18 @@
  * limitations under the License.
  */
 
-package com.android.server.wm.flicker.activityembedding
+package com.android.server.wm.flicker.activityembedding.layoutchange
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.datatypes.Rect
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
-import androidx.test.filters.RequiresDevice
+import androidx.test.filters.FlakyTest
+import com.android.server.wm.flicker.activityembedding.ActivityEmbeddingTestBase
 import com.android.server.wm.flicker.helpers.ActivityEmbeddingAppHelper
+import androidx.test.filters.RequiresDevice
 import org.junit.FixMethodOrder
 import org.junit.Test
 import org.junit.runner.RunWith
@@ -38,7 +39,7 @@
  * windows are equal in size. B is on the top and A is on the bottom. Transitions: Change the split
  * ratio to A:B=0.7:0.3, expect bounds change for both A and B.
  *
- * To run this test: `atest FlickerTests:HorizontalSplitChangeRatioTest`
+ * To run this test: `atest FlickerTestsOther:HorizontalSplitChangeRatioTest`
  */
 @RequiresDevice
 @RunWith(Parameterized::class)
@@ -148,6 +149,7 @@
     companion object {
         /** {@inheritDoc} */
         private var startDisplayBounds = Rect.EMPTY
+
         /**
          * Creates the test configurations.
          *
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/MainActivityStartsSecondaryWithAlwaysExpandTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/MainActivityStartsSecondaryWithAlwaysExpandTest.kt
index 244c5dc..ce9c337 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/MainActivityStartsSecondaryWithAlwaysExpandTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/MainActivityStartsSecondaryWithAlwaysExpandTest.kt
@@ -16,13 +16,13 @@
 
 package com.android.server.wm.flicker.activityembedding.open
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.datatypes.Rect
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.server.wm.flicker.activityembedding.ActivityEmbeddingTestBase
 import com.android.server.wm.flicker.helpers.ActivityEmbeddingAppHelper
@@ -39,7 +39,7 @@
  * Setup: Launch A|B in split with B being the secondary activity. Transitions: A start C with
  * alwaysExpand=true, expect C to launch in fullscreen and cover split A|B.
  *
- * To run this test: `atest FlickerTests:MainActivityStartsSecondaryWithAlwaysExpandTest`
+ * To run this test: `atest FlickerTestsOther:MainActivityStartsSecondaryWithAlwaysExpandTest`
  */
 @RequiresDevice
 @RunWith(Parameterized::class)
@@ -133,6 +133,7 @@
     companion object {
         /** {@inheritDoc} */
         private var startDisplayBounds = Rect.EMPTY
+
         /**
          * Creates the test configurations.
          *
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenActivityEmbeddingPlaceholderSplitTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenActivityEmbeddingPlaceholderSplitTest.kt
index 8a997dd..48edf6d 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenActivityEmbeddingPlaceholderSplitTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenActivityEmbeddingPlaceholderSplitTest.kt
@@ -34,7 +34,7 @@
  * Test opening an activity that will launch another activity as ActivityEmbedding placeholder in
  * split.
  *
- * To run this test: `atest FlickerTests:OpenActivityEmbeddingPlaceholderSplitTest`
+ * To run this test: `atest FlickerTestsOther:OpenActivityEmbeddingPlaceholderSplitTest`
  */
 @RequiresDevice
 @RunWith(Parameterized::class)
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenActivityEmbeddingSecondaryToSplitTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenActivityEmbeddingSecondaryToSplitTest.kt
index 49aa84b..3657820 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenActivityEmbeddingSecondaryToSplitTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenActivityEmbeddingSecondaryToSplitTest.kt
@@ -34,7 +34,7 @@
 /**
  * Test opening a secondary activity that will split with the main activity.
  *
- * To run this test: `atest FlickerTests:OpenActivityEmbeddingSecondaryToSplitTest`
+ * To run this test: `atest FlickerTestsOther:OpenActivityEmbeddingSecondaryToSplitTest`
  */
 @RequiresDevice
 @RunWith(Parameterized::class)
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenThirdActivityOverSplitTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenThirdActivityOverSplitTest.kt
index 4bb2246..9f9fc23 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenThirdActivityOverSplitTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenThirdActivityOverSplitTest.kt
@@ -39,7 +39,7 @@
  *
  * Transitions: Let B start C, expect C to cover B and end up in split A|C.
  *
- * To run this test: `atest FlickerTests:OpenThirdActivityOverSplitTest`
+ * To run this test: `atest FlickerTestsOther:OpenThirdActivityOverSplitTest`
  */
 @RequiresDevice
 @RunWith(Parameterized::class)
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenTrampolineActivityTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenTrampolineActivityTest.kt
index f409c4e..30e833f 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenTrampolineActivityTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/open/OpenTrampolineActivityTest.kt
@@ -16,7 +16,6 @@
 
 package com.android.server.wm.flicker.activityembedding.open
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.datatypes.Rect
 import android.tools.common.flicker.subject.region.RegionSubject
@@ -24,6 +23,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.server.wm.flicker.activityembedding.ActivityEmbeddingTestBase
 import com.android.server.wm.flicker.helpers.ActivityEmbeddingAppHelper
@@ -41,7 +41,7 @@
  * Transitions: From A launch a trampoline Activity T, T launches secondary Activity B and finishes
  * itself, end up in split A|B.
  *
- * To run this test: `atest FlickerTests:OpenTrampolineActivityTest`
+ * To run this test: `atest FlickerTestsOther:OpenTrampolineActivityTest`
  */
 @RequiresDevice
 @RunWith(Parameterized::class)
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/pip/SecondaryActivityEnterPipTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/pip/SecondaryActivityEnterPipTest.kt
index e4c35b2..359845d 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/pip/SecondaryActivityEnterPipTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/pip/SecondaryActivityEnterPipTest.kt
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.wm.flicker.activityembedding
+package com.android.server.wm.flicker.activityembedding.pip
 
 import android.platform.test.annotations.Presubmit
 import android.tools.common.datatypes.Rect
@@ -25,6 +25,7 @@
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
 import androidx.test.filters.RequiresDevice
+import com.android.server.wm.flicker.activityembedding.ActivityEmbeddingTestBase
 import com.android.server.wm.flicker.helpers.ActivityEmbeddingAppHelper
 import org.junit.FixMethodOrder
 import org.junit.Test
@@ -38,7 +39,7 @@
  * Setup: Start from a split A|B. Transition: B enters PIP, observe the window shrink to the bottom
  * right corner on screen.
  *
- * To run this test: `atest FlickerTests:SecondaryActivityEnterPipTest`
+ * To run this test: `atest FlickerTestsOther:SecondaryActivityEnterPipTest`
  */
 @RequiresDevice
 @RunWith(Parameterized::class)
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/rotation/RotateSplitNoChangeTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/rotation/RotateSplitNoChangeTest.kt
index da56500..4f7d8a4 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/rotation/RotateSplitNoChangeTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/rotation/RotateSplitNoChangeTest.kt
@@ -23,6 +23,7 @@
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
 import androidx.test.filters.RequiresDevice
+import com.android.server.wm.flicker.activityembedding.ActivityEmbeddingTestBase
 import com.android.server.wm.flicker.helpers.ActivityEmbeddingAppHelper
 import com.android.server.wm.flicker.rotation.RotationTransition
 import org.junit.FixMethodOrder
@@ -37,7 +38,7 @@
  * Setup: Launch A|B in split with B being the secondary activity. Transitions: Rotate display, and
  * expect A and B to split evenly in new rotation.
  *
- * To run this test: `atest FlickerTests:RotateSplitNoChangeTest`
+ * To run this test: `atest FlickerTestsOther:RotateSplitNoChangeTest`
  */
 @RequiresDevice
 @RunWith(Parameterized::class)
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/RTLStartSecondaryWithPlaceholderTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/rtl/RTLStartSecondaryWithPlaceholderTest.kt
similarity index 97%
rename from tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/RTLStartSecondaryWithPlaceholderTest.kt
rename to tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/rtl/RTLStartSecondaryWithPlaceholderTest.kt
index 4bc17ed..6be78f8 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/RTLStartSecondaryWithPlaceholderTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/rtl/RTLStartSecondaryWithPlaceholderTest.kt
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.wm.flicker.activityembedding
+package com.android.server.wm.flicker.activityembedding.rtl
 
 import android.platform.test.annotations.Presubmit
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
@@ -22,6 +22,7 @@
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
 import androidx.test.filters.RequiresDevice
+import com.android.server.wm.flicker.activityembedding.ActivityEmbeddingTestBase
 import com.android.server.wm.flicker.helpers.ActivityEmbeddingAppHelper
 import org.junit.FixMethodOrder
 import org.junit.Test
@@ -36,7 +37,7 @@
  * PlaceholderPrimary, which is configured to launch with PlaceholderSecondary in RTL. Expect split
  * PlaceholderSecondary|PlaceholderPrimary covering split B|A.
  *
- * To run this test: `atest FlickerTests:RTLStartSecondaryWithPlaceholderTest`
+ * To run this test: `atest FlickerTestsOther:RTLStartSecondaryWithPlaceholderTest`
  */
 @RequiresDevice
 @RunWith(Parameterized::class)
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/splitscreen/EnterSystemSplitTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/splitscreen/EnterSystemSplitTest.kt
new file mode 100644
index 0000000..87231c8
--- /dev/null
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/activityembedding/splitscreen/EnterSystemSplitTest.kt
@@ -0,0 +1,189 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.activityembedding.splitscreen
+
+import android.platform.test.annotations.Presubmit
+import android.platform.test.annotations.RequiresDevice
+import android.tools.common.datatypes.Rect
+import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
+import android.tools.device.flicker.legacy.FlickerBuilder
+import android.tools.device.flicker.legacy.LegacyFlickerTest
+import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import android.tools.device.traces.parsers.toFlickerComponent
+import com.android.server.wm.flicker.helpers.ActivityEmbeddingAppHelper
+import com.android.server.wm.flicker.activityembedding.ActivityEmbeddingTestBase
+import com.android.server.wm.flicker.testapp.ActivityOptions
+import com.android.wm.shell.flicker.utils.*
+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 entering System SplitScreen with Activity Embedding Split and another app.
+ *
+ * Setup: Launch A|B in split and secondaryApp, return to home.
+ * Transitions: Let AE Split A|B enter splitscreen with secondaryApp. Resulting in A|B|secondaryApp.
+ *
+ * To run this test: `atest FlickerTestsOther:EnterSystemSplitTest`
+ */
+@RequiresDevice
+@RunWith(Parameterized::class)
+@Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+class EnterSystemSplitTest(flicker: LegacyFlickerTest) :
+        ActivityEmbeddingTestBase(flicker) {
+
+    private val secondaryApp = SplitScreenUtils.getPrimary(instrumentation)
+    override val transition: FlickerBuilder.() -> Unit = {
+        setup {
+            testApp.launchViaIntent(wmHelper)
+            testApp.launchSecondaryActivity(wmHelper)
+            secondaryApp.launchViaIntent(wmHelper)
+            tapl.goHome()
+            wmHelper
+                    .StateSyncBuilder()
+                    .withAppTransitionIdle()
+                    .withHomeActivityVisible()
+                    .waitForAndVerify()
+            startDisplayBounds =
+                    wmHelper.currentState.layerState.physicalDisplayBounds ?:
+                    error("Display not found")
+        }
+        transitions {
+            SplitScreenUtils.enterSplit(wmHelper, tapl, device, testApp, secondaryApp)
+            SplitScreenUtils.waitForSplitComplete(wmHelper, testApp, secondaryApp)
+        }
+    }
+
+    @Presubmit
+    @Test
+    fun splitScreenDividerBecomesVisible() = flicker.splitScreenDividerBecomesVisible()
+
+    @Presubmit
+    @Test
+    fun activityEmbeddingSplitLayerBecomesVisible() {
+        flicker.splitAppLayerBoundsIsVisibleAtEnd(
+                testApp, landscapePosLeft = tapl.isTablet, portraitPosTop = false)
+    }
+
+    @Presubmit
+    @Test
+    fun activityEmbeddingSplitWindowBecomesVisible() = flicker.appWindowIsVisibleAtEnd(testApp)
+
+    @Presubmit
+    @Test
+    fun secondaryLayerBecomesVisible() {
+        flicker.splitAppLayerBoundsIsVisibleAtEnd(
+                secondaryApp, landscapePosLeft = !tapl.isTablet, portraitPosTop = true)
+    }
+
+    @Presubmit
+    @Test
+    fun secondaryAppWindowBecomesVisible() = flicker.appWindowIsVisibleAtEnd(secondaryApp)
+
+    /**
+     * After the transition there should be both ActivityEmbedding activities,
+     * SplitScreenPrimaryActivity and the system split divider on screen.
+     * Verify the layers are in expected sizes.
+     */
+    @Presubmit
+    @Test
+    fun activityEmbeddingSplitSurfaceAreEven() {
+        flicker.assertLayersEnd {
+            val leftAELayerRegion =
+                    visibleRegion(ActivityEmbeddingAppHelper.MAIN_ACTIVITY_COMPONENT)
+            val rightAELayerRegion =
+                    visibleRegion(ActivityEmbeddingAppHelper.SECONDARY_ACTIVITY_COMPONENT)
+            val secondaryAppLayerRegion =
+                    visibleRegion(
+                            ActivityOptions.SplitScreen.Primary.COMPONENT.toFlickerComponent())
+            val systemDivider = visibleRegion(SPLIT_SCREEN_DIVIDER_COMPONENT)
+            leftAELayerRegion
+                    .plus(rightAELayerRegion.region)
+                    .plus(secondaryAppLayerRegion.region)
+                    .plus(systemDivider.region)
+                    .coversExactly(startDisplayBounds)
+            check { "ActivityEmbeddingSplitHeight" }
+                    .that(leftAELayerRegion.region.height)
+                    .isEqual(rightAELayerRegion.region.height)
+            check { "SystemSplitHeight" }
+                    .that(rightAELayerRegion.region.height)
+                    .isEqual(secondaryAppLayerRegion.region.height)
+            // TODO(b/292283182): Remove this special case handling.
+            check { "ActivityEmbeddingSplitWidth" }
+                    .that(Math.abs(
+                            leftAELayerRegion.region.width - rightAELayerRegion.region.width))
+                    .isLower(2)
+            check { "SystemSplitWidth" }
+                    .that(Math.abs(secondaryAppLayerRegion.region.width -
+                            2 * rightAELayerRegion.region.width))
+                    .isLower(2)
+        }
+    }
+
+    /**
+     * Verify the windows are in expected sizes.
+     */
+    @Presubmit
+    @Test
+    fun activityEmbeddingSplitWindowsAreEven() {
+        flicker.assertWmEnd {
+            val leftAEWindowRegion =
+                    visibleRegion(ActivityEmbeddingAppHelper.MAIN_ACTIVITY_COMPONENT)
+            val rightAEWindowRegion =
+                    visibleRegion(ActivityEmbeddingAppHelper.SECONDARY_ACTIVITY_COMPONENT)
+            // There's no window for the divider bar.
+            val secondaryAppLayerRegion =
+                    visibleRegion(
+                            ActivityOptions.SplitScreen.Primary.COMPONENT.toFlickerComponent())
+            check { "ActivityEmbeddingSplitHeight" }
+                    .that(leftAEWindowRegion.region.height)
+                    .isEqual(rightAEWindowRegion.region.height)
+            check { "SystemSplitHeight" }
+                    .that(rightAEWindowRegion.region.height)
+                    .isEqual(secondaryAppLayerRegion.region.height)
+            check { "ActivityEmbeddingSplitWidth" }
+                    .that(Math.abs(
+                            leftAEWindowRegion.region.width - rightAEWindowRegion.region.width))
+                    .isLower(2)
+            check { "SystemSplitWidth" }
+                    .that(Math.abs(secondaryAppLayerRegion.region.width -
+                            2 * rightAEWindowRegion.region.width))
+                    .isLower(2)
+        }
+    }
+
+    @Ignore("Not applicable to this CUJ.")
+    override fun visibleLayersShownMoreThanOneConsecutiveEntry() {}
+
+    companion object {
+        /** {@inheritDoc} */
+        private var startDisplayBounds = Rect.EMPTY
+        /**
+         * Creates the test configurations.
+         *
+         * See [LegacyFlickerTestFactory.nonRotationTests] for configuring screen orientation and
+         * navigation modes.
+         */
+        @Parameterized.Parameters(name = "{0}")
+        @JvmStatic
+        fun getParams() = LegacyFlickerTestFactory.nonRotationTests()
+    }
+}
\ No newline at end of file
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppBackButtonTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppBackButtonTest.kt
index 71db76e..288558ae 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppBackButtonTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppBackButtonTest.kt
@@ -16,12 +16,12 @@
 
 package com.android.server.wm.flicker.close
 
-import android.platform.test.annotations.FlakyTest
 import android.tools.common.flicker.annotation.FlickerServiceCompatible
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import org.junit.FixMethodOrder
 import org.junit.Test
 import org.junit.runner.RunWith
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppHomeButtonTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppHomeButtonTest.kt
index 8dd7e65..32305c6 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppHomeButtonTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppHomeButtonTest.kt
@@ -16,12 +16,12 @@
 
 package com.android.server.wm.flicker.close
 
-import android.platform.test.annotations.FlakyTest
 import android.tools.common.flicker.annotation.FlickerServiceCompatible
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import org.junit.FixMethodOrder
 import org.junit.Test
 import org.junit.runner.RunWith
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppTransition.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppTransition.kt
index 8737edb..8d752cc 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppTransition.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/close/CloseAppTransition.kt
@@ -16,7 +16,6 @@
 
 package com.android.server.wm.flicker.close
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.flicker.subject.layers.LayersTraceSubject.Companion.VISIBLE_FOR_MORE_THAN_ONE_ENTRY_IGNORE_LAYERS
 import android.tools.common.traces.component.ComponentNameMatcher
@@ -24,6 +23,7 @@
 import android.tools.device.apphelpers.StandardAppHelper
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
+import androidx.test.filters.FlakyTest
 import com.android.server.wm.flicker.BaseTest
 import com.android.server.wm.flicker.helpers.SimpleAppHelper
 import com.android.server.wm.flicker.helpers.setRotation
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/TransferSplashscreenAppHelper.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/TransferSplashscreenAppHelper.kt
new file mode 100644
index 0000000..6311678
--- /dev/null
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/TransferSplashscreenAppHelper.kt
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.tools.common.traces.component.ComponentNameMatcher
+import android.tools.device.apphelpers.StandardAppHelper
+import android.tools.device.traces.parsers.toFlickerComponent
+import com.android.server.wm.flicker.testapp.ActivityOptions
+
+class TransferSplashscreenAppHelper
+@JvmOverloads
+constructor(
+    instr: Instrumentation,
+    launcherName: String = ActivityOptions.TransferSplashscreenActivity.LABEL,
+    component: ComponentNameMatcher =
+        ActivityOptions.TransferSplashscreenActivity.COMPONENT.toFlickerComponent()
+) : StandardAppHelper(instr, launcherName, component)
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/ime/CloseImeToHomeOnFinishActivityTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/ime/CloseImeToHomeOnFinishActivityTest.kt
index 99858ce..b44f1a6 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/ime/CloseImeToHomeOnFinishActivityTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/ime/CloseImeToHomeOnFinishActivityTest.kt
@@ -16,7 +16,6 @@
 
 package com.android.server.wm.flicker.ime
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.PlatinumTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.Rotation
@@ -24,6 +23,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import com.android.server.wm.flicker.BaseTest
 import com.android.server.wm.flicker.helpers.ImeAppHelper
 import com.android.server.wm.flicker.helpers.SimpleAppHelper
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromIconColdTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromIconColdTest.kt
index 3a784ff..48d5041 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromIconColdTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromIconColdTest.kt
@@ -16,13 +16,13 @@
 
 package com.android.server.wm.flicker.launch
 
-import android.platform.test.annotations.FlakyTest
 import android.tools.common.Rotation
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
 import android.tools.device.flicker.rules.RemoveAllTasksButHomeRule
+import androidx.test.filters.FlakyTest
 import org.junit.FixMethodOrder
 import org.junit.Test
 import org.junit.runner.RunWith
@@ -53,7 +53,8 @@
 @RunWith(Parameterized::class)
 @Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class)
 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
-class OpenAppFromIconColdTest(flicker: LegacyFlickerTest) : OpenAppFromLauncherTransition(flicker) {
+open class OpenAppFromIconColdTest(flicker: LegacyFlickerTest) :
+    OpenAppFromLauncherTransition(flicker) {
     /** {@inheritDoc} */
     override val transition: FlickerBuilder.() -> Unit
         get() = {
@@ -87,6 +88,7 @@
     override fun appWindowReplacesLauncherAsTopWindow() {
         super.appWindowReplacesLauncherAsTopWindow()
     }
+
     @FlakyTest(bugId = 240916028)
     @Test
     override fun appWindowAsTopWindowAtEnd() {
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromIntentWarmTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromIntentWarmTest.kt
index 0197e66..78b58f4 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromIntentWarmTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromIntentWarmTest.kt
@@ -16,13 +16,13 @@
 
 package com.android.server.wm.flicker.launch
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.flicker.annotation.FlickerServiceCompatible
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import com.android.server.wm.flicker.helpers.setRotation
 import org.junit.FixMethodOrder
 import org.junit.Test
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromLockscreenTransition.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromLockscreenTransition.kt
index 36e66c7..cc501e6 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromLockscreenTransition.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromLockscreenTransition.kt
@@ -16,11 +16,11 @@
 
 package com.android.server.wm.flicker.launch
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.traces.component.ComponentNameMatcher
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
+import androidx.test.filters.FlakyTest
 import com.android.server.wm.flicker.navBarLayerPositionAtEnd
 import com.android.server.wm.flicker.statusBarLayerPositionAtEnd
 import org.junit.Assume
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromLockscreenViaIntentTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromLockscreenViaIntentTest.kt
index e0fb751..3f931c4 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromLockscreenViaIntentTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromLockscreenViaIntentTest.kt
@@ -16,7 +16,6 @@
 
 package com.android.server.wm.flicker.launch
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
 import android.tools.common.Rotation
@@ -25,6 +24,7 @@
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.server.wm.flicker.helpers.NonResizeableAppHelper
 import org.junit.Assume
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromOverviewTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromOverviewTest.kt
index f1cd69a..b85362a 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromOverviewTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenAppFromOverviewTest.kt
@@ -16,7 +16,6 @@
 
 package com.android.server.wm.flicker.launch
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.Rotation
 import android.tools.common.flicker.annotation.FlickerServiceCompatible
@@ -24,6 +23,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import com.android.server.wm.flicker.helpers.setRotation
 import org.junit.FixMethodOrder
 import org.junit.Test
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenTransferSplashscreenAppFromLauncherTransition.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenTransferSplashscreenAppFromLauncherTransition.kt
new file mode 100644
index 0000000..3d9c067
--- /dev/null
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/OpenTransferSplashscreenAppFromLauncherTransition.kt
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.launch
+
+import android.platform.test.annotations.Presubmit
+import android.tools.common.traces.component.ComponentNameMatcher
+import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
+import android.tools.device.flicker.legacy.LegacyFlickerTest
+import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.RequiresDevice
+import com.android.server.wm.flicker.helpers.TransferSplashscreenAppHelper
+import org.junit.FixMethodOrder
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.MethodSorters
+import org.junit.runners.Parameterized
+
+/**
+ * Test cold launching an app from launcher
+ *
+ * To run this test: `atest FlickerTests:OpenTransferSplashscreenAppFromLauncherTransition`
+ *
+ * Actions:
+ * ```
+ *     Inherit from OpenAppFromIconColdTest, Launch an app [testApp] with an animated splash screen
+ *     by clicking it's icon on all apps, and wait for transfer splash screen complete
+ * ```
+ *
+ * Notes:
+ * ```
+ *     1. Some default assertions (e.g., nav bar, status bar and screen covered)
+ *        are inherited [OpenAppTransition]
+ *     2. Verify no flickering when transfer splash screen to app window.
+ * ```
+ */
+@RequiresDevice
+@RunWith(Parameterized::class)
+@Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+class OpenTransferSplashscreenAppFromLauncherTransition(flicker: LegacyFlickerTest) :
+    OpenAppFromIconColdTest(flicker) {
+    override val testApp = TransferSplashscreenAppHelper(instrumentation)
+
+    /**
+     * Checks that [ComponentNameMatcher.LAUNCHER] window is the top window at the start of the
+     * transition, and is replaced by [ComponentNameMatcher.SPLASH_SCREEN], then [testApp] remains
+     * visible until the end
+     */
+    @Presubmit
+    @Test
+    fun appWindowAfterSplash() {
+        flicker.assertWm {
+            this.isAppWindowOnTop(ComponentNameMatcher.LAUNCHER)
+                .then()
+                .isAppWindowOnTop(ComponentNameMatcher.SPLASH_SCREEN)
+                .then()
+                .isAppWindowOnTop(testApp)
+                .isAppWindowInvisible(ComponentNameMatcher.SPLASH_SCREEN)
+        }
+    }
+
+    companion object {
+        /**
+         * Creates the test configurations.
+         *
+         * See [LegacyFlickerTestFactory.nonRotationTests] for configuring screen orientation and
+         * navigation modes.
+         */
+        @Parameterized.Parameters(name = "{0}")
+        @JvmStatic
+        fun getParams() = LegacyFlickerTestFactory.nonRotationTests()
+    }
+}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/TaskTransitionTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/TaskTransitionTest.kt
index df9780e..b82a129 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/launch/TaskTransitionTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/launch/TaskTransitionTest.kt
@@ -19,7 +19,6 @@
 import android.app.Instrumentation
 import android.app.WallpaperManager
 import android.content.res.Resources
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.flicker.subject.layers.LayersTraceSubject.Companion.VISIBLE_FOR_MORE_THAN_ONE_ENTRY_IGNORE_LAYERS
 import android.tools.common.traces.component.ComponentNameMatcher
@@ -33,6 +32,7 @@
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
 import android.tools.device.helpers.WindowUtils
 import android.tools.device.traces.parsers.toFlickerComponent
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.server.wm.flicker.BaseTest
 import com.android.server.wm.flicker.helpers.NewTasksAppHelper
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/notification/OpenAppFromLockscreenNotificationWarmTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/notification/OpenAppFromLockscreenNotificationWarmTest.kt
index bf0f4ab..9722216 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/notification/OpenAppFromLockscreenNotificationWarmTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/notification/OpenAppFromLockscreenNotificationWarmTest.kt
@@ -16,7 +16,6 @@
 
 package com.android.server.wm.flicker.notification
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.platform.test.rule.SettingOverrideRule
 import android.provider.Settings
@@ -25,6 +24,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.server.wm.flicker.statusBarLayerPositionAtEnd
 import org.junit.ClassRule
@@ -174,7 +174,7 @@
         val disableUnseenNotifFilterRule =
             SettingOverrideRule(
                 Settings.Secure.LOCK_SCREEN_SHOW_ONLY_UNSEEN_NOTIFICATIONS,
-                /* value= */ "0",
+                "0",
             )
     }
 }
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/notification/OpenAppFromLockscreenNotificationWithOverlayAppTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/notification/OpenAppFromLockscreenNotificationWithOverlayAppTest.kt
index 3f3542d..ffd8171 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/notification/OpenAppFromLockscreenNotificationWithOverlayAppTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/notification/OpenAppFromLockscreenNotificationWithOverlayAppTest.kt
@@ -16,7 +16,6 @@
 
 package com.android.server.wm.flicker.notification
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Postsubmit
 import android.platform.test.annotations.Presubmit
 import android.tools.common.traces.component.ComponentNameMatcher
@@ -25,6 +24,7 @@
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
 import android.tools.device.helpers.wakeUpAndGoToHomeScreen
+import androidx.test.filters.FlakyTest
 import androidx.test.filters.RequiresDevice
 import com.android.server.wm.flicker.helpers.ShowWhenLockedAppHelper
 import org.junit.FixMethodOrder
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchBetweenTwoAppsBackTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchBetweenTwoAppsBackTest.kt
index 50ff62b..13fcc2b 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchBetweenTwoAppsBackTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchBetweenTwoAppsBackTest.kt
@@ -16,7 +16,6 @@
 
 package com.android.server.wm.flicker.quickswitch
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
 import android.tools.common.datatypes.Rect
@@ -25,6 +24,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import com.android.server.wm.flicker.BaseTest
 import com.android.server.wm.flicker.helpers.NonResizeableAppHelper
 import com.android.server.wm.flicker.helpers.SimpleAppHelper
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchBetweenTwoAppsForwardTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchBetweenTwoAppsForwardTest.kt
index aee9163..c090415 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchBetweenTwoAppsForwardTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchBetweenTwoAppsForwardTest.kt
@@ -16,7 +16,6 @@
 
 package com.android.server.wm.flicker.quickswitch
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
 import android.tools.common.datatypes.Rect
@@ -25,6 +24,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import com.android.server.wm.flicker.BaseTest
 import com.android.server.wm.flicker.helpers.NonResizeableAppHelper
 import com.android.server.wm.flicker.helpers.SimpleAppHelper
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchFromLauncherTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchFromLauncherTest.kt
index d6a951d..f51be90 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchFromLauncherTest.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/quickswitch/QuickSwitchFromLauncherTest.kt
@@ -16,7 +16,6 @@
 
 package com.android.server.wm.flicker.quickswitch
 
-import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Presubmit
 import android.tools.common.NavBar
 import android.tools.common.Rotation
@@ -26,6 +25,7 @@
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.LegacyFlickerTest
 import android.tools.device.flicker.legacy.LegacyFlickerTestFactory
+import androidx.test.filters.FlakyTest
 import com.android.server.wm.flicker.BaseTest
 import com.android.server.wm.flicker.helpers.SimpleAppHelper
 import org.junit.FixMethodOrder
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayApp3ButtonNavLandscape.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayApp3ButtonNavLandscape.kt
index b34da72..4adcc8b 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayApp3ButtonNavLandscape.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayApp3ButtonNavLandscape.kt
@@ -25,10 +25,12 @@
 import android.tools.common.flicker.config.FlickerServiceConfig
 import android.tools.device.flicker.junit.FlickerServiceJUnit4ClassRunner
 import com.android.server.wm.flicker.service.notification.scenarios.OpenAppFromLockscreenNotificationWithOverlayApp
+import org.junit.Ignore
 import org.junit.Test
 import org.junit.runner.RunWith
 
 @RunWith(FlickerServiceJUnit4ClassRunner::class)
+@Ignore("b/294418322: no notification launch animation exists when keyguard is occluded")
 class OpenAppFromLockscreenNotificationWithOverlayApp3ButtonNavLandscape :
     OpenAppFromLockscreenNotificationWithOverlayApp(NavBar.MODE_3BUTTON, Rotation.ROTATION_90) {
     @ExpectedScenarios(["APP_LAUNCH_FROM_NOTIFICATION"])
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayApp3ButtonNavPortrait.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayApp3ButtonNavPortrait.kt
index b163897..f7211e7 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayApp3ButtonNavPortrait.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayApp3ButtonNavPortrait.kt
@@ -25,10 +25,12 @@
 import android.tools.common.flicker.config.FlickerServiceConfig
 import android.tools.device.flicker.junit.FlickerServiceJUnit4ClassRunner
 import com.android.server.wm.flicker.service.notification.scenarios.OpenAppFromLockscreenNotificationWithOverlayApp
+import org.junit.Ignore
 import org.junit.Test
 import org.junit.runner.RunWith
 
 @RunWith(FlickerServiceJUnit4ClassRunner::class)
+@Ignore("b/294418322: no notification launch animation exists when keyguard is occluded")
 class OpenAppFromLockscreenNotificationWithOverlayApp3ButtonNavPortrait :
     OpenAppFromLockscreenNotificationWithOverlayApp(NavBar.MODE_3BUTTON, Rotation.ROTATION_0) {
     @ExpectedScenarios(["APP_LAUNCH_FROM_NOTIFICATION"])
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayAppGesturalNavLandscape.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayAppGesturalNavLandscape.kt
index 19b533e..1ade956 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayAppGesturalNavLandscape.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayAppGesturalNavLandscape.kt
@@ -25,10 +25,12 @@
 import android.tools.common.flicker.config.FlickerServiceConfig
 import android.tools.device.flicker.junit.FlickerServiceJUnit4ClassRunner
 import com.android.server.wm.flicker.service.notification.scenarios.OpenAppFromLockscreenNotificationWithOverlayApp
+import org.junit.Ignore
 import org.junit.Test
 import org.junit.runner.RunWith
 
 @RunWith(FlickerServiceJUnit4ClassRunner::class)
+@Ignore("b/294418322: no notification launch animation exists when keyguard is occluded")
 class OpenAppFromLockscreenNotificationWithOverlayAppGesturalNavLandscape :
     OpenAppFromLockscreenNotificationWithOverlayApp(NavBar.MODE_GESTURAL, Rotation.ROTATION_90) {
     @ExpectedScenarios(["APP_LAUNCH_FROM_NOTIFICATION"])
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayAppGesturalNavPortrait.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayAppGesturalNavPortrait.kt
index c9ed4f4..ea26f08 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayAppGesturalNavPortrait.kt
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/service/notification/flicker/OpenAppFromLockscreenNotificationWithOverlayAppGesturalNavPortrait.kt
@@ -25,10 +25,12 @@
 import android.tools.common.flicker.config.FlickerServiceConfig
 import android.tools.device.flicker.junit.FlickerServiceJUnit4ClassRunner
 import com.android.server.wm.flicker.service.notification.scenarios.OpenAppFromLockscreenNotificationWithOverlayApp
+import org.junit.Ignore
 import org.junit.Test
 import org.junit.runner.RunWith
 
 @RunWith(FlickerServiceJUnit4ClassRunner::class)
+@Ignore("b/294418322: no notification launch animation exists when keyguard is occluded")
 class OpenAppFromLockscreenNotificationWithOverlayAppGesturalNavPortrait :
     OpenAppFromLockscreenNotificationWithOverlayApp(NavBar.MODE_GESTURAL, Rotation.ROTATION_0) {
     @ExpectedScenarios(["APP_LAUNCH_FROM_NOTIFICATION"])
diff --git a/tests/FlickerTests/test-apps/flickerapp/Android.bp b/tests/FlickerTests/test-apps/flickerapp/Android.bp
index 75e35ee..e3b23b9 100644
--- a/tests/FlickerTests/test-apps/flickerapp/Android.bp
+++ b/tests/FlickerTests/test-apps/flickerapp/Android.bp
@@ -24,6 +24,9 @@
 android_test {
     name: "FlickerTestApp",
     srcs: ["**/*.java"],
+    resource_dirs: [
+        "res",
+    ],
     sdk_version: "current",
     test_suites: ["device-tests"],
     static_libs: [
diff --git a/tests/FlickerTests/test-apps/flickerapp/AndroidManifest.xml b/tests/FlickerTests/test-apps/flickerapp/AndroidManifest.xml
index ff9799a..704798e 100644
--- a/tests/FlickerTests/test-apps/flickerapp/AndroidManifest.xml
+++ b/tests/FlickerTests/test-apps/flickerapp/AndroidManifest.xml
@@ -347,6 +347,17 @@
             android:exported="false"
             android:theme="@style/CutoutShortEdges"
             android:resizeableActivity="true"/>
+        <activity
+            android:name=".TransferSplashscreenActivity"
+            android:taskAffinity="com.android.server.wm.flicker.testapp.TransferSplashscreenActivity"
+            android:label="TransferSplashscreenActivity"
+            android:theme="@style/SplashscreenAppTheme"
+            android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
         <service
             android:name=".AssistantInteractionSessionService"
             android:exported="true"
diff --git a/tests/FlickerTests/test-apps/flickerapp/res/drawable/avd_anim.xml b/tests/FlickerTests/test-apps/flickerapp/res/drawable/avd_anim.xml
new file mode 100644
index 0000000..19205d4
--- /dev/null
+++ b/tests/FlickerTests/test-apps/flickerapp/res/drawable/avd_anim.xml
@@ -0,0 +1,94 @@
+<animated-vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt">
+    <aapt:attr name="android:drawable">
+        <vector android:height="432dp" android:width="432dp" android:viewportHeight="432" android:viewportWidth="432">
+            <group android:name="_R_G">
+                <group android:name="_R_G_L_5_G" android:translateX="216" android:translateY="216" android:scaleX="1.5" android:scaleY="1.5">
+                    <path android:name="_R_G_L_5_G_D_0_P_0" android:fillColor="#555555" android:fillAlpha="1" android:fillType="nonZero" android:pathData=" M53.82 -56.7 C53.82,-56.7 43.64,-49.06 43.64,-49.06 C43.64,-49.06 0,-16.34 0,-16.34 C0,-16.34 -43.64,-49.06 -43.64,-49.06 C-43.64,-49.06 -53.82,-56.7 -53.82,-56.7 C-64.6,-64.79 -80,-57.09 -80,-43.61 C-80,-43.61 -80,-29.07 -80,-29.07 C-80,-29.07 -80,49.09 -80,49.09 C-80,55.12 -75.12,60 -69.09,60 C-69.09,60 -43.64,60 -43.64,60 C-43.64,60 -43.64,-1.8 -43.64,-1.8 C-43.64,-1.8 0,30.92 0,30.92 C0,30.92 43.64,-1.8 43.64,-1.8 C43.64,-1.8 43.64,60 43.64,60 C43.64,60 69.09,60 69.09,60 C75.12,60 80,55.12 80,49.09 C80,49.09 80,-29.07 80,-29.07 C80,-29.07 80,-43.61 80,-43.61 C80,-57.09 64.61,-64.79 53.82,-56.7c "/>
+                </group>
+                <group android:name="_R_G_L_4_G" android:translateX="216" android:translateY="216" android:scaleX="1.5" android:scaleY="1.5">
+                    <clip-path android:name="mask_x" android:pathData="M53.82 -56.7 C53.82,-56.7 43.64,-49.06 43.64,-49.06 C43.64,-49.06 0,-16.34 0,-16.34 C0,-16.34 -43.64,-49.06 -43.64,-49.06 C-43.64,-49.06 -53.82,-56.7 -53.82,-56.7 C-64.6,-64.79 -80,-57.09 -80,-43.61 C-80,-43.61 -80,-29.07 -80,-29.07 C-80,-29.07 -80,49.09 -80,49.09 C-80,55.12 -75.12,60 -69.09,60 C-69.09,60 -43.64,60 -43.64,60 C-43.64,60 -43.64,-1.8 -43.64,-1.8 C-43.64,-1.8 0,30.92 0,30.92 C0,30.92 43.64,-1.8 43.64,-1.8 C43.64,-1.8 43.64,60 43.64,60 C43.64,60 69.09,60 69.09,60 C75.12,60 80,55.12 80,49.09 C80,49.09 80,-29.07 80,-29.07 C80,-29.07 80,-43.61 80,-43.61 C80,-57.09 64.61,-64.79 53.82,-56.7c"/>
+                    <path android:name="_R_G_L_4_G_D_0_P_0" android:fillColor="#2684fc" android:fillAlpha="1" android:fillType="nonZero" android:pathData=" M-80.39 60 C-80.39,60 -105.84,60 -105.84,60 C-111.87,60 -116.75,55.12 -116.75,49.09 C-116.75,49.09 -116.75,-60 -116.75,-60 C-116.75,-60 -80.39,-60 -80.39,-60 C-80.39,-60 -80.39,60 -80.39,60c "/>
+                </group>
+                <group android:name="_R_G_L_3_G" android:translateX="216" android:translateY="216" android:scaleX="1.5" android:scaleY="1.5">
+                    <clip-path android:name="mask_x" android:pathData="M53.82 -56.7 C53.82,-56.7 43.64,-49.06 43.64,-49.06 C43.64,-49.06 0,-16.34 0,-16.34 C0,-16.34 -43.64,-49.06 -43.64,-49.06 C-43.64,-49.06 -53.82,-56.7 -53.82,-56.7 C-64.6,-64.79 -80,-57.09 -80,-43.61 C-80,-43.61 -80,-29.07 -80,-29.07 C-80,-29.07 -80,49.09 -80,49.09 C-80,55.12 -75.12,60 -69.09,60 C-69.09,60 -43.64,60 -43.64,60 C-43.64,60 -43.64,-1.8 -43.64,-1.8 C-43.64,-1.8 0,30.92 0,30.92 C0,30.92 43.64,-1.8 43.64,-1.8 C43.64,-1.8 43.64,60 43.64,60 C43.64,60 69.09,60 69.09,60 C75.12,60 80,55.12 80,49.09 C80,49.09 80,-29.07 80,-29.07 C80,-29.07 80,-43.61 80,-43.61 C80,-57.09 64.61,-64.79 53.82,-56.7c"/>
+                    <path android:name="_R_G_L_3_G_D_0_P_0" android:fillColor="#00ac47" android:fillAlpha="1" android:fillType="nonZero" android:pathData="M80.64 60 C80.64,60 106.09,60 106.09,60 C112.12,60 117,55.12 117,49.09 C117,49.09 117,-60 117,-60 C117,-60 80.64,-60 80.64,-60 C80.64,-60 80.64,60 80.64,60c "/>
+                </group>
+                <group android:name="_R_G_L_2_G" android:translateX="216" android:translateY="216" android:scaleX="1.5" android:scaleY="1.5">
+                    <clip-path android:name="mask_x" android:pathData="M53.82 -56.7 C53.82,-56.7 43.64,-49.06 43.64,-49.06 C43.64,-49.06 0,-16.34 0,-16.34 C0,-16.34 -43.64,-49.06 -43.64,-49.06 C-43.64,-49.06 -53.82,-56.7 -53.82,-56.7 C-64.6,-64.79 -80,-57.09 -80,-43.61 C-80,-43.61 -80,-29.07 -80,-29.07 C-80,-29.07 -80,49.09 -80,49.09 C-80,55.12 -75.12,60 -69.09,60 C-69.09,60 -43.64,60 -43.64,60 C-43.64,60 -43.64,-1.8 -43.64,-1.8 C-43.64,-1.8 0,30.92 0,30.92 C0,30.92 43.64,-1.8 43.64,-1.8 C43.64,-1.8 43.64,60 43.64,60 C43.64,60 69.09,60 69.09,60 C75.12,60 80,55.12 80,49.09 C80,49.09 80,-29.07 80,-29.07 C80,-29.07 80,-43.61 80,-43.61 C80,-57.09 64.61,-64.79 53.82,-56.7c"/>
+                    <path android:name="_R_G_L_2_G_D_0_P_0" android:fillColor="#fe2c25" android:fillAlpha="1" android:fillType="nonZero" android:pathData="M53.82 -104.7 C53.82,-104.7 0,-64.34 0,-64.34 C0,-64.34 -53.82,-104.7 -53.82,-104.7 C-64.6,-112.79 -80,-105.09 -80,-91.61 C-80,-91.61 -80,-77.07 -80,-77.07 C-80,-77.07 0,-17.08 0,-17.08 C0,-17.08 80,-77.07 80,-77.07 C80,-77.07 80,-91.61 80,-91.61 C80,-105.09 64.61,-112.79 53.82,-104.7c "/>
+                </group>
+                <group android:name="_R_G_L_1_G" android:translateX="216" android:translateY="216" android:scaleX="1.5" android:scaleY="1.5">
+                    <clip-path android:name="mask_x" android:pathData="M43.64 -1.8 C43.64,-1.8 43.64,-49.06 43.64,-49.06 C43.64,-49.06 53.82,-56.7 53.82,-56.7 C64.61,-64.79 80,-57.09 80,-43.61 C80,-43.61 80,-1.8 80,-1.8 C80,-1.8 43.64,-1.8 43.64,-1.8c"/>
+                    <path android:name="_R_G_L_1_G_D_0_P_0" android:fillColor="#ffba00" android:fillAlpha="1" android:fillType="nonZero" android:pathData="M80.64 -135 C80.64,-135 117,-135 117,-135 C117,-135 117,-104.07 117,-104.07 C117,-104.07 80.64,-76.8 80.64,-76.8 C80.64,-76.8 80.64,-135 80.64,-135c "/>
+                </group>
+                <group android:name="_R_G_L_0_G" android:translateX="216" android:translateY="216" android:scaleX="1.5" android:scaleY="1.5">
+                    <clip-path android:name="mask_x" android:pathData="M-43.64 -1.8 C-43.64,-1.8 -80,-1.8 -80,-1.8 C-80,-1.8 -80,-43.61 -80,-43.61 C-80,-57.09 -64.6,-64.79 -53.82,-56.7 C-53.82,-56.7 -43.64,-49.06 -43.64,-49.06 C-43.64,-49.06 -43.64,-1.8 -43.64,-1.8c"/>
+                    <path android:name="_R_G_L_0_G_D_0_P_0" android:fillColor="#d70007" android:fillAlpha="1" android:fillType="nonZero" android:pathData=" M-117 -104.07 C-117,-104.07 -117,-135 -117,-135 C-117,-135 -80.64,-135 -80.64,-135 C-80.64,-135 -80.64,-76.8 -80.64,-76.8 C-80.64,-76.8 -117,-104.07 -117,-104.07c "/>
+                </group>
+            </group>
+            <group android:name="time_group"/>
+        </vector>
+    </aapt:attr>
+    <target android:name="_R_G_L_4_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator android:propertyName="pathData" android:duration="1567" android:startOffset="233" android:valueFrom="M-80.39 60 C-80.39,60 -105.84,60 -105.84,60 C-111.87,60 -116.75,55.12 -116.75,49.09 C-116.75,49.09 -116.75,-60 -116.75,-60 C-116.75,-60 -80.39,-60 -80.39,-60 C-80.39,-60 -80.39,60 -80.39,60c " android:valueTo=" M-43.64 60 C-43.64,60 -69.09,60 -69.09,60 C-75.12,60 -80,55.12 -80,49.09 C-80,49.09 -80,-60 -80,-60 C-80,-60 -43.64,-60 -43.64,-60 C-43.64,-60 -43.64,60 -43.64,60c " android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0,1 1.0,1.0"/>
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_3_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator android:propertyName="pathData" android:duration="1567" android:startOffset="233" android:valueFrom=" M80.64 60 C80.64,60 106.09,60 106.09,60 C112.12,60 117,55.12 117,49.09 C117,49.09 117,-60 117,-60 C117,-60 80.64,-60 80.64,-60 C80.64,-60 80.64,60 80.64,60c " android:valueTo=" M43.64 60 C43.64,60 69.09,60 69.09,60 C75.12,60 80,55.12 80,49.09 C80,49.09 80,-60 80,-60 C80,-60 43.64,-60 43.64,-60 C43.64,-60 43.64,60 43.64,60c " android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0,1 1.0,1.0"/>
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_2_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator android:propertyName="pathData" android:duration="1567" android:startOffset="233" android:valueFrom="M53.82 -104.7 C53.82,-104.7 0,-64.34 0,-64.34 C0,-64.34 -53.82,-104.7 -53.82,-104.7 C-64.6,-112.79 -80,-105.09 -80,-91.61 C-80,-91.61 -80,-77.07 -80,-77.07 C-80,-77.07 0,-17.08 0,-17.08 C0,-17.08 80,-77.07 80,-77.07 C80,-77.07 80,-91.61 80,-91.61 C80,-105.09 64.61,-112.79 53.82,-104.7c" android:valueTo="M53.82 -56.7 C53.82,-56.7 0,-16.34 0,-16.34 C0,-16.34 -53.82,-56.7 -53.82,-56.7 C-64.6,-64.79 -80,-57.09 -80,-43.61 C-80,-43.61 -80,-29.07 -80,-29.07 C-80,-29.07 0,30.92 0,30.92 C0,30.92 80,-29.07 80,-29.07 C80,-29.07 80,-43.61 80,-43.61 C80,-57.09 64.61,-64.79 53.82,-56.7c " android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0,1 1.0,1.0"/>
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_1_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator android:propertyName="pathData" android:duration="1567" android:startOffset="233" android:valueFrom=" M80.64 -135 C80.64,-135 117,-135 117,-135 C117,-135 117,-104.07 117,-104.07 C117,-104.07 80.64,-76.8 80.64,-76.8 C80.64,-76.8 80.64,-135 80.64,-135c " android:valueTo=" M43.64 -60 C43.64,-60 80,-60 80,-60 C80,-60 80,-29.07 80,-29.07 C80,-29.07 43.64,-1.8 43.64,-1.8 C43.64,-1.8 43.64,-60 43.64,-60c " android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0,1 1.0,1.0"/>
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="_R_G_L_0_G_D_0_P_0">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator android:propertyName="pathData" android:duration="1567" android:startOffset="233" android:valueFrom=" M-117 -104.07 C-117,-104.07 -117,-135 -117,-135 C-117,-135 -80.64,-135 -80.64,-135 C-80.64,-135 -80.64,-76.8 -80.64,-76.8 C-80.64,-76.8 -117,-104.07 -117,-104.07c " android:valueTo=" M-80 -29.07 C-80,-29.07 -80,-60 -80,-60 C-80,-60 -43.64,-60 -43.64,-60 C-43.64,-60 -43.64,-1.8 -43.64,-1.8 C-43.64,-1.8 -80,-29.07 -80,-29.07c " android:valueType="pathType">
+                    <aapt:attr name="android:interpolator">
+                        <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0,1 1.0,1.0"/>
+                    </aapt:attr>
+                </objectAnimator>
+            </set>
+        </aapt:attr>
+    </target>
+    <target android:name="time_group">
+        <aapt:attr name="android:animation">
+            <set android:ordering="together">
+                <objectAnimator android:propertyName="translateX" android:duration="2017" android:startOffset="0" android:valueFrom="0" android:valueTo="1" android:valueType="floatType"/>
+            </set>
+        </aapt:attr>
+    </target>
+</animated-vector>
diff --git a/tests/FlickerTests/test-apps/flickerapp/res/values/styles.xml b/tests/FlickerTests/test-apps/flickerapp/res/values/styles.xml
index e51ed29..9b742d9 100644
--- a/tests/FlickerTests/test-apps/flickerapp/res/values/styles.xml
+++ b/tests/FlickerTests/test-apps/flickerapp/res/values/styles.xml
@@ -53,4 +53,11 @@
     <style name="no_starting_window" parent="@android:style/Theme.DeviceDefault">
         <item name="android:windowDisablePreview">true</item>
     </style>
+
+    <style name="SplashscreenAppTheme" parent="@android:style/Theme.DeviceDefault">
+        <!-- Splashscreen Attributes -->
+        <item name="android:windowSplashScreenAnimatedIcon">@drawable/avd_anim</item>
+        <!-- Here we want to match the duration of our AVD -->
+        <item name="android:windowSplashScreenAnimationDuration">900</item>
+    </style>
 </resources>
diff --git a/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/ActivityOptions.java b/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/ActivityOptions.java
index 2795a6c..7c5e9a3 100644
--- a/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/ActivityOptions.java
+++ b/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/ActivityOptions.java
@@ -178,6 +178,12 @@
                 FLICKER_APP_PACKAGE + ".LaunchNewActivity");
     }
 
+    public static class TransferSplashscreenActivity {
+        public static final String LABEL = "TransferSplashscreenActivity";
+        public static final ComponentName COMPONENT = new ComponentName(FLICKER_APP_PACKAGE,
+                FLICKER_APP_PACKAGE + ".TransferSplashscreenActivity");
+    }
+
     public static class Pip {
         // Test App > Pip Activity
         public static final String LABEL = "PipActivity";
diff --git a/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/TransferSplashscreenActivity.java b/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/TransferSplashscreenActivity.java
new file mode 100644
index 0000000..0323286
--- /dev/null
+++ b/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/TransferSplashscreenActivity.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.app.Activity;
+import android.os.Bundle;
+import android.os.SystemClock;
+import android.view.View;
+import android.view.ViewTreeObserver;
+import android.window.SplashScreen;
+import android.window.SplashScreenView;
+
+public class TransferSplashscreenActivity extends Activity {
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        final SplashScreen splashScreen = getSplashScreen();
+        // Register setOnExitAnimationListener to transfer the splash screen window to client.
+        splashScreen.setOnExitAnimationListener(this::onSplashScreenExit);
+        final View content = findViewById(android.R.id.content);
+        // By register preDrawListener to defer app window draw signal about 500ms, which to ensure
+        // the splash screen must show when cold launch.
+        content.getViewTreeObserver().addOnPreDrawListener(
+                new ViewTreeObserver.OnPreDrawListener() {
+                    final long mCreateTime = SystemClock.uptimeMillis();
+                    @Override
+                    public boolean onPreDraw() {
+                        return SystemClock.uptimeMillis() - mCreateTime > 500;
+                    }
+                }
+        );
+    }
+
+    private void onSplashScreenExit(SplashScreenView view) {
+        view.remove();
+    }
+}
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/BitmapsAlphaActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/BitmapsAlphaActivity.java
index ef49c7f..cb16191 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/BitmapsAlphaActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/BitmapsAlphaActivity.java
@@ -48,15 +48,15 @@
         BitmapsView(Context c) {
             super(c);
 
-            Log.d("OpenGLRenderer", "Loading sunset1, default options");
+            Log.d("HWUI", "Loading sunset1, default options");
             mBitmap1 = BitmapFactory.decodeResource(c.getResources(), R.drawable.sunset1);
-            Log.d("OpenGLRenderer", "Loading sunset2, default options");
+            Log.d("HWUI", "Loading sunset2, default options");
             mBitmap2 = BitmapFactory.decodeResource(c.getResources(), R.drawable.sunset2);
-            Log.d("OpenGLRenderer", "Loading sunset3, forcing ARGB-8888");
+            Log.d("HWUI", "Loading sunset3, forcing ARGB-8888");
             BitmapFactory.Options opts = new BitmapFactory.Options();
             opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
             mBitmap3 = BitmapFactory.decodeResource(c.getResources(), R.drawable.sunset3, opts);
-            Log.d("OpenGLRenderer", "    has bitmap alpha? " + mBitmap3.hasAlpha());
+            Log.d("HWUI", "    has bitmap alpha? " + mBitmap3.hasAlpha());
 
             mBitmapPaint = new Paint();
         }
@@ -65,7 +65,7 @@
         protected void onDraw(Canvas canvas) {
             super.onDraw(canvas);
             
-            Log.d("OpenGLRenderer", "================= Draw");
+            Log.d("HWUI", "================= Draw");
 
             canvas.translate(120.0f, 50.0f);
             canvas.drawBitmap(mBitmap1, 0.0f, 0.0f, mBitmapPaint);
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ClearActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ClearActivity.java
index 1c82e9b..dbfb4ca 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/ClearActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ClearActivity.java
@@ -77,7 +77,7 @@
                     canvas.drawPath(mPath, mClearPaint);
                 }
                 canvas.restore();
-                canvas.drawText("OpenGLRenderer", 50.0f, 50.0f, mClearPaint);
+                canvas.drawText("HWUI", 50.0f, 50.0f, mClearPaint);
                 mClearPaint.setColor(0xff000000);
                 canvas.drawRect(800.0f, 100.0f, 900.0f, 200.0f, mClearPaint);
                 mClearPaint.setColor(0x0000ff00);
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ColorBitmapActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ColorBitmapActivity.java
index e2d17cd..1f4c6c5 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/ColorBitmapActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ColorBitmapActivity.java
@@ -17,6 +17,7 @@
 package com.android.test.hwui;
 
 import android.app.Activity;
+import android.content.pm.ActivityInfo;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.ColorSpace;
@@ -72,6 +73,10 @@
     private int[] mGradientEndColors = {0xFFFFFFFF, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF};
     private String[] mGradientColorNames = {"Grayscale", "Red", "Green", "Blue"};
 
+    private int mColorMode = ActivityInfo.COLOR_MODE_DEFAULT;
+    private int[] mColorModes = {ActivityInfo.COLOR_MODE_DEFAULT, ActivityInfo.COLOR_MODE_HDR};
+    private String[] mColorModeNames = {"DEFAULT", "HDR"};
+
     private final ExecutorService mBufferFenceExecutor = Executors.newFixedThreadPool(1);
     private final ExecutorService mBufferExecutor = Executors.newFixedThreadPool(1);
 
@@ -139,6 +144,15 @@
             gradientColorSpinner
                     .setOnItemSelectedListener(new GradientColorOnItemSelectedListener());
 
+            ArrayAdapter<String> colorModeAdapter = new ArrayAdapter<>(
+                    this, android.R.layout.simple_spinner_item, mColorModeNames);
+
+            colorModeAdapter
+                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+            Spinner colorModeSpinner = new Spinner(this);
+            colorModeSpinner.setAdapter(colorModeAdapter);
+            colorModeSpinner.setOnItemSelectedListener(new ColorModeOnItemSelectedListener());
+
             mGradientBuffer = getGradientBuffer().get();
 
             LinearLayout linearLayout = new LinearLayout(this);
@@ -169,6 +183,10 @@
                     LinearLayout.LayoutParams.WRAP_CONTENT,
                     LinearLayout.LayoutParams.WRAP_CONTENT));
 
+            spinnerLayout.addView(colorModeSpinner, new LinearLayout.LayoutParams(
+                    LinearLayout.LayoutParams.WRAP_CONTENT,
+                    LinearLayout.LayoutParams.WRAP_CONTENT));
+
             linearLayout.addView(spinnerLayout, new LinearLayout.LayoutParams(
                     LinearLayout.LayoutParams.WRAP_CONTENT,
                     LinearLayout.LayoutParams.WRAP_CONTENT));
@@ -187,6 +205,8 @@
             linearLayout.addView(mSurfaceView, new LinearLayout.LayoutParams(WIDTH, HEIGHT));
 
             setContentView(linearLayout);
+
+            getWindow().setColorMode(mColorMode);
         } catch (Exception e) {
             throw new RuntimeException(e);
         }
@@ -312,4 +332,22 @@
 
         }
     }
+
+    private final class ColorModeOnItemSelectedListener
+            implements AdapterView.OnItemSelectedListener {
+
+        @Override
+        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
+            ColorBitmapActivity.this.mColorMode = ColorBitmapActivity.this.mColorModes[position];
+            ColorBitmapActivity.this.getMainExecutor()
+                    .execute(() -> {
+                        ColorBitmapActivity.this.getWindow().setColorMode(mColorMode);
+                    });
+        }
+
+        @Override
+        public void onNothingSelected(AdapterView<?> parent) {
+
+        }
+    }
 }
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/QuickRejectActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/QuickRejectActivity.java
index 5192bfe..11a2a41 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/QuickRejectActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/QuickRejectActivity.java
@@ -53,30 +53,30 @@
             super.onDraw(canvas);
 
             int count = canvas.getSaveCount();
-            Log.d("OpenGLRenderer", "count=" + count);
+            Log.d("HWUI", "count=" + count);
             count = canvas.save();
-            Log.d("OpenGLRenderer", "count after save=" + count);
+            Log.d("HWUI", "count after save=" + count);
             count = canvas.getSaveCount();
-            Log.d("OpenGLRenderer", "getSaveCount after save=" + count);
+            Log.d("HWUI", "getSaveCount after save=" + count);
             canvas.restore();
             count = canvas.getSaveCount();
-            Log.d("OpenGLRenderer", "count after restore=" + count);
+            Log.d("HWUI", "count after restore=" + count);
             canvas.save();
-            Log.d("OpenGLRenderer", "count after save=" + canvas.getSaveCount());
+            Log.d("HWUI", "count after save=" + canvas.getSaveCount());
             canvas.save();
-            Log.d("OpenGLRenderer", "count after save=" + canvas.getSaveCount());
+            Log.d("HWUI", "count after save=" + canvas.getSaveCount());
             canvas.save();
-            Log.d("OpenGLRenderer", "count after save=" + canvas.getSaveCount());
+            Log.d("HWUI", "count after save=" + canvas.getSaveCount());
             canvas.restoreToCount(count);
             count = canvas.getSaveCount();
-            Log.d("OpenGLRenderer", "count after restoreToCount=" + count);
+            Log.d("HWUI", "count after restoreToCount=" + count);
             count = canvas.saveLayer(0, 0, 10, 10, mBitmapPaint, Canvas.ALL_SAVE_FLAG);
-            Log.d("OpenGLRenderer", "count after saveLayer=" + count);
+            Log.d("HWUI", "count after saveLayer=" + count);
             count = canvas.getSaveCount();
-            Log.d("OpenGLRenderer", "getSaveCount after saveLayer=" + count);
+            Log.d("HWUI", "getSaveCount after saveLayer=" + count);
             canvas.restore();
             count = canvas.getSaveCount();
-            Log.d("OpenGLRenderer", "count after restore=" + count);
+            Log.d("HWUI", "count after restore=" + count);
 
             canvas.save();
             canvas.clipRect(0.0f, 0.0f, 40.0f, 40.0f);
diff --git a/tests/Input/src/com/android/server/input/FocusEventDebugViewTest.java b/tests/Input/src/com/android/server/input/FocusEventDebugViewTest.java
new file mode 100644
index 0000000..1b98887
--- /dev/null
+++ b/tests/Input/src/com/android/server/input/FocusEventDebugViewTest.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.input;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.view.InputChannel;
+import android.view.InputDevice;
+import android.view.MotionEvent;
+import android.view.MotionEvent.PointerCoords;
+import android.view.MotionEvent.PointerProperties;
+import android.view.ViewConfiguration;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Build/Install/Run:
+ * atest FocusEventDebugViewTest
+ */
+@RunWith(AndroidJUnit4.class)
+public class FocusEventDebugViewTest {
+
+    private FocusEventDebugView mFocusEventDebugView;
+    private FocusEventDebugView.RotaryInputValueView mRotaryInputValueView;
+    private FocusEventDebugView.RotaryInputGraphView mRotaryInputGraphView;
+    private float mScaledVerticalScrollFactor;
+
+    @Before
+    public void setUp() throws Exception {
+        Context context = InstrumentationRegistry.getContext();
+        mScaledVerticalScrollFactor =
+                ViewConfiguration.get(context).getScaledVerticalScrollFactor();
+        InputManagerService mockService = mock(InputManagerService.class);
+        when(mockService.monitorInput(anyString(), anyInt()))
+                .thenReturn(InputChannel.openInputChannelPair("FocusEventDebugViewTest")[1]);
+
+        mRotaryInputValueView = new FocusEventDebugView.RotaryInputValueView(context);
+        mRotaryInputGraphView = new FocusEventDebugView.RotaryInputGraphView(context);
+        mFocusEventDebugView = new FocusEventDebugView(context, mockService,
+                () -> mRotaryInputValueView, () -> mRotaryInputGraphView);
+    }
+
+    @Test
+    public void startsRotaryInputValueViewWithDefaultValue() {
+        assertEquals("+0.0", mRotaryInputValueView.getText());
+    }
+
+    @Test
+    public void startsRotaryInputGraphViewWithDefaultFrameCenter() {
+        assertEquals(0, mRotaryInputGraphView.getFrameCenterPosition(), 0.01);
+    }
+
+    @Test
+    public void handleRotaryInput_updatesRotaryInputValueViewWithScrollValue() {
+        mFocusEventDebugView.handleUpdateShowRotaryInput(true);
+
+        mFocusEventDebugView.handleRotaryInput(createRotaryMotionEvent(0.5f));
+
+        assertEquals(String.format("+%.1f", 0.5f * mScaledVerticalScrollFactor),
+                mRotaryInputValueView.getText());
+    }
+
+    @Test
+    public void handleRotaryInput_translatesRotaryInputGraphViewWithHighScrollValue() {
+        mFocusEventDebugView.handleUpdateShowRotaryInput(true);
+
+        mFocusEventDebugView.handleRotaryInput(createRotaryMotionEvent(1000f));
+
+        assertTrue(mRotaryInputGraphView.getFrameCenterPosition() > 0);
+    }
+
+    @Test
+    public void updateActivityStatus_setsAndRemovesColorFilter() {
+        // It should not be active initially.
+        assertNull(mRotaryInputValueView.getBackground().getColorFilter());
+
+        mRotaryInputValueView.updateActivityStatus(true);
+        // It should be active after rotary input.
+        assertNotNull(mRotaryInputValueView.getBackground().getColorFilter());
+
+        mRotaryInputValueView.updateActivityStatus(false);
+        // It should not be active after waiting for mUpdateActivityStatusCallback.
+        assertNull(mRotaryInputValueView.getBackground().getColorFilter());
+    }
+
+    private MotionEvent createRotaryMotionEvent(float scrollAxisValue) {
+        PointerCoords pointerCoords = new PointerCoords();
+        pointerCoords.setAxisValue(MotionEvent.AXIS_SCROLL, scrollAxisValue);
+        PointerProperties pointerProperties = new PointerProperties();
+
+        return MotionEvent.obtain(
+                /* downTime */ 0,
+                /* eventTime */ 0,
+                /* action */ MotionEvent.ACTION_SCROLL,
+                /* pointerCount */ 1,
+                /* pointerProperties */ new PointerProperties[] {pointerProperties},
+                /* pointerCoords */ new PointerCoords[] {pointerCoords},
+                /* metaState */ 0,
+                /* buttonState */ 0,
+                /* xPrecision */ 0,
+                /* yPrecision */ 0,
+                /* deviceId */ 0,
+                /* edgeFlags */ 0,
+                /* source */ InputDevice.SOURCE_ROTARY_ENCODER,
+                /* flags */ 0
+        );
+    }
+}
diff --git a/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt b/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt
index 56b0b9a..b39c932 100644
--- a/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt
+++ b/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt
@@ -123,10 +123,6 @@
             createImeSubtype(3, ULocale.forLanguageTag("en-US"), "qwerty"),
             KeyboardLayout(null, "German", null, 0, null, 0, 0, 0),
             KeyboardMetricsCollector.LAYOUT_SELECTION_CRITERIA_DEVICE
-        ).addLayoutSelection(
-            createImeSubtype(4, null, "qwerty"), // Default language tag
-            KeyboardLayout(null, "German", null, 0, null, 0, 0, 0),
-            KeyboardMetricsCollector.LAYOUT_SELECTION_CRITERIA_DEVICE
         ).setIsFirstTimeConfiguration(true).build()
 
         assertEquals(
@@ -142,8 +138,8 @@
         assertTrue(event.isFirstConfiguration)
 
         assertEquals(
-            "KeyboardConfigurationEvent should contain 4 configurations provided",
-            4,
+            "KeyboardConfigurationEvent should contain 3 configurations provided",
+            3,
             event.layoutConfigurations.size
         )
         assertExpectedLayoutConfiguration(
@@ -159,7 +155,7 @@
             event.layoutConfigurations[1],
             "de-CH",
             KeyboardLayout.LayoutType.getLayoutTypeEnumValue("qwertz"),
-            KeyboardMetricsCollector.DEFAULT_LAYOUT,
+            KeyboardMetricsCollector.DEFAULT_LAYOUT_NAME,
             KeyboardMetricsCollector.LAYOUT_SELECTION_CRITERIA_USER,
             "en-US",
             KeyboardLayout.LayoutType.getLayoutTypeEnumValue("azerty"),
@@ -173,10 +169,29 @@
             "en-US",
             KeyboardLayout.LayoutType.getLayoutTypeEnumValue("qwerty"),
         )
+    }
+
+    @Test
+    fun testCreateKeyboardConfigurationEvent_withDefaultLanguageTag() {
+        val builder = KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder(
+            createKeyboard(
+                DEVICE_ID,
+                DEFAULT_VENDOR_ID,
+                DEFAULT_PRODUCT_ID,
+                "und", // Undefined language tag
+                "azerty"
+            )
+        )
+        val event = builder.addLayoutSelection(
+            createImeSubtype(4, null, "qwerty"), // Default language tag
+            KeyboardLayout(null, "German", null, 0, null, 0, 0, 0),
+            KeyboardMetricsCollector.LAYOUT_SELECTION_CRITERIA_DEVICE
+        ).build()
+
         assertExpectedLayoutConfiguration(
-            event.layoutConfigurations[3],
-            "de-CH",
-            KeyboardLayout.LayoutType.getLayoutTypeEnumValue("qwertz"),
+            event.layoutConfigurations[0],
+            KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG,
+            KeyboardLayout.LayoutType.getLayoutTypeEnumValue("azerty"),
             "German",
             KeyboardMetricsCollector.LAYOUT_SELECTION_CRITERIA_DEVICE,
             KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG,
diff --git a/tests/Input/src/com/android/test/input/AnrTest.kt b/tests/Input/src/com/android/test/input/AnrTest.kt
index 5719273..4893d14 100644
--- a/tests/Input/src/com/android/test/input/AnrTest.kt
+++ b/tests/Input/src/com/android/test/input/AnrTest.kt
@@ -134,7 +134,7 @@
     private fun getExitReasons(): List<ApplicationExitInfo> {
         lateinit var infos: List<ApplicationExitInfo>
         instrumentation.runOnMainSync {
-            val am = instrumentation.getContext().getSystemService(ActivityManager::class.java)
+            val am = instrumentation.getContext().getSystemService(ActivityManager::class.java)!!
             infos = am.getHistoricalProcessExitReasons(PACKAGE_NAME, ALL_PIDS, NO_MAX)
         }
         return infos
diff --git a/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt b/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt
index 3a24406..e56ce81 100644
--- a/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt
+++ b/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt
@@ -48,6 +48,6 @@
         val inputManager = getSystemService(InputManager::class.java)
         mInputMonitor = inputManager.monitorGestureInput(MONITOR_NAME, displayId)
         mInputEventReceiver = UnresponsiveReceiver(
-                mInputMonitor.getInputChannel(), Looper.myLooper())
+                mInputMonitor.getInputChannel(), Looper.myLooper()!!)
     }
 }
diff --git a/tests/Internal/src/com/android/internal/app/LocaleStoreTest.java b/tests/Internal/src/com/android/internal/app/LocaleStoreTest.java
index f656881..c0d7cb4 100644
--- a/tests/Internal/src/com/android/internal/app/LocaleStoreTest.java
+++ b/tests/Internal/src/com/android/internal/app/LocaleStoreTest.java
@@ -63,6 +63,25 @@
     }
 
     @Test
+    public void testTransformImeLanguageTagToLocaleInfo_duplicateTagFilter() {
+        List<InputMethodSubtype> list = List.of(
+                new InputMethodSubtypeBuilder().setLanguageTag("en-US").build(),
+                new InputMethodSubtypeBuilder().setLanguageTag("en-US").build(),
+                new InputMethodSubtypeBuilder().setLanguageTag("en-US").build(),
+                new InputMethodSubtypeBuilder().setLanguageTag("zh-TW").build(),
+                new InputMethodSubtypeBuilder().setLanguageTag("ja-JP").build());
+
+        Set<LocaleInfo> localeSet = LocaleStore.transformImeLanguageTagToLocaleInfo(list);
+
+        Set<String> expectedLanguageTag = Set.of("en-US", "zh-TW", "ja-JP");
+        assertEquals(localeSet.size(), expectedLanguageTag.size());
+        for (LocaleInfo info : localeSet) {
+            assertEquals(info.mSuggestionFlags, LocaleInfo.SUGGESTION_TYPE_IME_LANGUAGE);
+            assertTrue(expectedLanguageTag.contains(info.getId()));
+        }
+    }
+
+    @Test
     public void convertExplicitLocales_noExplicitLcoales_returnEmptyHashMap() {
         Collection<LocaleInfo> supportedLocale = getFakeSupportedLocales();
 
diff --git a/tests/SilkFX/src/com/android/test/silkfx/hdr/GainmapImage.kt b/tests/SilkFX/src/com/android/test/silkfx/hdr/GainmapImage.kt
index 31ea832..c92d768 100644
--- a/tests/SilkFX/src/com/android/test/silkfx/hdr/GainmapImage.kt
+++ b/tests/SilkFX/src/com/android/test/silkfx/hdr/GainmapImage.kt
@@ -16,10 +16,6 @@
 
 package com.android.test.silkfx.hdr
 
-import android.animation.AnimatorSet
-import android.animation.ObjectAnimator
-import android.animation.ValueAnimator
-import android.animation.ValueAnimator.AnimatorUpdateListener
 import android.content.Context
 import android.graphics.Bitmap
 import android.graphics.Canvas
@@ -46,7 +42,7 @@
     private var selectedImage = -1
     private var outputMode = R.id.output_hdr
     private var bitmap: Bitmap? = null
-    private var gainmap: Gainmap? = null
+    private var originalGainmap: Gainmap? = null
     private var gainmapVisualizer: Bitmap? = null
     private lateinit var imageView: SubsamplingScaleImageView
     private lateinit var gainmapMetadataEditor: GainmapMetadataEditor
@@ -70,7 +66,6 @@
             it.check(outputMode)
             it.setOnCheckedChangeListener { _, checkedId ->
                 outputMode = checkedId
-                // Intentionally don't do anything fancy so that mode A/B comparisons are easy
                 updateDisplay()
             }
         }
@@ -101,41 +96,10 @@
 
         imageView.apply {
             isClickable = true
-            // Example of animating between SDR and HDR using gainmap params; animates HDR->SDR->HDR
-            // with a brief pause on SDR. The key thing here is that the gainmap's
-            // minDisplayRatioForHdrTransition is animated between its original value (for full HDR)
-            // and displayRatioForFullHdr (for full SDR). The view must also be invalidated during
-            // the animation for the updates to take effect.
             setOnClickListener {
-                if (gainmap != null && (outputMode == R.id.output_hdr ||
-                                        outputMode == R.id.output_hdr_test)) {
-                    val animationLengthMs: Long = 500
-                    val updateListener = object : AnimatorUpdateListener {
-                        override fun onAnimationUpdate(animation: ValueAnimator) {
-                            imageView.invalidate()
-                        }
-                    }
-                    val hdrToSdr = ObjectAnimator.ofFloat(
-                      gainmap, "minDisplayRatioForHdrTransition",
-                      gainmap!!.minDisplayRatioForHdrTransition,
-                      gainmap!!.displayRatioForFullHdr).apply {
-                        duration = animationLengthMs
-                        addUpdateListener(updateListener)
-                    }
-                    val sdrToHdr = ObjectAnimator.ofFloat(
-                      gainmap, "minDisplayRatioForHdrTransition",
-                      gainmap!!.displayRatioForFullHdr,
-                      gainmap!!.minDisplayRatioForHdrTransition).apply {
-                        duration = animationLengthMs
-                        addUpdateListener(updateListener)
-                    }
-
-                    AnimatorSet().apply {
-                        play(hdrToSdr)
-                        play(sdrToHdr).after(animationLengthMs)
-                        start()
-                    }
-                }
+                animate().alpha(.5f).withEndAction {
+                    animate().alpha(1f).start()
+                }.start()
             }
         }
     }
@@ -149,7 +113,7 @@
     }
 
     private fun doDecode(source: ImageDecoder.Source) {
-        gainmap = null
+        originalGainmap = null
         bitmap = ImageDecoder.decodeBitmap(source) { decoder, info, source ->
             decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
         }
@@ -167,9 +131,10 @@
             findViewById<TextView>(R.id.error_msg)!!.visibility = View.GONE
             findViewById<RadioGroup>(R.id.output_mode)!!.visibility = View.VISIBLE
 
-            gainmap = bitmap!!.gainmap
-            gainmapMetadataEditor.setGainmap(gainmap)
-            val map = gainmap!!.gainmapContents
+            val gainmap = bitmap!!.gainmap!!
+            originalGainmap = gainmap
+            gainmapMetadataEditor.setGainmap(Gainmap(gainmap, gainmap.gainmapContents))
+            val map = gainmap.gainmapContents
             if (map.config != Bitmap.Config.ALPHA_8) {
                 gainmapVisualizer = map
             } else {
@@ -198,14 +163,12 @@
 
         imageView.setImage(ImageSource.cachedBitmap(when (outputMode) {
             R.id.output_hdr -> {
-                gainmapMetadataEditor.useOriginalMetadata()
-                bitmap!!.gainmap = gainmap
+                bitmap!!.gainmap = originalGainmap
                 bitmap!!
             }
 
             R.id.output_hdr_test -> {
-                gainmapMetadataEditor.useEditMetadata()
-                bitmap!!.gainmap = gainmap
+                bitmap!!.gainmap = gainmapMetadataEditor.editedGainmap()
                 bitmap!!
             }
 
diff --git a/tests/SilkFX/src/com/android/test/silkfx/hdr/GainmapMetadataEditor.kt b/tests/SilkFX/src/com/android/test/silkfx/hdr/GainmapMetadataEditor.kt
index 8a65304..c4bc600 100644
--- a/tests/SilkFX/src/com/android/test/silkfx/hdr/GainmapMetadataEditor.kt
+++ b/tests/SilkFX/src/com/android/test/silkfx/hdr/GainmapMetadataEditor.kt
@@ -28,23 +28,27 @@
 import com.android.test.silkfx.R
 
 data class GainmapMetadata(
-    var ratioMin: Float,
-    var ratioMax: Float,
-    var capacityMin: Float,
-    var capacityMax: Float,
-    var gamma: Float,
-    var offsetSdr: Float,
-    var offsetHdr: Float
+        var ratioMin: Float,
+        var ratioMax: Float,
+        var capacityMin: Float,
+        var capacityMax: Float,
+        var gamma: Float,
+        var offsetSdr: Float,
+        var offsetHdr: Float
 )
 
+/**
+ * Note: This can only handle single-channel gainmaps nicely. It will force all 3-channel
+ * metadata to have the same value single value and is not intended to be a robust demonstration
+ * of gainmap metadata editing
+ */
 class GainmapMetadataEditor(val parent: ViewGroup, val renderView: View) {
-    private var gainmap: Gainmap? = null
-    private var showingEdits = false
+    private lateinit var gainmap: Gainmap
 
     private var metadataPopup: PopupWindow? = null
 
     private var originalMetadata: GainmapMetadata = GainmapMetadata(
-        1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f)
+            1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f)
     private var currentMetadata: GainmapMetadata = originalMetadata.copy()
 
     private val maxProgress = 100.0f
@@ -61,23 +65,18 @@
     private val maxGamma = 3.0f
     // Min and max offsets are 0.0 and 1.0 respectively
 
-    fun setGainmap(newGainmap: Gainmap?) {
+    fun setGainmap(newGainmap: Gainmap) {
         gainmap = newGainmap
-        originalMetadata = GainmapMetadata(gainmap!!.getRatioMin()[0],
-            gainmap!!.getRatioMax()[0], gainmap!!.getMinDisplayRatioForHdrTransition(),
-            gainmap!!.getDisplayRatioForFullHdr(), gainmap!!.getGamma()[0],
-            gainmap!!.getEpsilonSdr()[0], gainmap!!.getEpsilonHdr()[0])
+        originalMetadata = GainmapMetadata(gainmap.getRatioMin()[0],
+                gainmap.getRatioMax()[0], gainmap.getMinDisplayRatioForHdrTransition(),
+                gainmap.getDisplayRatioForFullHdr(), gainmap.getGamma()[0],
+                gainmap.getEpsilonSdr()[0], gainmap.getEpsilonHdr()[0])
         currentMetadata = originalMetadata.copy()
     }
 
-    fun useOriginalMetadata() {
-        showingEdits = false
-        applyMetadata(originalMetadata)
-    }
-
-    fun useEditMetadata() {
-        showingEdits = true
+    fun editedGainmap(): Gainmap {
         applyMetadata(currentMetadata)
+        return gainmap
     }
 
     fun closeEditor() {
@@ -93,7 +92,7 @@
         val view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gainmap_metadata, null)
 
         metadataPopup = PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT,
-            ViewGroup.LayoutParams.WRAP_CONTENT)
+                ViewGroup.LayoutParams.WRAP_CONTENT)
         metadataPopup!!.showAtLocation(view, Gravity.CENTER, 0, 0)
 
         (view.getParent() as ViewGroup).removeView(view)
@@ -117,7 +116,7 @@
         val offsetSdrSeek = view.findViewById<SeekBar>(R.id.gainmap_metadata_offsetsdr)
         val offsetHdrSeek = view.findViewById<SeekBar>(R.id.gainmap_metadata_offsethdr)
         arrayOf(gainmapMinSeek, gainmapMaxSeek, capacityMinSeek, capacityMaxSeek, gammaSeek,
-            offsetSdrSeek, offsetHdrSeek).forEach {
+                offsetSdrSeek, offsetHdrSeek).forEach {
             it.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
                 override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                     if (!fromUser) return
@@ -149,37 +148,37 @@
         val offsetHdrSeek = parent.findViewById<SeekBar>(R.id.gainmap_metadata_offsethdr)
 
         gainmapMinSeek.setProgress(
-            ((currentMetadata.ratioMin - minRatioMin) / maxRatioMin * maxProgress).toInt())
+                ((currentMetadata.ratioMin - minRatioMin) / maxRatioMin * maxProgress).toInt())
         gainmapMaxSeek.setProgress(
-            ((currentMetadata.ratioMax - minRatioMax) / maxRatioMax * maxProgress).toInt())
+                ((currentMetadata.ratioMax - minRatioMax) / maxRatioMax * maxProgress).toInt())
         capacityMinSeek.setProgress(
-            ((currentMetadata.capacityMin - minCapacityMin) / maxCapacityMin * maxProgress).toInt())
+                ((currentMetadata.capacityMin - minCapacityMin) / maxCapacityMin * maxProgress).toInt())
         capacityMaxSeek.setProgress(
-            ((currentMetadata.capacityMax - minCapacityMax) / maxCapacityMax * maxProgress).toInt())
+                ((currentMetadata.capacityMax - minCapacityMax) / maxCapacityMax * maxProgress).toInt())
         gammaSeek.setProgress(
-            ((currentMetadata.gamma - minGamma) / maxGamma * maxProgress).toInt())
+                ((currentMetadata.gamma - minGamma) / maxGamma * maxProgress).toInt())
         // Log base 3 via: log_b(x) = log_y(x) / log_y(b)
         offsetSdrSeek.setProgress(
-            ((1.0 - Math.log(currentMetadata.offsetSdr.toDouble() / Math.log(3.0)) / -11.0)
-             .toFloat() * maxProgress).toInt())
+                ((1.0 - Math.log(currentMetadata.offsetSdr.toDouble() / Math.log(3.0)) / -11.0)
+                        .toFloat() * maxProgress).toInt())
         offsetHdrSeek.setProgress(
-            ((1.0 - Math.log(currentMetadata.offsetHdr.toDouble() / Math.log(3.0)) / -11.0)
-             .toFloat() * maxProgress).toInt())
+                ((1.0 - Math.log(currentMetadata.offsetHdr.toDouble() / Math.log(3.0)) / -11.0)
+                        .toFloat() * maxProgress).toInt())
 
         parent.findViewById<TextView>(R.id.gainmap_metadata_gainmapmin_val)!!.setText(
-            "%.3f".format(currentMetadata.ratioMin))
+                "%.3f".format(currentMetadata.ratioMin))
         parent.findViewById<TextView>(R.id.gainmap_metadata_gainmapmax_val)!!.setText(
-            "%.3f".format(currentMetadata.ratioMax))
+                "%.3f".format(currentMetadata.ratioMax))
         parent.findViewById<TextView>(R.id.gainmap_metadata_capacitymin_val)!!.setText(
-            "%.3f".format(currentMetadata.capacityMin))
+                "%.3f".format(currentMetadata.capacityMin))
         parent.findViewById<TextView>(R.id.gainmap_metadata_capacitymax_val)!!.setText(
-            "%.3f".format(currentMetadata.capacityMax))
+                "%.3f".format(currentMetadata.capacityMax))
         parent.findViewById<TextView>(R.id.gainmap_metadata_gamma_val)!!.setText(
-            "%.3f".format(currentMetadata.gamma))
+                "%.3f".format(currentMetadata.gamma))
         parent.findViewById<TextView>(R.id.gainmap_metadata_offsetsdr_val)!!.setText(
-            "%.5f".format(currentMetadata.offsetSdr))
+                "%.5f".format(currentMetadata.offsetSdr))
         parent.findViewById<TextView>(R.id.gainmap_metadata_offsethdr_val)!!.setText(
-            "%.5f".format(currentMetadata.offsetHdr))
+                "%.5f".format(currentMetadata.offsetHdr))
     }
 
     private fun resetGainmapMetadata() {
@@ -189,69 +188,59 @@
     }
 
     private fun applyMetadata(newMetadata: GainmapMetadata) {
-        gainmap!!.setRatioMin(newMetadata.ratioMin, newMetadata.ratioMin, newMetadata.ratioMin)
-        gainmap!!.setRatioMax(newMetadata.ratioMax, newMetadata.ratioMax, newMetadata.ratioMax)
-        gainmap!!.setMinDisplayRatioForHdrTransition(newMetadata.capacityMin)
-        gainmap!!.setDisplayRatioForFullHdr(newMetadata.capacityMax)
-        gainmap!!.setGamma(newMetadata.gamma, newMetadata.gamma, newMetadata.gamma)
-        gainmap!!.setEpsilonSdr(newMetadata.offsetSdr, newMetadata.offsetSdr, newMetadata.offsetSdr)
-        gainmap!!.setEpsilonHdr(newMetadata.offsetHdr, newMetadata.offsetHdr, newMetadata.offsetHdr)
+        gainmap.setRatioMin(newMetadata.ratioMin, newMetadata.ratioMin, newMetadata.ratioMin)
+        gainmap.setRatioMax(newMetadata.ratioMax, newMetadata.ratioMax, newMetadata.ratioMax)
+        gainmap.setMinDisplayRatioForHdrTransition(newMetadata.capacityMin)
+        gainmap.setDisplayRatioForFullHdr(newMetadata.capacityMax)
+        gainmap.setGamma(newMetadata.gamma, newMetadata.gamma, newMetadata.gamma)
+        gainmap.setEpsilonSdr(newMetadata.offsetSdr, newMetadata.offsetSdr, newMetadata.offsetSdr)
+        gainmap.setEpsilonHdr(newMetadata.offsetHdr, newMetadata.offsetHdr, newMetadata.offsetHdr)
         renderView.invalidate()
     }
 
     private fun updateGainmapMin(normalized: Float) {
         val newValue = minRatioMin + normalized * (maxRatioMin - minRatioMin)
         parent.findViewById<TextView>(R.id.gainmap_metadata_gainmapmin_val)!!.setText(
-            "%.3f".format(newValue))
+                "%.3f".format(newValue))
         currentMetadata.ratioMin = newValue
-        if (showingEdits) {
-            gainmap!!.setRatioMin(newValue, newValue, newValue)
-            renderView.invalidate()
-        }
+        gainmap.setRatioMin(newValue, newValue, newValue)
+        renderView.invalidate()
     }
 
     private fun updateGainmapMax(normalized: Float) {
         val newValue = minRatioMax + normalized * (maxRatioMax - minRatioMax)
         parent.findViewById<TextView>(R.id.gainmap_metadata_gainmapmax_val)!!.setText(
-            "%.3f".format(newValue))
+                "%.3f".format(newValue))
         currentMetadata.ratioMax = newValue
-        if (showingEdits) {
-            gainmap!!.setRatioMax(newValue, newValue, newValue)
-            renderView.invalidate()
-        }
+        gainmap.setRatioMax(newValue, newValue, newValue)
+        renderView.invalidate()
     }
 
     private fun updateCapacityMin(normalized: Float) {
         val newValue = minCapacityMin + normalized * (maxCapacityMin - minCapacityMin)
         parent.findViewById<TextView>(R.id.gainmap_metadata_capacitymin_val)!!.setText(
-            "%.3f".format(newValue))
+                "%.3f".format(newValue))
         currentMetadata.capacityMin = newValue
-        if (showingEdits) {
-            gainmap!!.setMinDisplayRatioForHdrTransition(newValue)
-            renderView.invalidate()
-        }
+        gainmap.setMinDisplayRatioForHdrTransition(newValue)
+        renderView.invalidate()
     }
 
     private fun updateCapacityMax(normalized: Float) {
         val newValue = minCapacityMax + normalized * (maxCapacityMax - minCapacityMax)
         parent.findViewById<TextView>(R.id.gainmap_metadata_capacitymax_val)!!.setText(
-            "%.3f".format(newValue))
+                "%.3f".format(newValue))
         currentMetadata.capacityMax = newValue
-        if (showingEdits) {
-            gainmap!!.setDisplayRatioForFullHdr(newValue)
-            renderView.invalidate()
-        }
+        gainmap.setDisplayRatioForFullHdr(newValue)
+        renderView.invalidate()
     }
 
     private fun updateGamma(normalized: Float) {
         val newValue = minGamma + normalized * (maxGamma - minGamma)
         parent.findViewById<TextView>(R.id.gainmap_metadata_gamma_val)!!.setText(
-            "%.3f".format(newValue))
+                "%.3f".format(newValue))
         currentMetadata.gamma = newValue
-        if (showingEdits) {
-            gainmap!!.setGamma(newValue, newValue, newValue)
-            renderView.invalidate()
-        }
+        gainmap.setGamma(newValue, newValue, newValue)
+        renderView.invalidate()
     }
 
     private fun updateOffsetSdr(normalized: Float) {
@@ -260,12 +249,10 @@
             newValue = Math.pow(3.0, (1.0 - normalized.toDouble()) * -11.0).toFloat()
         }
         parent.findViewById<TextView>(R.id.gainmap_metadata_offsetsdr_val)!!.setText(
-            "%.5f".format(newValue))
+                "%.5f".format(newValue))
         currentMetadata.offsetSdr = newValue
-        if (showingEdits) {
-            gainmap!!.setEpsilonSdr(newValue, newValue, newValue)
-            renderView.invalidate()
-        }
+        gainmap.setEpsilonSdr(newValue, newValue, newValue)
+        renderView.invalidate()
     }
 
     private fun updateOffsetHdr(normalized: Float) {
@@ -274,11 +261,9 @@
             newValue = Math.pow(3.0, (1.0 - normalized.toDouble()) * -11.0).toFloat()
         }
         parent.findViewById<TextView>(R.id.gainmap_metadata_offsethdr_val)!!.setText(
-            "%.5f".format(newValue))
+                "%.5f".format(newValue))
         currentMetadata.offsetHdr = newValue
-        if (showingEdits) {
-            gainmap!!.setEpsilonHdr(newValue, newValue, newValue)
-            renderView.invalidate()
-        }
+        gainmap.setEpsilonHdr(newValue, newValue, newValue)
+        renderView.invalidate()
     }
 }
diff --git a/tests/SilkFX/src/com/android/test/silkfx/materials/BackgroundBlurActivity.kt b/tests/SilkFX/src/com/android/test/silkfx/materials/BackgroundBlurActivity.kt
index 9d17d38..4d38660 100644
--- a/tests/SilkFX/src/com/android/test/silkfx/materials/BackgroundBlurActivity.kt
+++ b/tests/SilkFX/src/com/android/test/silkfx/materials/BackgroundBlurActivity.kt
@@ -132,7 +132,7 @@
         mBlurForceDisabled = disabled
         Settings.Global.putInt(getContentResolver(), Settings.Global.DISABLE_WINDOW_BLURS,
                 if (mBlurForceDisabled) 1 else 0)
-        (findViewById(R.id.toggle_blur_enabled) as Button)
+        (requireViewById(R.id.toggle_blur_enabled) as Button)
                 .setText(if (mBlurForceDisabled) "Enable blurs" else "Disable blurs")
     }
 
@@ -142,13 +142,13 @@
 
     fun setBackgroundBlur(radius: Int) {
         mBackgroundBlurRadius = radius
-        (findViewById(R.id.background_blur_radius) as TextView).setText(radius.toString())
+        (requireViewById(R.id.background_blur_radius) as TextView).setText(radius.toString())
         window.setBackgroundBlurRadius(mBackgroundBlurRadius)
     }
 
     fun setBlurBehind(radius: Int) {
         mBlurBehindRadius = radius
-        (findViewById(R.id.blur_behind_radius) as TextView).setText(radius.toString())
+        (requireViewById(R.id.blur_behind_radius) as TextView).setText(radius.toString())
         window.getAttributes().setBlurBehindRadius(mBlurBehindRadius)
         window.setAttributes(window.getAttributes())
     }
@@ -159,7 +159,7 @@
         } else {
             mDimAmountNoBlur = amount
         }
-        (findViewById(R.id.dim_amount) as TextView).setText("%.2f".format(amount))
+        (requireViewById(R.id.dim_amount) as TextView).setText("%.2f".format(amount))
         window.getAttributes().dimAmount = amount
         window.setAttributes(window.getAttributes())
     }
@@ -168,7 +168,7 @@
         mBatterySavingModeOn = on
         Settings.Global.putInt(getContentResolver(),
             Settings.Global.LOW_POWER_MODE, if (on) 1 else 0)
-        (findViewById(R.id.toggle_battery_saving_mode) as Button).setText(
+        (requireViewById(R.id.toggle_battery_saving_mode) as Button).setText(
             if (on) "Exit low power mode" else "Enter low power mode")
     }
 
@@ -182,7 +182,7 @@
         } else {
             mAlphaNoBlur = alpha
         }
-        (findViewById(R.id.background_alpha) as TextView).setText("%.2f".format(alpha))
+        (requireViewById(R.id.background_alpha) as TextView).setText("%.2f".format(alpha))
         mBackgroundDrawable.setAlpha((alpha * 255f).toInt())
         getWindowManager().updateViewLayout(window.getDecorView(), window.getAttributes())
     }
diff --git a/tests/testables/src/android/testing/TestableResources.java b/tests/testables/src/android/testing/TestableResources.java
index 27d5b66..0ec106e 100644
--- a/tests/testables/src/android/testing/TestableResources.java
+++ b/tests/testables/src/android/testing/TestableResources.java
@@ -15,9 +15,11 @@
 package android.testing;
 
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 import static org.mockito.Mockito.withSettings;
 
 import android.content.Context;
+import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.util.Log;
 import android.util.SparseArray;
@@ -54,6 +56,16 @@
     }
 
     /**
+     * Sets a configuration for {@link #getResources()} to return to allow custom configs to
+     * be set and tested.
+     *
+     * @param configuration the configuration to return from resources.
+     */
+    public void overrideConfiguration(Configuration configuration) {
+        when(mResources.getConfiguration()).thenReturn(configuration);
+    }
+
+    /**
      * Sets the return value for the specified resource id.
      * <p>
      * Since resource ids are unique there is a single addOverride that will override the value
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index d02fd83..51cf38b 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -353,8 +353,8 @@
 }
 
 static void printUsesPermission(const String8& name, bool optional=false, int maxSdkVersion=-1,
-        const String8& requiredFeature = String8::empty(),
-        const String8& requiredNotFeature = String8::empty()) {
+        const String8& requiredFeature = String8(),
+        const String8& requiredNotFeature = String8()) {
     printf("uses-permission: name='%s'", ResTable::normalizeForOutput(name.string()).string());
     if (maxSdkVersion != -1) {
          printf(" maxSdkVersion='%d'", maxSdkVersion);
diff --git a/tools/aapt2/trace/TraceBuffer.cpp b/tools/aapt2/trace/TraceBuffer.cpp
index da53739..fab2df3 100644
--- a/tools/aapt2/trace/TraceBuffer.cpp
+++ b/tools/aapt2/trace/TraceBuffer.cpp
@@ -36,13 +36,14 @@
 constexpr char kEnd = 'E';
 
 struct TracePoint {
+  char type;
   pid_t tid;
   int64_t time;
   std::string tag;
-  char type;
 };
 
 std::vector<TracePoint> traces;
+bool enabled = true;
 
 int64_t GetTime() noexcept {
   auto now = std::chrono::steady_clock::now();
@@ -51,34 +52,39 @@
 
 } // namespace anonymous
 
-void AddWithTime(const std::string& tag, char type, int64_t time) noexcept {
-  TracePoint t = {getpid(), time, tag, type};
-  traces.emplace_back(t);
+void AddWithTime(std::string tag, char type, int64_t time) noexcept {
+  TracePoint t = {type, getpid(), time, std::move(tag)};
+  traces.emplace_back(std::move(t));
 }
 
-void Add(const std::string& tag, char type) noexcept {
-  AddWithTime(tag, type, GetTime());
+void Add(std::string tag, char type) noexcept {
+  AddWithTime(std::move(tag), type, GetTime());
 }
 
-
-
-
 void Flush(const std::string& basePath) {
-  TRACE_CALL();
   if (basePath.empty()) {
     return;
   }
+  BeginTrace(__func__);  // We can't do much here, only record that it happened.
 
-  std::stringstream s;
+  std::ostringstream s;
   s << basePath << aapt::file::sDirSep << "report_aapt2_" << getpid() << ".json";
   FILE* f = android::base::utf8::fopen(s.str().c_str(), "a");
   if (f == nullptr) {
     return;
   }
 
+  // Wrap the trace in a JSON array [] to make Chrome/Perfetto UI handle it.
+  char delimiter = '[';
   for(const TracePoint& trace : traces) {
-    fprintf(f, "{\"ts\" : \"%" PRIu64 "\", \"ph\" : \"%c\", \"tid\" : \"%d\" , \"pid\" : \"%d\", "
-            "\"name\" : \"%s\" },\n", trace.time, trace.type, 0, trace.tid, trace.tag.c_str());
+    fprintf(f,
+            "%c{\"ts\" : \"%" PRIu64
+            "\", \"ph\" : \"%c\", \"tid\" : \"%d\" , \"pid\" : \"%d\", \"name\" : \"%s\" }\n",
+            delimiter, trace.time, trace.type, 0, trace.tid, trace.tag.c_str());
+    delimiter = ',';
+  }
+  if (!traces.empty()) {
+    fprintf(f, "]");
   }
   fclose(f);
   traces.clear();
@@ -86,66 +92,82 @@
 
 } // namespace tracebuffer
 
-void BeginTrace(const std::string& tag) {
-  tracebuffer::Add(tag, tracebuffer::kBegin);
+void BeginTrace(std::string tag) {
+  if (!tracebuffer::enabled) return;
+  tracebuffer::Add(std::move(tag), tracebuffer::kBegin);
 }
 
-void EndTrace() {
-  tracebuffer::Add("", tracebuffer::kEnd);
+void EndTrace(std::string tag) {
+  if (!tracebuffer::enabled) return;
+  tracebuffer::Add(std::move(tag), tracebuffer::kEnd);
 }
 
-Trace::Trace(const std::string& tag) {
-  tracebuffer::Add(tag, tracebuffer::kBegin);
+bool Trace::enable(bool value) {
+  return tracebuffer::enabled = value;
 }
 
-Trace::Trace(const std::string& tag, const std::vector<android::StringPiece>& args) {
-  std::stringstream s;
+Trace::Trace(const char* tag) {
+  if (!tracebuffer::enabled) return;
+  tag_.assign(tag);
+  tracebuffer::Add(tag_, tracebuffer::kBegin);
+}
+
+Trace::Trace(std::string tag) : tag_(std::move(tag)) {
+  if (!tracebuffer::enabled) return;
+  tracebuffer::Add(tag_, tracebuffer::kBegin);
+}
+
+template <class SpanOfStrings>
+std::string makeTag(std::string_view tag, const SpanOfStrings& args) {
+  std::ostringstream s;
   s << tag;
-  s << " ";
-  for (auto& arg : args) {
-    s << arg;
-    s << " ";
+  if (!args.empty()) {
+    for (const auto& arg : args) {
+      s << ' ';
+      s << arg;
+    }
   }
-  tracebuffer::Add(s.str(), tracebuffer::kBegin);
+  return std::move(s).str();
+}
+
+Trace::Trace(std::string_view tag, const std::vector<android::StringPiece>& args) {
+  if (!tracebuffer::enabled) return;
+  tag_ = makeTag(tag, args);
+  tracebuffer::Add(tag_, tracebuffer::kBegin);
 }
 
 Trace::~Trace() {
-  tracebuffer::Add("", tracebuffer::kEnd);
+  if (!tracebuffer::enabled) return;
+  tracebuffer::Add(std::move(tag_), tracebuffer::kEnd);
 }
 
-FlushTrace::FlushTrace(const std::string& basepath, const std::string& tag)
-    : basepath_(basepath)  {
-  tracebuffer::Add(tag, tracebuffer::kBegin);
+FlushTrace::FlushTrace(std::string_view basepath, std::string_view tag) {
+  if (!Trace::enable(!basepath.empty())) return;
+  basepath_.assign(basepath);
+  tag_.assign(tag);
+  tracebuffer::Add(tag_, tracebuffer::kBegin);
 }
 
-FlushTrace::FlushTrace(const std::string& basepath, const std::string& tag,
-    const std::vector<android::StringPiece>& args) : basepath_(basepath) {
-  std::stringstream s;
-  s << tag;
-  s << " ";
-  for (auto& arg : args) {
-    s << arg;
-    s << " ";
-  }
-  tracebuffer::Add(s.str(), tracebuffer::kBegin);
+FlushTrace::FlushTrace(std::string_view basepath, std::string_view tag,
+                       const std::vector<android::StringPiece>& args) {
+  if (!Trace::enable(!basepath.empty())) return;
+  basepath_.assign(basepath);
+  tag_ = makeTag(tag, args);
+  tracebuffer::Add(tag_, tracebuffer::kBegin);
 }
 
-FlushTrace::FlushTrace(const std::string& basepath, const std::string& tag,
-    const std::vector<std::string>& args) : basepath_(basepath){
-  std::stringstream s;
-  s << tag;
-  s << " ";
-  for (auto& arg : args) {
-    s << arg;
-    s << " ";
-  }
-  tracebuffer::Add(s.str(), tracebuffer::kBegin);
+FlushTrace::FlushTrace(std::string_view basepath, std::string_view tag,
+                       const std::vector<std::string>& args) {
+  if (!Trace::enable(!basepath.empty())) return;
+  basepath_.assign(basepath);
+  tag_ = makeTag(tag, args);
+  tracebuffer::Add(tag_, tracebuffer::kBegin);
 }
 
 FlushTrace::~FlushTrace() {
-  tracebuffer::Add("", tracebuffer::kEnd);
+  if (!tracebuffer::enabled) return;
+  tracebuffer::Add(tag_, tracebuffer::kEnd);
   tracebuffer::Flush(basepath_);
 }
 
-} // namespace aapt
-
+}  // namespace aapt
diff --git a/tools/aapt2/trace/TraceBuffer.h b/tools/aapt2/trace/TraceBuffer.h
index ba751dd..f0333d1 100644
--- a/tools/aapt2/trace/TraceBuffer.h
+++ b/tools/aapt2/trace/TraceBuffer.h
@@ -17,41 +17,50 @@
 #ifndef AAPT_TRACEBUFFER_H
 #define AAPT_TRACEBUFFER_H
 
-#include <string>
-#include <vector>
-
 #include <androidfw/StringPiece.h>
 
+#include <string>
+#include <string_view>
+#include <vector>
+
 namespace aapt {
 
 // Record timestamps for beginning and end of a task and generate systrace json fragments.
 // This is an in-process ftrace which has the advantage of being platform independent.
 // These methods are NOT thread-safe since aapt2 is not multi-threaded.
 
-// Convenience RIAA object to automatically finish an event when object goes out of scope.
+// Convenience RAII object to automatically finish an event when object goes out of scope.
 class Trace {
 public:
-  Trace(const std::string& tag);
-  Trace(const std::string& tag, const std::vector<android::StringPiece>& args);
-  ~Trace();
+ Trace(const char* tag);
+ Trace(std::string tag);
+ Trace(std::string_view tag, const std::vector<android::StringPiece>& args);
+ ~Trace();
+
+ static bool enable(bool value = true);
+
+private:
+ std::string tag_;
 };
 
 // Manual markers.
-void BeginTrace(const std::string& tag);
-void EndTrace();
+void BeginTrace(std::string tag);
+void EndTrace(std::string tag);
 
 // A main trace is required to flush events to disk. Events are formatted in systrace
 // json format.
 class FlushTrace {
 public:
-  explicit FlushTrace(const std::string& basepath, const std::string& tag);
-  explicit FlushTrace(const std::string& basepath, const std::string& tag,
-      const std::vector<android::StringPiece>& args);
-  explicit FlushTrace(const std::string& basepath, const std::string& tag,
-      const std::vector<std::string>& args);
-  ~FlushTrace();
+ explicit FlushTrace(std::string_view basepath, std::string_view tag);
+ explicit FlushTrace(std::string_view basepath, std::string_view tag,
+                     const std::vector<android::StringPiece>& args);
+ explicit FlushTrace(std::string_view basepath, std::string_view tag,
+                     const std::vector<std::string>& args);
+ ~FlushTrace();
+
 private:
   std::string basepath_;
+  std::string tag_;
 };
 
 #define TRACE_CALL() Trace __t(__func__)
diff --git a/tools/hiddenapi/OWNERS b/tools/hiddenapi/OWNERS
index afbeef5..dc82aac 100644
--- a/tools/hiddenapi/OWNERS
+++ b/tools/hiddenapi/OWNERS
@@ -1,5 +1,4 @@
 # compat-team@ for changes to hiddenapi files
-andreionea@google.com
 mathewi@google.com
 satayev@google.com
 
diff --git a/wifi/java/src/android/net/wifi/sharedconnectivity/app/SharedConnectivitySettingsState.java b/wifi/java/src/android/net/wifi/sharedconnectivity/app/SharedConnectivitySettingsState.java
index 5ad3ede..c828de9f 100644
--- a/wifi/java/src/android/net/wifi/sharedconnectivity/app/SharedConnectivitySettingsState.java
+++ b/wifi/java/src/android/net/wifi/sharedconnectivity/app/SharedConnectivitySettingsState.java
@@ -196,7 +196,7 @@
     public String toString() {
         return new StringBuilder("SharedConnectivitySettingsState[")
                 .append("instantTetherEnabled=").append(mInstantTetherEnabled)
-                .append("PendingIntent=").append(mInstantTetherSettingsPendingIntent.toString())
+                .append("PendingIntent=").append(mInstantTetherSettingsPendingIntent)
                 .append("extras=").append(mExtras.toString())
                 .append("]").toString();
     }