Merge "Disable TARE."
diff --git a/apex/jobscheduler/service/java/com/android/server/job/PendingJobQueue.java b/apex/jobscheduler/service/java/com/android/server/job/PendingJobQueue.java
index 0a305a2..4f4096f 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/PendingJobQueue.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/PendingJobQueue.java
@@ -219,6 +219,8 @@
             ajq.clear();
             mAppJobQueuePool.release(ajq);
         } else if (prevTimestamp != ajq.peekNextTimestamp()) {
+            // Removing the job changed the "next timestamp" in the queue, so we need to reinsert
+            // it to fix the ordering.
             mOrderedQueues.remove(ajq);
             mOrderedQueues.offer(ajq);
         }
diff --git a/core/api/current.txt b/core/api/current.txt
index 0dcb177..7bdbd7b 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -42875,6 +42875,7 @@
     field public static final String KEY_PREMIUM_CAPABILITY_SUPPORTED_ON_LTE_BOOL = "premium_capability_supported_on_lte_bool";
     field public static final String KEY_PREVENT_CLIR_ACTIVATION_AND_DEACTIVATION_CODE_BOOL = "prevent_clir_activation_and_deactivation_code_bool";
     field public static final String KEY_RADIO_RESTART_FAILURE_CAUSES_INT_ARRAY = "radio_restart_failure_causes_int_array";
+    field public static final String KEY_RATCHET_NR_ADVANCED_BANDWIDTH_IF_RRC_IDLE_BOOL = "ratchet_nr_advanced_bandwidth_if_rrc_idle_bool";
     field public static final String KEY_RCS_CONFIG_SERVER_URL_STRING = "rcs_config_server_url_string";
     field public static final String KEY_READ_ONLY_APN_FIELDS_STRING_ARRAY = "read_only_apn_fields_string_array";
     field public static final String KEY_READ_ONLY_APN_TYPES_STRING_ARRAY = "read_only_apn_types_string_array";
diff --git a/core/java/android/app/PendingIntent.java b/core/java/android/app/PendingIntent.java
index dd44531..e1ee3e0 100644
--- a/core/java/android/app/PendingIntent.java
+++ b/core/java/android/app/PendingIntent.java
@@ -57,7 +57,6 @@
 import android.util.ArraySet;
 import android.util.Log;
 import android.util.Pair;
-import android.util.Slog;
 import android.util.proto.ProtoOutputStream;
 
 import com.android.internal.annotations.GuardedBy;
@@ -430,10 +429,9 @@
         }
 
         // Whenever creation or retrieval of a mutable implicit PendingIntent occurs:
-        // - For apps with target SDK >= U, Log.wtfStack() that it is blocked for security reasons.
-        //   This will be changed to a throw of an exception on the server side once we finish
-        //   migrating to safer PendingIntents b/262253127.
-        // - Otherwise, warn that it will be blocked from target SDK U.
+        // - For apps with target SDK >= U, throw an IllegalArgumentException for
+        //   security reasons.
+        // - Otherwise, warn that it will be blocked from target SDK U onwards.
         if (isNewMutableDisallowedImplicitPendingIntent(flags, intent)) {
             if (Compatibility.isChangeEnabled(BLOCK_MUTABLE_IMPLICIT_PENDING_INTENT)) {
                 String msg = packageName + ": Targeting U+ (version "
@@ -445,7 +443,7 @@
                         + " PendingIntent, use FLAG_NO_CREATE, however, to create a"
                         + " new PendingIntent with an implicit Intent use"
                         + " FLAG_IMMUTABLE.";
-                Slog.wtfStack(TAG, msg);
+                throw new IllegalArgumentException(msg);
             } else {
                 String msg = "New mutable implicit PendingIntent: pkg=" + packageName
                         + ", action=" + intent.getAction()
diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java
index 1f5182a..52d1d68 100644
--- a/core/java/android/app/SystemServiceRegistry.java
+++ b/core/java/android/app/SystemServiceRegistry.java
@@ -510,11 +510,12 @@
                 return new BinaryTransparencyManager(ctx, service);
             }});
 
+        // InputManager stores its own static instance for historical purposes.
         registerService(Context.INPUT_SERVICE, InputManager.class,
-                new StaticServiceFetcher<InputManager>() {
+                new ServiceFetcher<InputManager>() {
             @Override
-            public InputManager createService() {
-                return InputManager.getInstance();
+            public InputManager getService(ContextImpl ctx) {
+                return InputManager.getInstance(ctx);
             }});
 
         registerService(Context.DISPLAY_SERVICE, DisplayManager.class,
diff --git a/core/java/android/content/pm/ActivityInfo.java b/core/java/android/content/pm/ActivityInfo.java
index e803084..e7bac02 100644
--- a/core/java/android/content/pm/ActivityInfo.java
+++ b/core/java/android/content/pm/ActivityInfo.java
@@ -1234,6 +1234,56 @@
     @Overridable
     public static final long OVERRIDE_ENABLE_COMPAT_FAKE_FOCUS = 263259275L;
 
+    // Compat framework that per-app overrides rely on only supports booleans. That's why we have
+    // multiple OVERRIDE_*_ORIENTATION_* change ids below instead of just one override with
+    // the integer value.
+
+    /**
+     * Enables {@link #SCREEN_ORIENTATION_PORTRAIT}. Unless OVERRIDE_ANY_ORIENTATION
+     * is enabled, this override is used only when no other fixed orientation was specified by the
+     * activity.
+     * @hide
+     */
+    @ChangeId
+    @Disabled
+    @Overridable
+    public static final long OVERRIDE_UNDEFINED_ORIENTATION_TO_PORTRAIT = 265452344L;
+
+    /**
+     * Enables {@link #SCREEN_ORIENTATION_NOSENSOR}. Unless OVERRIDE_ANY_ORIENTATION
+     * is enabled, this override is used only when no other fixed orientation was specified by the
+     * activity.
+     * @hide
+     */
+    @ChangeId
+    @Disabled
+    @Overridable
+    public static final long OVERRIDE_UNDEFINED_ORIENTATION_TO_NOSENSOR = 265451093L;
+
+    /**
+     * Enables {@link #SCREEN_ORIENTATION_REVERSE_LANDSCAPE}. Unless OVERRIDE_ANY_ORIENTATION
+     * is enabled, this override is used only when activity specify landscape orientation.
+     * This can help apps that assume that landscape display orientation corresponds to {@link
+     * android.view.Surface#ROTATION_90}, while on some devices it can be {@link
+     * android.view.Surface#ROTATION_270}.
+     * @hide
+     */
+    @ChangeId
+    @Disabled
+    @Overridable
+    public static final long OVERRIDE_LANDSCAPE_ORIENTATION_TO_REVERSE_LANDSCAPE = 266124927L;
+
+    /**
+     * When enabled, allows OVERRIDE_LANDSCAPE_ORIENTATION_TO_REVERSE_LANDSCAPE,
+     * OVERRIDE_UNDEFINED_ORIENTATION_TO_NOSENSOR and OVERRIDE_UNDEFINED_ORIENTATION_TO_PORTRAIT
+     * to override any orientation requested by the activity.
+     * @hide
+     */
+    @ChangeId
+    @Disabled
+    @Overridable
+    public static final long OVERRIDE_ANY_ORIENTATION = 265464455L;
+
     /**
      * Compares activity window layout min width/height with require space for multi window to
      * determine if it can be put into multi window mode.
@@ -1453,8 +1503,19 @@
      * @hide
      */
     public boolean isFixedOrientation() {
-        return isFixedOrientationLandscape() || isFixedOrientationPortrait()
-                || screenOrientation == SCREEN_ORIENTATION_LOCKED;
+        return isFixedOrientation(screenOrientation);
+    }
+
+    /**
+     * Returns true if the passed activity's orientation is fixed.
+     * @hide
+     */
+    public static boolean isFixedOrientation(@ScreenOrientation int orientation) {
+        return orientation == SCREEN_ORIENTATION_LOCKED
+                // Orientation is fixed to natural display orientation
+                || orientation == SCREEN_ORIENTATION_NOSENSOR
+                || isFixedOrientationLandscape(orientation)
+                || isFixedOrientationPortrait(orientation);
     }
 
     /**
diff --git a/core/java/android/hardware/display/DisplayManagerInternal.java b/core/java/android/hardware/display/DisplayManagerInternal.java
index 7409187..9a092a5 100644
--- a/core/java/android/hardware/display/DisplayManagerInternal.java
+++ b/core/java/android/hardware/display/DisplayManagerInternal.java
@@ -21,6 +21,7 @@
 import android.companion.virtual.IVirtualDevice;
 import android.graphics.Point;
 import android.hardware.SensorManager;
+import android.hardware.input.HostUsiVersion;
 import android.os.Handler;
 import android.os.PowerManager;
 import android.util.IntArray;
@@ -403,6 +404,14 @@
     public abstract SurfaceControl.DisplayPrimaries getDisplayNativePrimaries(int displayId);
 
     /**
+     * Get the version of the Universal Stylus Initiative (USI) Protocol supported by the display.
+     * @param displayId The id of the display.
+     * @return The USI version, or null if not supported
+     */
+    @Nullable
+    public abstract HostUsiVersion getHostUsiVersion(int displayId);
+
+    /**
      * Describes the requested power state of the display.
      *
      * This object is intended to describe the general characteristics of the
diff --git a/core/java/android/hardware/input/IInputManager.aidl b/core/java/android/hardware/input/IInputManager.aidl
index 222cf08..c3fae55 100644
--- a/core/java/android/hardware/input/IInputManager.aidl
+++ b/core/java/android/hardware/input/IInputManager.aidl
@@ -17,6 +17,7 @@
 package android.hardware.input;
 
 import android.graphics.Rect;
+import android.hardware.input.HostUsiVersion;
 import android.hardware.input.InputDeviceIdentifier;
 import android.hardware.input.KeyboardLayout;
 import android.hardware.input.IInputDevicesChangedListener;
@@ -233,4 +234,6 @@
     @JavaPassthrough(annotation="@android.annotation.RequiresPermission(value = "
             + "android.Manifest.permission.MONITOR_KEYBOARD_BACKLIGHT)")
     void unregisterKeyboardBacklightListener(IKeyboardBacklightListener listener);
+
+    HostUsiVersion getHostUsiVersionFromDisplayConfig(int displayId);
 }
diff --git a/core/java/android/hardware/input/InputManager.java b/core/java/android/hardware/input/InputManager.java
index f27c34c..3ccc940 100644
--- a/core/java/android/hardware/input/InputManager.java
+++ b/core/java/android/hardware/input/InputManager.java
@@ -55,8 +55,6 @@
 import android.os.Vibrator;
 import android.os.VibratorManager;
 import android.provider.Settings;
-import android.provider.Settings.SettingNotFoundException;
-import android.util.DisplayUtils;
 import android.util.Log;
 import android.util.SparseArray;
 import android.view.Display;
@@ -71,7 +69,6 @@
 import android.view.inputmethod.InputMethodInfo;
 import android.view.inputmethod.InputMethodSubtype;
 
-import com.android.internal.R;
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.os.SomeArgs;
@@ -102,19 +99,33 @@
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
     private final IInputManager mIm;
 
-    private final boolean mIsStylusPointerIconEnabled;
+    /**
+     * InputManager has historically used its own static getter {@link #getInstance()} that doesn't
+     * provide a context. We provide a Context to the InputManager instance through the
+     * {@link android.app.SystemServiceRegistry}. Methods that need a Context must use
+     * {@link #getContext()} to obtain it.
+     */
+    @Nullable
+    private Context mLateInitContext;
+
+    /**
+     * Whether a PointerIcon is shown for stylus pointers.
+     * Obtain using {@link #isStylusPointerIconEnabled()}.
+     */
+    @Nullable
+    private Boolean mIsStylusPointerIconEnabled = null;
 
     // Guarded by mInputDevicesLock
     private final Object mInputDevicesLock = new Object();
     private SparseArray<InputDevice> mInputDevices;
     private InputDevicesChangedListener mInputDevicesChangedListener;
-    private final ArrayList<InputDeviceListenerDelegate> mInputDeviceListeners =
-            new ArrayList<InputDeviceListenerDelegate>();
+    private final ArrayList<InputDeviceListenerDelegate> mInputDeviceListeners = new ArrayList<>();
 
     // Guarded by mTabletModeLock
     private final Object mTabletModeLock = new Object();
+    @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
     private TabletModeChangedListener mTabletModeChangedListener;
-    private List<OnTabletModeChangedListenerDelegate> mOnTabletModeChangedListeners;
+    private ArrayList<OnTabletModeChangedListenerDelegate> mOnTabletModeChangedListeners;
 
     private final Object mBatteryListenersLock = new Object();
     // Maps a deviceId whose battery is currently being monitored to an entry containing the
@@ -126,7 +137,7 @@
 
     private final Object mKeyboardBacklightListenerLock = new Object();
     @GuardedBy("mKeyboardBacklightListenerLock")
-    private List<KeyboardBacklightListenerDelegate> mKeyboardBacklightListeners;
+    private ArrayList<KeyboardBacklightListenerDelegate> mKeyboardBacklightListeners;
     @GuardedBy("mKeyboardBacklightListenerLock")
     private IKeyboardBacklightListener mKeyboardBacklightListener;
 
@@ -326,15 +337,6 @@
         } catch (RemoteException ex) {
             Log.w(TAG, "Could not get VelocityTracker strategy: " + ex);
         }
-
-        // TODO(b/266013036): Pass a Context into InputManager constructor.
-        final Context context = ActivityThread.currentApplication();
-        if (context != null) {
-            mIsStylusPointerIconEnabled = context.getResources()
-                    .getBoolean(com.android.internal.R.bool.config_enableStylusPointerIcon);
-        } else {
-            mIsStylusPointerIconEnabled = false;
-        }
     }
 
     /**
@@ -368,24 +370,47 @@
      * Gets an instance of the input manager.
      *
      * @return The input manager instance.
-     *
+     * @deprecated Use {@link Context#getSystemService(Class)} or {@link #getInstance(Context)}
+     * to obtain the InputManager instance.
      * @hide
      */
+    @Deprecated
     @UnsupportedAppUsage
     public static InputManager getInstance() {
+        return getInstance(ActivityThread.currentApplication());
+    }
+
+    /**
+     * Gets an instance of the input manager.
+     *
+     * @return The input manager instance.
+     * @hide
+     */
+    public static InputManager getInstance(Context context) {
         synchronized (InputManager.class) {
             if (sInstance == null) {
                 try {
                     sInstance = new InputManager(IInputManager.Stub
                             .asInterface(ServiceManager.getServiceOrThrow(Context.INPUT_SERVICE)));
+
                 } catch (ServiceNotFoundException e) {
                     throw new IllegalStateException(e);
                 }
             }
+            if (sInstance.mLateInitContext == null) {
+                sInstance.mLateInitContext = context;
+            }
             return sInstance;
         }
     }
 
+    @NonNull
+    private Context getContext() {
+        return Objects.requireNonNull(mLateInitContext,
+                "A context is required for InputManager. Get the InputManager instance using "
+                        + "Context#getSystemService before calling this method.");
+    }
+
     /**
      * Get the current VelocityTracker strategy. Only works when the system has fully booted up.
      * @hide
@@ -499,7 +524,7 @@
     /**
      * Enables an InputDevice.
      * <p>
-     * Requires {@link android.Manifest.permission.DISABLE_INPUT_DEVICE}.
+     * Requires {@link android.Manifest.permission#DISABLE_INPUT_DEVICE}.
      * </p>
      *
      * @param id The input device Id.
@@ -518,7 +543,7 @@
     /**
      * Disables an InputDevice.
      * <p>
-     * Requires {@link android.Manifest.permission.DISABLE_INPUT_DEVICE}.
+     * Requires {@link android.Manifest.permission#DISABLE_INPUT_DEVICE}.
      * </p>
      *
      * @param id The input device Id.
@@ -975,6 +1000,7 @@
      */
     @TestApi
     @NonNull
+    @SuppressWarnings("unchecked")
     @RequiresPermission(Manifest.permission.REMAP_MODIFIER_KEYS)
     public Map<Integer, Integer> getModifierKeyRemapping() {
         try {
@@ -1005,7 +1031,7 @@
      * Sets the TouchCalibration to apply to the specified input device's coordinates.
      * <p>
      * This method may have the side-effect of causing the input device in question
-     * to be reconfigured. Requires {@link android.Manifest.permission.SET_INPUT_CALIBRATION}.
+     * to be reconfigured. Requires {@link android.Manifest.permission#SET_INPUT_CALIBRATION}.
      * </p>
      *
      * @param inputDeviceDescriptor The input device descriptor.
@@ -1121,19 +1147,14 @@
      * @hide
      */
     public int getPointerSpeed(Context context) {
-        int speed = DEFAULT_POINTER_SPEED;
-        try {
-            speed = Settings.System.getInt(context.getContentResolver(),
-                    Settings.System.POINTER_SPEED);
-        } catch (SettingNotFoundException snfe) {
-        }
-        return speed;
+        return Settings.System.getInt(context.getContentResolver(),
+                Settings.System.POINTER_SPEED, DEFAULT_POINTER_SPEED);
     }
 
     /**
      * Sets the mouse pointer speed.
      * <p>
-     * Requires {@link android.Manifest.permission.WRITE_SETTINGS}.
+     * Requires {@link android.Manifest.permission#WRITE_SETTINGS}.
      * </p>
      *
      * @param context The application context.
@@ -1154,7 +1175,7 @@
     /**
      * Changes the mouse pointer speed temporarily, but does not save the setting.
      * <p>
-     * Requires {@link android.Manifest.permission.SET_POINTER_SPEED}.
+     * Requires {@link android.Manifest.permission#SET_POINTER_SPEED}.
      * </p>
      *
      * @param speed The pointer speed as a value between {@link #MIN_POINTER_SPEED} and
@@ -1188,8 +1209,7 @@
      */
     @FloatRange(from = 0, to = 1)
     public float getMaximumObscuringOpacityForTouch() {
-        Context context = ActivityThread.currentApplication();
-        return Settings.Global.getFloat(context.getContentResolver(),
+        return Settings.Global.getFloat(getContext().getContentResolver(),
                 Settings.Global.MAXIMUM_OBSCURING_OPACITY_FOR_TOUCH,
                 DEFAULT_MAXIMUM_OBSCURING_OPACITY_FOR_TOUCH);
     }
@@ -1225,8 +1245,7 @@
             throw new IllegalArgumentException(
                     "Maximum obscuring opacity for touch should be >= 0 and <= 1");
         }
-        Context context = ActivityThread.currentApplication();
-        Settings.Global.putFloat(context.getContentResolver(),
+        Settings.Global.putFloat(getContext().getContentResolver(),
                 Settings.Global.MAXIMUM_OBSCURING_OPACITY_FOR_TOUCH, opacity);
     }
 
@@ -1307,7 +1326,7 @@
      * The synchronization mode determines whether the method blocks while waiting for
      * input injection to proceed.
      * <p>
-     * Requires the {@link android.Manifest.permission.INJECT_EVENTS} permission.
+     * Requires the {@link android.Manifest.permission#INJECT_EVENTS} permission.
      * </p><p>
      * Make sure you correctly set the event time and input source of the event
      * before calling this method.
@@ -1315,9 +1334,9 @@
      *
      * @param event The event to inject.
      * @param mode The synchronization mode.  One of:
-     * {@link android.os.InputEventInjectionSync.NONE},
-     * {@link android.os.InputEventInjectionSync.WAIT_FOR_RESULT}, or
-     * {@link android.os.InputEventInjectionSync.WAIT_FOR_FINISHED}.
+     * {@link android.os.InputEventInjectionSync#NONE},
+     * {@link android.os.InputEventInjectionSync#WAIT_FOR_RESULT}, or
+     * {@link android.os.InputEventInjectionSync#WAIT_FOR_FINISHED}.
      * @param targetUid The uid to target, or {@link android.os.Process#INVALID_UID} to target all
      *                 windows.
      * @return True if input event injection succeeded.
@@ -1347,7 +1366,7 @@
      * The synchronization mode determines whether the method blocks while waiting for
      * input injection to proceed.
      * <p>
-     * Requires the {@link android.Manifest.permission.INJECT_EVENTS} permission.
+     * Requires the {@link android.Manifest.permission#INJECT_EVENTS} permission.
      * </p><p>
      * Make sure you correctly set the event time and input source of the event
      * before calling this method.
@@ -1355,9 +1374,9 @@
      *
      * @param event The event to inject.
      * @param mode The synchronization mode.  One of:
-     * {@link android.os.InputEventInjectionSync.NONE},
-     * {@link android.os.InputEventInjectionSync.WAIT_FOR_RESULT}, or
-     * {@link android.os.InputEventInjectionSync.WAIT_FOR_FINISHED}.
+     * {@link android.os.InputEventInjectionSync#NONE},
+     * {@link android.os.InputEventInjectionSync#WAIT_FOR_RESULT}, or
+     * {@link android.os.InputEventInjectionSync#WAIT_FOR_FINISHED}.
      * @return True if input event injection succeeded.
      *
      * @hide
@@ -1381,7 +1400,8 @@
      * {@link android.view.InputEvent}
      *         {@code null} if the event could not be verified.
      */
-    public @Nullable VerifiedInputEvent verifyInputEvent(@NonNull InputEvent event) {
+    @Nullable
+    public VerifiedInputEvent verifyInputEvent(@NonNull InputEvent event) {
         try {
             return mIm.verifyInputEvent(event);
         } catch (RemoteException ex) {
@@ -1393,7 +1413,7 @@
      * Changes the mouse pointer's icon shape into the specified id.
      *
      * @param iconId The id of the pointer graphic, as a value between
-     * {@link PointerIcon.TYPE_ARROW} and {@link PointerIcon.TYPE_HANDWRITING}.
+     * {@link PointerIcon#TYPE_ARROW} and {@link PointerIcon#TYPE_HANDWRITING}.
      *
      * @hide
      */
@@ -1422,6 +1442,10 @@
      * stylus pointer, false if there is no pointer icon shown for styluses.
      */
     public boolean isStylusPointerIconEnabled() {
+        if (mIsStylusPointerIconEnabled == null) {
+            mIsStylusPointerIconEnabled = getContext().getResources()
+                    .getBoolean(com.android.internal.R.bool.config_enableStylusPointerIcon);
+        }
         return mIsStylusPointerIconEnabled;
     }
 
@@ -1543,7 +1567,7 @@
      * @param inputPort The port of the input device.
      * @param displayPort The physical port of the associated display.
      * <p>
-     * Requires {@link android.Manifest.permission.ASSOCIATE_INPUT_DEVICE_TO_DISPLAY}.
+     * Requires {@link android.Manifest.permission#ASSOCIATE_INPUT_DEVICE_TO_DISPLAY}.
      * </p>
      * @hide
      */
@@ -1560,7 +1584,7 @@
      * static association for the cleared input port will be restored.
      * @param inputPort The port of the input device to be cleared.
      * <p>
-     * Requires {@link android.Manifest.permission.ASSOCIATE_INPUT_DEVICE_TO_DISPLAY}.
+     * Requires {@link android.Manifest.permission#ASSOCIATE_INPUT_DEVICE_TO_DISPLAY}.
      * </p>
      * @hide
      */
@@ -1578,7 +1602,7 @@
      * @param inputPort The port of the input device.
      * @param displayUniqueId The unique id of the associated display.
      * <p>
-     * Requires {@link android.Manifest.permission.ASSOCIATE_INPUT_DEVICE_TO_DISPLAY}.
+     * Requires {@link android.Manifest.permission#ASSOCIATE_INPUT_DEVICE_TO_DISPLAY}.
      * </p>
      * @hide
      */
@@ -1595,7 +1619,7 @@
      * Removes a runtime association between the input device and display.
      * @param inputPort The port of the input device.
      * <p>
-     * Requires {@link android.Manifest.permission.ASSOCIATE_INPUT_DEVICE_TO_DISPLAY}.
+     * Requires {@link android.Manifest.permission#ASSOCIATE_INPUT_DEVICE_TO_DISPLAY}.
      * </p>
      * @hide
      */
@@ -1637,35 +1661,11 @@
         // If there are no input devices that report a valid USI version, see if there is a config
         // that specifies the USI version for the display. This is to handle cases where the USI
         // input device is not registered by the kernel/driver all the time.
-        return findConfigUsiVersionForDisplay(display);
-    }
-
-    private HostUsiVersion findConfigUsiVersionForDisplay(@NonNull Display display) {
-        final Context context = Objects.requireNonNull(ActivityThread.currentApplication());
-        final String[] displayUniqueIds = context.getResources().getStringArray(
-                R.array.config_displayUniqueIdArray);
-        final int index;
-        if (displayUniqueIds.length == 0 && display.getDisplayId() == context.getDisplayId()) {
-            index = 0;
-        } else {
-            index = DisplayUtils.getDisplayUniqueIdConfigIndex(context.getResources(),
-                    display.getUniqueId());
+        try {
+            return mIm.getHostUsiVersionFromDisplayConfig(display.getDisplayId());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
         }
-
-        final String[] versions = context.getResources().getStringArray(
-                R.array.config_displayUsiVersionArray);
-        if (index < 0 || index >= versions.length) {
-            return null;
-        }
-        final String version = versions[index];
-        if (version == null || version.isEmpty()) {
-            return null;
-        }
-        final String[] majorMinor = version.split("\\.");
-        if (majorMinor.length != 2) {
-            throw new IllegalStateException("Failed to parse USI version: " + version);
-        }
-        return new HostUsiVersion(Integer.parseInt(majorMinor[0]), Integer.parseInt(majorMinor[1]));
     }
 
     private void populateInputDevicesLocked() {
@@ -1687,9 +1687,9 @@
                 throw ex.rethrowFromSystemServer();
             }
 
-            mInputDevices = new SparseArray<InputDevice>();
-            for (int i = 0; i < ids.length; i++) {
-                mInputDevices.put(ids[i], null);
+            mInputDevices = new SparseArray<>();
+            for (int id : ids) {
+                mInputDevices.put(id, null);
             }
         }
     }
@@ -1761,8 +1761,8 @@
                     + "whenNanos=" + whenNanos + ", inTabletMode=" + inTabletMode);
         }
         synchronized (mTabletModeLock) {
-            final int N = mOnTabletModeChangedListeners.size();
-            for (int i = 0; i < N; i++) {
+            final int numListeners = mOnTabletModeChangedListeners.size();
+            for (int i = 0; i < numListeners; i++) {
                 OnTabletModeChangedListenerDelegate listener =
                         mOnTabletModeChangedListeners.get(i);
                 listener.sendTabletModeChanged(whenNanos, inTabletMode);
@@ -1965,7 +1965,7 @@
             }
             List<LightState> lightStateList = request.getLightStates();
             mIm.setLightStates(deviceId, lightIds,
-                    lightStateList.toArray(new LightState[lightStateList.size()]),
+                    lightStateList.toArray(new LightState[0]),
                     token);
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
@@ -2072,8 +2072,11 @@
             } else {
                 // The deviceId is already being monitored for battery changes.
                 // Ensure that the listener is not already registered.
-                for (InputDeviceBatteryListenerDelegate delegate : listenersForDevice.mDelegates) {
-                    if (Objects.equals(listener, delegate.mListener)) {
+                final int numDelegates = listenersForDevice.mDelegates.size();
+                for (int i = 0; i < numDelegates; i++) {
+                    InputDeviceBatteryListener registeredListener =
+                            listenersForDevice.mDelegates.get(i).mListener;
+                    if (Objects.equals(listener, registeredListener)) {
                         throw new IllegalArgumentException(
                                 "Attempting to register an InputDeviceBatteryListener that has "
                                         + "already been registered for deviceId: "
@@ -2208,7 +2211,7 @@
      * Changes the touchpad pointer speed temporarily, but does not save the setting.
      *
      * The new speed will only apply to gesture-compatible touchpads.
-     * Requires {@link android.Manifest.permission.SET_POINTER_SPEED}.
+     * Requires {@link android.Manifest.permission#SET_POINTER_SPEED}.
      *
      * @param speed The pointer speed as a value between {@link #MIN_POINTER_SPEED} and
      * {@link #MAX_POINTER_SPEED}, or the default value {@link #DEFAULT_POINTER_SPEED}.
@@ -2398,8 +2401,9 @@
                     throw e.rethrowFromSystemServer();
                 }
             }
-            for (KeyboardBacklightListenerDelegate delegate : mKeyboardBacklightListeners) {
-                if (delegate.mListener == listener) {
+            final int numListeners = mKeyboardBacklightListeners.size();
+            for (int i = 0; i < numListeners; i++) {
+                if (mKeyboardBacklightListeners.get(i).mListener == listener) {
                     throw new IllegalArgumentException("Listener has already been registered!");
                 }
             }
@@ -2572,21 +2576,19 @@
 
         public void sendTabletModeChanged(long whenNanos, boolean inTabletMode) {
             SomeArgs args = SomeArgs.obtain();
-            args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
+            args.argi1 = (int) whenNanos;
             args.argi2 = (int) (whenNanos >> 32);
-            args.arg1 = (Boolean) inTabletMode;
+            args.arg1 = inTabletMode;
             obtainMessage(MSG_TABLET_MODE_CHANGED, args).sendToTarget();
         }
 
         @Override
         public void handleMessage(Message msg) {
-            switch (msg.what) {
-                case MSG_TABLET_MODE_CHANGED:
-                    SomeArgs args = (SomeArgs) msg.obj;
-                    long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
-                    boolean inTabletMode = (boolean) args.arg1;
-                    mListener.onTabletModeChanged(whenNanos, inTabletMode);
-                    break;
+            if (msg.what == MSG_TABLET_MODE_CHANGED) {
+                SomeArgs args = (SomeArgs) msg.obj;
+                long whenNanos = (args.argi1 & 0xFFFFFFFFL) | ((long) args.argi2 << 32);
+                boolean inTabletMode = (boolean) args.arg1;
+                mListener.onTabletModeChanged(whenNanos, inTabletMode);
             }
         }
     }
@@ -2654,8 +2656,10 @@
                 if (entry == null) return;
 
                 entry.mInputDeviceBatteryState = state;
-                for (InputDeviceBatteryListenerDelegate delegate : entry.mDelegates) {
-                    delegate.notifyBatteryStateChanged(entry.mInputDeviceBatteryState);
+                final int numDelegates = entry.mDelegates.size();
+                for (int i = 0; i < numDelegates; i++) {
+                    entry.mDelegates.get(i)
+                            .notifyBatteryStateChanged(entry.mInputDeviceBatteryState);
                 }
             }
         }
@@ -2668,8 +2672,8 @@
         private final int mBrightnessLevel;
         private final int mMaxBrightnessLevel;
 
-        LocalKeyboardBacklightState(int brightnesslevel, int maxBrightnessLevel) {
-            mBrightnessLevel = brightnesslevel;
+        LocalKeyboardBacklightState(int brightnessLevel, int maxBrightnessLevel) {
+            mBrightnessLevel = brightnessLevel;
             mMaxBrightnessLevel = maxBrightnessLevel;
         }
 
@@ -2709,8 +2713,10 @@
                 boolean isTriggeredByKeyPress) {
             synchronized (mKeyboardBacklightListenerLock) {
                 if (mKeyboardBacklightListeners == null) return;
-                for (KeyboardBacklightListenerDelegate delegate : mKeyboardBacklightListeners) {
-                    delegate.notifyKeyboardBacklightChange(deviceId, state, isTriggeredByKeyPress);
+                final int numListeners = mKeyboardBacklightListeners.size();
+                for (int i = 0; i < numListeners; i++) {
+                    mKeyboardBacklightListeners.get(i)
+                            .notifyKeyboardBacklightChange(deviceId, state, isTriggeredByKeyPress);
                 }
             }
         }
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 6eb932e..84ed845 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -75,7 +75,6 @@
 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
 import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
-import static android.view.WindowManager.LayoutParams.TYPE_NOTIFICATION_SHADE;
 import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_ADDITIONAL;
 import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
 import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
@@ -440,6 +439,7 @@
     @NonNull Display mDisplay;
     final DisplayManager mDisplayManager;
     final String mBasePackageName;
+    final InputManager mInputManager;
 
     final int[] mTmpLocation = new int[2];
 
@@ -968,6 +968,7 @@
         // TODO(b/222696368): remove getSfInstance usage and use vsyncId for transactions
         mChoreographer = Choreographer.getInstance();
         mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
+        mInputManager = context.getSystemService(InputManager.class);
         mInsetsController = new InsetsController(new ViewRootInsetsControllerHost(this));
         mHandwritingInitiator = new HandwritingInitiator(
                 mViewConfiguration,
@@ -5337,7 +5338,7 @@
             Log.e(mTag, "No input channel to request Pointer Capture.");
             return;
         }
-        InputManager.getInstance().requestPointerCapture(inputToken, enabled);
+        mInputManager.requestPointerCapture(inputToken, enabled);
     }
 
     private void handlePointerCaptureChanged(boolean hasCapture) {
@@ -6860,9 +6861,8 @@
             if (event.getPointerCount() != 1) {
                 return;
             }
-            final boolean needsStylusPointerIcon =
-                    InputManager.getInstance().isStylusPointerIconEnabled()
-                            && event.isStylusPointer();
+            final boolean needsStylusPointerIcon = event.isStylusPointer()
+                    && mInputManager.isStylusPointerIconEnabled();
             if (needsStylusPointerIcon || event.isFromSource(InputDevice.SOURCE_MOUSE)) {
                 if (event.getActionMasked() == MotionEvent.ACTION_HOVER_ENTER
                         || event.getActionMasked() == MotionEvent.ACTION_HOVER_EXIT) {
@@ -6934,7 +6934,7 @@
 
         PointerIcon pointerIcon = null;
 
-        if (event.isStylusPointer() && InputManager.getInstance().isStylusPointerIconEnabled()) {
+        if (event.isStylusPointer() && mInputManager.isStylusPointerIconEnabled()) {
             pointerIcon = mHandwritingInitiator.onResolvePointerIcon(mContext, event);
         }
 
@@ -6949,14 +6949,14 @@
             mPointerIconType = pointerType;
             mCustomPointerIcon = null;
             if (mPointerIconType != PointerIcon.TYPE_CUSTOM) {
-                InputManager.getInstance().setPointerIconType(pointerType);
+                mInputManager.setPointerIconType(pointerType);
                 return true;
             }
         }
         if (mPointerIconType == PointerIcon.TYPE_CUSTOM &&
                 !pointerIcon.equals(mCustomPointerIcon)) {
             mCustomPointerIcon = pointerIcon;
-            InputManager.getInstance().setCustomPointerIcon(mCustomPointerIcon);
+            mInputManager.setCustomPointerIcon(mCustomPointerIcon);
         }
         return true;
     }
diff --git a/core/java/android/view/WindowManager.java b/core/java/android/view/WindowManager.java
index 5144f3a..ee4b6c4 100644
--- a/core/java/android/view/WindowManager.java
+++ b/core/java/android/view/WindowManager.java
@@ -1099,6 +1099,32 @@
             "android.window.PROPERTY_CAMERA_COMPAT_ENABLE_REFRESH_VIA_PAUSE";
 
     /**
+     * Activity level {@link android.content.pm.PackageManager.Property PackageManager
+     * .Property} for an app to inform the system that the activity should be excluded from the
+     * compatibility override for orientation set by the device manufacturer.
+     *
+     * <p>With this property set to {@code true} or unset, device manufacturers can override
+     * orientation for the activity using their discretion to improve display compatibility.
+     *
+     * <p>With this property set to {@code false}, device manufactured per-app override for
+     * orientation won't be applied.
+     *
+     * <p><b>Syntax:</b>
+     * <pre>
+     * &lt;activity&gt;
+     *   &lt;property
+     *     android:name="android.window.PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE"
+     *     android:value="true|false"/&gt;
+     * &lt;/activity&gt;
+     * </pre>
+     *
+     * @hide
+     */
+    // TODO(b/263984287): Make this public API.
+    String PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE =
+            "android.window.PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE";
+
+    /**
      * @hide
      */
     public static final String PARCEL_KEY_SHORTCUTS_ARRAY = "shortcuts_array";
diff --git a/core/java/com/android/internal/os/BatteryStatsHistory.java b/core/java/com/android/internal/os/BatteryStatsHistory.java
index 04b7239cb..ddc0c0c 100644
--- a/core/java/com/android/internal/os/BatteryStatsHistory.java
+++ b/core/java/com/android/internal/os/BatteryStatsHistory.java
@@ -115,9 +115,11 @@
     static final int STATE_BATTERY_HEALTH_SHIFT = 26;
     static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
     static final int STATE_BATTERY_PLUG_SHIFT = 24;
+
     // We use the low bit of the battery state int to indicate that we have full details
     // from a battery level change.
-    static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
+    static final int BATTERY_LEVEL_DETAILS_FLAG = 0x00000001;
+
     // Flag in history tag index: indicates that this is the first occurrence of this tag,
     // therefore the tag value is written in the parcel
     static final int TAG_FIRST_OCCURRENCE_FLAG = 0x8000;
@@ -1385,8 +1387,17 @@
 
         if (dataSize == 0) {
             // The history is currently empty; we need it to start with a time stamp.
-            cur.currentTime = mClock.currentTimeMillis();
-            writeHistoryItem(elapsedRealtimeMs, uptimeMs, cur, HistoryItem.CMD_RESET);
+            HistoryItem copy = new HistoryItem();
+            copy.setTo(cur);
+            copy.currentTime = mClock.currentTimeMillis();
+            copy.wakelockTag = null;
+            copy.wakeReasonTag = null;
+            copy.eventCode = HistoryItem.EVENT_NONE;
+            copy.eventTag = null;
+            copy.tagsFirstOccurrence = false;
+            copy.energyConsumerDetails = null;
+            copy.cpuUsageDetails = null;
+            writeHistoryItem(elapsedRealtimeMs, uptimeMs, copy, HistoryItem.CMD_RESET);
         }
         writeHistoryItem(elapsedRealtimeMs, uptimeMs, cur, HistoryItem.CMD_UPDATE);
     }
@@ -1516,10 +1527,19 @@
             deltaTimeToken = (int) deltaTime;
         }
         int firstToken = deltaTimeToken | (cur.states & BatteryStatsHistory.DELTA_STATE_MASK);
-        final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
-                ? BatteryStatsHistory.BATTERY_DELTA_LEVEL_FLAG : 0;
-        mLastHistoryStepLevel = cur.batteryLevel;
-        final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
+        int batteryLevelInt = buildBatteryLevelInt(cur);
+
+        if (cur.batteryLevel < mLastHistoryStepLevel || mLastHistoryStepLevel == 0) {
+            cur.stepDetails = mStepDetailsCalculator.getHistoryStepDetails();
+            if (cur.stepDetails != null) {
+                batteryLevelInt |= BatteryStatsHistory.BATTERY_LEVEL_DETAILS_FLAG;
+                mLastHistoryStepLevel = cur.batteryLevel;
+            }
+        } else {
+            cur.stepDetails = null;
+            mLastHistoryStepLevel = cur.batteryLevel;
+        }
+
         final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
         if (batteryLevelIntChanged) {
             firstToken |= BatteryStatsHistory.DELTA_BATTERY_LEVEL_FLAG;
@@ -1652,8 +1672,7 @@
             }
         }
 
-        cur.stepDetails = mStepDetailsCalculator.getHistoryStepDetails();
-        if (includeStepDetails != 0) {
+        if (cur.stepDetails != null) {
             cur.stepDetails.writeToParcel(dest);
         }
 
diff --git a/core/java/com/android/internal/os/BatteryStatsHistoryIterator.java b/core/java/com/android/internal/os/BatteryStatsHistoryIterator.java
index 67eee4f..ccc3454 100644
--- a/core/java/com/android/internal/os/BatteryStatsHistoryIterator.java
+++ b/core/java/com/android/internal/os/BatteryStatsHistoryIterator.java
@@ -215,7 +215,7 @@
             cur.eventCode = BatteryStats.HistoryItem.EVENT_NONE;
         }
 
-        if ((batteryLevelInt & BatteryStatsHistory.BATTERY_DELTA_LEVEL_FLAG) != 0) {
+        if ((batteryLevelInt & BatteryStatsHistory.BATTERY_LEVEL_DETAILS_FLAG) != 0) {
             cur.stepDetails = mReadHistoryStepDetails;
             cur.stepDetails.readFromParcel(src);
         } else {
diff --git a/core/java/com/android/internal/os/IBinaryTransparencyService.aidl b/core/java/com/android/internal/os/IBinaryTransparencyService.aidl
index a1ad5d5..b4a0aac 100644
--- a/core/java/com/android/internal/os/IBinaryTransparencyService.aidl
+++ b/core/java/com/android/internal/os/IBinaryTransparencyService.aidl
@@ -28,5 +28,26 @@
 
     List getApexInfo();
 
-    List getMeasurementsForAllPackages();
+    void recordMeasurementsForAllPackages();
+
+    parcelable ApexInfo {
+        String packageName;
+        long longVersion;
+        byte[] digest;
+        int digestAlgorithm;
+        String[] signerDigests;
+    }
+
+    parcelable AppInfo {
+        String packageName;
+        long longVersion;
+        byte[] digest;
+        int digestAlgorithm;
+        String[] signerDigests;
+        int mbaStatus;
+        String initiator;
+        String[] initiatorSignerDigests;
+        String installer;
+        String originator;
+    }
 }
\ No newline at end of file
diff --git a/core/jni/android_media_AudioTrack.cpp b/core/jni/android_media_AudioTrack.cpp
index ae45a0e..1557f9e 100644
--- a/core/jni/android_media_AudioTrack.cpp
+++ b/core/jni/android_media_AudioTrack.cpp
@@ -19,18 +19,18 @@
 
 #include "android_media_AudioTrack.h"
 
-#include <nativehelper/JNIHelp.h>
-#include <nativehelper/ScopedUtfChars.h>
-#include "core_jni_helpers.h"
-
-#include <utils/Log.h>
+#include <android-base/macros.h>
+#include <android_os_Parcel.h>
+#include <binder/MemoryBase.h>
+#include <binder/MemoryHeapBase.h>
 #include <media/AudioParameter.h>
 #include <media/AudioSystem.h>
 #include <media/AudioTrack.h>
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedUtfChars.h>
+#include <utils/Log.h>
 
-#include <android-base/macros.h>
-#include <binder/MemoryHeapBase.h>
-#include <binder/MemoryBase.h>
+#include <cinttypes>
 
 #include "android_media_AudioAttributes.h"
 #include "android_media_AudioErrors.h"
@@ -41,8 +41,7 @@
 #include "android_media_MediaMetricsJNI.h"
 #include "android_media_PlaybackParams.h"
 #include "android_media_VolumeShaper.h"
-
-#include <cinttypes>
+#include "core_jni_helpers.h"
 
 // ----------------------------------------------------------------------------
 
@@ -245,9 +244,10 @@
                                            jobject jaa, jintArray jSampleRate,
                                            jint channelPositionMask, jint channelIndexMask,
                                            jint audioFormat, jint buffSizeInBytes, jint memoryMode,
-                                           jintArray jSession, jlong nativeAudioTrack,
-                                           jboolean offload, jint encapsulationMode,
-                                           jobject tunerConfiguration, jstring opPackageName) {
+                                           jintArray jSession, jobject jAttributionSource,
+                                           jlong nativeAudioTrack, jboolean offload,
+                                           jint encapsulationMode, jobject tunerConfiguration,
+                                           jstring opPackageName) {
     ALOGV("sampleRates=%p, channel mask=%x, index mask=%x, audioFormat(Java)=%d, buffSize=%d,"
           " nativeAudioTrack=0x%" PRIX64 ", offload=%d encapsulationMode=%d tuner=%p",
           jSampleRate, channelPositionMask, channelIndexMask, audioFormat, buffSizeInBytes,
@@ -323,10 +323,9 @@
 
         // create the native AudioTrack object
         ScopedUtfChars opPackageNameStr(env, opPackageName);
-        // TODO b/182469354: make consistent with AudioRecord
-        AttributionSourceState attributionSource;
-        attributionSource.packageName = std::string(opPackageNameStr.c_str());
-        attributionSource.token = sp<BBinder>::make();
+
+        android::content::AttributionSourceState attributionSource;
+        attributionSource.readFromParcel(parcelForJavaObject(env, jAttributionSource));
         lpTrack = sp<AudioTrack>::make(attributionSource);
 
         // read the AudioAttributes values
@@ -382,7 +381,7 @@
                                   offload ? AudioTrack::TRANSFER_SYNC_NOTIF_CALLBACK
                                           : AudioTrack::TRANSFER_SYNC,
                                   (offload || encapsulationMode) ? &offloadInfo : NULL,
-                                  AttributionSourceState(), // default uid, pid values
+                                  attributionSource, // Passed from Java
                                   paa.get());
             break;
 
@@ -401,14 +400,14 @@
                                   format, // word length, PCM
                                   nativeChannelMask, frameCount, AUDIO_OUTPUT_FLAG_NONE,
                                   lpJniStorage,
-                                  0, // notificationFrames == 0 since not using EVENT_MORE_DATA
-                                     // to feed the AudioTrack
-                                  iMem,                   // shared mem
-                                  true,                   // thread can call Java
-                                  sessionId,              // audio session ID
+                                  0,    // notificationFrames == 0 since not using EVENT_MORE_DATA
+                                        // to feed the AudioTrack
+                                  iMem, // shared mem
+                                  true, // thread can call Java
+                                  sessionId, // audio session ID
                                   AudioTrack::TRANSFER_SHARED,
-                                  nullptr ,               // default offloadInfo
-                                  AttributionSourceState(), // default uid, pid values
+                                  nullptr,           // default offloadInfo
+                                  attributionSource, // Passed from Java
                                   paa.get());
             break;
         }
@@ -1456,7 +1455,8 @@
         {"native_pause", "()V", (void *)android_media_AudioTrack_pause},
         {"native_flush", "()V", (void *)android_media_AudioTrack_flush},
         {"native_setup",
-         "(Ljava/lang/Object;Ljava/lang/Object;[IIIIII[IJZILjava/lang/Object;Ljava/lang/String;)I",
+         "(Ljava/lang/Object;Ljava/lang/Object;[IIIIII[ILandroid/os/Parcel;"
+         "JZILjava/lang/Object;Ljava/lang/String;)I",
          (void *)android_media_AudioTrack_setup},
         {"native_finalize", "()V", (void *)android_media_AudioTrack_finalize},
         {"native_release", "()V", (void *)android_media_AudioTrack_release},
diff --git a/core/res/res/layout/resolve_grid_item.xml b/core/res/res/layout/resolve_grid_item.xml
index 50e6f33..a5ff470 100644
--- a/core/res/res/layout/resolve_grid_item.xml
+++ b/core/res/res/layout/resolve_grid_item.xml
@@ -17,6 +17,7 @@
 */
 -->
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:id="@+id/item"
               android:orientation="vertical"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index f544feb..602ee55 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -642,6 +642,16 @@
          The default is false. -->
     <bool name="config_lidControlsSleep">false</bool>
 
+    <!-- The device states (supplied by DeviceStateManager) that should be treated as open by the
+         device fold controller. Default is empty. -->
+    <integer-array name="config_openDeviceStates">
+        <!-- Example:
+        <item>0</item>
+        <item>1</item>
+        <item>2</item>
+        -->
+    </integer-array>
+
     <!-- The device states (supplied by DeviceStateManager) that should be treated as folded by the
          display fold controller. Default is empty. -->
     <integer-array name="config_foldedDeviceStates">
@@ -662,6 +672,16 @@
         -->
     </integer-array>
 
+    <!-- The device states (supplied by DeviceStateManager) that should be treated as a rear display
+     state. Default is empty. -->
+    <integer-array name="config_rearDisplayDeviceStates">
+        <!-- Example:
+        <item>0</item>
+        <item>1</item>
+        <item>2</item>
+        -->
+    </integer-array>
+
     <!-- Indicates whether the window manager reacts to half-fold device states by overriding
      rotation. -->
     <bool name="config_windowManagerHalfFoldAutoRotateOverride">false</bool>
@@ -5820,7 +5840,6 @@
            - config_roundedCornerDrawableArray (config in SystemUI resource)
            - config_roundedCornerTopDrawableArray (config in SystemUI resource)
            - config_roundedCornerBottomDrawableArray (config in SystemUI resource)
-           - config_displayUsiVersionArray
 
          Leave this array empty for single display device and the system will load the default main
          built-in related configs.
@@ -6189,21 +6208,4 @@
         trusted certificate using the SHA-256 digest algorithm. -->
     <string-array name="config_healthConnectMigrationKnownSigners">
     </string-array>
-
-    <!-- The Universal Stylus Initiative (USI) protocol version supported by each display.
-         (@see https://universalstylus.org/).
-
-         The i-th value in this array corresponds to the supported USI version of the i-th display
-         listed in config_displayUniqueIdArray. On a single-display device, the
-         config_displayUniqueIdArray may be empty, in which case the only value in this array should
-         be the USI version for the main built-in display.
-
-         If the display does not support USI, the version value should be an empty string. If the
-         display supports USI, the version must be in the following format:
-           "<major-version>.<minor-version>"
-
-         For example, "", "1.0", and "2.0" are valid values. -->
-    <string-array name="config_displayUsiVersionArray" translatable="false">
-        <item>""</item>
-    </string-array>
 </resources>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 9dc7835..a54e242 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -3960,8 +3960,10 @@
   <java-symbol type="integer" name="config_maxScanTasksForHomeVisibility" />
 
   <!-- For Foldables -->
+  <java-symbol type="array" name="config_openDeviceStates" />
   <java-symbol type="array" name="config_foldedDeviceStates" />
   <java-symbol type="array" name="config_halfFoldedDeviceStates" />
+  <java-symbol type="array" name="config_rearDisplayDeviceStates" />
   <java-symbol type="bool" name="config_windowManagerHalfFoldAutoRotateOverride" />
   <java-symbol type="array" name="config_deviceStatesOnWhichToWakeUp" />
   <java-symbol type="array" name="config_deviceStatesOnWhichToSleep" />
@@ -4781,7 +4783,6 @@
   <java-symbol type="array" name="config_mainBuiltInDisplayWaterfallCutout" />
   <java-symbol type="array" name="config_secondaryBuiltInDisplayWaterfallCutout" />
   <java-symbol type="array" name="config_waterfallCutoutArray" />
-  <java-symbol type="array" name="config_displayUsiVersionArray" />
 
   <java-symbol type="fraction" name="global_actions_vertical_padding_percentage" />
   <java-symbol type="fraction" name="global_actions_horizontal_padding_percentage" />
diff --git a/libs/hwui/renderthread/CanvasContext.cpp b/libs/hwui/renderthread/CanvasContext.cpp
index 6f549dc..8dea684 100644
--- a/libs/hwui/renderthread/CanvasContext.cpp
+++ b/libs/hwui/renderthread/CanvasContext.cpp
@@ -565,7 +565,7 @@
             const auto inputEventId =
                     static_cast<int32_t>(mCurrentFrameInfo->get(FrameInfoIndex::InputEventId));
             native_window_set_frame_timeline_info(
-                    mNativeSurface->getNativeWindow(), vsyncId, inputEventId,
+                    mNativeSurface->getNativeWindow(), frameCompleteNr, vsyncId, inputEventId,
                     mCurrentFrameInfo->get(FrameInfoIndex::FrameStartTime));
         }
     }
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index a4d5606..0636451 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -8329,7 +8329,8 @@
         Objects.requireNonNull(device);
         try {
             if (device.getId() == 0) {
-                throw new IllegalArgumentException("In valid device: " + device);
+                Log.w(TAG, "setCommunicationDevice: device not found: " + device);
+                return false;
             }
             return getService().setCommunicationDevice(mICallBack, device.getId());
         } catch (RemoteException e) {
diff --git a/media/java/android/media/AudioTrack.java b/media/java/android/media/AudioTrack.java
index 50749e7..948fef4 100644
--- a/media/java/android/media/AudioTrack.java
+++ b/media/java/android/media/AudioTrack.java
@@ -28,6 +28,8 @@
 import android.annotation.SystemApi;
 import android.annotation.TestApi;
 import android.compat.annotation.UnsupportedAppUsage;
+import android.content.AttributionSource;
+import android.content.AttributionSource.ScopedParcelState;
 import android.content.Context;
 import android.media.audiopolicy.AudioMix;
 import android.media.audiopolicy.AudioMixingRule;
@@ -39,6 +41,7 @@
 import android.os.HandlerThread;
 import android.os.Looper;
 import android.os.Message;
+import android.os.Parcel;
 import android.os.PersistableBundle;
 import android.util.ArrayMap;
 import android.util.Log;
@@ -822,15 +825,20 @@
         int[] session = new int[1];
         session[0] = resolvePlaybackSessionId(context, sessionId);
 
+        AttributionSource attributionSource = context == null
+                ? AttributionSource.myAttributionSource() : context.getAttributionSource();
+
         // native initialization
-        int initResult = native_setup(new WeakReference<AudioTrack>(this), mAttributes,
-                sampleRate, mChannelMask, mChannelIndexMask, mAudioFormat,
-                mNativeBufferSizeInBytes, mDataLoadMode, session, 0 /*nativeTrackInJavaObj*/,
-                offload, encapsulationMode, tunerConfiguration,
-                getCurrentOpPackageName());
-        if (initResult != SUCCESS) {
-            loge("Error code "+initResult+" when initializing AudioTrack.");
-            return; // with mState == STATE_UNINITIALIZED
+        try (ScopedParcelState attributionSourceState = attributionSource.asScopedParcelState()) {
+            int initResult = native_setup(new WeakReference<AudioTrack>(this), mAttributes,
+                    sampleRate, mChannelMask, mChannelIndexMask, mAudioFormat,
+                    mNativeBufferSizeInBytes, mDataLoadMode, session,
+                    attributionSourceState.getParcel(), 0 /*nativeTrackInJavaObj*/, offload,
+                    encapsulationMode, tunerConfiguration, getCurrentOpPackageName());
+            if (initResult != SUCCESS) {
+                loge("Error code " + initResult + " when initializing AudioTrack.");
+                return; // with mState == STATE_UNINITIALIZED
+            }
         }
 
         mSampleRate = sampleRate[0];
@@ -902,23 +910,27 @@
             // *Native* AudioTrack, so the attributes parameters to native_setup() are ignored.
             int[] session = { 0 };
             int[] rates = { 0 };
-            int initResult = native_setup(new WeakReference<AudioTrack>(this),
-                    null /*mAttributes - NA*/,
-                    rates /*sampleRate - NA*/,
-                    0 /*mChannelMask - NA*/,
-                    0 /*mChannelIndexMask - NA*/,
-                    0 /*mAudioFormat - NA*/,
-                    0 /*mNativeBufferSizeInBytes - NA*/,
-                    0 /*mDataLoadMode - NA*/,
-                    session,
-                    nativeTrackInJavaObj,
-                    false /*offload*/,
-                    ENCAPSULATION_MODE_NONE,
-                    null /* tunerConfiguration */,
-                    "" /* opPackagename */);
-            if (initResult != SUCCESS) {
-                loge("Error code "+initResult+" when initializing AudioTrack.");
-                return; // with mState == STATE_UNINITIALIZED
+            try (ScopedParcelState attributionSourceState =
+                         AttributionSource.myAttributionSource().asScopedParcelState()) {
+                int initResult = native_setup(new WeakReference<AudioTrack>(this),
+                        null /*mAttributes - NA*/,
+                        rates /*sampleRate - NA*/,
+                        0 /*mChannelMask - NA*/,
+                        0 /*mChannelIndexMask - NA*/,
+                        0 /*mAudioFormat - NA*/,
+                        0 /*mNativeBufferSizeInBytes - NA*/,
+                        0 /*mDataLoadMode - NA*/,
+                        session,
+                        attributionSourceState.getParcel(),
+                        nativeTrackInJavaObj,
+                        false /*offload*/,
+                        ENCAPSULATION_MODE_NONE,
+                        null /* tunerConfiguration */,
+                        "" /* opPackagename */);
+                if (initResult != SUCCESS) {
+                    loge("Error code " + initResult + " when initializing AudioTrack.");
+                    return; // with mState == STATE_UNINITIALIZED
+                }
             }
 
             mSessionId = session[0];
@@ -4371,9 +4383,9 @@
     private native final int native_setup(Object /*WeakReference<AudioTrack>*/ audiotrack_this,
             Object /*AudioAttributes*/ attributes,
             int[] sampleRate, int channelMask, int channelIndexMask, int audioFormat,
-            int buffSizeInBytes, int mode, int[] sessionId, long nativeAudioTrack,
-            boolean offload, int encapsulationMode, Object tunerConfiguration,
-            @NonNull String opPackageName);
+            int buffSizeInBytes, int mode, int[] sessionId, @NonNull Parcel attributionSource,
+            long nativeAudioTrack, boolean offload, int encapsulationMode,
+            Object tunerConfiguration, @NonNull String opPackageName);
 
     private native final void native_finalize();
 
diff --git a/packages/SystemUI/docs/device-entry/quickaffordance.md b/packages/SystemUI/docs/device-entry/quickaffordance.md
index ccb35fa..79d5718 100644
--- a/packages/SystemUI/docs/device-entry/quickaffordance.md
+++ b/packages/SystemUI/docs/device-entry/quickaffordance.md
@@ -52,6 +52,10 @@
 * Unselect an already-selected quick affordance from a slot
 * Unselect all already-selected quick affordances from a slot
 
+## Testing
+* Add a unit test for your implementation of `KeyguardQuickAffordanceConfig`
+* Manually verify that your implementation works in multi-user environments from both the main user and a secondary user
+
 ## Debugging
 To see the current state of the system, you can run `dumpsys`:
 
diff --git a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugStartable.kt b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugStartable.kt
index b94d781..dc7fc28 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugStartable.kt
+++ b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugStartable.kt
@@ -21,6 +21,7 @@
 import com.android.systemui.broadcast.BroadcastSender
 import com.android.systemui.dump.DumpManager
 import com.android.systemui.statusbar.commandline.CommandRegistry
+import com.android.systemui.util.InitializationChecker
 import dagger.Binds
 import dagger.Module
 import dagger.multibindings.ClassKey
@@ -34,7 +35,8 @@
     private val commandRegistry: CommandRegistry,
     private val flagCommand: FlagCommand,
     private val featureFlags: FeatureFlagsDebug,
-    private val broadcastSender: BroadcastSender
+    private val broadcastSender: BroadcastSender,
+    private val initializationChecker: InitializationChecker
 ) : CoreStartable {
 
     init {
@@ -46,8 +48,11 @@
     override fun start() {
         featureFlags.init()
         commandRegistry.registerCommand(FlagCommand.FLAG_COMMAND) { flagCommand }
-        val intent = Intent(FlagManager.ACTION_SYSUI_STARTED)
-        broadcastSender.sendBroadcast(intent)
+        if (initializationChecker.initializeComponents()) {
+            // protected broadcast should only be sent for the main process
+            val intent = Intent(FlagManager.ACTION_SYSUI_STARTED)
+            broadcastSender.sendBroadcast(intent)
+        }
     }
 }
 
diff --git a/packages/SystemUI/src/com/android/systemui/flags/Flags.kt b/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
index 8df3c99..2f974a3 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
+++ b/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
@@ -199,8 +199,7 @@
 
     /** A different path for unocclusion transitions back to keyguard */
     // TODO(b/262859270): Tracking Bug
-    @JvmField
-    val UNOCCLUSION_TRANSITION = unreleasedFlag(223, "unocclusion_transition", teamfood = true)
+    @JvmField val UNOCCLUSION_TRANSITION = releasedFlag(223, "unocclusion_transition")
 
     // flag for controlling auto pin confirmation and material u shapes in bouncer
     @JvmField
@@ -446,6 +445,12 @@
             teamfood = false
         )
 
+    // TODO(b/198643358): Tracking bug
+    @Keep
+    @JvmField
+    val ENABLE_PIP_SIZE_LARGE_SCREEN =
+        sysPropBooleanFlag(1114, "persist.wm.debug.enable_pip_size_large_screen", default = false)
+
     // 1200 - predictive back
     @Keep
     @JvmField
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/CustomizationProvider.kt b/packages/SystemUI/src/com/android/systemui/keyguard/CustomizationProvider.kt
index 482138e..680c504 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/CustomizationProvider.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/CustomizationProvider.kt
@@ -31,10 +31,12 @@
 import android.util.Log
 import com.android.systemui.SystemUIAppComponentFactoryBase
 import com.android.systemui.SystemUIAppComponentFactoryBase.ContextAvailableCallback
+import com.android.systemui.dagger.qualifiers.Main
 import com.android.systemui.keyguard.domain.interactor.KeyguardQuickAffordanceInteractor
 import com.android.systemui.keyguard.ui.preview.KeyguardRemotePreviewManager
 import com.android.systemui.shared.customization.data.content.CustomizationProviderContract as Contract
 import javax.inject.Inject
+import kotlinx.coroutines.CoroutineDispatcher
 import kotlinx.coroutines.runBlocking
 
 class CustomizationProvider :
@@ -42,6 +44,7 @@
 
     @Inject lateinit var interactor: KeyguardQuickAffordanceInteractor
     @Inject lateinit var previewManager: KeyguardRemotePreviewManager
+    @Inject @Main lateinit var mainDispatcher: CoroutineDispatcher
 
     private lateinit var contextAvailableCallback: ContextAvailableCallback
 
@@ -138,12 +141,14 @@
         selectionArgs: Array<out String>?,
         sortOrder: String?,
     ): Cursor? {
-        return when (uriMatcher.match(uri)) {
-            MATCH_CODE_ALL_AFFORDANCES -> runBlocking { queryAffordances() }
-            MATCH_CODE_ALL_SLOTS -> querySlots()
-            MATCH_CODE_ALL_SELECTIONS -> runBlocking { querySelections() }
-            MATCH_CODE_ALL_FLAGS -> queryFlags()
-            else -> null
+        return runBlocking(mainDispatcher) {
+            when (uriMatcher.match(uri)) {
+                MATCH_CODE_ALL_AFFORDANCES -> queryAffordances()
+                MATCH_CODE_ALL_SLOTS -> querySlots()
+                MATCH_CODE_ALL_SELECTIONS -> querySelections()
+                MATCH_CODE_ALL_FLAGS -> queryFlags()
+                else -> null
+            }
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfig.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfig.kt
index f6e6d6b..5a9f775 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfig.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfig.kt
@@ -19,6 +19,7 @@
 
 import android.app.StatusBarManager
 import android.content.Context
+import android.content.pm.PackageManager
 import com.android.systemui.R
 import com.android.systemui.animation.Expandable
 import com.android.systemui.camera.CameraGestureHelper
@@ -26,7 +27,6 @@
 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.statusbar.StatusBarState
 import dagger.Lazy
 import javax.inject.Inject
 import kotlinx.coroutines.flow.Flow
@@ -37,6 +37,7 @@
 @Inject
 constructor(
     @Application private val context: Context,
+    private val packageManager: PackageManager,
     private val cameraGestureHelper: Lazy<CameraGestureHelper>,
 ) : KeyguardQuickAffordanceConfig {
 
@@ -79,6 +80,6 @@
     }
 
     private fun isLaunchable(): Boolean {
-        return cameraGestureHelper.get().canCameraGestureBeLaunched(StatusBarState.KEYGUARD)
+        return packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskController.kt b/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskController.kt
index 08d1857..6bfe1a0 100644
--- a/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskController.kt
+++ b/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskController.kt
@@ -17,10 +17,12 @@
 package com.android.systemui.notetask
 
 import android.app.KeyguardManager
+import android.content.ActivityNotFoundException
 import android.content.ComponentName
 import android.content.Context
 import android.content.pm.PackageManager
 import android.os.UserManager
+import android.util.Log
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.notetask.shortcut.CreateNoteTaskShortcutActivity
 import com.android.systemui.util.kotlin.getOrNull
@@ -57,7 +59,7 @@
      * If the keyguard is locked, notes will open as a full screen experience. A locked device has
      * no contextual information which let us use the whole screen space available.
      *
-     * If no in multi-window or the keyguard is unlocked, notes will open as a bubble OR it will be
+     * If not in multi-window or the keyguard is unlocked, notes will open as a bubble OR it will be
      * collapsed if the notes bubble is already opened.
      *
      * That will let users open other apps in full screen, and take contextual notes.
@@ -68,16 +70,23 @@
         val bubbles = optionalBubbles.getOrNull() ?: return
         val keyguardManager = optionalKeyguardManager.getOrNull() ?: return
         val userManager = optionalUserManager.getOrNull() ?: return
-        val intent = intentResolver.resolveIntent() ?: return
 
         // TODO(b/249954038): We should handle direct boot (isUserUnlocked). For now, we do nothing.
         if (!userManager.isUserUnlocked) return
 
-        if (isInMultiWindowMode || keyguardManager.isKeyguardLocked) {
-            context.startActivity(intent)
-        } else {
-            // TODO(b/254606432): Should include Intent.EXTRA_FLOATING_WINDOW_MODE parameter.
-            bubbles.showOrHideAppBubble(intent)
+        val intent = intentResolver.resolveIntent() ?: return
+
+        // TODO(b/266686199): We should handle when app not available. For now, we log.
+        try {
+            if (isInMultiWindowMode || keyguardManager.isKeyguardLocked) {
+                context.startActivity(intent)
+            } else {
+                bubbles.showOrHideAppBubble(intent)
+            }
+        } catch (e: ActivityNotFoundException) {
+            val message =
+                "Activity not found for action: ${NoteTaskIntentResolver.ACTION_CREATE_NOTE}."
+            Log.e(TAG, message, e)
         }
     }
 
@@ -106,6 +115,8 @@
     }
 
     companion object {
+        private val TAG = NoteTaskController::class.simpleName.orEmpty()
+
         // TODO(b/254604589): Use final KeyEvent.KEYCODE_* instead.
         const val NOTE_TASK_KEY_EVENT = 311
     }
diff --git a/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskIntentResolver.kt b/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskIntentResolver.kt
index 4b10d69..11dc1d7 100644
--- a/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskIntentResolver.kt
+++ b/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskIntentResolver.kt
@@ -16,70 +16,39 @@
 
 package com.android.systemui.notetask
 
-import android.content.ComponentName
+import android.app.role.RoleManager
+import android.content.Context
 import android.content.Intent
-import android.content.pm.ActivityInfo
-import android.content.pm.PackageManager
-import android.content.pm.PackageManager.ResolveInfoFlags
-import com.android.systemui.notetask.NoteTaskIntentResolver.Companion.ACTION_CREATE_NOTE
 import javax.inject.Inject
 
-/**
- * Class responsible to query all apps and find one that can handle the [ACTION_CREATE_NOTE]. If
- * found, an [Intent] ready for be launched will be returned. Otherwise, returns null.
- *
- * TODO(b/248274123): should be revisited once the notes role is implemented.
- */
 internal class NoteTaskIntentResolver
 @Inject
 constructor(
-    private val packageManager: PackageManager,
+    private val context: Context,
+    private val roleManager: RoleManager,
 ) {
 
     fun resolveIntent(): Intent? {
-        val intent = Intent(ACTION_CREATE_NOTE)
-        val flags = ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY.toLong())
-        val infoList = packageManager.queryIntentActivities(intent, flags)
+        val packageName = roleManager.getRoleHoldersAsUser(ROLE_NOTES, context.user).firstOrNull()
 
-        for (info in infoList) {
-            val packageName = info.activityInfo.applicationInfo.packageName ?: continue
-            val activityName = resolveActivityNameForNotesAction(packageName) ?: continue
+        if (packageName.isNullOrEmpty()) return null
 
-            return Intent(ACTION_CREATE_NOTE)
-                .setPackage(packageName)
-                .setComponent(ComponentName(packageName, activityName))
-                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
-        }
-
-        return null
-    }
-
-    private fun resolveActivityNameForNotesAction(packageName: String): String? {
-        val intent = Intent(ACTION_CREATE_NOTE).setPackage(packageName)
-        val flags = ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY.toLong())
-        val resolveInfo = packageManager.resolveActivity(intent, flags)
-
-        val activityInfo = resolveInfo?.activityInfo ?: return null
-        if (activityInfo.name.isNullOrBlank()) return null
-        if (!activityInfo.exported) return null
-        if (!activityInfo.enabled) return null
-        if (!activityInfo.showWhenLocked) return null
-        if (!activityInfo.turnScreenOn) return null
-
-        return activityInfo.name
+        return Intent(ACTION_CREATE_NOTE)
+            .setPackage(packageName)
+            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+            // EXTRA_USE_STYLUS_MODE does not mean a stylus is in-use, but a stylus entrypoint was
+            // used to start it.
+            .putExtra(INTENT_EXTRA_USE_STYLUS_MODE, true)
     }
 
     companion object {
-        // TODO(b/254606432): Use Intent.ACTION_CREATE_NOTE instead.
+        // TODO(b/265912743): Use Intent.ACTION_CREATE_NOTE instead.
         const val ACTION_CREATE_NOTE = "android.intent.action.CREATE_NOTE"
 
         // TODO(b/265912743): Use RoleManager.NOTES_ROLE instead.
-        const val NOTE_ROLE = "android.app.role.NOTES"
+        const val ROLE_NOTES = "android.app.role.NOTES"
+
+        // TODO(b/265912743): Use Intent.INTENT_EXTRA_USE_STYLUS_MODE instead.
+        const val INTENT_EXTRA_USE_STYLUS_MODE = "android.intent.extra.USE_STYLUS_MODE"
     }
 }
-
-private val ActivityInfo.showWhenLocked: Boolean
-    get() = flags and ActivityInfo.FLAG_SHOW_WHEN_LOCKED != 0
-
-private val ActivityInfo.turnScreenOn: Boolean
-    get() = flags and ActivityInfo.FLAG_TURN_SCREEN_ON != 0
diff --git a/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskModule.kt b/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskModule.kt
index 22ce121..ec6a16a 100644
--- a/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/notetask/NoteTaskModule.kt
@@ -51,7 +51,7 @@
             featureFlags: FeatureFlags,
             roleManager: RoleManager,
         ): Boolean {
-            val isRoleAvailable = roleManager.isRoleAvailable(NoteTaskIntentResolver.NOTE_ROLE)
+            val isRoleAvailable = roleManager.isRoleAvailable(NoteTaskIntentResolver.ROLE_NOTES)
             val isFeatureEnabled = featureFlags.isEnabled(Flags.NOTE_TASKS)
             return isRoleAvailable && isFeatureEnabled
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/FlashlightControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/FlashlightControllerImpl.java
index 9946b4b..5dcafb3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/FlashlightControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/FlashlightControllerImpl.java
@@ -17,7 +17,6 @@
 package com.android.systemui.statusbar.policy;
 
 import android.annotation.WorkerThread;
-import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.hardware.camera2.CameraAccessException;
 import android.hardware.camera2.CameraCharacteristics;
@@ -255,7 +254,6 @@
                 setTorchMode(enabled);
                 mSecureSettings.putInt(Settings.Secure.FLASHLIGHT_AVAILABLE, 1);
                 mSecureSettings.putInt(Secure.FLASHLIGHT_ENABLED, enabled ? 1 : 0);
-                mBroadcastSender.sendBroadcast(new Intent(ACTION_FLASHLIGHT_CHANGED));
             }
         }
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/CustomizationProviderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/CustomizationProviderTest.kt
index c0af0cb..fb54d6d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/CustomizationProviderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/CustomizationProviderTest.kt
@@ -62,6 +62,7 @@
 import kotlinx.coroutines.ExperimentalCoroutinesApi
 import kotlinx.coroutines.test.StandardTestDispatcher
 import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.UnconfinedTestDispatcher
 import kotlinx.coroutines.test.runTest
 import org.junit.Before
 import org.junit.Test
@@ -184,6 +185,7 @@
                 mainDispatcher = testDispatcher,
                 backgroundHandler = backgroundHandler,
             )
+        underTest.mainDispatcher = UnconfinedTestDispatcher()
 
         underTest.attachInfoForTesting(
             context,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfigTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfigTest.kt
index 8da4eae..58cdec4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfigTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfigTest.kt
@@ -19,6 +19,7 @@
 
 import android.app.StatusBarManager
 import android.content.Context
+import android.content.pm.PackageManager
 import androidx.test.filters.SmallTest
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.camera.CameraGestureHelper
@@ -32,7 +33,6 @@
 import org.junit.runner.RunWith
 import org.junit.runners.JUnit4
 import org.mockito.Mock
-import org.mockito.Mockito.anyInt
 import org.mockito.Mockito.verify
 import org.mockito.MockitoAnnotations
 
@@ -43,16 +43,19 @@
 
     @Mock private lateinit var cameraGestureHelper: CameraGestureHelper
     @Mock private lateinit var context: Context
+    @Mock private lateinit var packageManager: PackageManager
 
     private lateinit var underTest: CameraQuickAffordanceConfig
 
     @Before
     fun setUp() {
         MockitoAnnotations.initMocks(this)
+        setLaunchable(true)
 
         underTest =
             CameraQuickAffordanceConfig(
                 context,
+                packageManager,
             ) {
                 cameraGestureHelper
             }
@@ -86,6 +89,7 @@
     }
 
     private fun setLaunchable(isLaunchable: Boolean) {
-        whenever(cameraGestureHelper.canCameraGestureBeLaunched(anyInt())).thenReturn(isLaunchable)
+        whenever(packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY))
+            .thenReturn(isLaunchable)
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/notetask/NoteTaskIntentResolverTest.kt b/packages/SystemUI/tests/src/com/android/systemui/notetask/NoteTaskIntentResolverTest.kt
index bbe60f4..18be92b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/notetask/NoteTaskIntentResolverTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/notetask/NoteTaskIntentResolverTest.kt
@@ -16,17 +16,14 @@
 
 package com.android.systemui.notetask
 
-import android.content.ComponentName
+import android.app.role.RoleManager
 import android.content.Intent
-import android.content.pm.ActivityInfo
-import android.content.pm.ApplicationInfo
 import android.content.pm.PackageManager
-import android.content.pm.PackageManager.ResolveInfoFlags
-import android.content.pm.ResolveInfo
 import android.test.suitebuilder.annotation.SmallTest
 import androidx.test.runner.AndroidJUnit4
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.notetask.NoteTaskIntentResolver.Companion.ACTION_CREATE_NOTE
+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
@@ -47,172 +44,39 @@
 internal class NoteTaskIntentResolverTest : SysuiTestCase() {
 
     @Mock lateinit var packageManager: PackageManager
+    @Mock lateinit var roleManager: RoleManager
 
-    private lateinit var resolver: NoteTaskIntentResolver
+    private lateinit var underTest: NoteTaskIntentResolver
 
     @Before
     fun setUp() {
         MockitoAnnotations.initMocks(this)
-        resolver = NoteTaskIntentResolver(packageManager)
-    }
-
-    private fun createResolveInfo(
-        activityInfo: ActivityInfo? = createActivityInfo(),
-    ): ResolveInfo {
-        return ResolveInfo().apply { this.activityInfo = activityInfo }
-    }
-
-    private fun createActivityInfo(
-        packageName: String = "PackageName",
-        name: String? = "ActivityName",
-        exported: Boolean = true,
-        enabled: Boolean = true,
-        showWhenLocked: Boolean = true,
-        turnScreenOn: Boolean = true,
-    ): ActivityInfo {
-        return ActivityInfo().apply {
-            this.name = name
-            this.exported = exported
-            this.enabled = enabled
-            if (showWhenLocked) {
-                flags = flags or ActivityInfo.FLAG_SHOW_WHEN_LOCKED
-            }
-            if (turnScreenOn) {
-                flags = flags or ActivityInfo.FLAG_TURN_SCREEN_ON
-            }
-            this.applicationInfo = ApplicationInfo().apply { this.packageName = packageName }
-        }
-    }
-
-    private fun givenQueryIntentActivities(block: () -> List<ResolveInfo>) {
-        whenever(packageManager.queryIntentActivities(any(), any<ResolveInfoFlags>()))
-            .thenReturn(block())
-    }
-
-    private fun givenResolveActivity(block: () -> ResolveInfo?) {
-        whenever(packageManager.resolveActivity(any(), any<ResolveInfoFlags>())).thenReturn(block())
+        underTest = NoteTaskIntentResolver(context, roleManager)
     }
 
     @Test
-    fun resolveIntent_shouldReturnNotesIntent() {
-        givenQueryIntentActivities { listOf(createResolveInfo()) }
-        givenResolveActivity { createResolveInfo(activityInfo = createActivityInfo()) }
+    fun resolveIntent_shouldReturnIntentInStylusMode() {
+        val packageName = "com.android.note.app"
+        whenever(roleManager.getRoleHoldersAsUser(NoteTaskIntentResolver.ROLE_NOTES, context.user))
+            .then { listOf(packageName) }
 
-        val actual = resolver.resolveIntent()
+        val actual = underTest.resolveIntent()
 
-        val expected =
-            Intent(ACTION_CREATE_NOTE)
-                .setPackage("PackageName")
-                .setComponent(ComponentName("PackageName", "ActivityName"))
-                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
-        // Compares the string representation of both intents, as they are different instances.
-        assertThat(actual.toString()).isEqualTo(expected.toString())
+        requireNotNull(actual) { "Intent must not be null" }
+        assertThat(actual.action).isEqualTo(ACTION_CREATE_NOTE)
+        assertThat(actual.`package`).isEqualTo(packageName)
+        val expectedExtra = actual.getExtra(NoteTaskIntentResolver.INTENT_EXTRA_USE_STYLUS_MODE)
+        assertThat(expectedExtra).isEqualTo(true)
+        val expectedFlag = actual.flags and Intent.FLAG_ACTIVITY_NEW_TASK
+        assertThat(expectedFlag).isEqualTo(Intent.FLAG_ACTIVITY_NEW_TASK)
     }
 
     @Test
-    fun resolveIntent_activityInfoEnabledIsFalse_shouldReturnNull() {
-        givenQueryIntentActivities { listOf(createResolveInfo()) }
-        givenResolveActivity {
-            createResolveInfo(activityInfo = createActivityInfo(enabled = false))
-        }
+    fun resolveIntent_noRoleHolderIsSet_shouldReturnNull() {
+        whenever(roleManager.getRoleHoldersAsUser(eq(NoteTaskIntentResolver.ROLE_NOTES), any()))
+            .then { listOf<String>() }
 
-        val actual = resolver.resolveIntent()
-
-        assertThat(actual).isNull()
-    }
-
-    @Test
-    fun resolveIntent_activityInfoExportedIsFalse_shouldReturnNull() {
-        givenQueryIntentActivities { listOf(createResolveInfo()) }
-        givenResolveActivity {
-            createResolveInfo(activityInfo = createActivityInfo(exported = false))
-        }
-
-        val actual = resolver.resolveIntent()
-
-        assertThat(actual).isNull()
-    }
-
-    @Test
-    fun resolveIntent_activityInfoShowWhenLockedIsFalse_shouldReturnNull() {
-        givenQueryIntentActivities { listOf(createResolveInfo()) }
-        givenResolveActivity {
-            createResolveInfo(activityInfo = createActivityInfo(showWhenLocked = false))
-        }
-
-        val actual = resolver.resolveIntent()
-
-        assertThat(actual).isNull()
-    }
-
-    @Test
-    fun resolveIntent_activityInfoTurnScreenOnIsFalse_shouldReturnNull() {
-        givenQueryIntentActivities { listOf(createResolveInfo()) }
-        givenResolveActivity {
-            createResolveInfo(activityInfo = createActivityInfo(turnScreenOn = false))
-        }
-
-        val actual = resolver.resolveIntent()
-
-        assertThat(actual).isNull()
-    }
-
-    @Test
-    fun resolveIntent_activityInfoNameIsBlank_shouldReturnNull() {
-        givenQueryIntentActivities { listOf(createResolveInfo()) }
-        givenResolveActivity { createResolveInfo(activityInfo = createActivityInfo(name = "")) }
-
-        val actual = resolver.resolveIntent()
-
-        assertThat(actual).isNull()
-    }
-
-    @Test
-    fun resolveIntent_activityInfoNameIsNull_shouldReturnNull() {
-        givenQueryIntentActivities { listOf(createResolveInfo()) }
-        givenResolveActivity { createResolveInfo(activityInfo = createActivityInfo(name = null)) }
-
-        val actual = resolver.resolveIntent()
-
-        assertThat(actual).isNull()
-    }
-
-    @Test
-    fun resolveIntent_activityInfoIsNull_shouldReturnNull() {
-        givenQueryIntentActivities { listOf(createResolveInfo()) }
-        givenResolveActivity { createResolveInfo(activityInfo = null) }
-
-        val actual = resolver.resolveIntent()
-
-        assertThat(actual).isNull()
-    }
-
-    @Test
-    fun resolveIntent_resolveActivityIsNull_shouldReturnNull() {
-        givenQueryIntentActivities { listOf(createResolveInfo()) }
-        givenResolveActivity { null }
-
-        val actual = resolver.resolveIntent()
-
-        assertThat(actual).isNull()
-    }
-
-    @Test
-    fun resolveIntent_packageNameIsBlank_shouldReturnNull() {
-        givenQueryIntentActivities {
-            listOf(createResolveInfo(createActivityInfo(packageName = "")))
-        }
-
-        val actual = resolver.resolveIntent()
-
-        assertThat(actual).isNull()
-    }
-
-    @Test
-    fun resolveIntent_activityNotFoundForAction_shouldReturnNull() {
-        givenQueryIntentActivities { emptyList() }
-
-        val actual = resolver.resolveIntent()
+        val actual = underTest.resolveIntent()
 
         assertThat(actual).isNull()
     }
diff --git a/services/autofill/java/com/android/server/autofill/ui/SaveUi.java b/services/autofill/java/com/android/server/autofill/ui/SaveUi.java
index 7db27ac..b68adab 100644
--- a/services/autofill/java/com/android/server/autofill/ui/SaveUi.java
+++ b/services/autofill/java/com/android/server/autofill/ui/SaveUi.java
@@ -199,8 +199,10 @@
                 intent.putExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY, true);
 
                 PendingIntent p = PendingIntent.getActivityAsUser(this, /* requestCode= */ 0,
-                        intent, PendingIntent.FLAG_MUTABLE, /* options= */ null,
-                        UserHandle.CURRENT);
+                        intent,
+                        PendingIntent.FLAG_MUTABLE
+                                | PendingIntent.FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT,
+                        /* options= */ null, UserHandle.CURRENT);
                 if (sDebug) {
                     Slog.d(TAG, "startActivity add save UI restored with intent=" + intent);
                 }
diff --git a/services/companion/java/com/android/server/companion/datatransfer/contextsync/CallMetadataSyncCallback.java b/services/companion/java/com/android/server/companion/datatransfer/contextsync/CallMetadataSyncCallback.java
index 56e777f..7c339d2 100644
--- a/services/companion/java/com/android/server/companion/datatransfer/contextsync/CallMetadataSyncCallback.java
+++ b/services/companion/java/com/android/server/companion/datatransfer/contextsync/CallMetadataSyncCallback.java
@@ -22,4 +22,6 @@
     abstract void processCallControlAction(int crossDeviceCallId, int callControlAction);
 
     abstract void requestCrossDeviceSync(int userId);
+
+    abstract void updateStatus(int userId, boolean shouldSyncCallMetadata);
 }
diff --git a/services/companion/java/com/android/server/companion/datatransfer/contextsync/CallMetadataSyncInCallService.java b/services/companion/java/com/android/server/companion/datatransfer/contextsync/CallMetadataSyncInCallService.java
index 97e70a4..ae4766a 100644
--- a/services/companion/java/com/android/server/companion/datatransfer/contextsync/CallMetadataSyncInCallService.java
+++ b/services/companion/java/com/android/server/companion/datatransfer/contextsync/CallMetadataSyncInCallService.java
@@ -39,6 +39,8 @@
 
     @VisibleForTesting
     final Map<Call, CrossDeviceCall> mCurrentCalls = new HashMap<>();
+    @VisibleForTesting
+    boolean mShouldSync;
     final Call.Callback mTelecomCallback = new Call.Callback() {
         @Override
         public void onDetailsChanged(Call call, Call.Details details) {
@@ -92,12 +94,29 @@
         @Override
         void requestCrossDeviceSync(int userId) {
         }
+
+        @Override
+        void updateStatus(int userId, boolean shouldSyncCallMetadata) {
+            if (userId == getUserId()) {
+                mShouldSync = shouldSyncCallMetadata;
+                if (shouldSyncCallMetadata) {
+                    initializeCalls();
+                } else {
+                    mCurrentCalls.clear();
+                }
+            }
+        }
     };
 
     @Override
     public void onCreate() {
         super.onCreate();
-        if (CompanionDeviceConfig.isEnabled(CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
+        initializeCalls();
+    }
+
+    private void initializeCalls() {
+        if (CompanionDeviceConfig.isEnabled(CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)
+                && mShouldSync) {
             mCurrentCalls.putAll(getCalls().stream().collect(Collectors.toMap(call -> call,
                     call -> new CrossDeviceCall(getPackageManager(), call, getCallAudioState()))));
         }
@@ -119,7 +138,8 @@
 
     @Override
     public void onCallAdded(Call call) {
-        if (CompanionDeviceConfig.isEnabled(CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
+        if (CompanionDeviceConfig.isEnabled(CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)
+                && mShouldSync) {
             mCurrentCalls.put(call,
                     new CrossDeviceCall(getPackageManager(), call, getCallAudioState()));
         }
@@ -127,21 +147,24 @@
 
     @Override
     public void onCallRemoved(Call call) {
-        if (CompanionDeviceConfig.isEnabled(CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
+        if (CompanionDeviceConfig.isEnabled(CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)
+                && mShouldSync) {
             mCurrentCalls.remove(call);
         }
     }
 
     @Override
     public void onMuteStateChanged(boolean isMuted) {
-        if (CompanionDeviceConfig.isEnabled(CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
+        if (CompanionDeviceConfig.isEnabled(CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)
+                && mShouldSync) {
             mCurrentCalls.values().forEach(call -> call.updateMuted(isMuted));
         }
     }
 
     @Override
     public void onSilenceRinger() {
-        if (CompanionDeviceConfig.isEnabled(CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)) {
+        if (CompanionDeviceConfig.isEnabled(CompanionDeviceConfig.ENABLE_CONTEXT_SYNC_TELECOM)
+                && mShouldSync) {
             mCurrentCalls.values().forEach(call -> call.updateSilencedIfRinging());
         }
     }
diff --git a/services/core/java/android/os/BatteryStatsInternal.java b/services/core/java/android/os/BatteryStatsInternal.java
index b70cbe3..9c2de65 100644
--- a/services/core/java/android/os/BatteryStatsInternal.java
+++ b/services/core/java/android/os/BatteryStatsInternal.java
@@ -18,6 +18,7 @@
 
 import android.annotation.IntDef;
 import android.annotation.NonNull;
+import android.net.Network;
 
 import com.android.internal.os.BinderCallsStats;
 import com.android.server.power.stats.SystemServerCpuThreadReader.SystemServiceCpuThreadTimes;
@@ -82,6 +83,15 @@
     public abstract void noteJobsDeferred(int uid, int numDeferred, long sinceLast);
 
     /**
+     * Informs battery stats of a data packet that woke up the CPU.
+     *
+     * @param network The network over which the packet arrived.
+     * @param elapsedMillis The time of the packet's arrival in elapsed timebase.
+     * @param uid The uid that received the packet.
+     */
+    public abstract void noteCpuWakingNetworkPacket(Network network, long elapsedMillis, int uid);
+
+    /**
      * Informs battery stats of binder stats for the given work source UID.
      */
     public abstract void noteBinderCallStats(int workSourceUid, long incrementalBinderCallCount,
diff --git a/services/core/java/com/android/server/BinaryTransparencyService.java b/services/core/java/com/android/server/BinaryTransparencyService.java
index 8f594a5..ecc303f 100644
--- a/services/core/java/com/android/server/BinaryTransparencyService.java
+++ b/services/core/java/com/android/server/BinaryTransparencyService.java
@@ -53,9 +53,12 @@
 import android.hardware.biometrics.SensorProperties.ComponentInfo;
 import android.hardware.face.FaceManager;
 import android.hardware.face.FaceSensorProperties;
+import android.hardware.face.FaceSensorPropertiesInternal;
+import android.hardware.face.IFaceAuthenticatorsRegisteredCallback;
 import android.hardware.fingerprint.FingerprintManager;
 import android.hardware.fingerprint.FingerprintSensorProperties;
 import android.hardware.fingerprint.FingerprintSensorPropertiesInternal;
+import android.hardware.fingerprint.IFingerprintAuthenticatorsRegisteredCallback;
 import android.net.Uri;
 import android.os.Binder;
 import android.os.Build;
@@ -100,7 +103,6 @@
  */
 public class BinaryTransparencyService extends SystemService {
     private static final String TAG = "TransparencyService";
-    private static final String EXTRA_SERVICE = "service";
 
     @VisibleForTesting
     static final String VBMETA_DIGEST_UNINITIALIZED = "vbmeta-digest-uninitialized";
@@ -254,31 +256,30 @@
         /**
          * Measures and records digests for *all* covered binaries/packages.
          *
-         * This method will be called in a Job scheduled to take measurements periodically.
+         * This method will be called in a Job scheduled to take measurements periodically. If the
+         * last measurement was performaned recently (less than RECORD_MEASUREMENT_COOLDOWN_MS
+         * ago), the measurement and recording will be skipped.
          *
          * Packages that are covered so far are:
          * - all APEXs (introduced in Android T)
          * - all mainline modules (introduced in Android T)
          * - all preloaded apps and their update(s) (new in Android U)
          * - dynamically installed mobile bundled apps (MBAs) (new in Android U)
-         *
-         * @return a {@code List<Bundle>}. Each Bundle item contains values as
-         *          defined by the return value of {@link #measurePackage(PackageInfo)}.
          */
-        public List getMeasurementsForAllPackages() {
-            List<Bundle> results = new ArrayList<>();
-            PackageManager pm = mContext.getPackageManager();
-            Set<String> packagesMeasured = new HashSet<>();
-
+        public void recordMeasurementsForAllPackages() {
             // check if we should record the resulting measurements
             long currentTimeMs = System.currentTimeMillis();
-            boolean record = false;
-            if ((currentTimeMs - mMeasurementsLastRecordedMs) >= RECORD_MEASUREMENTS_COOLDOWN_MS) {
-                Slog.d(TAG, "Measurement was last taken at " + mMeasurementsLastRecordedMs
-                        + " and is now updated to: " + currentTimeMs);
-                mMeasurementsLastRecordedMs = currentTimeMs;
-                record = true;
+            if ((currentTimeMs - mMeasurementsLastRecordedMs) < RECORD_MEASUREMENTS_COOLDOWN_MS) {
+                Slog.d(TAG, "Skip measurement since the last measurement was only taken at "
+                        + mMeasurementsLastRecordedMs + " within the cooldown period");
+                return;
             }
+            Slog.d(TAG, "Measurement was last taken at " + mMeasurementsLastRecordedMs
+                    + " and is now updated to: " + currentTimeMs);
+            mMeasurementsLastRecordedMs = currentTimeMs;
+
+            PackageManager pm = mContext.getPackageManager();
+            Set<String> packagesMeasured = new HashSet<>();
 
             // measure all APEXs first
             if (DEBUG) {
@@ -288,22 +289,17 @@
                 packagesMeasured.add(packageInfo.packageName);
 
                 Bundle apexMeasurement = measurePackage(packageInfo);
-                results.add(apexMeasurement);
 
-                if (record) {
-                    // compute digests of signing info
-                    String[] signerDigestHexStrings = computePackageSignerSha256Digests(
-                            packageInfo.signingInfo);
+                var apexInfo = new IBinaryTransparencyService.ApexInfo();
+                apexInfo.packageName = packageInfo.packageName;
+                apexInfo.longVersion = packageInfo.getLongVersionCode();
+                apexInfo.digest = apexMeasurement.getByteArray(BUNDLE_CONTENT_DIGEST);
+                apexInfo.digestAlgorithm =
+                        apexMeasurement.getInt(BUNDLE_CONTENT_DIGEST_ALGORITHM);
+                apexInfo.signerDigests =
+                        computePackageSignerSha256Digests(packageInfo.signingInfo);
 
-                    // log to statsd
-                    FrameworkStatsLog.write(FrameworkStatsLog.APEX_INFO_GATHERED,
-                                            packageInfo.packageName,
-                                            packageInfo.getLongVersionCode(),
-                                            HexEncoding.encodeToString(apexMeasurement.getByteArray(
-                                                    BUNDLE_CONTENT_DIGEST), false),
-                                            apexMeasurement.getInt(BUNDLE_CONTENT_DIGEST_ALGORITHM),
-                                            signerDigestHexStrings);
-                }
+                recordApexInfo(apexInfo);
             }
             if (DEBUG) {
                 Slog.d(TAG, "Measured " + packagesMeasured.size()
@@ -319,11 +315,11 @@
                 }
                 packagesMeasured.add(packageInfo.packageName);
 
-                int mba_status = MBA_STATUS_PRELOADED;
+                int mbaStatus = MBA_STATUS_PRELOADED;
                 if (packageInfo.signingInfo == null) {
                     Slog.d(TAG, "Preload " + packageInfo.packageName  + " at "
                             + packageInfo.applicationInfo.sourceDir + " has likely been updated.");
-                    mba_status = MBA_STATUS_UPDATED_PRELOAD;
+                    mbaStatus = MBA_STATUS_UPDATED_PRELOAD;
 
                     PackageInfo origPackageInfo = packageInfo;
                     try {
@@ -334,33 +330,24 @@
                         Slog.e(TAG, "Failed to obtain an updated PackageInfo of "
                                 + origPackageInfo.packageName, e);
                         packageInfo = origPackageInfo;
-                        mba_status = MBA_STATUS_ERROR;
+                        mbaStatus = MBA_STATUS_ERROR;
                     }
                 }
 
+                if (mbaStatus == MBA_STATUS_UPDATED_PRELOAD) {
+                    Bundle packageMeasurement = measurePackage(packageInfo);
 
-                Bundle packageMeasurement = measurePackage(packageInfo);
-                results.add(packageMeasurement);
+                    var appInfo = new IBinaryTransparencyService.AppInfo();
+                    appInfo.packageName = packageInfo.packageName;
+                    appInfo.longVersion = packageInfo.getLongVersionCode();
+                    appInfo.digest = packageMeasurement.getByteArray(BUNDLE_CONTENT_DIGEST);
+                    appInfo.digestAlgorithm =
+                            packageMeasurement.getInt(BUNDLE_CONTENT_DIGEST_ALGORITHM);
+                    appInfo.signerDigests =
+                            computePackageSignerSha256Digests(packageInfo.signingInfo);
+                    appInfo.mbaStatus = mbaStatus;
 
-                if (record && (mba_status == MBA_STATUS_UPDATED_PRELOAD)) {
-                    // compute digests of signing info
-                    String[] signerDigestHexStrings = computePackageSignerSha256Digests(
-                            packageInfo.signingInfo);
-
-                    // now we should have all the bits for the atom
-                    byte[] cDigest = packageMeasurement.getByteArray(BUNDLE_CONTENT_DIGEST);
-                    FrameworkStatsLog.write(FrameworkStatsLog.MOBILE_BUNDLED_APP_INFO_GATHERED,
-                            packageInfo.packageName,
-                            packageInfo.getLongVersionCode(),
-                            (cDigest != null) ? HexEncoding.encodeToString(cDigest, false) : null,
-                            packageMeasurement.getInt(BUNDLE_CONTENT_DIGEST_ALGORITHM),
-                            signerDigestHexStrings, // signer_cert_digest
-                            mba_status,             // mba_status
-                            null,                   // initiator
-                            null,                   // initiator_signer_digest
-                            null,                   // installer
-                            null                    // originator
-                    );
+                    writeAppInfoToLog(appInfo);
                 }
             }
             if (DEBUG) {
@@ -377,54 +364,37 @@
                     packagesMeasured.add(packageInfo.packageName);
 
                     Bundle packageMeasurement = measurePackage(packageInfo);
-                    results.add(packageMeasurement);
 
-                    if (record) {
-                        // compute digests of signing info
-                        String[] signerDigestHexStrings = computePackageSignerSha256Digests(
-                                packageInfo.signingInfo);
-
-                        // then extract package's InstallSourceInfo
-                        if (DEBUG) {
-                            Slog.d(TAG,
-                                    "Extracting InstallSourceInfo for " + packageInfo.packageName);
-                        }
-                        InstallSourceInfo installSourceInfo = getInstallSourceInfo(
-                                packageInfo.packageName);
-                        String initiator = null;
-                        SigningInfo initiatorSignerInfo = null;
-                        String[] initiatorSignerInfoDigest = null;
-                        String installer = null;
-                        String originator = null;
-
-                        if (installSourceInfo != null) {
-                            initiator = installSourceInfo.getInitiatingPackageName();
-                            initiatorSignerInfo =
-                                    installSourceInfo.getInitiatingPackageSigningInfo();
-                            if (initiatorSignerInfo != null) {
-                                initiatorSignerInfoDigest = computePackageSignerSha256Digests(
-                                        initiatorSignerInfo);
-                            }
-                            installer = installSourceInfo.getInstallingPackageName();
-                            originator = installSourceInfo.getOriginatingPackageName();
-                        }
-
-                        // we should now have all the info needed for the atom
-                        byte[] cDigest = packageMeasurement.getByteArray(BUNDLE_CONTENT_DIGEST);
-                        FrameworkStatsLog.write(FrameworkStatsLog.MOBILE_BUNDLED_APP_INFO_GATHERED,
-                                packageInfo.packageName,
-                                packageInfo.getLongVersionCode(),
-                                (cDigest != null) ? HexEncoding.encodeToString(cDigest, false)
-                                        : null,
-                                packageMeasurement.getInt(BUNDLE_CONTENT_DIGEST_ALGORITHM),
-                                signerDigestHexStrings,
-                                MBA_STATUS_NEW_INSTALL,   // mba_status
-                                initiator,
-                                initiatorSignerInfoDigest,
-                                installer,
-                                originator
-                        );
+                    if (DEBUG) {
+                        Slog.d(TAG,
+                                "Extracting InstallSourceInfo for " + packageInfo.packageName);
                     }
+                    var appInfo = new IBinaryTransparencyService.AppInfo();
+                    appInfo.packageName = packageInfo.packageName;
+                    appInfo.longVersion = packageInfo.getLongVersionCode();
+                    appInfo.digest = packageMeasurement.getByteArray(BUNDLE_CONTENT_DIGEST);
+                    appInfo.digestAlgorithm =
+                            packageMeasurement.getInt(BUNDLE_CONTENT_DIGEST_ALGORITHM);
+                    appInfo.signerDigests =
+                            computePackageSignerSha256Digests(packageInfo.signingInfo);
+                    appInfo.mbaStatus = MBA_STATUS_NEW_INSTALL;
+
+                    // extract package's InstallSourceInfo
+                    InstallSourceInfo installSourceInfo = getInstallSourceInfo(
+                            packageInfo.packageName);
+                    if (installSourceInfo != null) {
+                        appInfo.initiator = installSourceInfo.getInitiatingPackageName();
+                        SigningInfo initiatorSignerInfo =
+                                installSourceInfo.getInitiatingPackageSigningInfo();
+                        if (initiatorSignerInfo != null) {
+                            appInfo.initiatorSignerDigests =
+                                    computePackageSignerSha256Digests(initiatorSignerInfo);
+                        }
+                        appInfo.installer = installSourceInfo.getInstallingPackageName();
+                        appInfo.originator = installSourceInfo.getOriginatingPackageName();
+                    }
+
+                    writeAppInfoToLog(appInfo);
                 }
             }
             if (DEBUG) {
@@ -432,8 +402,31 @@
                 Slog.d(TAG, "Measured " + packagesMeasured.size()
                         + " packages altogether in " + timeSpentMeasuring + "ms");
             }
+        }
 
-            return results;
+        private void recordApexInfo(IBinaryTransparencyService.ApexInfo apexInfo) {
+            FrameworkStatsLog.write(FrameworkStatsLog.APEX_INFO_GATHERED,
+                    apexInfo.packageName,
+                    apexInfo.longVersion,
+                    (apexInfo.digest != null) ? HexEncoding.encodeToString(apexInfo.digest, false)
+                            : null,
+                    apexInfo.digestAlgorithm,
+                    apexInfo.signerDigests);
+        }
+
+        private void writeAppInfoToLog(IBinaryTransparencyService.AppInfo appInfo) {
+            FrameworkStatsLog.write(FrameworkStatsLog.MOBILE_BUNDLED_APP_INFO_GATHERED,
+                    appInfo.packageName,
+                    appInfo.longVersion,
+                    (appInfo.digest != null) ? HexEncoding.encodeToString(appInfo.digest, false)
+                            : null,
+                    appInfo.digestAlgorithm,
+                    appInfo.signerDigests,
+                    appInfo.mbaStatus,
+                    appInfo.initiator,
+                    appInfo.initiatorSignerDigests,
+                    appInfo.installer,
+                    appInfo.originator);
         }
 
         /**
@@ -1179,14 +1172,11 @@
             // where this operation might take longer than expected, and so that we don't block
             // system_server's main thread.
             Executors.defaultThreadFactory().newThread(() -> {
-                // we discard the return value of getMeasurementsForAllPackages() as the
-                // results of the measurements will be recorded, and that is what we're aiming
-                // for with this job.
                 IBinder b = ServiceManager.getService(Context.BINARY_TRANSPARENCY_SERVICE);
                 IBinaryTransparencyService iBtsService =
                         IBinaryTransparencyService.Stub.asInterface(b);
                 try {
-                    iBtsService.getMeasurementsForAllPackages();
+                    iBtsService.recordMeasurementsForAllPackages();
                 } catch (RemoteException e) {
                     Slog.e(TAG, "Taking binary measurements was interrupted.", e);
                     return;
@@ -1371,25 +1361,51 @@
         }
 
         if (fpManager != null) {
-            // Log data for each fingerprint sensor
-            for (FingerprintSensorPropertiesInternal propInternal :
-                    fpManager.getSensorPropertiesInternal()) {
-                final FingerprintSensorProperties prop =
-                        FingerprintSensorProperties.from(propInternal);
-                logBiometricProperties(prop,
-                        FrameworkStatsLog
-                                .BIOMETRIC_PROPERTIES_COLLECTED__MODALITY__MODALITY_FINGERPRINT,
-                        toFingerprintSensorType(prop.getSensorType()));
-            }
+            final int fpModality = FrameworkStatsLog
+                    .BIOMETRIC_PROPERTIES_COLLECTED__MODALITY__MODALITY_FINGERPRINT;
+            fpManager.addAuthenticatorsRegisteredCallback(
+                    new IFingerprintAuthenticatorsRegisteredCallback.Stub() {
+                        @Override
+                        public void onAllAuthenticatorsRegistered(
+                                List<FingerprintSensorPropertiesInternal> sensors) {
+                            if (DEBUG) {
+                                Slog.d(TAG, "Retrieve fingerprint sensor properties. "
+                                        + "sensors.size()=" + sensors.size());
+                            }
+                            // Log data for each fingerprint sensor
+                            for (FingerprintSensorPropertiesInternal propInternal : sensors) {
+                                final FingerprintSensorProperties prop =
+                                        FingerprintSensorProperties.from(propInternal);
+                                logBiometricProperties(prop,
+                                        fpModality,
+                                        toFingerprintSensorType(prop.getSensorType()));
+                            }
+                        }
+                    });
         }
 
         if (faceManager != null) {
-            // Log data for each face sensor
-            for (FaceSensorProperties prop : faceManager.getSensorProperties()) {
-                logBiometricProperties(prop,
-                        FrameworkStatsLog.BIOMETRIC_PROPERTIES_COLLECTED__MODALITY__MODALITY_FACE,
-                        toFaceSensorType(prop.getSensorType()));
-            }
+            final int faceModality = FrameworkStatsLog
+                    .BIOMETRIC_PROPERTIES_COLLECTED__MODALITY__MODALITY_FACE;
+            faceManager.addAuthenticatorsRegisteredCallback(
+                    new IFaceAuthenticatorsRegisteredCallback.Stub() {
+                        @Override
+                        public void onAllAuthenticatorsRegistered(
+                                List<FaceSensorPropertiesInternal> sensors) {
+                            if (DEBUG) {
+                                Slog.d(TAG, "Retrieve face sensor properties. sensors.size()="
+                                        + sensors.size());
+                            }
+                            // Log data for each face sensor
+                            for (FaceSensorPropertiesInternal propInternal : sensors) {
+                                final FaceSensorProperties prop =
+                                        FaceSensorProperties.from(propInternal);
+                                logBiometricProperties(prop,
+                                        faceModality,
+                                        toFaceSensorType(prop.getSensorType()));
+                            }
+                        }
+                    });
         }
     }
 
diff --git a/services/core/java/com/android/server/am/BatteryStatsService.java b/services/core/java/com/android/server/am/BatteryStatsService.java
index 0327d16..7719c5a 100644
--- a/services/core/java/com/android/server/am/BatteryStatsService.java
+++ b/services/core/java/com/android/server/am/BatteryStatsService.java
@@ -457,6 +457,11 @@
         }
 
         @Override
+        public void noteCpuWakingNetworkPacket(Network network, long elapsedMillis, int uid) {
+            Slog.d(TAG, "Wakeup due to incoming packet on network " + network + " to uid " + uid);
+        }
+
+        @Override
         public void noteBinderCallStats(int workSourceUid, long incrementatCallCount,
                 Collection<BinderCallsStats.CallStat> callStats) {
             synchronized (BatteryStatsService.this.mLock) {
diff --git a/services/core/java/com/android/server/ambientcontext/AmbientContextManagerService.java b/services/core/java/com/android/server/ambientcontext/AmbientContextManagerService.java
index 7d9b272..a9a77bf 100644
--- a/services/core/java/com/android/server/ambientcontext/AmbientContextManagerService.java
+++ b/services/core/java/com/android/server/ambientcontext/AmbientContextManagerService.java
@@ -593,16 +593,19 @@
                     Manifest.permission.ACCESS_AMBIENT_CONTEXT_EVENT, TAG);
             assertCalledByPackageOwner(callingPackage);
 
-            for (ClientRequest cr : mExistingClientRequests) {
-                if (cr.getPackageName().equals(callingPackage)) {
-                    AmbientContextManagerPerUserService service =
-                            getAmbientContextManagerPerUserServiceForEventTypes(
-                            UserHandle.getCallingUserId(), cr.getRequest().getEventTypes());
-                    if (service != null) {
-                        service.onUnregisterObserver(callingPackage);
-                    } else {
-                        Slog.w(TAG, "onUnregisterObserver unavailable user_id: "
-                                + UserHandle.getCallingUserId());
+            synchronized (mLock) {
+                for (ClientRequest cr : mExistingClientRequests) {
+                    if (cr.getPackageName().equals(callingPackage)) {
+                        AmbientContextManagerPerUserService service =
+                                getAmbientContextManagerPerUserServiceForEventTypes(
+                                        UserHandle.getCallingUserId(),
+                                        cr.getRequest().getEventTypes());
+                        if (service != null) {
+                            service.onUnregisterObserver(callingPackage);
+                        } else {
+                            Slog.w(TAG, "onUnregisterObserver unavailable user_id: "
+                                    + UserHandle.getCallingUserId());
+                        }
                     }
                 }
             }
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index 4eb6c7f..4d8242c 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -6118,7 +6118,8 @@
         if (portId != 0) {
             device = AudioManager.getDeviceForPortId(portId, AudioManager.GET_DEVICES_OUTPUTS);
             if (device == null) {
-                throw new IllegalArgumentException("invalid portID " + portId);
+                Log.w(TAG, "setCommunicationDevice: invalid portID " + portId);
+                return false;
             }
             if (!isValidCommunicationDevice(device)) {
                 if (!device.isSink()) {
diff --git a/services/core/java/com/android/server/display/DisplayBrightnessState.java b/services/core/java/com/android/server/display/DisplayBrightnessState.java
index 87cbbfe..e27182f 100644
--- a/services/core/java/com/android/server/display/DisplayBrightnessState.java
+++ b/services/core/java/com/android/server/display/DisplayBrightnessState.java
@@ -28,11 +28,13 @@
     private final float mBrightness;
     private final float mSdrBrightness;
     private final BrightnessReason mBrightnessReason;
+    private final String mDisplayBrightnessStrategyName;
 
     private DisplayBrightnessState(Builder builder) {
         this.mBrightness = builder.getBrightness();
         this.mSdrBrightness = builder.getSdrBrightness();
         this.mBrightnessReason = builder.getBrightnessReason();
+        this.mDisplayBrightnessStrategyName = builder.getDisplayBrightnessStrategyName();
     }
 
     /**
@@ -56,6 +58,14 @@
         return mBrightnessReason;
     }
 
+    /**
+     * Gets the {@link com.android.server.display.brightness.strategy.DisplayBrightnessStrategy}
+     * name
+     */
+    public String getDisplayBrightnessStrategyName() {
+        return mDisplayBrightnessStrategyName;
+    }
+
     @Override
     public String toString() {
         StringBuilder stringBuilder = new StringBuilder("DisplayBrightnessState:");
@@ -93,6 +103,10 @@
         if (!mBrightnessReason.equals(displayBrightnessState.getBrightnessReason())) {
             return false;
         }
+        if (!mDisplayBrightnessStrategyName.equals(
+                displayBrightnessState.getDisplayBrightnessStrategyName())) {
+            return false;
+        }
         return true;
     }
 
@@ -108,6 +122,7 @@
         private float mBrightness;
         private float mSdrBrightness;
         private BrightnessReason mBrightnessReason = new BrightnessReason();
+        private String mDisplayBrightnessStrategyName;
 
         /**
          * Gets the brightness
@@ -164,6 +179,27 @@
         }
 
         /**
+         * Gets the {@link com.android.server.display.brightness.strategy.DisplayBrightnessStrategy}
+         * name
+         */
+        public String getDisplayBrightnessStrategyName() {
+            return mDisplayBrightnessStrategyName;
+        }
+
+        /**
+         * Sets the
+         * {@link com.android.server.display.brightness.strategy.DisplayBrightnessStrategy}'s name
+         *
+         * @param displayBrightnessStrategyName The name of the
+         * {@link com.android.server.display.brightness.strategy.DisplayBrightnessStrategy} being
+         *                                      used.
+         */
+        public Builder setDisplayBrightnessStrategyName(String displayBrightnessStrategyName) {
+            this.mDisplayBrightnessStrategyName = displayBrightnessStrategyName;
+            return this;
+        }
+
+        /**
          * This is used to construct an immutable DisplayBrightnessState object from its builder
          */
         public DisplayBrightnessState build() {
diff --git a/services/core/java/com/android/server/display/DisplayDeviceConfig.java b/services/core/java/com/android/server/display/DisplayDeviceConfig.java
index 535129c..e048a0f 100644
--- a/services/core/java/com/android/server/display/DisplayDeviceConfig.java
+++ b/services/core/java/com/android/server/display/DisplayDeviceConfig.java
@@ -17,12 +17,14 @@
 package com.android.server.display;
 
 import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.content.Context;
 import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.content.res.TypedArray;
 import android.hardware.display.DisplayManagerInternal;
 import android.hardware.display.DisplayManagerInternal.RefreshRateLimitation;
+import android.hardware.input.HostUsiVersion;
 import android.os.Environment;
 import android.os.PowerManager;
 import android.text.TextUtils;
@@ -57,6 +59,7 @@
 import com.android.server.display.config.ThermalStatus;
 import com.android.server.display.config.ThermalThrottling;
 import com.android.server.display.config.ThresholdPoint;
+import com.android.server.display.config.UsiVersion;
 import com.android.server.display.config.XmlParser;
 
 import org.xmlpull.v1.XmlPullParserException;
@@ -390,6 +393,12 @@
  *         <item>80</item>
  *         <item>1500</item>
  *     </screenOffBrightnessSensorValueToLux>
+ *     // The version of the Universal Stylus Initiative (USI) protocol supported by this display.
+ *     // This should be omitted if the display does not support USI styluses.
+ *     <usiVersion>
+ *         <majorVersion>2</majorVersion>
+ *         <minorVersion>0</minorVersion>
+ *     </usiVersion>
  *    </displayConfiguration>
  *  }
  *  </pre>
@@ -626,6 +635,9 @@
     // The concurrent displays mode might need a stricter throttling policy
     private BrightnessThrottlingData mConcurrentDisplaysBrightnessThrottlingData;
 
+    @Nullable
+    private HostUsiVersion mHostUsiVersion;
+
     @VisibleForTesting
     DisplayDeviceConfig(Context context) {
         mContext = context;
@@ -1370,6 +1382,15 @@
         return mScreenOffBrightnessSensorValueToLux;
     }
 
+    /**
+     * @return The USI version supported by this display, or null if USI is not supported.
+     * @see HostUsiVersion
+     */
+    @Nullable
+    public HostUsiVersion getHostUsiVersion() {
+        return mHostUsiVersion;
+    }
+
     @Override
     public String toString() {
         return "DisplayDeviceConfig{"
@@ -1474,6 +1495,8 @@
                 + "\n"
                 + ", mScreenOffBrightnessSensorValueToLux=" + Arrays.toString(
                 mScreenOffBrightnessSensorValueToLux)
+                + "\n"
+                + ", mUsiVersion= " + mHostUsiVersion
                 + "}";
     }
 
@@ -1535,6 +1558,7 @@
                 loadAutoBrightnessConfigValues(config);
                 loadRefreshRateSetting(config);
                 loadScreenOffBrightnessSensorValueToLuxFromDdc(config);
+                loadUsiVersion(config);
             } else {
                 Slog.w(TAG, "DisplayDeviceConfig file is null");
             }
@@ -2689,6 +2713,15 @@
         }
     }
 
+    private void loadUsiVersion(DisplayConfiguration config) {
+        final UsiVersion usiVersion = config.getUsiVersion();
+        mHostUsiVersion = usiVersion != null
+                ? new HostUsiVersion(
+                        usiVersion.getMajorVersion().intValue(),
+                        usiVersion.getMinorVersion().intValue())
+                : null;
+    }
+
     /**
      * Uniquely identifies a Sensor, with the combination of Type and Name.
      */
diff --git a/services/core/java/com/android/server/display/DisplayManagerService.java b/services/core/java/com/android/server/display/DisplayManagerService.java
index f2110fe..3f49ebe 100644
--- a/services/core/java/com/android/server/display/DisplayManagerService.java
+++ b/services/core/java/com/android/server/display/DisplayManagerService.java
@@ -86,6 +86,7 @@
 import android.hardware.display.VirtualDisplayConfig;
 import android.hardware.display.WifiDisplayStatus;
 import android.hardware.graphics.common.DisplayDecorationSupport;
+import android.hardware.input.HostUsiVersion;
 import android.media.projection.IMediaProjection;
 import android.media.projection.IMediaProjectionManager;
 import android.net.Uri;
@@ -4151,6 +4152,19 @@
 
             return SurfaceControl.getDisplayNativePrimaries(displayToken);
         }
+
+        @Override
+        public HostUsiVersion getHostUsiVersion(int displayId) {
+            synchronized (mSyncRoot) {
+                final LogicalDisplay display = mLogicalDisplayMapper.getDisplayLocked(displayId);
+                if (display == null) {
+                    return null;
+                }
+
+                return display.getPrimaryDisplayDeviceLocked().getDisplayDeviceConfig()
+                        .getHostUsiVersion();
+            }
+        }
     }
 
     class DesiredDisplayModeSpecsObserver
diff --git a/services/core/java/com/android/server/display/DisplayPowerController2.java b/services/core/java/com/android/server/display/DisplayPowerController2.java
index 103a1da..ae4824d7 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController2.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController2.java
@@ -1548,6 +1548,8 @@
                 ? mCdsi.getReduceBrightColorsStrength() : -1);
         mTempBrightnessEvent.setPowerFactor(mPowerRequest.screenLowPowerBrightnessFactor);
         mTempBrightnessEvent.setWasShortTermModelActive(hadUserBrightnessPoint);
+        mTempBrightnessEvent.setDisplayBrightnessStrategyName(displayBrightnessState
+                .getDisplayBrightnessStrategyName());
         // Temporary is what we use during slider interactions. We avoid logging those so that
         // we don't spam logcat when the slider is being used.
         boolean tempToTempTransition =
diff --git a/services/core/java/com/android/server/display/brightness/BrightnessEvent.java b/services/core/java/com/android/server/display/brightness/BrightnessEvent.java
index f19852b..8b09571 100644
--- a/services/core/java/com/android/server/display/brightness/BrightnessEvent.java
+++ b/services/core/java/com/android/server/display/brightness/BrightnessEvent.java
@@ -53,6 +53,7 @@
     private int mFlags;
     private int mAdjustmentFlags;
     private boolean mAutomaticBrightnessEnabled;
+    private String mDisplayBrightnessStrategyName;
 
     public BrightnessEvent(BrightnessEvent that) {
         copyFrom(that);
@@ -92,6 +93,7 @@
         mAdjustmentFlags = that.getAdjustmentFlags();
         // Auto-brightness setting
         mAutomaticBrightnessEnabled = that.isAutomaticBrightnessEnabled();
+        mDisplayBrightnessStrategyName = that.getDisplayBrightnessStrategyName();
     }
 
     /**
@@ -120,6 +122,7 @@
         mAdjustmentFlags = 0;
         // Auto-brightness setting
         mAutomaticBrightnessEnabled = true;
+        mDisplayBrightnessStrategyName = "";
     }
 
     /**
@@ -157,7 +160,8 @@
                 && mWasShortTermModelActive == that.mWasShortTermModelActive
                 && mFlags == that.mFlags
                 && mAdjustmentFlags == that.mAdjustmentFlags
-                && mAutomaticBrightnessEnabled == that.mAutomaticBrightnessEnabled;
+                && mAutomaticBrightnessEnabled == that.mAutomaticBrightnessEnabled
+                && mDisplayBrightnessStrategyName.equals(that.mDisplayBrightnessStrategyName);
     }
 
     /**
@@ -185,7 +189,8 @@
                 + ", wasShortTermModelActive=" + mWasShortTermModelActive
                 + ", flags=" + flagsToString()
                 + ", reason=" + mReason.toString(mAdjustmentFlags)
-                + ", autoBrightness=" + mAutomaticBrightnessEnabled;
+                + ", autoBrightness=" + mAutomaticBrightnessEnabled
+                + ", strategy=" + mDisplayBrightnessStrategyName;
     }
 
     @Override
@@ -355,6 +360,14 @@
         return mAutomaticBrightnessEnabled;
     }
 
+    public void setDisplayBrightnessStrategyName(String displayBrightnessStrategyName) {
+        mDisplayBrightnessStrategyName = displayBrightnessStrategyName;
+    }
+
+    public String getDisplayBrightnessStrategyName() {
+        return mDisplayBrightnessStrategyName;
+    }
+
     public void setAutomaticBrightnessEnabled(boolean mAutomaticBrightnessEnabled) {
         this.mAutomaticBrightnessEnabled = mAutomaticBrightnessEnabled;
     }
diff --git a/services/core/java/com/android/server/display/brightness/BrightnessUtils.java b/services/core/java/com/android/server/display/brightness/BrightnessUtils.java
index d5aeba1..169cc4a 100644
--- a/services/core/java/com/android/server/display/brightness/BrightnessUtils.java
+++ b/services/core/java/com/android/server/display/brightness/BrightnessUtils.java
@@ -45,13 +45,15 @@
      * A utility to construct the DisplayBrightnessState
      */
     public static DisplayBrightnessState constructDisplayBrightnessState(
-            int brightnessChangeReason, float brightness, float sdrBrightness) {
+            int brightnessChangeReason, float brightness, float sdrBrightness,
+            String displayBrightnessStrategyName) {
         BrightnessReason brightnessReason = new BrightnessReason();
         brightnessReason.setReason(brightnessChangeReason);
         return new DisplayBrightnessState.Builder()
                 .setBrightness(brightness)
                 .setSdrBrightness(sdrBrightness)
                 .setBrightnessReason(brightnessReason)
+                .setDisplayBrightnessStrategyName(displayBrightnessStrategyName)
                 .build();
     }
 }
diff --git a/services/core/java/com/android/server/display/brightness/strategy/BoostBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/BoostBrightnessStrategy.java
index 0cf234b..dd400d9 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/BoostBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/BoostBrightnessStrategy.java
@@ -40,7 +40,7 @@
         DisplayBrightnessState displayBrightnessState =
                 BrightnessUtils.constructDisplayBrightnessState(BrightnessReason.REASON_BOOST,
                         PowerManager.BRIGHTNESS_MAX,
-                        PowerManager.BRIGHTNESS_MAX);
+                        PowerManager.BRIGHTNESS_MAX, getName());
         return displayBrightnessState;
     }
 
diff --git a/services/core/java/com/android/server/display/brightness/strategy/DozeBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/DozeBrightnessStrategy.java
index 98075f9..8299586 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/DozeBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/DozeBrightnessStrategy.java
@@ -33,7 +33,8 @@
         // Todo(b/241308599): Introduce a validator class and add validations before setting
         // the brightness
         return BrightnessUtils.constructDisplayBrightnessState(BrightnessReason.REASON_DOZE,
-                displayPowerRequest.dozeScreenBrightness, displayPowerRequest.dozeScreenBrightness);
+                displayPowerRequest.dozeScreenBrightness, displayPowerRequest.dozeScreenBrightness,
+                getName());
     }
 
     @Override
diff --git a/services/core/java/com/android/server/display/brightness/strategy/FollowerBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/FollowerBrightnessStrategy.java
index fe684a4..090ec13 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/FollowerBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/FollowerBrightnessStrategy.java
@@ -48,7 +48,7 @@
         // Todo(b/241308599): Introduce a validator class and add validations before setting
         // the brightness
         return BrightnessUtils.constructDisplayBrightnessState(BrightnessReason.REASON_FOLLOWER,
-                mBrightnessToFollow, mBrightnessToFollow);
+                mBrightnessToFollow, mBrightnessToFollow, getName());
     }
 
     @Override
diff --git a/services/core/java/com/android/server/display/brightness/strategy/InvalidBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/InvalidBrightnessStrategy.java
index 612bbe9..bc24196 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/InvalidBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/InvalidBrightnessStrategy.java
@@ -31,7 +31,8 @@
     public DisplayBrightnessState updateBrightness(
             DisplayManagerInternal.DisplayPowerRequest displayPowerRequest) {
         return BrightnessUtils.constructDisplayBrightnessState(BrightnessReason.REASON_UNKNOWN,
-                PowerManager.BRIGHTNESS_INVALID_FLOAT, PowerManager.BRIGHTNESS_INVALID_FLOAT);
+                PowerManager.BRIGHTNESS_INVALID_FLOAT, PowerManager.BRIGHTNESS_INVALID_FLOAT,
+                getName());
     }
 
     @Override
diff --git a/services/core/java/com/android/server/display/brightness/strategy/OverrideBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/OverrideBrightnessStrategy.java
index 6d3830a..13327cb 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/OverrideBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/OverrideBrightnessStrategy.java
@@ -33,7 +33,7 @@
         // the brightness
         return BrightnessUtils.constructDisplayBrightnessState(BrightnessReason.REASON_OVERRIDE,
                 displayPowerRequest.screenBrightnessOverride,
-                displayPowerRequest.screenBrightnessOverride);
+                displayPowerRequest.screenBrightnessOverride, getName());
     }
 
     @Override
diff --git a/services/core/java/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategy.java
index ee5e066..3d411d3 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategy.java
@@ -34,7 +34,7 @@
         // the brightness
         return BrightnessUtils.constructDisplayBrightnessState(BrightnessReason.REASON_SCREEN_OFF,
                 PowerManager.BRIGHTNESS_OFF_FLOAT,
-                PowerManager.BRIGHTNESS_OFF_FLOAT);
+                PowerManager.BRIGHTNESS_OFF_FLOAT, getName());
     }
 
     @Override
diff --git a/services/core/java/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategy.java
index d97415d..35f7dd0 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategy.java
@@ -48,7 +48,7 @@
         DisplayBrightnessState displayBrightnessState =
                 BrightnessUtils.constructDisplayBrightnessState(BrightnessReason.REASON_TEMPORARY,
                         mTemporaryScreenBrightness,
-                        mTemporaryScreenBrightness);
+                        mTemporaryScreenBrightness, getName());
         return displayBrightnessState;
     }
 
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecController.java b/services/core/java/com/android/server/hdmi/HdmiCecController.java
index 376e6f8..b460745 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecController.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecController.java
@@ -727,7 +727,7 @@
     void sendCommand(final HdmiCecMessage cecMessage,
             final HdmiControlService.SendMessageCallback callback) {
         assertRunOnServiceThread();
-        addCecMessageToHistory(false /* isReceived */, cecMessage);
+        List<String> sendResults = new ArrayList<>();
         runOnIoThread(new Runnable() {
             @Override
             public void run() {
@@ -738,6 +738,12 @@
                 do {
                     errorCode = mNativeWrapperImpl.nativeSendCecCommand(
                         cecMessage.getSource(), cecMessage.getDestination(), body);
+                    switch (errorCode) {
+                        case SendMessageResult.SUCCESS: sendResults.add("ACK"); break;
+                        case SendMessageResult.FAIL: sendResults.add("FAIL"); break;
+                        case SendMessageResult.NACK: sendResults.add("NACK"); break;
+                        case SendMessageResult.BUSY: sendResults.add("BUSY"); break;
+                    }
                     if (errorCode == SendMessageResult.SUCCESS) {
                         break;
                     }
@@ -763,6 +769,8 @@
                 });
             }
         });
+
+        addCecMessageToHistory(false /* isReceived */, cecMessage, sendResults);
     }
 
     /**
@@ -785,7 +793,7 @@
         }
 
         HdmiLogger.debug("[R]:" + command);
-        addCecMessageToHistory(true /* isReceived */, command);
+        addCecMessageToHistory(true /* isReceived */, command, null);
 
         mHdmiCecAtomWriter.messageReported(command,
                 incomingMessageDirection(srcAddress, dstAddress), getCallingUid());
@@ -836,9 +844,10 @@
     }
 
     @ServiceThreadOnly
-    private void addCecMessageToHistory(boolean isReceived, HdmiCecMessage message) {
+    private void addCecMessageToHistory(boolean isReceived, HdmiCecMessage message,
+            List<String> sendResults) {
         assertRunOnServiceThread();
-        addEventToHistory(new MessageHistoryRecord(isReceived, message));
+        addEventToHistory(new MessageHistoryRecord(isReceived, message, sendResults));
     }
 
     private void addEventToHistory(Dumpable event) {
@@ -1720,11 +1729,13 @@
     private static final class MessageHistoryRecord extends Dumpable {
         private final boolean mIsReceived; // true if received message and false if sent message
         private final HdmiCecMessage mMessage;
+        private final List<String> mSendResults;
 
-        MessageHistoryRecord(boolean isReceived, HdmiCecMessage message) {
+        MessageHistoryRecord(boolean isReceived, HdmiCecMessage message, List<String> sendResults) {
             super();
             mIsReceived = isReceived;
             mMessage = message;
+            mSendResults = sendResults;
         }
 
         @Override
@@ -1733,7 +1744,16 @@
             pw.print(" time=");
             pw.print(sdf.format(new Date(mTime)));
             pw.print(" message=");
-            pw.println(mMessage);
+            pw.print(mMessage);
+
+            StringBuilder results = new StringBuilder();
+            if (!mIsReceived && mSendResults != null) {
+                results.append(" (");
+                results.append(String.join(", ", mSendResults));
+                results.append(")");
+            }
+
+            pw.println(results);
         }
     }
 
diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java
index be4373a..8c13297 100644
--- a/services/core/java/com/android/server/input/InputManagerService.java
+++ b/services/core/java/com/android/server/input/InputManagerService.java
@@ -38,7 +38,9 @@
 import android.hardware.SensorPrivacyManager.Sensors;
 import android.hardware.SensorPrivacyManagerInternal;
 import android.hardware.display.DisplayManager;
+import android.hardware.display.DisplayManagerInternal;
 import android.hardware.display.DisplayViewport;
+import android.hardware.input.HostUsiVersion;
 import android.hardware.input.IInputDeviceBatteryListener;
 import android.hardware.input.IInputDeviceBatteryState;
 import android.hardware.input.IInputDevicesChangedListener;
@@ -168,6 +170,7 @@
 
     private final Context mContext;
     private final InputManagerHandler mHandler;
+    private DisplayManagerInternal mDisplayManagerInternal;
 
     // Context cache used for loading pointer resources.
     private Context mPointerIconDisplayContext;
@@ -519,6 +522,8 @@
             Slog.d(TAG, "System ready.");
         }
 
+        mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
+
         synchronized (mLidSwitchLock) {
             mSystemReady = true;
 
@@ -1450,7 +1455,8 @@
     }
 
     private void updateMaximumObscuringOpacityForTouchFromSettings() {
-        final float opacity = InputManager.getInstance().getMaximumObscuringOpacityForTouch();
+        InputManager im = Objects.requireNonNull(mContext.getSystemService(InputManager.class));
+        final float opacity = im.getMaximumObscuringOpacityForTouch();
         if (opacity < 0 || opacity > 1) {
             Log.e(TAG, "Invalid maximum obscuring opacity " + opacity
                     + ", it should be >= 0 and <= 1, rejecting update.");
@@ -2254,6 +2260,11 @@
     }
 
     @Override
+    public HostUsiVersion getHostUsiVersionFromDisplayConfig(int displayId) {
+        return mDisplayManagerInternal.getHostUsiVersion(displayId);
+    }
+
+    @Override
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
         IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
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 052c785..287cc29 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
@@ -16,6 +16,7 @@
 
 package com.android.server.pm.permission;
 
+import static android.Manifest.permission.CAMERA;
 import static android.Manifest.permission.CAPTURE_AUDIO_HOTWORD;
 import static android.Manifest.permission.CAPTURE_AUDIO_OUTPUT;
 import static android.Manifest.permission.RECORD_AUDIO;
@@ -1379,14 +1380,15 @@
             boolean permissionGranted = context.checkPermission(permission, /*pid*/ -1,
                     uid) == PackageManager.PERMISSION_GRANTED;
 
-            // Override certain permissions checks for the HotwordDetectionService. This service is
-            // an isolated service, which ordinarily cannot hold permissions.
+            // Override certain permissions checks for the shared isolated process for both
+            // HotwordDetectionService and VisualQueryDetectionService, which ordinarily cannot hold
+            // any permissions.
             // There's probably a cleaner, more generalizable way to do this. For now, this is
             // the only use case for this, so simply override here.
             if (!permissionGranted
                     && Process.isIsolated(uid) // simple check which fails-fast for the common case
                     && (permission.equals(RECORD_AUDIO) || permission.equals(CAPTURE_AUDIO_HOTWORD)
-                    || permission.equals(CAPTURE_AUDIO_OUTPUT))) {
+                    || permission.equals(CAPTURE_AUDIO_OUTPUT) || permission.equals(CAMERA))) {
                 HotwordDetectionServiceProvider hotwordServiceProvider =
                         permissionManagerServiceInt.getHotwordDetectionServiceProvider();
                 permissionGranted = hotwordServiceProvider != null
diff --git a/services/core/java/com/android/server/policy/AppOpsPolicy.java b/services/core/java/com/android/server/policy/AppOpsPolicy.java
index 383249f..401eac6 100644
--- a/services/core/java/com/android/server/policy/AppOpsPolicy.java
+++ b/services/core/java/com/android/server/policy/AppOpsPolicy.java
@@ -447,7 +447,8 @@
         // package, so we don't need to modify it.
         if (Process.isIsolated(uid) // simple check which fails-fast for the common case
                 && (code == AppOpsManager.OP_RECORD_AUDIO
-                || code == AppOpsManager.OP_RECORD_AUDIO_HOTWORD)) {
+                || code == AppOpsManager.OP_RECORD_AUDIO_HOTWORD
+                || code == AppOpsManager.OP_CAMERA)) {
             final HotwordDetectionServiceIdentity hotwordDetectionServiceIdentity =
                     mVoiceInteractionManagerInternal.getHotwordDetectionServiceIdentity();
             if (hotwordDetectionServiceIdentity != null
diff --git a/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java b/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java
index 2fb5cec..c278550 100644
--- a/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java
+++ b/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java
@@ -3926,8 +3926,6 @@
 
         private boolean mHasHistoryStepDetails;
 
-        private int mLastHistoryStepLevel;
-
         /**
          * Total time (in milliseconds) spent executing in user code.
          */
@@ -3956,11 +3954,6 @@
 
         @Override
         public HistoryStepDetails getHistoryStepDetails() {
-            if (mBatteryLevel >= mLastHistoryStepLevel && mHasHistoryStepDetails) {
-                mLastHistoryStepLevel = mBatteryLevel;
-                return null;
-            }
-
             // Perform a CPU update right after we do this collection, so we have started
             // collecting good data for the next step.
             requestImmediateCpuUpdate();
@@ -3989,7 +3982,7 @@
                 mLastStepStatIrqTimeMs = mCurStepStatIrqTimeMs;
                 mLastStepStatSoftIrqTimeMs = mCurStepStatSoftIrqTimeMs;
                 mLastStepStatIdleTimeMs = mCurStepStatIdleTimeMs;
-                mDetails.clear();
+                return null;
             } else {
                 if (DEBUG) {
                     Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTimeMs + " sys="
@@ -4058,12 +4051,8 @@
                 mLastStepStatIrqTimeMs = mCurStepStatIrqTimeMs;
                 mLastStepStatSoftIrqTimeMs = mCurStepStatSoftIrqTimeMs;
                 mLastStepStatIdleTimeMs = mCurStepStatIdleTimeMs;
+                return mDetails;
             }
-
-            mHasHistoryStepDetails = mBatteryLevel <= mLastHistoryStepLevel;
-            mLastHistoryStepLevel = mBatteryLevel;
-
-            return mDetails;
         }
 
         public void addCpuStats(int totalUTimeMs, int totalSTimeMs, int statUserTimeMs,
@@ -4083,6 +4072,7 @@
             mCurStepStatIrqTimeMs += statIrqTimeMs;
             mCurStepStatSoftIrqTimeMs += statSoftIrqTimeMs;
             mCurStepStatIdleTimeMs += statIdleTimeMs;
+            mHasHistoryStepDetails = true;
         }
 
         @Override
diff --git a/services/core/java/com/android/server/wm/ActivityClientController.java b/services/core/java/com/android/server/wm/ActivityClientController.java
index d4895ed..316b12a 100644
--- a/services/core/java/com/android/server/wm/ActivityClientController.java
+++ b/services/core/java/com/android/server/wm/ActivityClientController.java
@@ -762,7 +762,8 @@
         synchronized (mGlobalLock) {
             final ActivityRecord r = ActivityRecord.isInRootTaskLocked(token);
             return r != null
-                    ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
+                    ? r.getOverrideOrientation()
+                    : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
         }
     }
 
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index fd3f32d..6ba3866 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -1172,8 +1172,10 @@
             pw.println(prefix + "mVoiceInteraction=true");
         }
         pw.print(prefix); pw.print("mOccludesParent="); pw.println(mOccludesParent);
-        pw.print(prefix); pw.print("mOrientation=");
-        pw.println(ActivityInfo.screenOrientationToString(mOrientation));
+        pw.print(prefix); pw.print("overrideOrientation=");
+        pw.println(ActivityInfo.screenOrientationToString(getOverrideOrientation()));
+        pw.print(prefix); pw.print("requestedOrientation=");
+        pw.println(ActivityInfo.screenOrientationToString(super.getOverrideOrientation()));
         pw.println(prefix + "mVisibleRequested=" + mVisibleRequested
                 + " mVisible=" + mVisible + " mClientVisible=" + isClientVisible()
                 + ((mDeferHidingClient) ? " mDeferHidingClient=" + mDeferHidingClient : "")
@@ -1960,6 +1962,15 @@
                     new ComponentName(info.packageName, info.targetActivity);
         }
 
+        // Don't move below setActivityType since it triggers onConfigurationChange ->
+        // resolveOverrideConfiguration that requires having mLetterboxUiController initialised.
+        // Don't move below setOrientation(info.screenOrientation) since it triggers
+        // getOverrideOrientation that requires having mLetterboxUiController
+        // initialised.
+        mLetterboxUiController = new LetterboxUiController(mWmService, this);
+        mCameraCompatControlEnabled = mWmService.mContext.getResources()
+                .getBoolean(R.bool.config_isCameraCompatControlForStretchedIssuesEnabled);
+
         mTargetSdk = info.applicationInfo.targetSdkVersion;
         mShowForAllUsers = (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0;
         setOrientation(info.screenOrientation);
@@ -2080,12 +2091,6 @@
 
         launchMode = aInfo.launchMode;
 
-        // Don't move below setActivityType since it triggers onConfigurationChange ->
-        // resolveOverrideConfiguration that requires having mLetterboxUiController initialised.
-        mLetterboxUiController = new LetterboxUiController(mWmService, this);
-        mCameraCompatControlEnabled = mWmService.mContext.getResources()
-                .getBoolean(R.bool.config_isCameraCompatControlForStretchedIssuesEnabled);
-
         setActivityType(_componentSpecified, _launchedFromUid, _intent, options, sourceRecord);
 
         immersive = (aInfo.flags & FLAG_IMMERSIVE) != 0;
@@ -2499,7 +2504,8 @@
             if (topAttached != null) {
                 if (topAttached.isSnapshotCompatible(snapshot)
                         // This trampoline must be the same rotation.
-                        && mDisplayContent.getDisplayRotation().rotationForOrientation(mOrientation,
+                        && mDisplayContent.getDisplayRotation().rotationForOrientation(
+                                getOverrideOrientation(),
                                 mDisplayContent.getRotation()) == snapshot.getRotation()) {
                     return STARTING_WINDOW_TYPE_SNAPSHOT;
                 }
@@ -7759,13 +7765,13 @@
                 return mLetterboxUiController.getInheritedOrientation();
             }
         }
-        if (mOrientation == SCREEN_ORIENTATION_BEHIND && task != null) {
+        if (task != null && getOverrideOrientation() == SCREEN_ORIENTATION_BEHIND) {
             // We use Task here because we want to be consistent with what happens in
             // multi-window mode where other tasks orientations are ignored.
             final ActivityRecord belowCandidate = task.getActivity(
-                    a -> a.mOrientation != SCREEN_ORIENTATION_UNSET && !a.finishing
-                            && a.mOrientation != ActivityInfo.SCREEN_ORIENTATION_BEHIND, this,
-                    false /* includeBoundary */, true /* traverseTopToBottom */);
+                    a -> a.canDefineOrientationForActivitiesAbove() /* callback */,
+                    this /* boundary */, false /* includeBoundary */,
+                    true /* traverseTopToBottom */);
             if (belowCandidate != null) {
                 return belowCandidate.getRequestedConfigurationOrientation(forDisplay);
             }
@@ -7773,6 +7779,19 @@
         return super.getRequestedConfigurationOrientation(forDisplay);
     }
 
+    /**
+     * Whether this activity can be used as an orientation source for activities above with
+     * {@link SCREEN_ORIENTATION_BEHIND}.
+     */
+    boolean canDefineOrientationForActivitiesAbove() {
+        if (finishing) {
+            return false;
+        }
+        final int overrideOrientation = getOverrideOrientation();
+        return overrideOrientation != SCREEN_ORIENTATION_UNSET
+                && overrideOrientation != SCREEN_ORIENTATION_BEHIND;
+    }
+
     @Override
     void onCancelFixedRotationTransform(int originalDisplayRotation) {
         if (this != mDisplayContent.getLastOrientationSource()) {
@@ -7799,7 +7818,7 @@
         }
     }
 
-    void setRequestedOrientation(int requestedOrientation) {
+    void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
         if (mLetterboxUiController.shouldIgnoreRequestedOrientation(requestedOrientation)) {
             return;
         }
@@ -7842,7 +7861,7 @@
     @VisibleForTesting
     boolean shouldIgnoreOrientationRequests() {
         if (!mAppActivityEmbeddingSplitsEnabled
-                || !ActivityInfo.isFixedOrientationPortrait(mOrientation)
+                || !ActivityInfo.isFixedOrientationPortrait(getOverrideOrientation())
                 || task.inMultiWindowMode()) {
             return false;
         }
@@ -7865,7 +7884,7 @@
             // Allow app to specify orientation regardless of its visibility state if the current
             // candidate want us to use orientation behind. I.e. the visible app on-top of this one
             // wants us to use the orientation of the app behind it.
-            return mOrientation;
+            return getOverrideOrientation();
         }
 
         // The {@link ActivityRecord} should only specify an orientation when it is not closing.
@@ -7873,15 +7892,31 @@
         // task being started in the wrong orientation during the transition.
         if (!getDisplayContent().mClosingApps.contains(this)
                 && (isVisibleRequested() || getDisplayContent().mOpeningApps.contains(this))) {
-            return mOrientation;
+            return getOverrideOrientation();
         }
 
         return SCREEN_ORIENTATION_UNSET;
     }
 
-    /** Returns the app's preferred orientation regardless of its currently visibility state. */
+    /**
+     * Returns the app's preferred orientation regardless of its current visibility state taking
+     * into account orientation per-app overrides applied by the device manufacturers.
+     */
+    @Override
+    protected int getOverrideOrientation() {
+        return mLetterboxUiController.overrideOrientationIfNeeded(super.getOverrideOrientation());
+    }
+
+    /**
+     * Returns the app's preferred orientation regardless of its currently visibility state. This
+     * is used to return a requested value to an app if they call {@link
+     * android.app.Activity#getRequestedOrientation} since {@link #getOverrideOrientation} value
+     * with override can confuse an app if it's different from what they requested with {@link
+     * android.app.Activity#setRequestedOrientation}.
+     */
+    @ActivityInfo.ScreenOrientation
     int getRequestedOrientation() {
-        return mOrientation;
+        return super.getOverrideOrientation();
     }
 
     /**
@@ -8444,8 +8479,8 @@
         // If orientation is respected when insets are applied, then stableBounds will be empty.
         boolean orientationRespectedWithInsets =
                 orientationRespectedWithInsets(parentBounds, stableBounds);
-        if (orientationRespectedWithInsets
-                && handlesOrientationChangeFromDescendant(mOrientation)) {
+        if (orientationRespectedWithInsets && handlesOrientationChangeFromDescendant(
+                getOverrideOrientation())) {
             // No need to letterbox because of fixed orientation. Display will handle
             // fixed-orientation requests and a display rotation is enough to respect requested
             // orientation with insets applied.
@@ -9083,7 +9118,8 @@
         }
 
         if (info.isChangeEnabled(OVERRIDE_MIN_ASPECT_RATIO_PORTRAIT_ONLY)
-                && !ActivityInfo.isFixedOrientationPortrait(getRequestedOrientation())) {
+                && !ActivityInfo.isFixedOrientationPortrait(
+                        getOverrideOrientation())) {
             return info.getMinAspectRatio();
         }
 
diff --git a/services/core/java/com/android/server/wm/DeviceStateController.java b/services/core/java/com/android/server/wm/DeviceStateController.java
index a6f8557..2e67399 100644
--- a/services/core/java/com/android/server/wm/DeviceStateController.java
+++ b/services/core/java/com/android/server/wm/DeviceStateController.java
@@ -16,80 +16,92 @@
 
 package com.android.server.wm;
 
+import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.content.Context;
 import android.hardware.devicestate.DeviceStateManager;
 import android.os.Handler;
 import android.os.HandlerExecutor;
 
+import com.android.internal.R;
 import com.android.internal.util.ArrayUtils;
 
+import java.util.ArrayList;
+import java.util.List;
 import java.util.function.Consumer;
 
 /**
- * Class that registers callbacks with the {@link DeviceStateManager} and
- * responds to fold state changes by forwarding such events to a delegate.
+ * Class that registers callbacks with the {@link DeviceStateManager} and responds to device
+ * changes.
  */
-final class DeviceStateController {
+final class DeviceStateController implements DeviceStateManager.DeviceStateCallback {
+
+    @NonNull
     private final DeviceStateManager mDeviceStateManager;
-    private final Context mContext;
+    @NonNull
+    private final int[] mOpenDeviceStates;
+    @NonNull
+    private final int[] mHalfFoldedDeviceStates;
+    @NonNull
+    private final int[] mFoldedDeviceStates;
+    @NonNull
+    private final int[] mRearDisplayDeviceStates;
+    @NonNull
+    private final List<Consumer<DeviceState>> mDeviceStateCallbacks = new ArrayList<>();
 
-    private FoldStateListener mDeviceStateListener;
+    @Nullable
+    private DeviceState mLastDeviceState;
 
-    public enum FoldState {
-        UNKNOWN, OPEN, FOLDED, HALF_FOLDED
+    public enum DeviceState {
+        UNKNOWN, OPEN, FOLDED, HALF_FOLDED, REAR,
     }
 
-    DeviceStateController(Context context, Handler handler, Consumer<FoldState> delegate) {
-        mContext = context;
-        mDeviceStateManager = mContext.getSystemService(DeviceStateManager.class);
+    DeviceStateController(@NonNull Context context, @NonNull Handler handler) {
+        mDeviceStateManager = context.getSystemService(DeviceStateManager.class);
+        mOpenDeviceStates = context.getResources()
+                .getIntArray(R.array.config_openDeviceStates);
+        mHalfFoldedDeviceStates = context.getResources()
+                .getIntArray(R.array.config_halfFoldedDeviceStates);
+        mFoldedDeviceStates = context.getResources()
+                .getIntArray(R.array.config_foldedDeviceStates);
+        mRearDisplayDeviceStates = context.getResources()
+                .getIntArray(R.array.config_rearDisplayDeviceStates);
+
         if (mDeviceStateManager != null) {
-            mDeviceStateListener = new FoldStateListener(mContext, delegate);
-            mDeviceStateManager
-                    .registerCallback(new HandlerExecutor(handler),
-                            mDeviceStateListener);
+            mDeviceStateManager.registerCallback(new HandlerExecutor(handler), this);
         }
     }
 
     void unregisterFromDeviceStateManager() {
-        if (mDeviceStateListener != null) {
-            mDeviceStateManager.unregisterCallback(mDeviceStateListener);
+        if (mDeviceStateManager != null) {
+            mDeviceStateManager.unregisterCallback(this);
         }
     }
 
-    /**
-     * A listener for half-fold device state events that dispatches state changes to a delegate.
-     */
-    static final class FoldStateListener implements DeviceStateManager.DeviceStateCallback {
+    void registerDeviceStateCallback(@NonNull Consumer<DeviceState> callback) {
+        mDeviceStateCallbacks.add(callback);
+    }
 
-        private final int[] mHalfFoldedDeviceStates;
-        private final int[] mFoldedDeviceStates;
-
-        @Nullable
-        private FoldState mLastResult;
-        private final Consumer<FoldState> mDelegate;
-
-        FoldStateListener(Context context, Consumer<FoldState> delegate) {
-            mFoldedDeviceStates = context.getResources().getIntArray(
-                    com.android.internal.R.array.config_foldedDeviceStates);
-            mHalfFoldedDeviceStates = context.getResources().getIntArray(
-                    com.android.internal.R.array.config_halfFoldedDeviceStates);
-            mDelegate = delegate;
+    @Override
+    public void onStateChanged(int state) {
+        final DeviceState deviceState;
+        if (ArrayUtils.contains(mHalfFoldedDeviceStates, state)) {
+            deviceState = DeviceState.HALF_FOLDED;
+        } else if (ArrayUtils.contains(mFoldedDeviceStates, state)) {
+            deviceState = DeviceState.FOLDED;
+        } else if (ArrayUtils.contains(mRearDisplayDeviceStates, state)) {
+            deviceState = DeviceState.REAR;
+        } else if (ArrayUtils.contains(mOpenDeviceStates, state)) {
+            deviceState = DeviceState.OPEN;
+        } else {
+            deviceState = DeviceState.UNKNOWN;
         }
 
-        @Override
-        public void onStateChanged(int state) {
-            final boolean halfFolded = ArrayUtils.contains(mHalfFoldedDeviceStates, state);
-            FoldState result;
-            if (halfFolded) {
-                result = FoldState.HALF_FOLDED;
-            } else {
-                final boolean folded = ArrayUtils.contains(mFoldedDeviceStates, state);
-                result = folded ? FoldState.FOLDED : FoldState.OPEN;
-            }
-            if (mLastResult == null || !mLastResult.equals(result)) {
-                mLastResult = result;
-                mDelegate.accept(result);
+        if (mLastDeviceState == null || !mLastDeviceState.equals(deviceState)) {
+            mLastDeviceState = deviceState;
+
+            for (Consumer<DeviceState> callback : mDeviceStateCallbacks) {
+                callback.accept(mLastDeviceState);
             }
         }
     }
diff --git a/services/core/java/com/android/server/wm/DisplayArea.java b/services/core/java/com/android/server/wm/DisplayArea.java
index a15453e..de63191 100644
--- a/services/core/java/com/android/server/wm/DisplayArea.java
+++ b/services/core/java/com/android/server/wm/DisplayArea.java
@@ -94,7 +94,7 @@
     DisplayArea(WindowManagerService wms, Type type, String name, int featureId) {
         super(wms);
         // TODO(display-area): move this up to ConfigurationContainer
-        mOrientation = SCREEN_ORIENTATION_UNSET;
+        setOverrideOrientation(SCREEN_ORIENTATION_UNSET);
         mType = type;
         mName = name;
         mFeatureId = featureId;
@@ -166,7 +166,8 @@
         // If this is set to ignore the orientation request, we don't propagate descendant
         // orientation request.
         final int orientation = requestingContainer != null
-                ? requestingContainer.mOrientation : SCREEN_ORIENTATION_UNSET;
+                ? requestingContainer.getOverrideOrientation()
+                : SCREEN_ORIENTATION_UNSET;
         return !getIgnoreOrientationRequest(orientation)
                 && super.onDescendantOrientationChanged(requestingContainer);
     }
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 1794e2a..9581ffe 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -1145,14 +1145,17 @@
                     mWmService.mAtmService.getRecentTasks().getInputListener());
         }
 
+        mDeviceStateController = new DeviceStateController(mWmService.mContext, mWmService.mH);
+
         mDisplayPolicy = new DisplayPolicy(mWmService, this);
         mDisplayRotation = new DisplayRotation(mWmService, this, mDisplayInfo.address);
 
-        mDeviceStateController = new DeviceStateController(mWmService.mContext, mWmService.mH,
-                newFoldState -> {
+        final Consumer<DeviceStateController.DeviceState> deviceStateConsumer =
+                (@NonNull DeviceStateController.DeviceState newFoldState) -> {
                     mDisplaySwitchTransitionLauncher.foldStateChanged(newFoldState);
                     mDisplayRotation.foldStateChanged(newFoldState);
-                });
+                };
+        mDeviceStateController.registerDeviceStateCallback(deviceStateConsumer);
 
         mCloseToSquareMaxAspectRatio = mWmService.mContext.getResources().getFloat(
                 R.dimen.config_closeToSquareDisplayMaxAspectRatio);
@@ -1618,7 +1621,8 @@
         // If display rotation class tells us that it doesn't consider app requested orientation,
         // this display won't rotate just because of an app changes its requested orientation. Thus
         // it indicates that this display chooses not to handle this request.
-        final int orientation = requestingContainer != null ? requestingContainer.mOrientation
+        final int orientation = requestingContainer != null
+                ? requestingContainer.getOverrideOrientation()
                 : SCREEN_ORIENTATION_UNSET;
         final boolean handled = handlesOrientationChangeFromDescendant(orientation);
         if (config == null) {
@@ -1744,14 +1748,17 @@
         if (mTransitionController.useShellTransitionsRotation()) {
             return ROTATION_UNDEFINED;
         }
+        final int activityOrientation = r.getOverrideOrientation();
         if (!WindowManagerService.ENABLE_FIXED_ROTATION_TRANSFORM
-                || getIgnoreOrientationRequest(r.mOrientation)) {
+                || getIgnoreOrientationRequest(activityOrientation)) {
             return ROTATION_UNDEFINED;
         }
-        if (r.mOrientation == ActivityInfo.SCREEN_ORIENTATION_BEHIND) {
+        if (activityOrientation == ActivityInfo.SCREEN_ORIENTATION_BEHIND) {
+            // TODO(b/266280737): Use ActivityRecord#canDefineOrientationForActivitiesAbove
             final ActivityRecord nextCandidate = getActivity(
-                    a -> a.mOrientation != SCREEN_ORIENTATION_UNSET
-                            && a.mOrientation != ActivityInfo.SCREEN_ORIENTATION_BEHIND,
+                    a -> a.getOverrideOrientation() != SCREEN_ORIENTATION_UNSET
+                            && a.getOverrideOrientation()
+                                    != ActivityInfo.SCREEN_ORIENTATION_BEHIND,
                     r, false /* includeBoundary */, true /* traverseTopToBottom */);
             if (nextCandidate != null) {
                 r = nextCandidate;
diff --git a/services/core/java/com/android/server/wm/DisplayRotation.java b/services/core/java/com/android/server/wm/DisplayRotation.java
index e6d8b3d..762f49a 100644
--- a/services/core/java/com/android/server/wm/DisplayRotation.java
+++ b/services/core/java/com/android/server/wm/DisplayRotation.java
@@ -1573,7 +1573,7 @@
         proto.end(token);
     }
 
-    boolean isDeviceInPosture(DeviceStateController.FoldState state, boolean isTabletop) {
+    boolean isDeviceInPosture(DeviceStateController.DeviceState state, boolean isTabletop) {
         if (mFoldController == null) return false;
         return mFoldController.isDeviceInPosture(state, isTabletop);
     }
@@ -1585,10 +1585,10 @@
     /**
      * Called by the DeviceStateManager callback when the device state changes.
      */
-    void foldStateChanged(DeviceStateController.FoldState foldState) {
+    void foldStateChanged(DeviceStateController.DeviceState deviceState) {
         if (mFoldController != null) {
             synchronized (mLock) {
-                mFoldController.foldStateChanged(foldState);
+                mFoldController.foldStateChanged(deviceState);
             }
         }
     }
@@ -1596,8 +1596,8 @@
     private class FoldController {
         @Surface.Rotation
         private int mHalfFoldSavedRotation = -1; // No saved rotation
-        private DeviceStateController.FoldState mFoldState =
-                DeviceStateController.FoldState.UNKNOWN;
+        private DeviceStateController.DeviceState mDeviceState =
+                DeviceStateController.DeviceState.UNKNOWN;
         private boolean mInHalfFoldTransition = false;
         private final boolean mIsDisplayAlwaysSeparatingHinge;
         private final Set<Integer> mTabletopRotations;
@@ -1637,32 +1637,33 @@
                     R.bool.config_isDisplayHingeAlwaysSeparating);
         }
 
-        boolean isDeviceInPosture(DeviceStateController.FoldState state, boolean isTabletop) {
-            if (state != mFoldState) {
+        boolean isDeviceInPosture(DeviceStateController.DeviceState state, boolean isTabletop) {
+            if (state != mDeviceState) {
                 return false;
             }
-            if (mFoldState == DeviceStateController.FoldState.HALF_FOLDED) {
+            if (mDeviceState == DeviceStateController.DeviceState.HALF_FOLDED) {
                 return !(isTabletop ^ mTabletopRotations.contains(mRotation));
             }
             return true;
         }
 
-        DeviceStateController.FoldState getFoldState() {
-            return mFoldState;
+        DeviceStateController.DeviceState getFoldState() {
+            return mDeviceState;
         }
 
         boolean isSeparatingHinge() {
-            return mFoldState == DeviceStateController.FoldState.HALF_FOLDED
-                    || (mFoldState == DeviceStateController.FoldState.OPEN
+            return mDeviceState == DeviceStateController.DeviceState.HALF_FOLDED
+                    || (mDeviceState == DeviceStateController.DeviceState.OPEN
                         && mIsDisplayAlwaysSeparatingHinge);
         }
 
         boolean overrideFrozenRotation() {
-            return mFoldState == DeviceStateController.FoldState.HALF_FOLDED;
+            return mDeviceState == DeviceStateController.DeviceState.HALF_FOLDED;
         }
 
         boolean shouldRevertOverriddenRotation() {
-            return mFoldState == DeviceStateController.FoldState.OPEN // When transitioning to open.
+            // When transitioning to open.
+            return mDeviceState == DeviceStateController.DeviceState.OPEN
                     && mInHalfFoldTransition
                     && mHalfFoldSavedRotation != -1 // Ignore if we've already reverted.
                     && mUserRotationMode
@@ -1676,30 +1677,30 @@
             return savedRotation;
         }
 
-        void foldStateChanged(DeviceStateController.FoldState newState) {
+        void foldStateChanged(DeviceStateController.DeviceState newState) {
             ProtoLog.v(WM_DEBUG_ORIENTATION,
                     "foldStateChanged: displayId %d, halfFoldStateChanged %s, "
                     + "saved rotation: %d, mUserRotation: %d, mLastSensorRotation: %d, "
                     + "mLastOrientation: %d, mRotation: %d",
                     mDisplayContent.getDisplayId(), newState.name(), mHalfFoldSavedRotation,
                     mUserRotation, mLastSensorRotation, mLastOrientation, mRotation);
-            if (mFoldState == DeviceStateController.FoldState.UNKNOWN) {
-                mFoldState = newState;
+            if (mDeviceState == DeviceStateController.DeviceState.UNKNOWN) {
+                mDeviceState = newState;
                 return;
             }
-            if (newState == DeviceStateController.FoldState.HALF_FOLDED
-                    && mFoldState != DeviceStateController.FoldState.HALF_FOLDED) {
+            if (newState == DeviceStateController.DeviceState.HALF_FOLDED
+                    && mDeviceState != DeviceStateController.DeviceState.HALF_FOLDED) {
                 // The device has transitioned to HALF_FOLDED state: save the current rotation and
                 // update the device rotation.
                 mHalfFoldSavedRotation = mRotation;
-                mFoldState = newState;
+                mDeviceState = newState;
                 // Now mFoldState is set to HALF_FOLDED, the overrideFrozenRotation function will
                 // return true, so rotation is unlocked.
                 mService.updateRotation(false /* alwaysSendConfiguration */,
                         false /* forceRelayout */);
             } else {
                 mInHalfFoldTransition = true;
-                mFoldState = newState;
+                mDeviceState = newState;
                 // Tell the device to update its orientation.
                 mService.updateRotation(false /* alwaysSendConfiguration */,
                         false /* forceRelayout */);
@@ -1822,7 +1823,7 @@
             final long mTimestamp = System.currentTimeMillis();
             final int mHalfFoldSavedRotation;
             final boolean mInHalfFoldTransition;
-            final DeviceStateController.FoldState mFoldState;
+            final DeviceStateController.DeviceState mDeviceState;
             @Nullable final String mDisplayRotationCompatPolicySummary;
 
             Record(DisplayRotation dr, int fromRotation, int toRotation) {
@@ -1843,8 +1844,9 @@
                 if (source != null) {
                     mLastOrientationSource = source.toString();
                     final WindowState w = source.asWindowState();
-                    mSourceOrientation =
-                            w != null ? w.mAttrs.screenOrientation : source.mOrientation;
+                    mSourceOrientation = w != null
+                            ? w.mAttrs.screenOrientation
+                            : source.getOverrideOrientation();
                 } else {
                     mLastOrientationSource = null;
                     mSourceOrientation = SCREEN_ORIENTATION_UNSET;
@@ -1852,11 +1854,11 @@
                 if (dr.mFoldController != null) {
                     mHalfFoldSavedRotation = dr.mFoldController.mHalfFoldSavedRotation;
                     mInHalfFoldTransition = dr.mFoldController.mInHalfFoldTransition;
-                    mFoldState = dr.mFoldController.mFoldState;
+                    mDeviceState = dr.mFoldController.mDeviceState;
                 } else {
                     mHalfFoldSavedRotation = NO_FOLD_CONTROLLER;
                     mInHalfFoldTransition = false;
-                    mFoldState = DeviceStateController.FoldState.UNKNOWN;
+                    mDeviceState = DeviceStateController.DeviceState.UNKNOWN;
                 }
                 mDisplayRotationCompatPolicySummary = dc.mDisplayRotationCompatPolicy == null
                         ? null
@@ -1882,7 +1884,7 @@
                     pw.println(prefix + " halfFoldSavedRotation="
                             + mHalfFoldSavedRotation
                             + " mInHalfFoldTransition=" + mInHalfFoldTransition
-                            + " mFoldState=" + mFoldState);
+                            + " mFoldState=" + mDeviceState);
                 }
                 if (mDisplayRotationCompatPolicySummary != null) {
                     pw.println(prefix + mDisplayRotationCompatPolicySummary);
diff --git a/services/core/java/com/android/server/wm/DisplayRotationCompatPolicy.java b/services/core/java/com/android/server/wm/DisplayRotationCompatPolicy.java
index c6037da..3ffb2fa 100644
--- a/services/core/java/com/android/server/wm/DisplayRotationCompatPolicy.java
+++ b/services/core/java/com/android/server/wm/DisplayRotationCompatPolicy.java
@@ -296,8 +296,8 @@
                 && activity.getRequestedConfigurationOrientation() != ORIENTATION_UNDEFINED
                 // "locked" and "nosensor" values are often used by camera apps that can't
                 // handle dynamic changes so we shouldn't force rotate them.
-                && activity.getRequestedOrientation() != SCREEN_ORIENTATION_NOSENSOR
-                && activity.getRequestedOrientation() != SCREEN_ORIENTATION_LOCKED
+                && activity.getOverrideOrientation() != SCREEN_ORIENTATION_NOSENSOR
+                && activity.getOverrideOrientation() != SCREEN_ORIENTATION_LOCKED
                 && mCameraIdPackageBiMap.containsPackageName(activity.packageName)
                 && activity.mLetterboxUiController.shouldForceRotateForCameraCompat();
     }
diff --git a/services/core/java/com/android/server/wm/LetterboxUiController.java b/services/core/java/com/android/server/wm/LetterboxUiController.java
index 73d1ff9d..d73be18 100644
--- a/services/core/java/com/android/server/wm/LetterboxUiController.java
+++ b/services/core/java/com/android/server/wm/LetterboxUiController.java
@@ -17,11 +17,20 @@
 package com.android.server.wm;
 
 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
+import static android.content.pm.ActivityInfo.OVERRIDE_ANY_ORIENTATION;
 import static android.content.pm.ActivityInfo.OVERRIDE_CAMERA_COMPAT_DISABLE_FORCE_ROTATION;
 import static android.content.pm.ActivityInfo.OVERRIDE_CAMERA_COMPAT_DISABLE_REFRESH;
 import static android.content.pm.ActivityInfo.OVERRIDE_CAMERA_COMPAT_ENABLE_REFRESH_VIA_PAUSE;
 import static android.content.pm.ActivityInfo.OVERRIDE_ENABLE_COMPAT_IGNORE_REQUESTED_ORIENTATION;
+import static android.content.pm.ActivityInfo.OVERRIDE_LANDSCAPE_ORIENTATION_TO_REVERSE_LANDSCAPE;
+import static android.content.pm.ActivityInfo.OVERRIDE_UNDEFINED_ORIENTATION_TO_NOSENSOR;
+import static android.content.pm.ActivityInfo.OVERRIDE_UNDEFINED_ORIENTATION_TO_PORTRAIT;
+import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
+import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
+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.isFixedOrientation;
+import static android.content.pm.ActivityInfo.isFixedOrientationLandscape;
 import static android.content.pm.ActivityInfo.screenOrientationToString;
 import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
 import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
@@ -29,6 +38,7 @@
 import static android.view.WindowManager.PROPERTY_CAMERA_COMPAT_ALLOW_FORCE_ROTATION;
 import static android.view.WindowManager.PROPERTY_CAMERA_COMPAT_ALLOW_REFRESH;
 import static android.view.WindowManager.PROPERTY_CAMERA_COMPAT_ENABLE_REFRESH_VIA_PAUSE;
+import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE;
 import static android.view.WindowManager.PROPERTY_COMPAT_IGNORE_REQUESTED_ORIENTATION;
 
 import static com.android.internal.util.FrameworkStatsLog.APP_COMPAT_STATE_CHANGED__LETTERBOX_POSITION__BOTTOM;
@@ -111,6 +121,20 @@
      */
     private final float mExpandedTaskBarHeight;
 
+    // TODO(b/265576778): Cache other overrides as well.
+
+    // Corresponds to OVERRIDE_ANY_ORIENTATION
+    private final boolean mIsOverrideAnyOrientationEnabled;
+    // Corresponds to OVERRIDE_UNDEFINED_ORIENTATION_TO_PORTRAIT
+    private final boolean mIsOverrideToPortraitOrientationEnabled;
+    // Corresponds to OVERRIDE_UNDEFINED_ORIENTATION_TO_NOSENSOR
+    private final boolean mIsOverrideToNosensorOrientationEnabled;
+    // Corresponds to OVERRIDE_LANDSCAPE_ORIENTATION_TO_REVERSE_LANDSCAPE
+    private final boolean mIsOverrideToReverseLandscapeOrientationEnabled;
+
+    @Nullable
+    private final Boolean mBooleanPropertyAllowOrientationOverride;
+
     /*
      * WindowContainerListener responsible to make translucent activities inherit
      * constraints from the first opaque activity beneath them. It's null for not
@@ -193,6 +217,19 @@
 
         mExpandedTaskBarHeight =
                 getResources().getDimensionPixelSize(R.dimen.taskbar_frame_height);
+
+        mBooleanPropertyAllowOrientationOverride =
+                readComponentProperty(packageManager, mActivityRecord.packageName,
+                        /* gatingCondition */ null,
+                        PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE);
+
+        mIsOverrideAnyOrientationEnabled = isCompatChangeEnabled(OVERRIDE_ANY_ORIENTATION);
+        mIsOverrideToPortraitOrientationEnabled =
+                isCompatChangeEnabled(OVERRIDE_UNDEFINED_ORIENTATION_TO_PORTRAIT);
+        mIsOverrideToReverseLandscapeOrientationEnabled =
+                isCompatChangeEnabled(OVERRIDE_LANDSCAPE_ORIENTATION_TO_REVERSE_LANDSCAPE);
+        mIsOverrideToNosensorOrientationEnabled =
+                isCompatChangeEnabled(OVERRIDE_UNDEFINED_ORIENTATION_TO_NOSENSOR);
     }
 
     /**
@@ -207,8 +244,8 @@
      */
     @Nullable
     private static Boolean readComponentProperty(PackageManager packageManager, String packageName,
-            BooleanSupplier gatingCondition, String propertyName) {
-        if (!gatingCondition.getAsBoolean()) {
+            @Nullable BooleanSupplier gatingCondition, String propertyName) {
+        if (gatingCondition != null && !gatingCondition.getAsBoolean()) {
             return null;
         }
         try {
@@ -307,6 +344,41 @@
         mIsRefreshAfterRotationRequested = isRequested;
     }
 
+    @ScreenOrientation
+    int overrideOrientationIfNeeded(@ScreenOrientation int candidate) {
+        if (Boolean.FALSE.equals(mBooleanPropertyAllowOrientationOverride)) {
+            return candidate;
+        }
+
+        if (mIsOverrideToReverseLandscapeOrientationEnabled
+                && (isFixedOrientationLandscape(candidate) || mIsOverrideAnyOrientationEnabled)) {
+            Slog.w(TAG, "Requested orientation  " + screenOrientationToString(candidate) + " for "
+                    + mActivityRecord + " is overridden to "
+                    + screenOrientationToString(SCREEN_ORIENTATION_REVERSE_LANDSCAPE));
+            return SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
+        }
+
+        if (!mIsOverrideAnyOrientationEnabled && isFixedOrientation(candidate)) {
+            return candidate;
+        }
+
+        if (mIsOverrideToPortraitOrientationEnabled) {
+            Slog.w(TAG, "Requested orientation  " + screenOrientationToString(candidate) + " for "
+                    + mActivityRecord + " is overridden to "
+                    + screenOrientationToString(SCREEN_ORIENTATION_PORTRAIT));
+            return SCREEN_ORIENTATION_PORTRAIT;
+        }
+
+        if (mIsOverrideToNosensorOrientationEnabled) {
+            Slog.w(TAG, "Requested orientation  " + screenOrientationToString(candidate) + " for "
+                    + mActivityRecord + " is overridden to "
+                    + screenOrientationToString(SCREEN_ORIENTATION_NOSENSOR));
+            return SCREEN_ORIENTATION_NOSENSOR;
+        }
+
+        return candidate;
+    }
+
     /**
      * Whether activity is eligible for activity "refresh" after camera compat force rotation
      * treatment. See {@link DisplayRotationCompatPolicy} for context.
@@ -367,6 +439,10 @@
                 mBooleanPropertyCameraCompatAllowForceRotation);
     }
 
+    private boolean isCompatChangeEnabled(long overrideChangeId) {
+        return mActivityRecord.info.isChangeEnabled(overrideChangeId);
+    }
+
     /**
      * Returns {@code true} when the following conditions are met:
      * <ul>
@@ -383,8 +459,7 @@
         if (!gatingCondition.getAsBoolean()) {
             return false;
         }
-        return !Boolean.FALSE.equals(property)
-                && !mActivityRecord.info.isChangeEnabled(overrideChangeId);
+        return !Boolean.FALSE.equals(property) && !isCompatChangeEnabled(overrideChangeId);
     }
 
     /**
@@ -393,7 +468,7 @@
      *     <li>{@code gatingCondition} isn't {@code false}
      *     <li>App developers didn't opt out with a component {@code property}
      *     <li>App developers opted in with a component {@code property} or an OEM opted in with a
-     *     component {@code property}
+     *     {@code overrideChangeId} override
      * </ul>
      *
      * <p>This is used for the treatments that are enabled only on per-app basis.
@@ -406,8 +481,7 @@
         if (Boolean.FALSE.equals(property)) {
             return false;
         }
-        return Boolean.TRUE.equals(property)
-                || mActivityRecord.info.isChangeEnabled(overrideChangeId);
+        return Boolean.TRUE.equals(property) || isCompatChangeEnabled(overrideChangeId);
     }
 
     boolean hasWallpaperBackgroundForLetterbox() {
@@ -542,7 +616,7 @@
     // Note that we check the task rather than the parent as with ActivityEmbedding the parent might
     // be a TaskFragment, and its windowing mode is always MULTI_WINDOW, even if the task is
     // actually fullscreen.
-    private boolean isDisplayFullScreenAndInPosture(DeviceStateController.FoldState state,
+    private boolean isDisplayFullScreenAndInPosture(DeviceStateController.DeviceState state,
             boolean isTabletop) {
         Task task = mActivityRecord.getTask();
         return mActivityRecord.mDisplayContent != null
@@ -568,7 +642,7 @@
         // Don't check resolved configuration because it may not be updated yet during
         // configuration change.
         boolean bookMode = isDisplayFullScreenAndInPosture(
-                DeviceStateController.FoldState.HALF_FOLDED, false /* isTabletop */);
+                DeviceStateController.DeviceState.HALF_FOLDED, false /* isTabletop */);
         return isHorizontalReachabilityEnabled(parentConfiguration)
                 // Using the last global dynamic position to avoid "jumps" when moving
                 // between apps or activities.
@@ -580,7 +654,7 @@
         // Don't check resolved configuration because it may not be updated yet during
         // configuration change.
         boolean tabletopMode = isDisplayFullScreenAndInPosture(
-                DeviceStateController.FoldState.HALF_FOLDED, true /* isTabletop */);
+                DeviceStateController.DeviceState.HALF_FOLDED, true /* isTabletop */);
         return isVerticalReachabilityEnabled(parentConfiguration)
                 // Using the last global dynamic position to avoid "jumps" when moving
                 // between apps or activities.
@@ -1107,7 +1181,7 @@
             int letterboxPositionForHorizontalReachability = getLetterboxConfiguration()
                     .getLetterboxPositionForHorizontalReachability(
                             isDisplayFullScreenAndInPosture(
-                                    DeviceStateController.FoldState.HALF_FOLDED,
+                                    DeviceStateController.DeviceState.HALF_FOLDED,
                                     false /* isTabletop */));
             positionToLog = letterboxHorizontalReachabilityPositionToLetterboxPosition(
                     letterboxPositionForHorizontalReachability);
@@ -1115,7 +1189,7 @@
             int letterboxPositionForVerticalReachability = getLetterboxConfiguration()
                     .getLetterboxPositionForVerticalReachability(
                             isDisplayFullScreenAndInPosture(
-                                    DeviceStateController.FoldState.HALF_FOLDED,
+                                    DeviceStateController.DeviceState.HALF_FOLDED,
                                     true /* isTabletop */));
             positionToLog = letterboxVerticalReachabilityPositionToLetterboxPosition(
                     letterboxPositionForVerticalReachability);
@@ -1224,7 +1298,8 @@
         // To avoid wrong behaviour, we're not forcing orientation for activities with not
         // fixed orientation (e.g. permission dialogs).
         return hasInheritedLetterboxBehavior()
-                && mActivityRecord.mOrientation != SCREEN_ORIENTATION_UNSPECIFIED;
+                && mActivityRecord.getOverrideOrientation()
+                        != SCREEN_ORIENTATION_UNSPECIFIED;
     }
 
     float getInheritedMinAspectRatio() {
diff --git a/services/core/java/com/android/server/wm/PhysicalDisplaySwitchTransitionLauncher.java b/services/core/java/com/android/server/wm/PhysicalDisplaySwitchTransitionLauncher.java
index 30bdc34..2edb082 100644
--- a/services/core/java/com/android/server/wm/PhysicalDisplaySwitchTransitionLauncher.java
+++ b/services/core/java/com/android/server/wm/PhysicalDisplaySwitchTransitionLauncher.java
@@ -51,10 +51,10 @@
     /**
      *   Called by the DeviceStateManager callback when the state changes.
      */
-    void foldStateChanged(DeviceStateController.FoldState newFoldState) {
+    void foldStateChanged(DeviceStateController.DeviceState newDeviceState) {
         // Ignore transitions to/from half-folded.
-        if (newFoldState == DeviceStateController.FoldState.HALF_FOLDED) return;
-        mIsFolded = newFoldState == DeviceStateController.FoldState.FOLDED;
+        if (newDeviceState == DeviceStateController.DeviceState.HALF_FOLDED) return;
+        mIsFolded = newDeviceState == DeviceStateController.DeviceState.FOLDED;
     }
 
     /**
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 1b59d8d..adc82ec 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -5020,70 +5020,76 @@
         ProtoLog.i(WM_DEBUG_ADD_REMOVE, "Adding activity %s to task %s "
                         + "callers: %s", r, task, new RuntimeException("here").fillInStackTrace());
 
-        // The transition animation and starting window are not needed if {@code allowMoveToFront}
-        // is false, because the activity won't be visible.
-        if ((!isActivityTypeHomeOrRecents() || hasActivity()) && allowMoveToFront) {
-            final DisplayContent dc = mDisplayContent;
-            if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
-                    "Prepare open transition: starting " + r);
-            if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
-                dc.prepareAppTransition(TRANSIT_NONE);
-                mTaskSupervisor.mNoAnimActivities.add(r);
-                mTransitionController.setNoAnimation(r);
-            } else {
-                dc.prepareAppTransition(TRANSIT_OPEN);
-                mTaskSupervisor.mNoAnimActivities.remove(r);
-            }
-            if (newTask && !r.mLaunchTaskBehind) {
-                // If a new task is being launched, then mark the existing top activity as
-                // supporting picture-in-picture while pausing only if the starting activity
-                // would not be considered an overlay on top of the current activity
-                // (eg. not fullscreen, or the assistant)
-                enableEnterPipOnTaskSwitch(pipCandidate,
-                        null /* toFrontTask */, r, options);
-            }
-            boolean doShow = true;
-            if (newTask) {
-                // Even though this activity is starting fresh, we still need
-                // to reset it to make sure we apply affinities to move any
-                // existing activities from other tasks in to it.
-                // If the caller has requested that the target task be
-                // reset, then do so.
-                if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
-                    resetTaskIfNeeded(r, r);
-                    doShow = topRunningNonDelayedActivityLocked(null) == r;
-                }
-            } else if (options != null && options.getAnimationType()
-                    == ActivityOptions.ANIM_SCENE_TRANSITION) {
-                doShow = false;
-            }
-            if (options != null && options.getDisableStartingWindow()) {
-                doShow = false;
-            }
-            if (r.mLaunchTaskBehind) {
-                // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we
-                // tell WindowManager that r is visible even though it is at the back of the root
-                // task.
-                r.setVisibility(true);
-                ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
-                // Go ahead to execute app transition for this activity since the app transition
-                // will not be triggered through the resume channel.
-                mDisplayContent.executeAppTransition();
-            } else if (SHOW_APP_STARTING_PREVIEW && doShow) {
-                // Figure out if we are transitioning from another activity that is
-                // "has the same starting icon" as the next one.  This allows the
-                // window manager to keep the previous window it had previously
-                // created, if it still had one.
-                Task baseTask = r.getTask();
-                final ActivityRecord prev = baseTask.getActivity(
-                        a -> a.mStartingData != null && a.showToCurrentUser());
-                mWmService.mStartingSurfaceController.showStartingWindow(r, prev, newTask,
-                        isTaskSwitch, sourceRecord);
-            }
-        } else {
+        if (isActivityTypeHomeOrRecents() && getActivityBelow(r) == null) {
             // If this is the first activity, don't do any fancy animations,
             // because there is nothing for it to animate on top of.
             ActivityOptions.abort(options);
+            return;
+        }
+
+        if (!allowMoveToFront) {
+            // The transition animation and starting window are not needed if
+            // {@code allowMoveToFront} is false, because the activity won't be visible.
+            ActivityOptions.abort(options);
+            return;
+        }
+
+        final DisplayContent dc = mDisplayContent;
+        if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
+                "Prepare open transition: starting " + r);
+        if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
+            dc.prepareAppTransition(TRANSIT_NONE);
+            mTaskSupervisor.mNoAnimActivities.add(r);
+            mTransitionController.setNoAnimation(r);
+        } else {
+            dc.prepareAppTransition(TRANSIT_OPEN);
+            mTaskSupervisor.mNoAnimActivities.remove(r);
+        }
+        if (newTask && !r.mLaunchTaskBehind) {
+            // If a new task is being launched, then mark the existing top activity as
+            // supporting picture-in-picture while pausing only if the starting activity
+            // would not be considered an overlay on top of the current activity
+            // (eg. not fullscreen, or the assistant)
+            enableEnterPipOnTaskSwitch(pipCandidate,
+                    null /* toFrontTask */, r, options);
+        }
+        boolean doShow = true;
+        if (newTask) {
+            // Even though this activity is starting fresh, we still need
+            // to reset it to make sure we apply affinities to move any
+            // existing activities from other tasks in to it.
+            // If the caller has requested that the target task be
+            // reset, then do so.
+            if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
+                resetTaskIfNeeded(r, r);
+                doShow = topRunningNonDelayedActivityLocked(null) == r;
+            }
+        } else if (options != null && options.getAnimationType()
+                == ActivityOptions.ANIM_SCENE_TRANSITION) {
+            doShow = false;
+        }
+        if (options != null && options.getDisableStartingWindow()) {
+            doShow = false;
+        }
+        if (r.mLaunchTaskBehind) {
+            // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we
+            // tell WindowManager that r is visible even though it is at the back of the root
+            // task.
+            r.setVisibility(true);
+            ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
+            // Go ahead to execute app transition for this activity since the app transition
+            // will not be triggered through the resume channel.
+            mDisplayContent.executeAppTransition();
+        } else if (SHOW_APP_STARTING_PREVIEW && doShow) {
+            // Figure out if we are transitioning from another activity that is
+            // "has the same starting icon" as the next one.  This allows the
+            // window manager to keep the previous window it had previously
+            // created, if it still had one.
+            Task baseTask = r.getTask();
+            final ActivityRecord prev = baseTask.getActivity(
+                    a -> a.mStartingData != null && a.showToCurrentUser());
+            mWmService.mStartingSurfaceController.showStartingWindow(r, prev, newTask,
+                    isTaskSwitch, sourceRecord);
         }
     }
 
diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java
index 63bb5c3..b06bdb1 100644
--- a/services/core/java/com/android/server/wm/WindowContainer.java
+++ b/services/core/java/com/android/server/wm/WindowContainer.java
@@ -73,6 +73,7 @@
 import android.annotation.Nullable;
 import android.content.Context;
 import android.content.pm.ActivityInfo;
+import android.content.pm.ActivityInfo.ScreenOrientation;
 import android.content.res.Configuration;
 import android.graphics.Color;
 import android.graphics.Point;
@@ -178,8 +179,9 @@
     protected final WindowList<E> mChildren = new WindowList<E>();
 
     // The specified orientation for this window container.
-    @ActivityInfo.ScreenOrientation
-    protected int mOrientation = SCREEN_ORIENTATION_UNSPECIFIED;
+    // Shouldn't be accessed directly since subclasses can override getOverrideOrientation.
+    @ScreenOrientation
+    private int mOverrideOrientation = SCREEN_ORIENTATION_UNSPECIFIED;
 
     /**
      * The window container which decides its orientation since the last time
@@ -1456,19 +1458,20 @@
 
     /**
      * Gets the configuration orientation by the requested screen orientation
-     * ({@link ActivityInfo.ScreenOrientation}) of this activity.
+     * ({@link ScreenOrientation}) of this activity.
      *
      * @return orientation in ({@link Configuration#ORIENTATION_LANDSCAPE},
      *         {@link Configuration#ORIENTATION_PORTRAIT},
      *         {@link Configuration#ORIENTATION_UNDEFINED}).
      */
+    @ScreenOrientation
     int getRequestedConfigurationOrientation() {
         return getRequestedConfigurationOrientation(false /* forDisplay */);
     }
 
     /**
      * Gets the configuration orientation by the requested screen orientation
-     * ({@link ActivityInfo.ScreenOrientation}) of this activity.
+     * ({@link ScreenOrientation}) of this activity.
      *
      * @param forDisplay whether it is the requested config orientation for display.
      *                   If {@code true}, we may reverse the requested orientation if the root is
@@ -1479,8 +1482,9 @@
      *         {@link Configuration#ORIENTATION_PORTRAIT},
      *         {@link Configuration#ORIENTATION_UNDEFINED}).
      */
+    @ScreenOrientation
     int getRequestedConfigurationOrientation(boolean forDisplay) {
-        int requestedOrientation = mOrientation;
+        int requestedOrientation = getOverrideOrientation();
         final RootDisplayArea root = getRootDisplayArea();
         if (forDisplay && root != null && root.isOrientationDifferentFromDisplay()) {
             // Reverse the requested orientation if the orientation of its root is different from
@@ -1490,7 +1494,7 @@
             // (portrait).
             // When an app below the DAG is requesting landscape, it should actually request the
             // display to be portrait, so that the DAG and the app will be in landscape.
-            requestedOrientation = reverseOrientation(mOrientation);
+            requestedOrientation = reverseOrientation(getOverrideOrientation());
         }
 
         if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
@@ -1515,7 +1519,7 @@
      *
      * @param orientation the specified orientation.
      */
-    void setOrientation(int orientation) {
+    void setOrientation(@ScreenOrientation int orientation) {
         setOrientation(orientation, null /* requestingContainer */);
     }
 
@@ -1523,17 +1527,17 @@
      * Sets the specified orientation of this container. It percolates this change upward along the
      * hierarchy to let each level of the hierarchy a chance to respond to it.
      *
-     * @param orientation the specified orientation. Needs to be one of {@link
-     *      android.content.pm.ActivityInfo.ScreenOrientation}.
+     * @param orientation the specified orientation. Needs to be one of {@link ScreenOrientation}.
      * @param requestingContainer the container which orientation request has changed. Mostly used
      *                            to ensure it gets correct configuration.
      */
-    void setOrientation(int orientation, @Nullable WindowContainer requestingContainer) {
-        if (mOrientation == orientation) {
+    void setOrientation(@ScreenOrientation int orientation,
+            @Nullable WindowContainer requestingContainer) {
+        if (getOverrideOrientation() == orientation) {
             return;
         }
 
-        mOrientation = orientation;
+        setOverrideOrientation(orientation);
         final WindowContainer parent = getParent();
         if (parent != null) {
             if (getConfiguration().orientation != getRequestedConfigurationOrientation()
@@ -1552,9 +1556,9 @@
         }
     }
 
-    @ActivityInfo.ScreenOrientation
+    @ScreenOrientation
     int getOrientation() {
-        return getOrientation(mOrientation);
+        return getOrientation(getOverrideOrientation());
     }
 
     /**
@@ -1568,7 +1572,8 @@
      *                  better match.
      * @return The orientation as specified by this branch or the window hierarchy.
      */
-    int getOrientation(int candidate) {
+    @ScreenOrientation
+    int getOrientation(@ScreenOrientation int candidate) {
         mLastOrientationSource = null;
         if (!providesOrientation()) {
             return SCREEN_ORIENTATION_UNSET;
@@ -1578,16 +1583,16 @@
         // specified; otherwise we prefer to use the orientation of its topmost child that has one
         // specified and fall back on this container's unset or unspecified value as a candidate
         // if none of the children have a better candidate for the orientation.
-        if (mOrientation != SCREEN_ORIENTATION_UNSET
-                && mOrientation != SCREEN_ORIENTATION_UNSPECIFIED) {
+        if (getOverrideOrientation() != SCREEN_ORIENTATION_UNSET
+                && getOverrideOrientation() != SCREEN_ORIENTATION_UNSPECIFIED) {
             mLastOrientationSource = this;
-            return mOrientation;
+            return getOverrideOrientation();
         }
 
         for (int i = mChildren.size() - 1; i >= 0; --i) {
             final WindowContainer wc = mChildren.get(i);
 
-            // TODO: Maybe mOrientation should default to SCREEN_ORIENTATION_UNSET vs.
+            // TODO: Maybe mOverrideOrientation should default to SCREEN_ORIENTATION_UNSET vs.
             // SCREEN_ORIENTATION_UNSPECIFIED?
             final int orientation = wc.getOrientation(candidate == SCREEN_ORIENTATION_BEHIND
                     ? SCREEN_ORIENTATION_BEHIND : SCREEN_ORIENTATION_UNSET);
@@ -1619,6 +1624,20 @@
     }
 
     /**
+     * Returns orientation specified on this level of hierarchy without taking children into
+     * account, like {@link #getOrientation} does, allowing subclasses to override. See {@link
+     * ActivityRecord#getOverrideOrientation} for an example.
+     */
+    @ScreenOrientation
+    protected int getOverrideOrientation() {
+        return mOverrideOrientation;
+    }
+
+    protected void setOverrideOrientation(@ScreenOrientation int orientation) {
+        mOverrideOrientation = orientation;
+    }
+
+    /**
      * @return The deepest source which decides the orientation of this window container since the
      *         last time {@link #getOrientation(int) was called.
      */
@@ -2674,7 +2693,7 @@
 
         final long token = proto.start(fieldId);
         super.dumpDebug(proto, CONFIGURATION_CONTAINER, logLevel);
-        proto.write(ORIENTATION, mOrientation);
+        proto.write(ORIENTATION, mOverrideOrientation);
         proto.write(VISIBLE, isVisible);
         writeIdentifierToProto(proto, IDENTIFIER);
         if (mSurfaceAnimator.isAnimating()) {
diff --git a/services/core/xsd/display-device-config/display-device-config.xsd b/services/core/xsd/display-device-config/display-device-config.xsd
index a27eb7f..97dbe04 100644
--- a/services/core/xsd/display-device-config/display-device-config.xsd
+++ b/services/core/xsd/display-device-config/display-device-config.xsd
@@ -117,6 +117,11 @@
                 <xs:element type="integer-array" name="screenOffBrightnessSensorValueToLux">
                     <xs:annotation name="final"/>
                 </xs:element>
+                <!-- The version of the Universal Stylus Initiative
+                 (USI, https://universalstylus.org/) protocol supported by the display, if any. -->
+                <xs:element type="usiVersion" name="usiVersion">
+                    <xs:annotation name="final"/>
+                </xs:element>
             </xs:sequence>
         </xs:complexType>
     </xs:element>
@@ -502,4 +507,15 @@
             <xs:element name="item" type="xs:nonNegativeInteger" minOccurs="0" maxOccurs="unbounded"/>
         </xs:sequence>
     </xs:complexType>
+
+    <xs:complexType name="usiVersion">
+        <xs:element name="majorVersion" type="xs:nonNegativeInteger"
+                    minOccurs="1" maxOccurs="1">
+            <xs:annotation name="final"/>
+        </xs:element>
+        <xs:element name="minorVersion" type="xs:nonNegativeInteger"
+                    minOccurs="1" maxOccurs="1">
+            <xs:annotation name="final"/>
+        </xs:element>
+    </xs:complexType>
 </xs:schema>
diff --git a/services/core/xsd/display-device-config/schema/current.txt b/services/core/xsd/display-device-config/schema/current.txt
index 6c66d0d..aba8a2c 100644
--- a/services/core/xsd/display-device-config/schema/current.txt
+++ b/services/core/xsd/display-device-config/schema/current.txt
@@ -101,6 +101,7 @@
     method public final com.android.server.display.config.SensorDetails getScreenOffBrightnessSensor();
     method public final com.android.server.display.config.IntegerArray getScreenOffBrightnessSensorValueToLux();
     method @NonNull public final com.android.server.display.config.ThermalThrottling getThermalThrottling();
+    method public final com.android.server.display.config.UsiVersion getUsiVersion();
     method public final void setAmbientBrightnessChangeThresholds(@NonNull com.android.server.display.config.Thresholds);
     method public final void setAmbientBrightnessChangeThresholdsIdle(com.android.server.display.config.Thresholds);
     method public final void setAmbientLightHorizonLong(java.math.BigInteger);
@@ -125,6 +126,7 @@
     method public final void setScreenOffBrightnessSensor(com.android.server.display.config.SensorDetails);
     method public final void setScreenOffBrightnessSensorValueToLux(com.android.server.display.config.IntegerArray);
     method public final void setThermalThrottling(@NonNull com.android.server.display.config.ThermalThrottling);
+    method public final void setUsiVersion(com.android.server.display.config.UsiVersion);
   }
 
   public class DisplayQuirks {
@@ -263,6 +265,14 @@
     method public final void setDarkeningThresholds(@NonNull com.android.server.display.config.BrightnessThresholds);
   }
 
+  public class UsiVersion {
+    ctor public UsiVersion();
+    method public final java.math.BigInteger getMajorVersion();
+    method public final java.math.BigInteger getMinorVersion();
+    method public final void setMajorVersion(java.math.BigInteger);
+    method public final void setMinorVersion(java.math.BigInteger);
+  }
+
   public class XmlParser {
     ctor public XmlParser();
     method public static com.android.server.display.config.DisplayConfiguration read(java.io.InputStream) throws javax.xml.datatype.DatatypeConfigurationException, java.io.IOException, org.xmlpull.v1.XmlPullParserException;
diff --git a/services/tests/servicestests/src/com/android/server/BinaryTransparencyServiceTest.java b/services/tests/servicestests/src/com/android/server/BinaryTransparencyServiceTest.java
index 0b25f38..49f27e9 100644
--- a/services/tests/servicestests/src/com/android/server/BinaryTransparencyServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/BinaryTransparencyServiceTest.java
@@ -16,6 +16,8 @@
 
 package com.android.server;
 
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.eq;
 import static org.mockito.Mockito.never;
@@ -33,9 +35,11 @@
 import android.hardware.face.FaceManager;
 import android.hardware.face.FaceSensorProperties;
 import android.hardware.face.FaceSensorPropertiesInternal;
+import android.hardware.face.IFaceAuthenticatorsRegisteredCallback;
 import android.hardware.fingerprint.FingerprintManager;
 import android.hardware.fingerprint.FingerprintSensorProperties;
 import android.hardware.fingerprint.FingerprintSensorPropertiesInternal;
+import android.hardware.fingerprint.IFingerprintAuthenticatorsRegisteredCallback;
 import android.os.Bundle;
 import android.os.RemoteException;
 import android.os.ResultReceiver;
@@ -53,6 +57,8 @@
 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;
 
@@ -74,6 +80,15 @@
     private FingerprintManager mFpManager;
     @Mock
     private FaceManager mFaceManager;
+    @Mock
+    private PackageManager mPackageManager;
+
+    @Captor
+    private ArgumentCaptor<IFingerprintAuthenticatorsRegisteredCallback>
+            mFpAuthenticatorsRegisteredCaptor;
+    @Captor
+    private ArgumentCaptor<IFaceAuthenticatorsRegisteredCallback>
+            mFaceAuthenticatorsRegisteredCaptor;
 
     @Before
     public void setUp() {
@@ -83,9 +98,6 @@
         mBinaryTransparencyService = new BinaryTransparencyService(mContext, mBiometricLogger);
         mTestInterface = mBinaryTransparencyService.new BinaryTransparencyServiceImpl();
         mOriginalBiometricsFlags = DeviceConfig.getProperties(DeviceConfig.NAMESPACE_BIOMETRICS);
-
-        when(mContext.getSystemService(FingerprintManager.class)).thenReturn(mFpManager);
-        when(mContext.getSystemService(FaceManager.class)).thenReturn(mFaceManager);
     }
 
     @After
@@ -112,6 +124,14 @@
                 args, null, new ResultReceiver(null));
     }
 
+    private void prepBiometricsTesting() {
+        when(mContext.getPackageManager()).thenReturn(mPackageManager);
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)).thenReturn(true);
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE)).thenReturn(true);
+        when(mContext.getSystemService(FingerprintManager.class)).thenReturn(mFpManager);
+        when(mContext.getSystemService(FaceManager.class)).thenReturn(mFaceManager);
+    }
+
     @Test
     public void getSignedImageInfo_preInitialize_returnsUninitializedString() {
         String result = mTestInterface.getSignedImageInfo();
@@ -175,25 +195,14 @@
 
         mBinaryTransparencyService.collectBiometricProperties();
 
-        verify(mFpManager, never()).getSensorPropertiesInternal();
-        verify(mFaceManager, never()).getSensorProperties();
+        verify(mBiometricLogger, never()).logStats(anyInt(), anyInt(), anyInt(), anyInt(),
+                anyString(), anyString(), anyString(), anyString(), anyString());
     }
 
     @Test
-    public void testCollectBiometricProperties_enablesFeature() {
-        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_BIOMETRICS,
-                BinaryTransparencyService.KEY_ENABLE_BIOMETRIC_PROPERTY_VERIFICATION,
-                Boolean.TRUE.toString(),
-                false /* makeDefault */);
-
-        mBinaryTransparencyService.collectBiometricProperties();
-
-        verify(mFpManager, times(1)).getSensorPropertiesInternal();
-        verify(mFaceManager, times(1)).getSensorProperties();
-    }
-
-    @Test
-    public void testCollectBiometricProperties_enablesFeature_logsFingerprintProperties() {
+    public void testCollectBiometricProperties_enablesFeature_logsFingerprintProperties()
+            throws RemoteException {
+        prepBiometricsTesting();
         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_BIOMETRICS,
                 BinaryTransparencyService.KEY_ENABLE_BIOMETRIC_PROPERTY_VERIFICATION,
                 Boolean.TRUE.toString(),
@@ -209,10 +218,13 @@
                                 "" /* softwareVersion */)),
                         FingerprintSensorProperties.TYPE_REAR,
                         true /* resetLockoutRequiresHardwareAuthToken */));
-        when(mFpManager.getSensorPropertiesInternal()).thenReturn(props);
 
         mBinaryTransparencyService.collectBiometricProperties();
 
+        verify(mFpManager).addAuthenticatorsRegisteredCallback(mFpAuthenticatorsRegisteredCaptor
+                .capture());
+        mFpAuthenticatorsRegisteredCaptor.getValue().onAllAuthenticatorsRegistered(props);
+
         verify(mBiometricLogger, times(1)).logStats(
                 eq(1) /* sensorId */,
                 eq(FrameworkStatsLog
@@ -230,28 +242,33 @@
     }
 
     @Test
-    public void testCollectBiometricProperties_enablesFeature_logsFaceProperties() {
+    public void testCollectBiometricProperties_enablesFeature_logsFaceProperties()
+            throws RemoteException {
+        prepBiometricsTesting();
         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_BIOMETRICS,
                 BinaryTransparencyService.KEY_ENABLE_BIOMETRIC_PROPERTY_VERIFICATION,
                 Boolean.TRUE.toString(),
                 false /* makeDefault */);
-        final List<FaceSensorProperties> props = List.of(FaceSensorProperties.from(
-                        new FaceSensorPropertiesInternal(
-                                1 /* sensorId */,
-                                SensorProperties.STRENGTH_CONVENIENCE,
-                                1 /* maxEnrollmentsPerUser */,
-                                List.of(new ComponentInfoInternal("sensor" /* componentId */,
-                                        "vendor/model/revision" /* hardwareVersion */,
-                                        "1.01" /* firmwareVersion */, "00000001" /* serialNumber */,
-                                        "" /* softwareVersion */)),
-                                FaceSensorProperties.TYPE_RGB,
-                                true /* supportsFaceDetection */,
-                                true /* supportsSelfIllumination */,
-                                true /* resetLockoutRequiresHardwareAuthToken */)));
-        when(mFaceManager.getSensorProperties()).thenReturn(props);
+        final List<FaceSensorPropertiesInternal> props = List.of(
+                new FaceSensorPropertiesInternal(
+                        1 /* sensorId */,
+                        SensorProperties.STRENGTH_CONVENIENCE,
+                        1 /* maxEnrollmentsPerUser */,
+                        List.of(new ComponentInfoInternal("sensor" /* componentId */,
+                                "vendor/model/revision" /* hardwareVersion */,
+                                "1.01" /* firmwareVersion */, "00000001" /* serialNumber */,
+                                "" /* softwareVersion */)),
+                        FaceSensorProperties.TYPE_RGB,
+                        true /* supportsFaceDetection */,
+                        true /* supportsSelfIllumination */,
+                        true /* resetLockoutRequiresHardwareAuthToken */));
 
         mBinaryTransparencyService.collectBiometricProperties();
 
+        verify(mFaceManager).addAuthenticatorsRegisteredCallback(mFaceAuthenticatorsRegisteredCaptor
+                .capture());
+        mFaceAuthenticatorsRegisteredCaptor.getValue().onAllAuthenticatorsRegistered(props);
+
         verify(mBiometricLogger, times(1)).logStats(
                 eq(1) /* sensorId */,
                 eq(FrameworkStatsLog
diff --git a/services/tests/servicestests/src/com/android/server/display/DisplayDeviceConfigTest.java b/services/tests/servicestests/src/com/android/server/display/DisplayDeviceConfigTest.java
index 4bc8242..0ea20a8 100644
--- a/services/tests/servicestests/src/com/android/server/display/DisplayDeviceConfigTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/DisplayDeviceConfigTest.java
@@ -19,6 +19,7 @@
 
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
 import static org.mockito.ArgumentMatchers.anyFloat;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.Mockito.mock;
@@ -212,6 +213,10 @@
         assertEquals(new DisplayDeviceConfig.BrightnessThrottlingData(throttlingLevels),
                 mDisplayDeviceConfig.getConcurrentDisplaysBrightnessThrottlingData());
 
+        assertNotNull(mDisplayDeviceConfig.getHostUsiVersion());
+        assertEquals(mDisplayDeviceConfig.getHostUsiVersion().getMajorVersion(), 2);
+        assertEquals(mDisplayDeviceConfig.getHostUsiVersion().getMinorVersion(), 0);
+
         // Todo: Add asserts for BrightnessThrottlingData, DensityMapping,
         // HighBrightnessModeData AmbientLightSensor, RefreshRateLimitations and ProximitySensor.
     }
@@ -570,6 +575,10 @@
                 +       "<item>30</item>\n"
                 +       "<item>40</item>\n"
                 +   "</screenOffBrightnessSensorValueToLux>\n"
+                +   "<usiVersion>\n"
+                +       "<majorVersion>2</majorVersion>\n"
+                +       "<minorVersion>0</minorVersion>\n"
+                +   "</usiVersion>\n"
                 + "</displayConfiguration>\n";
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/display/brightness/BrightnessEventTest.java b/services/tests/servicestests/src/com/android/server/display/brightness/BrightnessEventTest.java
index d332b30..c0c63c6 100644
--- a/services/tests/servicestests/src/com/android/server/display/brightness/BrightnessEventTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/brightness/BrightnessEventTest.java
@@ -30,6 +30,7 @@
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public final class BrightnessEventTest {
+    private static final String DISPLAY_BRIGHTNESS_STRATEGY_NAME = "strategy_name";
     private BrightnessEvent mBrightnessEvent;
 
     @Before
@@ -53,6 +54,7 @@
         mBrightnessEvent.setFlags(0);
         mBrightnessEvent.setAdjustmentFlags(0);
         mBrightnessEvent.setAutomaticBrightnessEnabled(true);
+        mBrightnessEvent.setDisplayBrightnessStrategyName(DISPLAY_BRIGHTNESS_STRATEGY_NAME);
     }
 
     @Test
@@ -70,7 +72,8 @@
                 "BrightnessEvent: disp=1, physDisp=test, brt=0.6, initBrt=25.0, rcmdBrt=0.6,"
                 + " preBrt=NaN, lux=100.0, preLux=150.0, hbmMax=0.62, hbmMode=off, rbcStrength=-1,"
                 + " thrmMax=0.65, powerFactor=0.2, wasShortTermModelActive=true, flags=,"
-                + " reason=doze [ low_pwr ], autoBrightness=true";
+                + " reason=doze [ low_pwr ], autoBrightness=true, strategy="
+                        + DISPLAY_BRIGHTNESS_STRATEGY_NAME;
         assertEquals(expectedString, actualString);
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/BoostBrightnessStrategyTest.java b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/BoostBrightnessStrategyTest.java
index c1de894..c434631 100644
--- a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/BoostBrightnessStrategyTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/BoostBrightnessStrategyTest.java
@@ -55,6 +55,7 @@
                         .setBrightness(PowerManager.BRIGHTNESS_MAX)
                         .setBrightnessReason(brightnessReason)
                         .setSdrBrightness(PowerManager.BRIGHTNESS_MAX)
+                        .setDisplayBrightnessStrategyName(mBoostBrightnessStrategy.getName())
                         .build();
         DisplayBrightnessState updatedDisplayBrightnessState =
                 mBoostBrightnessStrategy.updateBrightness(displayPowerRequest);
diff --git a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/DozeBrightnessStrategyTest.java b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/DozeBrightnessStrategyTest.java
index 76fa172..d60caf6 100644
--- a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/DozeBrightnessStrategyTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/DozeBrightnessStrategyTest.java
@@ -52,6 +52,7 @@
                         .setBrightness(dozeScreenBrightness)
                         .setBrightnessReason(brightnessReason)
                         .setSdrBrightness(dozeScreenBrightness)
+                        .setDisplayBrightnessStrategyName(mDozeBrightnessModeStrategy.getName())
                         .build();
         DisplayBrightnessState updatedDisplayBrightnessState =
                 mDozeBrightnessModeStrategy.updateBrightness(displayPowerRequest);
diff --git a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/FollowerBrightnessStrategyTest.java b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/FollowerBrightnessStrategyTest.java
index f20404e..081f19d 100644
--- a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/FollowerBrightnessStrategyTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/FollowerBrightnessStrategyTest.java
@@ -54,6 +54,7 @@
                         .setBrightness(brightnessToFollow)
                         .setBrightnessReason(brightnessReason)
                         .setSdrBrightness(brightnessToFollow)
+                        .setDisplayBrightnessStrategyName(mFollowerBrightnessStrategy.getName())
                         .build();
         DisplayBrightnessState updatedDisplayBrightnessState =
                 mFollowerBrightnessStrategy.updateBrightness(displayPowerRequest);
diff --git a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/OverrideBrightnessStrategyTest.java b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/OverrideBrightnessStrategyTest.java
index 2487b32b..530245d 100644
--- a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/OverrideBrightnessStrategyTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/OverrideBrightnessStrategyTest.java
@@ -55,6 +55,7 @@
                         .setBrightness(overrideBrightness)
                         .setBrightnessReason(brightnessReason)
                         .setSdrBrightness(overrideBrightness)
+                        .setDisplayBrightnessStrategyName(mOverrideBrightnessStrategy.getName())
                         .build();
         DisplayBrightnessState updatedDisplayBrightnessState =
                 mOverrideBrightnessStrategy.updateBrightness(displayPowerRequest);
diff --git a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategyTest.java b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategyTest.java
index 353e92e..7147aa8 100644
--- a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategyTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/ScreenOffBrightnessStrategyTest.java
@@ -52,6 +52,8 @@
                         .setBrightness(PowerManager.BRIGHTNESS_OFF_FLOAT)
                         .setSdrBrightness(PowerManager.BRIGHTNESS_OFF_FLOAT)
                         .setBrightnessReason(brightnessReason)
+                        .setDisplayBrightnessStrategyName(mScreenOffBrightnessModeStrategy
+                                .getName())
                         .build();
         DisplayBrightnessState updatedDisplayBrightnessState =
                 mScreenOffBrightnessModeStrategy.updateBrightness(displayPowerRequest);
diff --git a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategyTest.java b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategyTest.java
index 99679a3..9830edb 100644
--- a/services/tests/servicestests/src/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategyTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/brightness/strategy/TemporaryBrightnessStrategyTest.java
@@ -55,6 +55,7 @@
                         .setBrightness(temporaryBrightness)
                         .setBrightnessReason(brightnessReason)
                         .setSdrBrightness(temporaryBrightness)
+                        .setDisplayBrightnessStrategyName(mTemporaryBrightnessStrategy.getName())
                         .build();
         DisplayBrightnessState updatedDisplayBrightnessState =
                 mTemporaryBrightnessStrategy.updateBrightness(displayPowerRequest);
diff --git a/services/tests/servicestests/src/com/android/server/job/PendingJobQueueTest.java b/services/tests/servicestests/src/com/android/server/job/PendingJobQueueTest.java
index 8c3838b..23d7082 100644
--- a/services/tests/servicestests/src/com/android/server/job/PendingJobQueueTest.java
+++ b/services/tests/servicestests/src/com/android/server/job/PendingJobQueueTest.java
@@ -201,6 +201,32 @@
             }
         }
         assertNull(jobQueue.next());
+        assertEquals(0, jobQueue.size());
+    }
+
+    @Test
+    public void testRemove_duringIteration() {
+        List<JobStatus> jobs = new ArrayList<>();
+        jobs.add(createJobStatus("testRemove", createJobInfo(1), 1));
+        jobs.add(createJobStatus("testRemove", createJobInfo(2), 2));
+        jobs.add(createJobStatus("testRemove", createJobInfo(3).setExpedited(true), 3));
+        jobs.add(createJobStatus("testRemove", createJobInfo(4), 4));
+        jobs.add(createJobStatus("testRemove", createJobInfo(5).setExpedited(true), 5));
+
+        PendingJobQueue jobQueue = new PendingJobQueue();
+        jobQueue.addAll(jobs);
+
+        ArraySet<JobStatus> removed = new ArraySet<>();
+        JobStatus job;
+        jobQueue.resetIterator();
+        while ((job = jobQueue.next()) != null) {
+            jobQueue.remove(job);
+            removed.add(job);
+            assertFalse("Queue retained a removed job " + testJobToString(job),
+                    jobQueue.contains(job));
+        }
+        assertNull(jobQueue.next());
+        assertEquals(0, jobQueue.size());
     }
 
     @Test
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsHistoryIteratorTest.java b/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsHistoryIteratorTest.java
index 71c8c1d..74189fd 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsHistoryIteratorTest.java
+++ b/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsHistoryIteratorTest.java
@@ -33,21 +33,27 @@
 
 import java.io.File;
 import java.util.Random;
+import java.util.concurrent.Future;
 
 @RunWith(AndroidJUnit4.class)
 @SmallTest
+@SuppressWarnings("GuardedBy")
 public class BatteryStatsHistoryIteratorTest {
     private static final int APP_UID = Process.FIRST_APPLICATION_UID + 42;
 
     private MockClock mMockClock = new MockClock();
     private MockBatteryStatsImpl mBatteryStats;
     private Random mRandom = new Random();
+    private MockExternalStatsSync mExternalStatsSync = new MockExternalStatsSync();
 
     @Before
     public void setup() {
-        final File historyDir =
-                createTemporaryDirectory(getClass().getSimpleName());
+        final File historyDir = createTemporaryDirectory(getClass().getSimpleName());
         mBatteryStats = new MockBatteryStatsImpl(mMockClock, historyDir);
+        mBatteryStats.setDummyExternalStatsSync(mExternalStatsSync);
+        mBatteryStats.setRecordAllHistoryLocked(true);
+        mBatteryStats.forceRecordAllHistory();
+        mBatteryStats.setNoAutoReset(true);
     }
 
     /**
@@ -65,42 +71,24 @@
 
     @Test
     public void testIterator() {
-        synchronized (mBatteryStats) {
-            mBatteryStats.setRecordAllHistoryLocked(true);
-        }
-        mBatteryStats.forceRecordAllHistory();
-
         mMockClock.realtime = 1000;
         mMockClock.uptime = 1000;
-        mBatteryStats.setNoAutoReset(true);
 
-        synchronized (mBatteryStats) {
-            mBatteryStats.setBatteryStateLocked(BatteryManager.BATTERY_STATUS_DISCHARGING,
-                    100, /* plugType */ 0, 90, 72, 3700, 3_600_000, 4_000_000, 0, 1_000_000,
-                    1_000_000, 1_000_000);
-        }
-        synchronized (mBatteryStats) {
-            mBatteryStats.setBatteryStateLocked(BatteryManager.BATTERY_STATUS_DISCHARGING,
-                    100, /* plugType */ 0, 80, 72, 3700, 2_400_000, 4_000_000, 0, 2_000_000,
-                    2_000_000, 2_000_000);
-        }
+        mBatteryStats.setBatteryStateLocked(BatteryManager.BATTERY_STATUS_DISCHARGING,
+                100, /* plugType */ 0, 90, 72, 3700, 3_600_000, 4_000_000, 0, 1_000_000,
+                1_000_000, 1_000_000);
+        mBatteryStats.setBatteryStateLocked(BatteryManager.BATTERY_STATUS_DISCHARGING,
+                100, /* plugType */ 0, 80, 72, 3700, 2_400_000, 4_000_000, 0, 2_000_000,
+                2_000_000, 2_000_000);
+        mBatteryStats.noteAlarmStartLocked("foo", null, APP_UID, 3_000_000, 2_000_000);
+        mBatteryStats.noteAlarmFinishLocked("foo", null, APP_UID, 3_001_000, 2_001_000);
 
-        synchronized (mBatteryStats) {
-            mBatteryStats.noteAlarmStartLocked("foo", null, APP_UID, 3_000_000, 2_000_000);
-        }
-        synchronized (mBatteryStats) {
-            mBatteryStats.noteAlarmFinishLocked("foo", null, APP_UID, 3_001_000, 2_001_000);
-        }
-
-        final BatteryStatsHistoryIterator iterator =
-                mBatteryStats.iterateBatteryStatsHistory();
+        final BatteryStatsHistoryIterator iterator = mBatteryStats.iterateBatteryStatsHistory();
 
         BatteryStats.HistoryItem item;
 
         assertThat(item = iterator.next()).isNotNull();
-        assertHistoryItem(item,
-                BatteryStats.HistoryItem.CMD_RESET, BatteryStats.HistoryItem.EVENT_NONE,
-                null, 0, 3_600_000, 90, 1_000_000);
+        assertThat(item.cmd).isEqualTo(BatteryStats.HistoryItem.CMD_RESET);
 
         assertThat(item = iterator.next()).isNotNull();
         assertHistoryItem(item,
@@ -114,11 +102,6 @@
 
         assertThat(item = iterator.next()).isNotNull();
         assertHistoryItem(item,
-                BatteryStats.HistoryItem.CMD_UPDATE, BatteryStats.HistoryItem.EVENT_NONE,
-                null, 0, 2_400_000, 80, 2_000_000);
-
-        assertThat(item = iterator.next()).isNotNull();
-        assertHistoryItem(item,
                 BatteryStats.HistoryItem.CMD_UPDATE,
                 BatteryStats.HistoryItem.EVENT_ALARM | BatteryStats.HistoryItem.EVENT_FLAG_START,
                 "foo", APP_UID, 2_400_000, 80, 3_000_000);
@@ -136,35 +119,20 @@
     // Test history that spans multiple buffers and uses more than 32k different strings.
     @Test
     public void tagsLongHistory() {
-        synchronized (mBatteryStats) {
-            mBatteryStats.setRecordAllHistoryLocked(true);
-        }
-        mBatteryStats.forceRecordAllHistory();
+        mBatteryStats.setBatteryStateLocked(BatteryManager.BATTERY_STATUS_DISCHARGING,
+                100, /* plugType */ 0, 90, 72, 3700, 3_600_000, 4_000_000, 0, 1_000_000,
+                1_000_000, 1_000_000);
 
-        mMockClock.realtime = 1000;
-        mMockClock.uptime = 1000;
-        mBatteryStats.setNoAutoReset(true);
-
-        synchronized (mBatteryStats) {
-            mBatteryStats.setBatteryStateLocked(BatteryManager.BATTERY_STATUS_DISCHARGING,
-                    100, /* plugType */ 0, 90, 72, 3700, 3_600_000, 4_000_000, 0, 1_000_000,
-                    1_000_000, 1_000_000);
-        }
         // More than 32k strings
         final int eventCount = 0x7FFF + 100;
         for (int i = 0; i < eventCount; i++) {
             // Names repeat in order to verify de-duping of identical history tags.
             String name = "a" + (i % 10);
-            synchronized (mBatteryStats) {
-                mBatteryStats.noteAlarmStartLocked(name, null, APP_UID, 3_000_000, 2_000_000);
-            }
-            synchronized (mBatteryStats) {
-                mBatteryStats.noteAlarmFinishLocked(name, null, APP_UID, 3_500_000, 2_500_000);
-            }
+            mBatteryStats.noteAlarmStartLocked(name, null, APP_UID, 3_000_000, 2_000_000);
+            mBatteryStats.noteAlarmFinishLocked(name, null, APP_UID, 3_500_000, 2_500_000);
         }
 
-        final BatteryStatsHistoryIterator iterator =
-                mBatteryStats.iterateBatteryStatsHistory();
+        final BatteryStatsHistoryIterator iterator = mBatteryStats.iterateBatteryStatsHistory();
 
         BatteryStats.HistoryItem item;
         assertThat(item = iterator.next()).isNotNull();
@@ -210,6 +178,69 @@
         assertThat(iterator.next()).isNull();
     }
 
+    @Test
+    public void cpuSuspendHistoryEvents() {
+        mBatteryStats.setBatteryStateLocked(BatteryManager.BATTERY_STATUS_DISCHARGING,
+                100, /* plugType */ 0, 90, 72, 3700, 3_600_000, 4_000_000, 0,
+                1_000_000, 1_000_000, 1_000_000);
+
+        assertThat(mExternalStatsSync.mSyncScheduled).isTrue();
+        mBatteryStats.finishAddingCpuLocked(100, 0, 0, 0, 0, 0, 0, 0);
+        mExternalStatsSync.mSyncScheduled = false;
+
+        // Device was suspended for 3_000 seconds, note the difference in elapsed time and uptime
+        mBatteryStats.setBatteryStateLocked(BatteryManager.BATTERY_STATUS_DISCHARGING,
+                100, /* plugType */ 0, 80, 72, 3700, 2_400_000, 4_000_000, 0,
+                5_000_000, 2_000_000, 5_000_000);
+
+        assertThat(mExternalStatsSync.mSyncScheduled).isTrue();
+        mBatteryStats.finishAddingCpuLocked(200, 0, 0, 0, 0, 0, 0, 0);
+        mExternalStatsSync.mSyncScheduled = false;
+
+        // Battery level is unchanged, so we don't write battery level details in history
+        mBatteryStats.noteAlarmStartLocked("wakeup", null, APP_UID, 6_000_000, 3_000_000);
+
+        assertThat(mExternalStatsSync.mSyncScheduled).isFalse();
+
+        // Battery level drops, so we write the accumulated battery level details
+        mBatteryStats.setBatteryStateLocked(BatteryManager.BATTERY_STATUS_DISCHARGING,
+                100, /* plugType */ 0, 79, 72, 3700, 2_000_000, 4_000_000, 0,
+                7_000_000, 4_000_000, 6_000_000);
+
+        final BatteryStatsHistoryIterator iterator = mBatteryStats.iterateBatteryStatsHistory();
+
+        BatteryStats.HistoryItem item;
+        assertThat(item = iterator.next()).isNotNull();
+        assertThat(item.cmd).isEqualTo((int) BatteryStats.HistoryItem.CMD_RESET);
+        assertThat(item.stepDetails).isNull();
+
+        assertThat(item = iterator.next()).isNotNull();
+        assertThat(item.batteryLevel).isEqualTo(90);
+        assertThat(item.stepDetails).isNull();
+
+        assertThat(item = iterator.next()).isNotNull();
+        assertThat(item.batteryLevel).isEqualTo(90);
+        assertThat(item.states & BatteryStats.HistoryItem.STATE_CPU_RUNNING_FLAG).isEqualTo(0);
+        assertThat(item.stepDetails.userTime).isEqualTo(100);
+
+        assertThat(item = iterator.next()).isNotNull();
+        assertThat(item.batteryLevel).isEqualTo(80);
+        assertThat(item.states & BatteryStats.HistoryItem.STATE_CPU_RUNNING_FLAG).isNotEqualTo(0);
+        assertThat(item.stepDetails.userTime).isEqualTo(0);
+
+        assertThat(item = iterator.next()).isNotNull();
+        assertThat(item.batteryLevel).isEqualTo(80);
+        assertThat(item.eventCode).isEqualTo(BatteryStats.HistoryItem.EVENT_ALARM_START);
+        assertThat(item.stepDetails).isNull();
+
+        assertThat(item = iterator.next()).isNotNull();
+        assertThat(item.batteryLevel).isEqualTo(79);
+        assertThat(item.states & BatteryStats.HistoryItem.STATE_CPU_RUNNING_FLAG).isNotEqualTo(0);
+        assertThat(item.stepDetails.userTime).isEqualTo(200);
+
+        assertThat(item = iterator.next()).isNull();
+    }
+
     private void assertHistoryItem(BatteryStats.HistoryItem item, int command, int eventCode,
             String tag, int uid, int batteryChargeUah, int batteryLevel,
             long elapsedTimeMs) {
@@ -226,4 +257,14 @@
 
         assertThat(item.time).isEqualTo(elapsedTimeMs);
     }
+
+    private static class MockExternalStatsSync extends MockBatteryStatsImpl.DummyExternalStatsSync {
+        private boolean mSyncScheduled;
+
+        @Override
+        public Future<?> scheduleCpuSyncDueToWakelockChange(long delayMillis) {
+            mSyncScheduled = true;
+            return null;
+        }
+    }
 }
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsNoteTest.java b/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsNoteTest.java
index 998d22e..6b21eb0 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsNoteTest.java
+++ b/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsNoteTest.java
@@ -937,15 +937,14 @@
         HistoryItem item;
 
         assertThat(item = iterator.next()).isNotNull();
+        assertEquals(HistoryItem.CMD_RESET, item.cmd);
+        assertEquals(HistoryItem.EVENT_NONE, item.eventCode);
+
+        assertThat(item = iterator.next()).isNotNull();
         assertEquals(HistoryItem.EVENT_ALARM_START, item.eventCode);
         assertEquals("foo", item.eventTag.string);
         assertEquals(UID, item.eventTag.uid);
 
-        // TODO(narayan): Figure out why this event is written to the history buffer. See
-        // test below where it is being interspersed between multiple START events too.
-        assertThat(item = iterator.next()).isNotNull();
-        assertEquals(HistoryItem.EVENT_NONE, item.eventCode);
-
         assertThat(item = iterator.next()).isNotNull();
         assertEquals(HistoryItem.EVENT_ALARM_FINISH, item.eventCode);
         assertTrue(item.isDeltaData());
@@ -977,14 +976,15 @@
         HistoryItem item;
 
         assertThat(item = iterator.next()).isNotNull();
+        assertEquals(HistoryItem.CMD_RESET, item.cmd);
+        assertEquals(HistoryItem.EVENT_NONE, item.eventCode);
+
+        assertThat(item = iterator.next()).isNotNull();
         assertEquals(HistoryItem.EVENT_ALARM_START, item.eventCode);
         assertEquals("foo", item.eventTag.string);
         assertEquals(100, item.eventTag.uid);
 
         assertThat(item = iterator.next()).isNotNull();
-        assertEquals(HistoryItem.EVENT_NONE, item.eventCode);
-
-        assertThat(item = iterator.next()).isNotNull();
         assertEquals(HistoryItem.EVENT_ALARM_START, item.eventCode);
         assertEquals("foo", item.eventTag.string);
         assertEquals(500, item.eventTag.uid);
diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java b/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java
index 968609b..2f64506 100644
--- a/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java
+++ b/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java
@@ -230,11 +230,13 @@
         assertHistoryItem(item,
                 BatteryStats.HistoryItem.CMD_UPDATE, BatteryStats.HistoryItem.EVENT_NONE,
                 null, 0, 3_600_000, 90, 1_000_000);
+        assertThat(item.states & BatteryStats.HistoryItem.STATE_CPU_RUNNING_FLAG).isNotEqualTo(0);
 
         assertThat(item = iterator.next()).isNotNull();
         assertHistoryItem(item,
                 BatteryStats.HistoryItem.CMD_UPDATE, BatteryStats.HistoryItem.EVENT_NONE,
                 null, 0, 3_600_000, 90, 2_000_000);
+        assertThat(item.states & BatteryStats.HistoryItem.STATE_CPU_RUNNING_FLAG).isEqualTo(0);
 
         assertThat(item = iterator.next()).isNotNull();
         assertHistoryItem(item,
diff --git a/services/tests/wmtests/src/com/android/server/wm/DeviceStateControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/DeviceStateControllerTests.java
index 86732c9..2a28ae2 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DeviceStateControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DeviceStateControllerTests.java
@@ -16,13 +16,12 @@
 
 package com.android.server.wm;
 
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.any;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.times;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.when;
 
 import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
 
 import android.content.Context;
 import android.content.res.Resources;
@@ -32,9 +31,10 @@
 
 import androidx.test.filters.SmallTest;
 
+import com.android.internal.R;
+
 import org.junit.Before;
 import org.junit.Test;
-import org.mockito.ArgumentCaptor;
 
 import java.util.function.Consumer;
 
@@ -48,92 +48,76 @@
 @Presubmit
 public class DeviceStateControllerTests {
 
-    private DeviceStateController.FoldStateListener mFoldStateListener;
     private DeviceStateController mTarget;
     private DeviceStateControllerBuilder mBuilder;
 
     private Context mMockContext;
-    private Handler mMockHandler;
-    private Resources mMockRes;
     private DeviceStateManager mMockDeviceStateManager;
-
-    private Consumer<DeviceStateController.FoldState> mDelegate;
-    private DeviceStateController.FoldState mCurrentState = DeviceStateController.FoldState.UNKNOWN;
+    private DeviceStateController.DeviceState mCurrentState =
+            DeviceStateController.DeviceState.UNKNOWN;
 
     @Before
     public void setUp() {
         mBuilder = new DeviceStateControllerBuilder();
-        mCurrentState = DeviceStateController.FoldState.UNKNOWN;
+        mCurrentState = DeviceStateController.DeviceState.UNKNOWN;
     }
 
-    private void initialize(boolean supportFold, boolean supportHalfFold) throws Exception {
+    private void initialize(boolean supportFold, boolean supportHalfFold) {
         mBuilder.setSupportFold(supportFold, supportHalfFold);
-        mDelegate = (newFoldState) -> {
+        Consumer<DeviceStateController.DeviceState> delegate = (newFoldState) -> {
             mCurrentState = newFoldState;
         };
-        mBuilder.setDelegate(mDelegate);
+        mBuilder.setDelegate(delegate);
         mBuilder.build();
-        verifyFoldStateListenerRegistration(1);
+        verify(mMockDeviceStateManager).registerCallback(any(), any());
     }
 
     @Test
-    public void testInitialization() throws Exception {
+    public void testInitialization() {
         initialize(true /* supportFold */, true /* supportHalfFolded */);
-        mFoldStateListener.onStateChanged(mUnfoldedStates[0]);
-        assertEquals(mCurrentState, DeviceStateController.FoldState.OPEN);
+        mTarget.onStateChanged(mOpenDeviceStates[0]);
+        assertEquals(DeviceStateController.DeviceState.OPEN, mCurrentState);
     }
 
     @Test
-    public void testInitializationWithNoFoldSupport() throws Exception {
+    public void testInitializationWithNoFoldSupport() {
         initialize(false /* supportFold */, false /* supportHalfFolded */);
-        mFoldStateListener.onStateChanged(mFoldedStates[0]);
+        mTarget.onStateChanged(mFoldedStates[0]);
         // Note that the folded state is ignored.
-        assertEquals(mCurrentState, DeviceStateController.FoldState.OPEN);
+        assertEquals(DeviceStateController.DeviceState.UNKNOWN, mCurrentState);
     }
 
     @Test
-    public void testWithFoldSupported() throws Exception {
+    public void testWithFoldSupported() {
         initialize(true /* supportFold */, false /* supportHalfFolded */);
-        mFoldStateListener.onStateChanged(mUnfoldedStates[0]);
-        assertEquals(mCurrentState, DeviceStateController.FoldState.OPEN);
-        mFoldStateListener.onStateChanged(mFoldedStates[0]);
-        assertEquals(mCurrentState, DeviceStateController.FoldState.FOLDED);
-        mFoldStateListener.onStateChanged(mHalfFoldedStates[0]);
-        assertEquals(mCurrentState, DeviceStateController.FoldState.OPEN); // Ignored
+        mTarget.onStateChanged(mOpenDeviceStates[0]);
+        assertEquals(DeviceStateController.DeviceState.OPEN, mCurrentState);
+        mTarget.onStateChanged(mFoldedStates[0]);
+        assertEquals(DeviceStateController.DeviceState.FOLDED, mCurrentState);
+        mTarget.onStateChanged(mHalfFoldedStates[0]);
+        assertEquals(DeviceStateController.DeviceState.UNKNOWN, mCurrentState); // Ignored
     }
 
     @Test
-    public void testWithHalfFoldSupported() throws Exception {
+    public void testWithHalfFoldSupported() {
         initialize(true /* supportFold */, true /* supportHalfFolded */);
-        mFoldStateListener.onStateChanged(mUnfoldedStates[0]);
-        assertEquals(mCurrentState, DeviceStateController.FoldState.OPEN);
-        mFoldStateListener.onStateChanged(mFoldedStates[0]);
-        assertEquals(mCurrentState, DeviceStateController.FoldState.FOLDED);
-        mFoldStateListener.onStateChanged(mHalfFoldedStates[0]);
-        assertEquals(mCurrentState, DeviceStateController.FoldState.HALF_FOLDED);
+        mTarget.onStateChanged(mOpenDeviceStates[0]);
+        assertEquals(DeviceStateController.DeviceState.OPEN, mCurrentState);
+        mTarget.onStateChanged(mFoldedStates[0]);
+        assertEquals(DeviceStateController.DeviceState.FOLDED, mCurrentState);
+        mTarget.onStateChanged(mHalfFoldedStates[0]);
+        assertEquals(DeviceStateController.DeviceState.HALF_FOLDED, mCurrentState);
     }
 
-
     private final int[] mFoldedStates = {0};
-    private final int[] mUnfoldedStates = {1};
+    private final int[] mOpenDeviceStates = {1};
     private final int[] mHalfFoldedStates = {2};
-
-
-    private void verifyFoldStateListenerRegistration(int numOfInvocation) {
-        final ArgumentCaptor<DeviceStateController.FoldStateListener> listenerCaptor =
-                ArgumentCaptor.forClass(DeviceStateController.FoldStateListener.class);
-        verify(mMockDeviceStateManager, times(numOfInvocation)).registerCallback(
-                any(),
-                listenerCaptor.capture());
-        if (numOfInvocation > 0) {
-            mFoldStateListener = listenerCaptor.getValue();
-        }
-    }
+    private final int[] mRearDisplayStates = {3};
 
     private class DeviceStateControllerBuilder {
         private boolean mSupportFold = false;
         private boolean mSupportHalfFold = false;
-        private Consumer<DeviceStateController.FoldState> mDelegate;
+        private Consumer<DeviceStateController.DeviceState> mDelegate;
 
         DeviceStateControllerBuilder setSupportFold(
                 boolean supportFold, boolean supportHalfFold) {
@@ -143,34 +127,44 @@
         }
 
         DeviceStateControllerBuilder setDelegate(
-                Consumer<DeviceStateController.FoldState> delegate) {
+                Consumer<DeviceStateController.DeviceState> delegate) {
             mDelegate = delegate;
             return this;
         }
 
         private void mockFold(boolean enableFold, boolean enableHalfFold) {
+            if (enableFold || enableHalfFold) {
+                when(mMockContext.getResources()
+                        .getIntArray(R.array.config_openDeviceStates))
+                        .thenReturn(mOpenDeviceStates);
+                when(mMockContext.getResources()
+                        .getIntArray(R.array.config_rearDisplayDeviceStates))
+                        .thenReturn(mRearDisplayStates);
+            }
+
             if (enableFold) {
-                when(mMockContext.getResources().getIntArray(
-                        com.android.internal.R.array.config_foldedDeviceStates))
+                when(mMockContext.getResources()
+                        .getIntArray(R.array.config_foldedDeviceStates))
                         .thenReturn(mFoldedStates);
             }
             if (enableHalfFold) {
-                when(mMockContext.getResources().getIntArray(
-                        com.android.internal.R.array.config_halfFoldedDeviceStates))
+                when(mMockContext.getResources()
+                        .getIntArray(R.array.config_halfFoldedDeviceStates))
                         .thenReturn(mHalfFoldedStates);
             }
         }
 
-        private void build() throws Exception {
+        private void build() {
             mMockContext = mock(Context.class);
-            mMockRes = mock(Resources.class);
-            when(mMockContext.getResources()).thenReturn((mMockRes));
             mMockDeviceStateManager = mock(DeviceStateManager.class);
             when(mMockContext.getSystemService(DeviceStateManager.class))
                     .thenReturn(mMockDeviceStateManager);
+            Resources mockRes = mock(Resources.class);
+            when(mMockContext.getResources()).thenReturn((mockRes));
             mockFold(mSupportFold, mSupportHalfFold);
-            mMockHandler = mock(Handler.class);
-            mTarget = new DeviceStateController(mMockContext, mMockHandler, mDelegate);
+            Handler mockHandler = mock(Handler.class);
+            mTarget = new DeviceStateController(mMockContext, mockHandler);
+            mTarget.registerDeviceStateCallback(mDelegate);
         }
     }
 }
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 78707d6..3b34ba4 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
@@ -1738,7 +1738,7 @@
 
         // No need to apply rotation if the display ignores orientation request.
         doCallRealMethod().when(displayContent).rotationForActivityInDifferentOrientation(any());
-        pinnedActivity.mOrientation = SCREEN_ORIENTATION_LANDSCAPE;
+        pinnedActivity.setOverrideOrientation(SCREEN_ORIENTATION_LANDSCAPE);
         displayContent.setIgnoreOrientationRequest(true);
         assertEquals(WindowConfiguration.ROTATION_UNDEFINED,
                 displayContent.rotationForActivityInDifferentOrientation(pinnedActivity));
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 4ce43e1..f814608 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayRotationTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayRotationTests.java
@@ -705,7 +705,7 @@
 
         enableOrientationSensor();
 
-        mTarget.foldStateChanged(DeviceStateController.FoldState.OPEN);
+        mTarget.foldStateChanged(DeviceStateController.DeviceState.OPEN);
         freezeRotation(Surface.ROTATION_270);
 
         mOrientationSensorListener.onSensorChanged(createSensorEvent(Surface.ROTATION_0));
@@ -715,7 +715,7 @@
                 SCREEN_ORIENTATION_UNSPECIFIED, Surface.ROTATION_0));
 
         // ... until half-fold
-        mTarget.foldStateChanged(DeviceStateController.FoldState.HALF_FOLDED);
+        mTarget.foldStateChanged(DeviceStateController.DeviceState.HALF_FOLDED);
         assertTrue(waitForUiHandler());
         verify(sMockWm).updateRotation(false, false);
         assertTrue(waitForUiHandler());
@@ -723,7 +723,7 @@
                 SCREEN_ORIENTATION_UNSPECIFIED, Surface.ROTATION_0));
 
         // ... then transition back to flat
-        mTarget.foldStateChanged(DeviceStateController.FoldState.OPEN);
+        mTarget.foldStateChanged(DeviceStateController.DeviceState.OPEN);
         assertTrue(waitForUiHandler());
         verify(sMockWm, atLeast(1)).updateRotation(false, false);
         assertTrue(waitForUiHandler());
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 791d6f2..7d30b60 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LetterboxUiControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LetterboxUiControllerTest.java
@@ -16,14 +16,23 @@
 
 package com.android.server.wm;
 
+import static android.content.pm.ActivityInfo.OVERRIDE_ANY_ORIENTATION;
 import static android.content.pm.ActivityInfo.OVERRIDE_CAMERA_COMPAT_DISABLE_FORCE_ROTATION;
 import static android.content.pm.ActivityInfo.OVERRIDE_CAMERA_COMPAT_DISABLE_REFRESH;
 import static android.content.pm.ActivityInfo.OVERRIDE_CAMERA_COMPAT_ENABLE_REFRESH_VIA_PAUSE;
 import static android.content.pm.ActivityInfo.OVERRIDE_ENABLE_COMPAT_IGNORE_REQUESTED_ORIENTATION;
+import static android.content.pm.ActivityInfo.OVERRIDE_LANDSCAPE_ORIENTATION_TO_REVERSE_LANDSCAPE;
+import static android.content.pm.ActivityInfo.OVERRIDE_UNDEFINED_ORIENTATION_TO_NOSENSOR;
+import static android.content.pm.ActivityInfo.OVERRIDE_UNDEFINED_ORIENTATION_TO_PORTRAIT;
+import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
+import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
+import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
+import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
 import static android.view.WindowManager.PROPERTY_CAMERA_COMPAT_ALLOW_FORCE_ROTATION;
 import static android.view.WindowManager.PROPERTY_CAMERA_COMPAT_ALLOW_REFRESH;
 import static android.view.WindowManager.PROPERTY_CAMERA_COMPAT_ENABLE_REFRESH_VIA_PAUSE;
+import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE;
 import static android.view.WindowManager.PROPERTY_COMPAT_IGNORE_REQUESTED_ORIENTATION;
 
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
@@ -491,6 +500,80 @@
         return mainWindow;
     }
 
+    // overrideOrientationIfNeeded
+
+    @Test
+    @EnableCompatChanges({OVERRIDE_UNDEFINED_ORIENTATION_TO_PORTRAIT})
+    public void testOverrideOrientationIfNeeded_portraitOverrideEnabled_returnsPortrait()
+            throws Exception {
+        assertEquals(mController.overrideOrientationIfNeeded(
+                /* candidate */ SCREEN_ORIENTATION_UNSPECIFIED), SCREEN_ORIENTATION_PORTRAIT);
+    }
+
+    @Test
+    @EnableCompatChanges({OVERRIDE_UNDEFINED_ORIENTATION_TO_NOSENSOR})
+    public void testOverrideOrientationIfNeeded_portraitOverrideEnabled_returnsNosensor() {
+        assertEquals(mController.overrideOrientationIfNeeded(
+                /* candidate */ SCREEN_ORIENTATION_UNSPECIFIED), SCREEN_ORIENTATION_NOSENSOR);
+    }
+
+    @Test
+    @EnableCompatChanges({OVERRIDE_UNDEFINED_ORIENTATION_TO_NOSENSOR})
+    public void testOverrideOrientationIfNeeded_nosensorOverride_orientationFixed_returnsUnchanged() {
+        assertEquals(mController.overrideOrientationIfNeeded(
+                /* candidate */ SCREEN_ORIENTATION_PORTRAIT), SCREEN_ORIENTATION_PORTRAIT);
+    }
+
+    @Test
+    @EnableCompatChanges({OVERRIDE_LANDSCAPE_ORIENTATION_TO_REVERSE_LANDSCAPE})
+    public void testOverrideOrientationIfNeeded_reverseLandscapeOverride_orientationPortraitOrUndefined_returnsUnchanged() {
+        assertEquals(mController.overrideOrientationIfNeeded(
+                /* candidate */ SCREEN_ORIENTATION_PORTRAIT), SCREEN_ORIENTATION_PORTRAIT);
+        assertEquals(mController.overrideOrientationIfNeeded(
+                /* candidate */ SCREEN_ORIENTATION_UNSPECIFIED), SCREEN_ORIENTATION_UNSPECIFIED);
+    }
+
+    @Test
+    @EnableCompatChanges({OVERRIDE_LANDSCAPE_ORIENTATION_TO_REVERSE_LANDSCAPE})
+    public void testOverrideOrientationIfNeeded_reverseLandscapeOverride_orientationLandscape_returnsReverseLandscape() {
+        assertEquals(mController.overrideOrientationIfNeeded(
+                /* candidate */ SCREEN_ORIENTATION_LANDSCAPE),
+                SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
+    }
+
+    @Test
+    @EnableCompatChanges({OVERRIDE_UNDEFINED_ORIENTATION_TO_PORTRAIT})
+    public void testOverrideOrientationIfNeeded_portraitOverride_orientationFixed_returnsUnchanged() {
+        assertEquals(mController.overrideOrientationIfNeeded(
+                /* candidate */ SCREEN_ORIENTATION_NOSENSOR), SCREEN_ORIENTATION_NOSENSOR);
+    }
+
+    @Test
+    @EnableCompatChanges({OVERRIDE_UNDEFINED_ORIENTATION_TO_PORTRAIT, OVERRIDE_ANY_ORIENTATION})
+    public void testOverrideOrientationIfNeeded_portraitAndIgnoreFixedOverrides_returnsPortrait() {
+        assertEquals(mController.overrideOrientationIfNeeded(
+                /* candidate */ SCREEN_ORIENTATION_NOSENSOR), SCREEN_ORIENTATION_PORTRAIT);
+    }
+
+    @Test
+    @EnableCompatChanges({OVERRIDE_UNDEFINED_ORIENTATION_TO_NOSENSOR, OVERRIDE_ANY_ORIENTATION})
+    public void testOverrideOrientationIfNeeded_noSensorAndIgnoreFixedOverrides_returnsNosensor() {
+        assertEquals(mController.overrideOrientationIfNeeded(
+                /* candidate */ SCREEN_ORIENTATION_PORTRAIT), SCREEN_ORIENTATION_NOSENSOR);
+    }
+
+    @Test
+    @EnableCompatChanges({OVERRIDE_UNDEFINED_ORIENTATION_TO_PORTRAIT})
+    public void testOverrideOrientationIfNeeded_propertyIsFalse_returnsUnchanged()
+            throws Exception {
+        mockThatProperty(PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE, /* value */ false);
+
+        mController = new LetterboxUiController(mWm, mActivity);
+
+        assertEquals(mController.overrideOrientationIfNeeded(
+                /* candidate */ SCREEN_ORIENTATION_UNSPECIFIED), SCREEN_ORIENTATION_UNSPECIFIED);
+    }
+
     private void mockThatProperty(String propertyName, boolean value) throws Exception {
         Property property = new Property(propertyName, /* value */ value, /* packageName */ "",
                  /* className */ "");
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 08635ab..c131c84 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
@@ -468,7 +468,7 @@
         mWm.setRecentsAnimationController(mController);
         spyOn(mDisplayContent.mFixedRotationTransitionListener);
         final ActivityRecord recents = mock(ActivityRecord.class);
-        recents.mOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
+        recents.setOverrideOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
         doReturn(ORIENTATION_PORTRAIT).when(recents)
                 .getRequestedConfigurationOrientation(anyBoolean());
         mDisplayContent.mFixedRotationTransitionListener.onStartRecentsAnimation(recents);
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 7e150e9..91e875f 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
@@ -102,7 +102,7 @@
 import com.android.internal.policy.SystemBarUtils;
 import com.android.internal.statusbar.LetterboxDetails;
 import com.android.server.statusbar.StatusBarManagerInternal;
-import com.android.server.wm.DeviceStateController.FoldState;
+import com.android.server.wm.DeviceStateController.DeviceState;
 
 import libcore.junit.util.compat.CoreCompatChangeRule.DisableCompatChanges;
 import libcore.junit.util.compat.CoreCompatChangeRule.EnableCompatChanges;
@@ -3202,9 +3202,9 @@
     private void setFoldablePosture(boolean isHalfFolded, boolean isTabletop) {
         final DisplayRotation r = mActivity.mDisplayContent.getDisplayRotation();
         doReturn(isHalfFolded).when(r).isDisplaySeparatingHinge();
-        doReturn(false).when(r).isDeviceInPosture(any(FoldState.class), anyBoolean());
+        doReturn(false).when(r).isDeviceInPosture(any(DeviceState.class), anyBoolean());
         if (isHalfFolded) {
-            doReturn(true).when(r).isDeviceInPosture(FoldState.HALF_FOLDED, isTabletop);
+            doReturn(true).when(r).isDeviceInPosture(DeviceState.HALF_FOLDED, isTabletop);
         }
         mActivity.recomputeConfiguration();
     }
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
index 1a1ca54..5006bf7 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
@@ -1665,7 +1665,7 @@
 
         @Override
         int getOrientation() {
-            return getOrientation(super.mOrientation);
+            return getOrientation(super.getOverrideOrientation());
         }
 
         @Override
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
index 665d5e7..591e35a 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
@@ -108,7 +108,7 @@
     final int mUser;
     final Context mContext;
     volatile HotwordDetectionServiceIdentity mIdentity;
-    //TODO: add similar identity for visual query service for the use of content capturing
+    //TODO: Consider rename this to SandboxedDetectionIdentity
     private Instant mLastRestartInstant;
 
     private ScheduledFuture<?> mDebugHotwordLoggingTimeoutFuture = null;
@@ -117,6 +117,7 @@
     @GuardedBy("mLock")
     @Nullable
     private final Identity mVoiceInteractorIdentity;
+    private int mRestartCount = 0;
     @NonNull private ServiceConnection mRemoteHotwordDetectionService;
     @NonNull private ServiceConnection mRemoteVisualQueryDetectionService;
     private IBinder mAudioFlinger;
@@ -234,10 +235,6 @@
         mDebugHotwordLogging = false;
         unbindVisualQueryDetectionService();
         unbindHotwordDetectionService();
-        if (mIdentity != null) {
-            removeServiceUidForAudioPolicy(mIdentity.getIsolatedUid());
-        }
-        mIdentity = null;
         if (mCancellationTaskFuture != null) {
             mCancellationTaskFuture.cancel(/* mayInterruptIfRunning= */ true);
         }
@@ -246,18 +243,34 @@
         }
     }
 
+    @SuppressWarnings("GuardedBy")
     private void unbindVisualQueryDetectionService() {
         if (mRemoteVisualQueryDetectionService != null) {
             mRemoteVisualQueryDetectionService.unbind();
-            //TODO: Set visual query detection service provider to null
+            mRemoteVisualQueryDetectionService = null;
         }
+        resetDetectionProcessIdentityIfEmptyLocked();
     }
 
+    @SuppressWarnings("GuardedBy")
     private void unbindHotwordDetectionService() {
         if (mRemoteHotwordDetectionService != null) {
             mRemoteHotwordDetectionService.unbind();
+            mRemoteHotwordDetectionService = null;
+        }
+        resetDetectionProcessIdentityIfEmptyLocked();
+    }
+
+    // TODO(b/266669849): Clean up SuppressWarnings for calling methods.
+    @GuardedBy("mLock")
+    private void resetDetectionProcessIdentityIfEmptyLocked() {
+        if (mRemoteHotwordDetectionService == null && mRemoteVisualQueryDetectionService == null) {
             LocalServices.getService(PermissionManagerServiceInternal.class)
                 .setHotwordDetectionServiceProvider(null);
+            if (mIdentity != null) {
+                removeServiceUidForAudioPolicy(mIdentity.getIsolatedUid());
+            }
+            mIdentity = null;
         }
     }
 
@@ -427,14 +440,20 @@
         ServiceConnection oldHotwordConnection = mRemoteHotwordDetectionService;
         ServiceConnection oldVisualQueryDetectionConnection = mRemoteVisualQueryDetectionService;
         HotwordDetectionServiceIdentity previousIdentity = mIdentity;
-        //TODO: Add previousIdentity for visual query detection service
 
         mLastRestartInstant = Instant.now();
         // Recreate connection to reset the cache.
+        mRestartCount++;
 
-        mRemoteHotwordDetectionService = mHotwordDetectionServiceConnectionFactory.createLocked();
-        mRemoteVisualQueryDetectionService =
-                mVisualQueryDetectionServiceConnectionFactory.createLocked();
+        if (oldHotwordConnection != null) {
+            mRemoteHotwordDetectionService =
+                    mHotwordDetectionServiceConnectionFactory.createLocked();
+        }
+
+        if (oldVisualQueryDetectionConnection != null) {
+            mRemoteVisualQueryDetectionService =
+                    mVisualQueryDetectionServiceConnectionFactory.createLocked();
+        }
 
         Slog.v(TAG, "Started the new process, dispatching processRestarted to detector");
         runForEachDetectorSessionLocked((session) -> {
@@ -458,6 +477,9 @@
             oldVisualQueryDetectionConnection.unbind();
         }
 
+        // TODO(b/266670431): Handles identity resetting for the new process to make sure the
+        // correct identity is provided.
+
         if (previousIdentity != null) {
             removeServiceUidForAudioPolicy(previousIdentity.getIsolatedUid());
         }
@@ -531,8 +553,7 @@
                     && mRemoteHotwordDetectionService != null
                     && mRemoteHotwordDetectionService.isBound());
             pw.print(prefix); pw.print("mRestartCount=");
-            pw.println(mHotwordDetectionServiceConnectionFactory.mRestartCount);
-            pw.println(mVisualQueryDetectionServiceConnectionFactory.mRestartCount);
+            pw.println(mRestartCount);
             pw.print(prefix); pw.print("mLastRestartInstant="); pw.println(mLastRestartInstant);
             pw.print(prefix); pw.print("mDetectorType=");
             pw.println(HotwordDetector.detectorTypeToString(mDetectorType));
@@ -547,8 +568,6 @@
         private final Intent mIntent;
         private final int mBindingFlags;
 
-        private int mRestartCount = 0;
-
         ServiceConnectionFactory(@NonNull Intent intent, boolean bindInstantServiceAllowed) {
             mIntent = intent;
             mBindingFlags = bindInstantServiceAllowed ? Context.BIND_ALLOW_INSTANT : 0;
@@ -558,7 +577,7 @@
             ServiceConnection connection =
                     new ServiceConnection(mContext, mIntent, mBindingFlags, mUser,
                             ISandboxedDetectionService.Stub::asInterface,
-                            mRestartCount++ % MAX_ISOLATED_PROCESS_NUMBER);
+                            mRestartCount % MAX_ISOLATED_PROCESS_NUMBER);
             connection.connect();
 
             updateAudioFlinger(connection, mAudioFlinger);
@@ -660,13 +679,11 @@
                             HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_BIND_SERVICE,
                             mVoiceInteractionServiceUid);
                 }
-                String instancePrefix =
-                        mIntent.getAction().equals(HotwordDetectionService.SERVICE_INTERFACE)
-                                ? "hotword_detector_" : "visual_query_detector_";
                 boolean bindResult = mContext.bindIsolatedService(
                         mIntent,
-                        Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE | mBindingFlags,
-                        instancePrefix + mInstanceNumber,
+                        Context.BIND_SHARED_ISOLATED_PROCESS | Context.BIND_AUTO_CREATE
+                                | Context.BIND_FOREGROUND_SERVICE | mBindingFlags,
+                        "hotword_detector_" + mInstanceNumber,
                         mExecutor,
                         serviceConnection);
                 if (!bindResult) {
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index 7950351..f0f230f 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -34,6 +34,7 @@
 import android.net.NetworkCapabilities;
 import android.net.ipsec.ike.SaProposal;
 import android.os.Build;
+import android.os.Handler;
 import android.os.PersistableBundle;
 import android.os.RemoteException;
 import android.service.carrier.CarrierService;
@@ -49,6 +50,7 @@
 import android.telephony.ims.RcsUceAdapter;
 import android.telephony.ims.feature.MmTelFeature;
 import android.telephony.ims.feature.RcsFeature;
+import android.telephony.ims.stub.ImsRegistrationImplBase;
 
 import com.android.internal.telephony.ICarrierConfigLoader;
 import com.android.telephony.Rlog;
@@ -65,7 +67,7 @@
 @SystemService(Context.CARRIER_CONFIG_SERVICE)
 @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
 public class CarrierConfigManager {
-    private final static String TAG = "CarrierConfigManager";
+    private static final String TAG = "CarrierConfigManager";
 
     /**
      * Extra included in {@link #ACTION_CARRIER_CONFIG_CHANGED} to indicate the slot index that the
@@ -108,25 +110,25 @@
      * Only send USSD over IMS while CS is out of service, otherwise send USSD over CS.
      * {@link #KEY_CARRIER_USSD_METHOD_INT}
      */
-    public static final int USSD_OVER_CS_PREFERRED   = 0;
+    public static final int USSD_OVER_CS_PREFERRED = 0;
 
     /**
      * Send USSD over IMS or CS while IMS is out of service or silent redial over CS if needed.
      * {@link #KEY_CARRIER_USSD_METHOD_INT}
      */
-    public static final int USSD_OVER_IMS_PREFERRED  = 1;
+    public static final int USSD_OVER_IMS_PREFERRED = 1;
 
     /**
      * Only send USSD over CS.
      * {@link #KEY_CARRIER_USSD_METHOD_INT}
      */
-    public static final int USSD_OVER_CS_ONLY        = 2;
+    public static final int USSD_OVER_CS_ONLY = 2;
 
     /**
      * Only send USSD over IMS and disallow silent redial over CS.
      * {@link #KEY_CARRIER_USSD_METHOD_INT}
      */
-    public static final int USSD_OVER_IMS_ONLY       = 3;
+    public static final int USSD_OVER_IMS_ONLY = 3;
 
     /**
      * Indicates CARRIER_NR_AVAILABILITY_NSA determine that the carrier enable the non-standalone
@@ -161,8 +163,8 @@
      * @see TelephonyManager#getSimCarrierId()
      * @see TelephonyManager#getSimSpecificCarrierId()
      */
-    public static final String
-            ACTION_CARRIER_CONFIG_CHANGED = "android.telephony.action.CARRIER_CONFIG_CHANGED";
+    public static final String ACTION_CARRIER_CONFIG_CHANGED =
+            "android.telephony.action.CARRIER_CONFIG_CHANGED";
 
     // Below are the keys used in carrier config bundles. To add a new variable, define the key and
     // give it a default value in sDefaults. If you need to ship a per-network override in the
@@ -183,8 +185,8 @@
      * @deprecated Use {@link Ims#KEY_CARRIER_RCS_PROVISIONING_REQUIRED_BOOL} instead.
      */
     @Deprecated
-    public static final String
-            KEY_CARRIER_VOLTE_PROVISIONED_BOOL = "carrier_volte_provisioned_bool";
+    public static final String KEY_CARRIER_VOLTE_PROVISIONED_BOOL =
+            "carrier_volte_provisioned_bool";
 
     /**
      * Boolean indicating the Supplementary Services(SS) is disable when airplane mode on in the
@@ -217,29 +219,29 @@
     public static final String KEY_CALL_FORWARDING_WHEN_UNREACHABLE_SUPPORTED_BOOL =
             "call_forwarding_when_unreachable_supported_bool";
 
-     /**
-      * Boolean indicating if carrier supports call forwarding option "When unanswered".
-      *
-      * {@code true}: Call forwarding option "When unanswered" is supported.
-      * {@code false}: Call forwarding option "When unanswered" is not supported. Option will be
-      * removed in the UI.
-      *
-      * By default this value is true.
-      * @hide
-      */
+    /**
+     * Boolean indicating if carrier supports call forwarding option "When unanswered".
+     *
+     * {@code true}: Call forwarding option "When unanswered" is supported.
+     * {@code false}: Call forwarding option "When unanswered" is not supported. Option will be
+     * removed in the UI.
+     *
+     * By default this value is true.
+     * @hide
+     */
     public static final String KEY_CALL_FORWARDING_WHEN_UNANSWERED_SUPPORTED_BOOL =
             "call_forwarding_when_unanswered_supported_bool";
 
-     /**
-      * Boolean indicating if carrier supports call forwarding option "When busy".
-      *
-      * {@code true}: Call forwarding option "When busy" is supported.
-      * {@code false}: Call forwarding option "When busy" is not supported. Option will be
-      * removed in the UI.
-      *
-      * By default this value is true.
-      * @hide
-      */
+    /**
+     * Boolean indicating if carrier supports call forwarding option "When busy".
+     *
+     * {@code true}: Call forwarding option "When busy" is supported.
+     * {@code false}: Call forwarding option "When busy" is not supported. Option will be
+     * removed in the UI.
+     *
+     * By default this value is true.
+     * @hide
+     */
     public static final String KEY_CALL_FORWARDING_WHEN_BUSY_SUPPORTED_BOOL =
             "call_forwarding_when_busy_supported_bool";
 
@@ -259,12 +261,12 @@
     public static final String KEY_ADDITIONAL_SETTINGS_CALL_WAITING_VISIBILITY_BOOL =
             "additional_settings_call_waiting_visibility_bool";
 
-   /**
-    * Boolean indicating if the "Call barring" item is visible in the Call Settings menu.
-    * If true, the "Call Barring" menu will be visible. If false, the menu will be gone.
-    *
-    * Disabled by default.
-    */
+    /**
+     * Boolean indicating if the "Call barring" item is visible in the Call Settings menu.
+     * If true, the "Call Barring" menu will be visible. If false, the menu will be gone.
+     *
+     * Disabled by default.
+     */
     public static final String KEY_CALL_BARRING_VISIBILITY_BOOL =
             "call_barring_visibility_bool";
 
@@ -321,8 +323,8 @@
      * If true, this will prevent the IccNetworkDepersonalizationPanel from being shown, and
      * effectively disable the "Sim network lock" feature.
      */
-    public static final String
-            KEY_IGNORE_SIM_NETWORK_LOCKED_EVENTS_BOOL = "ignore_sim_network_locked_events_bool";
+    public static final String KEY_IGNORE_SIM_NETWORK_LOCKED_EVENTS_BOOL =
+            "ignore_sim_network_locked_events_bool";
 
     /**
      * When checking if a given number is the voicemail number, if this flag is true
@@ -340,16 +342,15 @@
      * consequence: there will be no way to make an Emergency Call if your SIM is network-locked and
      * you don't know the PIN.)
      */
-    public static final String
-            KEY_SIM_NETWORK_UNLOCK_ALLOW_DISMISS_BOOL = "sim_network_unlock_allow_dismiss_bool";
+    public static final String KEY_SIM_NETWORK_UNLOCK_ALLOW_DISMISS_BOOL =
+            "sim_network_unlock_allow_dismiss_bool";
 
     /**
      * Flag indicating whether or not sending emergency SMS messages over IMS
      * is supported when in LTE/limited LTE (Emergency only) service mode..
-     *
      */
-    public static final String
-            KEY_SUPPORT_EMERGENCY_SMS_OVER_IMS_BOOL = "support_emergency_sms_over_ims_bool";
+    public static final String KEY_SUPPORT_EMERGENCY_SMS_OVER_IMS_BOOL =
+            "support_emergency_sms_over_ims_bool";
 
     /** Flag indicating if the phone is a world phone */
     public static final String KEY_WORLD_PHONE_BOOL = "world_phone_bool";
@@ -359,8 +360,8 @@
      * If true, entitlement checks will be executed if device has been configured for it,
      * If false, entitlement checks will be skipped.
      */
-    public static final String
-            KEY_REQUIRE_ENTITLEMENT_CHECKS_BOOL = "require_entitlement_checks_bool";
+    public static final String KEY_REQUIRE_ENTITLEMENT_CHECKS_BOOL =
+            "require_entitlement_checks_bool";
 
     /**
      * Flag indicating if the carrier supports tethering of mobile data.
@@ -392,8 +393,8 @@
      * consistent with the regular Dialer, this value should agree with the corresponding values
      * from config.xml under apps/Contacts.
      */
-    public static final String
-            KEY_ENABLE_DIALER_KEY_VIBRATION_BOOL = "enable_dialer_key_vibration_bool";
+    public static final String KEY_ENABLE_DIALER_KEY_VIBRATION_BOOL =
+            "enable_dialer_key_vibration_bool";
 
     /** Flag indicating if dtmf tone type is enabled */
     public static final String KEY_DTMF_TYPE_ENABLED_BOOL = "dtmf_type_enabled_bool";
@@ -416,11 +417,12 @@
      * @hide
      */
     public static final String KEY_PLAY_CALL_RECORDING_TONE_BOOL = "play_call_recording_tone_bool";
+
     /**
      * Determines if the carrier requires converting the destination number before sending out an
      * SMS. Certain networks and numbering plans require different formats.
      */
-    public static final String KEY_SMS_REQUIRES_DESTINATION_NUMBER_CONVERSION_BOOL=
+    public static final String KEY_SMS_REQUIRES_DESTINATION_NUMBER_CONVERSION_BOOL =
             "sms_requires_destination_number_conversion_bool";
 
     /**
@@ -428,7 +430,8 @@
      * platforms, even the ones with hard SEND/END keys, but for maximum flexibility it's controlled
      * by a flag here (which can be overridden on a per-product basis.)
      */
-    public static final String KEY_SHOW_ONSCREEN_DIAL_BUTTON_BOOL = "show_onscreen_dial_button_bool";
+    public static final String KEY_SHOW_ONSCREEN_DIAL_BUTTON_BOOL =
+            "show_onscreen_dial_button_bool";
 
     /** Determines if device implements a noise suppression device for in call audio. */
     public static final String
@@ -440,8 +443,8 @@
      * accidental redialing from the call log UI. This is a good idea, so the default here is
      * false.)
      */
-    public static final String
-            KEY_ALLOW_EMERGENCY_NUMBERS_IN_CALL_LOG_BOOL = "allow_emergency_numbers_in_call_log_bool";
+    public static final String KEY_ALLOW_EMERGENCY_NUMBERS_IN_CALL_LOG_BOOL =
+            "allow_emergency_numbers_in_call_log_bool";
 
     /**
      * A string array containing numbers that shouldn't be included in the call log.
@@ -467,10 +470,9 @@
      * Flag indicating whether to show single operator row in the choose network setting.
      *
      * The device configuration value {@code config_enableNewAutoSelectNetworkUI} ultimately
-     * controls whether this carrier configuration option is used.  Where
-     * {@code config_enableNewAutoSelectNetworkUI} is false, the value of the
-     * {@link #KEY_SHOW_SINGLE_OPERATOR_ROW_IN_CHOOSE_NETWORK_SETTING_BOOL} carrier configuration
-     * option is ignored.
+     * controls whether this carrier configuration option is used.
+     * Where {@code config_enableNewAutoSelectNetworkUI} is false, the value of this
+     * carrier configuration is ignored.
      *
      * If {@code true}, default value, merge the duplicate networks which with the same plmn, keep
      * the one that with the higher signal strength level.
@@ -498,18 +500,18 @@
      * @deprecated Never implemented. Has no behavior impact when override. DO NOT USE.
      */
     @Deprecated
-    public static final String
-            KEY_SIMPLIFIED_NETWORK_SETTINGS_BOOL = "simplified_network_settings_bool";
+    public static final String KEY_SIMPLIFIED_NETWORK_SETTINGS_BOOL =
+            "simplified_network_settings_bool";
 
     /** Control whether users can reach the SIM lock settings. */
-    public static final String
-            KEY_HIDE_SIM_LOCK_SETTINGS_BOOL = "hide_sim_lock_settings_bool";
+    public static final String KEY_HIDE_SIM_LOCK_SETTINGS_BOOL = "hide_sim_lock_settings_bool";
 
     /** Control whether users can edit APNs in Settings. */
     public static final String KEY_APN_EXPAND_BOOL = "apn_expand_bool";
 
     /** Control whether users can choose a network operator. */
-    public static final String KEY_OPERATOR_SELECTION_EXPAND_BOOL = "operator_selection_expand_bool";
+    public static final String KEY_OPERATOR_SELECTION_EXPAND_BOOL =
+            "operator_selection_expand_bool";
 
     /**
      * Used in the Preferred Network Types menu to determine if the 2G option is displayed.
@@ -537,7 +539,8 @@
      * TODO: This should be combined with config_use_hfa_for_provisioning and implemented as an enum
      * (NONE, HFA, OTASP).
      */
-    public static final String KEY_USE_OTASP_FOR_PROVISIONING_BOOL = "use_otasp_for_provisioning_bool";
+    public static final String KEY_USE_OTASP_FOR_PROVISIONING_BOOL =
+            "use_otasp_for_provisioning_bool";
 
     /** Display carrier settings menu if true */
     public static final String KEY_CARRIER_SETTINGS_ENABLE_BOOL = "carrier_settings_enable_bool";
@@ -562,25 +565,26 @@
      * available the user cannot use voicemail. This flag allows the user to edit the voicemail
      * number in such cases, and is false by default.
      */
-    public static final String KEY_EDITABLE_VOICEMAIL_NUMBER_BOOL= "editable_voicemail_number_bool";
+    public static final String KEY_EDITABLE_VOICEMAIL_NUMBER_BOOL =
+            "editable_voicemail_number_bool";
 
     /**
      * Determine whether the voicemail notification is persistent in the notification bar. If true,
      * the voicemail notifications cannot be dismissed from the notification bar.
      */
-    public static final String
-            KEY_VOICEMAIL_NOTIFICATION_PERSISTENT_BOOL = "voicemail_notification_persistent_bool";
+    public static final String KEY_VOICEMAIL_NOTIFICATION_PERSISTENT_BOOL =
+            "voicemail_notification_persistent_bool";
 
     /** For IMS video over LTE calls, determines whether video pause signalling is supported. */
-    public static final String
-            KEY_SUPPORT_PAUSE_IMS_VIDEO_CALLS_BOOL = "support_pause_ims_video_calls_bool";
+    public static final String KEY_SUPPORT_PAUSE_IMS_VIDEO_CALLS_BOOL =
+            "support_pause_ims_video_calls_bool";
 
     /**
      * Disables dialing "*228" (OTASP provisioning) on CDMA carriers where it is not supported or is
      * potentially harmful by locking the SIM to 3G.
      */
-    public static final String
-            KEY_DISABLE_CDMA_ACTIVATION_CODE_BOOL = "disable_cdma_activation_code_bool";
+    public static final String KEY_DISABLE_CDMA_ACTIVATION_CODE_BOOL =
+            "disable_cdma_activation_code_bool";
 
     /**
      * List of network type constants which support only a single data connection at a time.
@@ -588,8 +592,8 @@
      * @see TelephonyManager NETWORK_TYPE_*
      * @see #KEY_ONLY_SINGLE_DC_ALLOWED_INT_ARRAY
      */
-    public static final String
-            KEY_ONLY_SINGLE_DC_ALLOWED_INT_ARRAY = "only_single_dc_allowed_int_array";
+    public static final String KEY_ONLY_SINGLE_DC_ALLOWED_INT_ARRAY =
+            "only_single_dc_allowed_int_array";
 
     /**
      * Only apply if {@link #KEY_ONLY_SINGLE_DC_ALLOWED_INT_ARRAY} specifies the network types that
@@ -604,15 +608,15 @@
      * Override the platform's notion of a network operator being considered roaming.
      * Value is string array of MCCMNCs to be considered roaming for 3GPP RATs.
      */
-    public static final String
-            KEY_GSM_ROAMING_NETWORKS_STRING_ARRAY = "gsm_roaming_networks_string_array";
+    public static final String KEY_GSM_ROAMING_NETWORKS_STRING_ARRAY =
+            "gsm_roaming_networks_string_array";
 
     /**
      * Override the platform's notion of a network operator being considered not roaming.
      * Value is string array of MCCMNCs to be considered not roaming for 3GPP RATs.
      */
-    public static final String
-            KEY_GSM_NONROAMING_NETWORKS_STRING_ARRAY = "gsm_nonroaming_networks_string_array";
+    public static final String KEY_GSM_NONROAMING_NETWORKS_STRING_ARRAY =
+            "gsm_nonroaming_networks_string_array";
 
     /**
      * The package name containing the ImsService that will be bound to the telephony framework to
@@ -622,6 +626,7 @@
      * {@link #KEY_CONFIG_IMS_RCS_PACKAGE_OVERRIDE_STRING} instead to configure these values
      * separately. If any of those values are not empty, they will override this value.
      */
+    @Deprecated
     public static final String KEY_CONFIG_IMS_PACKAGE_OVERRIDE_STRING =
             "config_ims_package_override_string";
 
@@ -668,7 +673,7 @@
 
     /**
      * Override the platform's notion of a network operator being considered non roaming.
-     * If true all networks are considered as home network a.k.a non-roaming.  When false,
+     * If true all networks are considered as home network a.k.a. non-roaming. When false,
      * the 2 pairs of CMDA and GSM roaming/non-roaming arrays are consulted.
      *
      * @see #KEY_GSM_ROAMING_NETWORKS_STRING_ARRAY
@@ -703,8 +708,7 @@
      *   <li>3: {@link #USSD_OVER_IMS_ONLY} </li>
      * </ul>
      */
-    public static final String KEY_CARRIER_USSD_METHOD_INT =
-            "carrier_ussd_method_int";
+    public static final String KEY_CARRIER_USSD_METHOD_INT = "carrier_ussd_method_int";
 
     /**
      * Flag specifying whether to show an alert dialog for 5G disable when the user disables VoLTE.
@@ -735,8 +739,7 @@
      * downgrading the call in the process.
      * @hide
      */
-    public static final String KEY_ALLOW_MERGING_RTT_CALLS_BOOL =
-             "allow_merging_rtt_calls_bool";
+    public static final String KEY_ALLOW_MERGING_RTT_CALLS_BOOL = "allow_merging_rtt_calls_bool";
 
     /**
      * Flag specifying whether the carrier wants to notify the user when a VT call has been handed
@@ -797,7 +800,7 @@
 
     /**
      * When {@code true}, changes to the mobile data enabled switch will not cause the VT
-     * registration state to change.  That is, turning on or off mobile data will not cause VT to be
+     * registration state to change. That is, turning on or off mobile data will not cause VT to be
      * enabled or disabled.
      * When {@code false}, disabling mobile data will cause VT to be de-registered.
      */
@@ -820,7 +823,8 @@
      * carrier provisioning. If false: hard disabled. If true: then depends on carrier
      * provisioning, availability etc.
      */
-    public static final String KEY_CARRIER_WFC_IMS_AVAILABLE_BOOL = "carrier_wfc_ims_available_bool";
+    public static final String KEY_CARRIER_WFC_IMS_AVAILABLE_BOOL =
+            "carrier_wfc_ims_available_bool";
 
     /**
      * Flag specifying whether Cross SIM over IMS should be available for carrier.
@@ -860,8 +864,8 @@
             "international_roaming_dial_string_replace_string_array";
 
     /**
-     * Flag specifying whether WFC over IMS supports the "wifi only" option.  If false, the wifi
-     * calling settings will not include an option for "wifi only".  If true, the wifi calling
+     * Flag specifying whether WFC over IMS supports the "wifi only" option. If false, the wifi
+     * calling settings will not include an option for "wifi only". If true, the wifi calling
      * settings will include an option for "wifi only"
      * <p>
      * By default, it is assumed that WFC supports "wifi only".
@@ -904,7 +908,7 @@
 
     /**
      * Flag indicating whether failed calls due to no service should prompt the user to enable
-     * WIFI calling.  When {@code true}, if the user attempts to establish a call when there is no
+     * WIFI calling. When {@code true}, if the user attempts to establish a call when there is no
      * service available, they are connected to WIFI, and WIFI calling is disabled, a different
      * call failure message will be used to encourage the user to enable WIFI calling.
      * @hide
@@ -930,8 +934,8 @@
      * {@link Ims#KEY_MMTEL_REQUIRES_PROVISIONING_BUNDLE}
      */
     @Deprecated
-    public static final String KEY_CARRIER_VOLTE_PROVISIONING_REQUIRED_BOOL
-            = "carrier_volte_provisioning_required_bool";
+    public static final String KEY_CARRIER_VOLTE_PROVISIONING_REQUIRED_BOOL =
+            "carrier_volte_provisioning_required_bool";
 
     /**
      * Flag indicating whether or not the IMS MmTel UT capability requires carrier provisioning
@@ -974,22 +978,22 @@
      * As of now, Verizon is the only carrier enforcing this dependency in their
      * WFC awareness and activation requirements.
      */
-    public static final String KEY_CARRIER_VOLTE_OVERRIDE_WFC_PROVISIONING_BOOL
-            = "carrier_volte_override_wfc_provisioning_bool";
+    public static final String KEY_CARRIER_VOLTE_OVERRIDE_WFC_PROVISIONING_BOOL =
+            "carrier_volte_override_wfc_provisioning_bool";
 
     /**
      * Override the device's configuration for the cellular data service to use for this SIM card.
      * @hide
      */
-    public static final String KEY_CARRIER_DATA_SERVICE_WWAN_PACKAGE_OVERRIDE_STRING
-            = "carrier_data_service_wwan_package_override_string";
+    public static final String KEY_CARRIER_DATA_SERVICE_WWAN_PACKAGE_OVERRIDE_STRING =
+            "carrier_data_service_wwan_package_override_string";
 
     /**
      * Override the device's configuration for the IWLAN data service to use for this SIM card.
      * @hide
      */
-    public static final String KEY_CARRIER_DATA_SERVICE_WLAN_PACKAGE_OVERRIDE_STRING
-            = "carrier_data_service_wlan_package_override_string";
+    public static final String KEY_CARRIER_DATA_SERVICE_WLAN_PACKAGE_OVERRIDE_STRING =
+            "carrier_data_service_wlan_package_override_string";
 
     /**
      * Override the device's configuration for the cellular data service class to use
@@ -1008,8 +1012,8 @@
             "carrier_data_service_wlan_class_override_string";
 
     /** Flag specifying whether VoLTE TTY is supported. */
-    public static final String KEY_CARRIER_VOLTE_TTY_SUPPORTED_BOOL
-            = "carrier_volte_tty_supported_bool";
+    public static final String KEY_CARRIER_VOLTE_TTY_SUPPORTED_BOOL =
+            "carrier_volte_tty_supported_bool";
 
     /** Flag specifying whether VoWIFI TTY is supported.
      * @hide
@@ -1021,37 +1025,37 @@
      * Flag specifying whether IMS service can be turned off. If false then the service will not be
      * turned-off completely, but individual features can be disabled.
      */
-    public static final String KEY_CARRIER_ALLOW_TURNOFF_IMS_BOOL
-            = "carrier_allow_turnoff_ims_bool";
+    public static final String KEY_CARRIER_ALLOW_TURNOFF_IMS_BOOL =
+            "carrier_allow_turnoff_ims_bool";
 
     /**
      * Flag specifying whether Generic Bootstrapping Architecture capable SIM is required for IMS.
      */
-    public static final String KEY_CARRIER_IMS_GBA_REQUIRED_BOOL
-            = "carrier_ims_gba_required_bool";
+    public static final String KEY_CARRIER_IMS_GBA_REQUIRED_BOOL =
+            "carrier_ims_gba_required_bool";
 
     /**
-     * Flag specifying whether IMS instant lettering is available for the carrier.  {@code True} if
+     * Flag specifying whether IMS instant lettering is available for the carrier. {@code True} if
      * instant lettering is available for the carrier, {@code false} otherwise.
      */
     public static final String KEY_CARRIER_INSTANT_LETTERING_AVAILABLE_BOOL =
             "carrier_instant_lettering_available_bool";
 
-    /*
+    /**
      * Flag specifying whether IMS should be the first phone attempted for E911 even if the
      * phone is not in service.
      */
-    public static final String KEY_CARRIER_USE_IMS_FIRST_FOR_EMERGENCY_BOOL
-            = "carrier_use_ims_first_for_emergency_bool";
+    public static final String KEY_CARRIER_USE_IMS_FIRST_FOR_EMERGENCY_BOOL =
+            "carrier_use_ims_first_for_emergency_bool";
 
     /**
      * When {@code true}, the determination of whether to place a call as an emergency call will be
      * based on the known {@link android.telephony.emergency.EmergencyNumber}s for the SIM on which
-     * the call is being placed.  In a dual SIM scenario, if Sim A has the emergency numbers
+     * the call is being placed. In a dual SIM scenario, if Sim A has the emergency numbers
      * 123, 456 and Sim B has the emergency numbers 789, and the user places a call on SIM A to 789,
      * it will not be treated as an emergency call in this case.
      * When {@code false}, the determination is based on the emergency numbers from all device SIMs,
-     * regardless of which SIM the call is being placed on.  If Sim A has the emergency numbers
+     * regardless of which SIM the call is being placed on. If Sim A has the emergency numbers
      * 123, 456 and Sim B has the emergency numbers 789, and the user places a call on SIM A to 789,
      * the call will be dialed as an emergency number, but with an unspecified routing.
      * @hide
@@ -1062,7 +1066,7 @@
     /**
      * When IMS instant lettering is available for a carrier (see
      * {@link #KEY_CARRIER_INSTANT_LETTERING_AVAILABLE_BOOL}), determines the list of characters
-     * which may not be contained in messages.  Should be specified as a regular expression suitable
+     * which may not be contained in messages. Should be specified as a regular expression suitable
      * for use with {@link String#matches(String)}.
      */
     public static final String KEY_CARRIER_INSTANT_LETTERING_INVALID_CHARS_STRING =
@@ -1071,8 +1075,8 @@
     /**
      * When IMS instant lettering is available for a carrier (see
      * {@link #KEY_CARRIER_INSTANT_LETTERING_AVAILABLE_BOOL}), determines a list of characters which
-     * must be escaped with a backslash '\' character.  Should be specified as a string containing
-     * the characters to be escaped.  For example to escape quote and backslash the string would be
+     * must be escaped with a backslash '\' character. Should be specified as a string containing
+     * the characters to be escaped. For example to escape quote and backslash the string would be
      * a quote and a backslash.
      */
     public static final String KEY_CARRIER_INSTANT_LETTERING_ESCAPED_CHARS_STRING =
@@ -1081,10 +1085,10 @@
     /**
      * When IMS instant lettering is available for a carrier (see
      * {@link #KEY_CARRIER_INSTANT_LETTERING_AVAILABLE_BOOL}), determines the character encoding
-     * which will be used when determining the length of messages.  Used in the InCall UI to limit
-     * the number of characters the user may type.  If empty-string, the instant lettering
-     * message size limit will be enforced on a 1:1 basis.  That is, each character will count
-     * towards the messages size limit as a single bye.  If a character encoding is specified, the
+     * which will be used when determining the length of messages. Used in the InCall UI to limit
+     * the number of characters the user may type. If empty-string, the instant lettering
+     * message size limit will be enforced on a 1:1 basis. That is, each character will count
+     * towards the messages size limit as a single byte. If a character encoding is specified, the
      * message size limit will be based on the number of bytes in the message per the specified
      * encoding.
      */
@@ -1093,7 +1097,7 @@
 
     /**
      * When IMS instant lettering is available for a carrier (see
-     * {@link #KEY_CARRIER_INSTANT_LETTERING_AVAILABLE_BOOL}), the length limit for messages.  Used
+     * {@link #KEY_CARRIER_INSTANT_LETTERING_AVAILABLE_BOOL}), the length limit for messages. Used
      * in the InCall UI to ensure the user cannot enter more characters than allowed by the carrier.
      * See also {@link #KEY_CARRIER_INSTANT_LETTERING_ENCODING_STRING} for more information on how
      * the length of the message is calculated.
@@ -1114,7 +1118,8 @@
      * manager can control and route outgoing and incoming phone calls, even if they're placed
      * using another connection service (PSTN, for example).
      */
-    public static final String KEY_DEFAULT_SIM_CALL_MANAGER_STRING = "default_sim_call_manager_string";
+    public static final String KEY_DEFAULT_SIM_CALL_MANAGER_STRING =
+            "default_sim_call_manager_string";
 
     /**
      * The default flag specifying whether ETWS/CMAS test setting is forcibly disabled in
@@ -1217,8 +1222,7 @@
      * CDMA carrier ERI (Enhanced Roaming Indicator) file name
      * @hide
      */
-    public static final String KEY_CARRIER_ERI_FILE_NAME_STRING =
-            "carrier_eri_file_name_string";
+    public static final String KEY_CARRIER_ERI_FILE_NAME_STRING = "carrier_eri_file_name_string";
 
     /* The following 3 fields are related to carrier visual voicemail. */
 
@@ -1242,13 +1246,12 @@
      * Whether cellular data is required to access visual voicemail.
      */
     public static final String KEY_VVM_CELLULAR_DATA_REQUIRED_BOOL =
-        "vvm_cellular_data_required_bool";
+            "vvm_cellular_data_required_bool";
 
     /**
      * The default OMTP visual voicemail client prefix to use. Defaulted to "//VVM"
      */
-    public static final String KEY_VVM_CLIENT_PREFIX_STRING =
-            "vvm_client_prefix_string";
+    public static final String KEY_VVM_CLIENT_PREFIX_STRING = "vvm_client_prefix_string";
 
     /**
      * Whether to use SSL to connect to the visual voicemail IMAP server. Defaulted to false.
@@ -1273,8 +1276,7 @@
      * <p>This is for carriers that does not support VVM deactivation so voicemail can continue to
      * function without the data cost.
      */
-    public static final String KEY_VVM_LEGACY_MODE_ENABLED_BOOL =
-            "vvm_legacy_mode_enabled_bool";
+    public static final String KEY_VVM_LEGACY_MODE_ENABLED_BOOL = "vvm_legacy_mode_enabled_bool";
 
     /**
      * Whether to prefetch audio data on new voicemail arrival, defaulted to true.
@@ -1288,7 +1290,8 @@
      * @deprecated use {@link #KEY_CARRIER_VVM_PACKAGE_NAME_STRING_ARRAY}.
      */
     @Deprecated
-    public static final String KEY_CARRIER_VVM_PACKAGE_NAME_STRING = "carrier_vvm_package_name_string";
+    public static final String KEY_CARRIER_VVM_PACKAGE_NAME_STRING =
+            "carrier_vvm_package_name_string";
 
     /**
      * A list of the carrier's visual voicemail app package names to ensure that dialer visual
@@ -1307,7 +1310,7 @@
      * Status screen. The default value is true.
      */
     public static final String KEY_SHOW_SIGNAL_STRENGTH_IN_SIM_STATUS_BOOL =
-        "show_signal_strength_in_sim_status_bool";
+            "show_signal_strength_in_sim_status_bool";
 
     /**
      * Flag specifying if we should interpret all signal strength as one bar higher
@@ -1386,9 +1389,8 @@
     public static final String KEY_IGNORE_RTT_MODE_SETTING_BOOL =
             "ignore_rtt_mode_setting_bool";
 
-
     /**
-     * Determines whether adhoc conference calls are supported by a carrier.  When {@code true},
+     * Determines whether adhoc conference calls are supported by a carrier. When {@code true},
      * adhoc conference calling is supported, {@code false otherwise}.
      */
     public static final String KEY_SUPPORT_ADHOC_CONFERENCE_CALLS_BOOL =
@@ -1396,14 +1398,14 @@
 
     /**
      * Determines whether conference participants can be added to existing call to form an adhoc
-     * conference call (in contrast to merging calls to form a conference).  When {@code true},
+     * conference call (in contrast to merging calls to form a conference). When {@code true},
      * adding conference participants to existing call is supported, {@code false otherwise}.
      */
     public static final String KEY_SUPPORT_ADD_CONFERENCE_PARTICIPANTS_BOOL =
             "support_add_conference_participants_bool";
 
     /**
-     * Determines whether conference calls are supported by a carrier.  When {@code true},
+     * Determines whether conference calls are supported by a carrier. When {@code true},
      * conference calling is supported, {@code false otherwise}.
      */
     public static final String KEY_SUPPORT_CONFERENCE_CALL_BOOL = "support_conference_call_bool";
@@ -1411,7 +1413,7 @@
     /**
      * Determines whether a maximum size limit for IMS conference calls is enforced on the device.
      * When {@code true}, IMS conference calls will be limited to at most
-     * {@link #KEY_IMS_CONFERENCE_SIZE_LIMIT_INT} participants.  When {@code false}, no attempt is
+     * {@link #KEY_IMS_CONFERENCE_SIZE_LIMIT_INT} participants. When {@code false}, no attempt is
      * made to limit the number of participants in a conference (the carrier will raise an error
      * when an attempt is made to merge too many participants into a conference).
      * <p>
@@ -1425,14 +1427,14 @@
 
     /**
      * Determines the maximum number of participants the carrier supports for a conference call.
-     * This number is exclusive of the current device.  A conference between 3 devices, for example,
+     * This number is exclusive of the current device. A conference between 3 devices, for example,
      * would have a size limit of 2 participants.
      * Enforced when {@link #KEY_IS_IMS_CONFERENCE_SIZE_ENFORCED_BOOL} is {@code true}.
      */
     public static final String KEY_IMS_CONFERENCE_SIZE_LIMIT_INT = "ims_conference_size_limit_int";
 
     /**
-     * Determines whether manage IMS conference calls is supported by a carrier.  When {@code true},
+     * Determines whether manage IMS conference calls is supported by a carrier. When {@code true},
      * manage IMS conference call is supported, {@code false otherwise}.
      * @hide
      */
@@ -1455,7 +1457,7 @@
      * and B and C are considered the conference peers.
      * <p>
      * When {@code true}, the conference peer will display the conference state if it receives
-     * conference event package data from the network.  When {@code false}, the conference peer will
+     * conference event package data from the network. When {@code false}, the conference peer will
      * ignore conference event package data received from the network.
      * @hide
      */
@@ -1473,7 +1475,7 @@
 
     /**
      * Indicates whether the carrier supports the negotiations of RFC8285 compliant RTP header
-     * extensions supported on a call during the Session Description Protocol (SDP).  This option
+     * extensions supported on a call during the Session Description Protocol (SDP). This option
      * is only used when {@link #KEY_SUPPORTS_DEVICE_TO_DEVICE_COMMUNICATION_USING_RTP_BOOL} is
      * {@code true}.
      * <p>
@@ -1503,7 +1505,7 @@
             "display_hd_audio_property_bool";
 
     /**
-     * Determines whether IMS conference calls are supported by a carrier.  When {@code true},
+     * Determines whether IMS conference calls are supported by a carrier. When {@code true},
      * IMS conference calling is supported, {@code false} otherwise.
      * @hide
      */
@@ -1512,9 +1514,9 @@
 
     /**
      * Determines whether the device will locally disconnect an IMS conference when the participant
-     * count drops to zero.  When {@code true}, it is assumed the carrier does NOT disconnect a
+     * count drops to zero. When {@code true}, it is assumed the carrier does NOT disconnect a
      * conference when the participant count drops to zero and that the device must do this by
-     * disconnecting the conference locally.  When {@code false}, it is assumed that the carrier
+     * disconnecting the conference locally. When {@code false}, it is assumed that the carrier
      * is responsible for disconnecting the conference when there are no longer any participants
      * present.
      * <p>
@@ -1530,8 +1532,8 @@
             "local_disconnect_empty_ims_conference_bool";
 
     /**
-     * Determines whether video conference calls are supported by a carrier.  When {@code true},
-     * video calls can be merged into conference calls, {@code false} otherwiwse.
+     * Determines whether video conference calls are supported by a carrier. When {@code true},
+     * video calls can be merged into conference calls, {@code false} otherwise.
      * <p>
      * Note: even if video conference calls are not supported, audio calls may be merged into a
      * conference if {@link #KEY_SUPPORT_CONFERENCE_CALL_BOOL} is {@code true}.
@@ -1568,7 +1570,8 @@
     /**
      * Determine whether preferred network type can be shown.
      */
-    public static final String KEY_HIDE_PREFERRED_NETWORK_TYPE_BOOL = "hide_preferred_network_type_bool";
+    public static final String KEY_HIDE_PREFERRED_NETWORK_TYPE_BOOL =
+            "hide_preferred_network_type_bool";
 
     /**
      * String array for package names that need to be enabled for this carrier.
@@ -1800,20 +1803,20 @@
     public static final String KEY_SIM_COUNTRY_ISO_OVERRIDE_STRING =
             "sim_country_iso_override_string";
 
-   /**
-    * The Component Name of a carrier-provided CallScreeningService implementation. Telecom will
-    * bind to {@link android.telecom.CallScreeningService} for ALL incoming calls and provide
-    * the carrier
-    * CallScreeningService with the opportunity to allow or block calls.
-    * <p>
-    * The String includes the package name/the class name.
-    * Example:
-    * <item>com.android.carrier/com.android.carrier.callscreeningserviceimpl</item>
-    * <p>
-    * Using {@link ComponentName#flattenToString()} to convert a ComponentName object to String.
-    * Using {@link ComponentName#unflattenFromString(String)} to convert a String object to a
-    * ComponentName.
-    */
+    /**
+     * The Component Name of a carrier-provided CallScreeningService implementation. Telecom will
+     * bind to {@link android.telecom.CallScreeningService} for ALL incoming calls and provide
+     * the carrier
+     * CallScreeningService with the opportunity to allow or block calls.
+     * <p>
+     * The String includes the package name/the class name.
+     * Example:
+     * <item>com.android.carrier/com.android.carrier.callscreeningserviceimpl</item>
+     * <p>
+     * Using {@link ComponentName#flattenToString()} to convert a ComponentName object to String.
+     * Using {@link ComponentName#unflattenFromString(String)} to convert a String object to a
+     * ComponentName.
+     */
     public static final String KEY_CARRIER_CALL_SCREENING_APP_STRING = "call_screening_app";
 
     /**
@@ -1925,20 +1928,20 @@
             "broadcast_emergency_call_state_changes_bool";
 
     /**
-      * Indicates whether STK LAUNCH_BROWSER command is disabled.
-      * If {@code true}, then the browser will not be launched
-      * on UI for the LAUNCH_BROWSER STK command.
-      * @hide
-      */
+     * Indicates whether STK LAUNCH_BROWSER command is disabled.
+     * If {@code true}, then the browser will not be launched
+     * on UI for the LAUNCH_BROWSER STK command.
+     * @hide
+     */
     public static final String KEY_STK_DISABLE_LAUNCH_BROWSER_BOOL =
             "stk_disable_launch_browser_bool";
 
     /**
-      * Boolean indicating if the helper text for STK GET INKEY/INPUT commands with the digit only
-      * mode is displayed on the input screen.
-      * The helper text is dispayed regardless of the input mode, if {@code false}.
-      * @hide
-      */
+     * Boolean indicating if the helper text for STK GET INKEY/INPUT commands with the digit only
+     * mode is displayed on the input screen.
+     * The helper text is displayed regardless of the input mode, if {@code false}.
+     * @hide
+     */
     public static final String KEY_HIDE_DIGITS_HELPER_TEXT_ON_STK_INPUT_SCREEN_BOOL =
             "hide_digits_helper_text_on_stk_input_screen_bool";
 
@@ -2006,6 +2009,19 @@
             "include_lte_for_nr_advanced_threshold_bandwidth_bool";
 
     /**
+     * Indicating whether to ratchet the aggregated cell bandwidths on receiving new values when
+     * the device is in RRC IDLE mode.
+     * The aggregated cell bandwidths are used for determining NR advanced state.
+     *
+     * If this is {@code true}, we will only update the aggregate cell bandwidths if the new
+     * aggregate is higher than the current aggregate and the anchor NR cell is the same.
+     * If this is {@code false}, we will always update the aggregate cell bandwidths when receiving
+     * new values.
+     */
+    public static final String KEY_RATCHET_NR_ADVANCED_BANDWIDTH_IF_RRC_IDLE_BOOL =
+            "ratchet_nr_advanced_bandwidth_if_rrc_idle_bool";
+
+    /**
      * Boolean indicating if operator name should be shown in the status bar
      * @hide
      */
@@ -2085,16 +2101,22 @@
     public static final String KEY_MMS_ALLOW_ATTACH_AUDIO_BOOL = "allowAttachAudio";
     public static final String KEY_MMS_APPEND_TRANSACTION_ID_BOOL = "enabledTransID";
     public static final String KEY_MMS_GROUP_MMS_ENABLED_BOOL = "enableGroupMms";
-    public static final String KEY_MMS_MMS_DELIVERY_REPORT_ENABLED_BOOL = "enableMMSDeliveryReports";
+    public static final String KEY_MMS_MMS_DELIVERY_REPORT_ENABLED_BOOL =
+            "enableMMSDeliveryReports";
     public static final String KEY_MMS_MMS_ENABLED_BOOL = "enabledMMS";
     public static final String KEY_MMS_MMS_READ_REPORT_ENABLED_BOOL = "enableMMSReadReports";
     public static final String KEY_MMS_MULTIPART_SMS_ENABLED_BOOL = "enableMultipartSMS";
     public static final String KEY_MMS_NOTIFY_WAP_MMSC_ENABLED_BOOL = "enabledNotifyWapMMSC";
-    public static final String KEY_MMS_SEND_MULTIPART_SMS_AS_SEPARATE_MESSAGES_BOOL = "sendMultipartSmsAsSeparateMessages";
-    public static final String KEY_MMS_SHOW_CELL_BROADCAST_APP_LINKS_BOOL = "config_cellBroadcastAppLinks";
-    public static final String KEY_MMS_SMS_DELIVERY_REPORT_ENABLED_BOOL = "enableSMSDeliveryReports";
-    public static final String KEY_MMS_SUPPORT_HTTP_CHARSET_HEADER_BOOL = "supportHttpCharsetHeader";
-    public static final String KEY_MMS_SUPPORT_MMS_CONTENT_DISPOSITION_BOOL = "supportMmsContentDisposition";
+    public static final String KEY_MMS_SEND_MULTIPART_SMS_AS_SEPARATE_MESSAGES_BOOL =
+            "sendMultipartSmsAsSeparateMessages";
+    public static final String KEY_MMS_SHOW_CELL_BROADCAST_APP_LINKS_BOOL =
+            "config_cellBroadcastAppLinks";
+    public static final String KEY_MMS_SMS_DELIVERY_REPORT_ENABLED_BOOL =
+            "enableSMSDeliveryReports";
+    public static final String KEY_MMS_SUPPORT_HTTP_CHARSET_HEADER_BOOL =
+            "supportHttpCharsetHeader";
+    public static final String KEY_MMS_SUPPORT_MMS_CONTENT_DISPOSITION_BOOL =
+            "supportMmsContentDisposition";
     public static final String KEY_MMS_ALIAS_MAX_CHARS_INT = "aliasMaxChars";
     public static final String KEY_MMS_ALIAS_MIN_CHARS_INT = "aliasMinChars";
     public static final String KEY_MMS_HTTP_SOCKET_TIMEOUT_INT = "httpSocketTimeout";
@@ -2103,7 +2125,8 @@
     public static final String KEY_MMS_MAX_MESSAGE_SIZE_INT = "maxMessageSize";
     public static final String KEY_MMS_MESSAGE_TEXT_MAX_SIZE_INT = "maxMessageTextSize";
     public static final String KEY_MMS_RECIPIENT_LIMIT_INT = "recipientLimit";
-    public static final String KEY_MMS_SMS_TO_MMS_TEXT_LENGTH_THRESHOLD_INT = "smsToMmsTextLengthThreshold";
+    public static final String KEY_MMS_SMS_TO_MMS_TEXT_LENGTH_THRESHOLD_INT =
+            "smsToMmsTextLengthThreshold";
     public static final String KEY_MMS_SMS_TO_MMS_TEXT_THRESHOLD_INT = "smsToMmsTextThreshold";
     public static final String KEY_MMS_SUBJECT_MAX_LENGTH_INT = "maxSubjectLength";
     public static final String KEY_MMS_EMAIL_GATEWAY_NUMBER_STRING = "emailGatewayNumber";
@@ -2132,7 +2155,7 @@
      * The flatten {@link android.content.ComponentName componentName} of the activity that can
      * setup the device and activate with the network per carrier requirements.
      *
-     * e.g, com.google.android.carrierPackageName/.CarrierActivityName
+     * e.g., com.google.android.carrierPackageName/.CarrierActivityName
      * @hide
      */
     @SystemApi
@@ -2273,7 +2296,7 @@
 
     /**
      * Determines whether the carrier supports making non-emergency phone calls while the phone is
-     * in emergency callback mode.  Default value is {@code true}, meaning that non-emergency calls
+     * in emergency callback mode. Default value is {@code true}, meaning that non-emergency calls
      * are allowed in emergency callback mode.
      */
     public static final String KEY_ALLOW_NON_EMERGENCY_CALLS_IN_ECM_BOOL =
@@ -2296,7 +2319,7 @@
 
     /**
      * Flag indicating whether to allow carrier video calls to emergency numbers.
-     * When {@code true}, video calls to emergency numbers will be allowed.  When {@code false},
+     * When {@code true}, video calls to emergency numbers will be allowed. When {@code false},
      * video calls to emergency numbers will be initiated as audio-only calls instead.
      */
     public static final String KEY_ALLOW_EMERGENCY_VIDEO_CALLS_BOOL =
@@ -2324,7 +2347,7 @@
      * When presence is supported, the device should use the
      * {@link android.provider.ContactsContract.Data#CARRIER_PRESENCE} bit mask and set the
      * {@link android.provider.ContactsContract.Data#CARRIER_PRESENCE_VT_CAPABLE} bit to indicate
-     * whether each contact supports video calling.  The UI is made aware that presence is enabled
+     * whether each contact supports video calling. The UI is made aware that presence is enabled
      * via {@link android.telecom.PhoneAccount#CAPABILITY_VIDEO_CALLING_RELIES_ON_PRESENCE}
      * and can choose to hide or show the video calling icon based on whether a contact supports
      * video.
@@ -2348,7 +2371,7 @@
      * contacts emergency services. Platform considers values for below cases:
      *  1) 0 <= VALUE <= 604800(one week): the value will be used as the duration directly.
      *  2) VALUE > 604800(one week): will use the default value as duration instead.
-     *  3) VALUE < 0: block will be disabled forever until user re-eanble block manually,
+     *  3) VALUE < 0: block will be disabled forever until user re-enable block manually,
      *     the suggested value to disable forever is -1.
      * See {@code android.provider.BlockedNumberContract#notifyEmergencyContact(Context)}
      * See {@code android.provider.BlockedNumberContract#isBlocked(Context, String)}.
@@ -2378,7 +2401,7 @@
 
     /**
      * For carriers which require an empty flash to be sent before sending the normal 3-way calling
-     * flash, the duration in milliseconds of the empty flash to send.  When {@code 0}, no empty
+     * flash, the duration in milliseconds of the empty flash to send. When {@code 0}, no empty
      * flash is sent.
      */
     public static final String KEY_CDMA_3WAYCALL_FLASH_DELAY_INT = "cdma_3waycall_flash_delay_int";
@@ -2418,8 +2441,7 @@
      * Int indicating the max number length for FDN
      * @hide
      */
-    public static final String KEY_FDN_NUMBER_LENGTH_LIMIT_INT =
-            "fdn_number_length_limit_int";
+    public static final String KEY_FDN_NUMBER_LENGTH_LIMIT_INT = "fdn_number_length_limit_int";
 
     /**
      * Report IMEI as device id even if it's a CDMA/LTE phone.
@@ -2431,16 +2453,15 @@
     /**
      * The families of Radio Access Technologies that will get clustered and ratcheted,
      * ie, we will report transitions up within the family, but not down until we change
-     * cells.  This prevents flapping between base technologies and higher techs that are
+     * cells. This prevents flapping between base technologies and higher techs that are
      * granted on demand within the cell.
      * @hide
      */
-    public static final String KEY_RATCHET_RAT_FAMILIES =
-            "ratchet_rat_families";
+    public static final String KEY_RATCHET_RAT_FAMILIES = "ratchet_rat_families";
 
     /**
      * Flag indicating whether some telephony logic will treat a call which was formerly a video
-     * call as if it is still a video call.  When {@code true}:
+     * call as if it is still a video call. When {@code true}:
      * <p>
      * Logic which will automatically drop a video call which takes place over WIFI when a
      * voice call is answered (see {@link #KEY_DROP_VIDEO_CALL_WHEN_ANSWERING_AUDIO_CALL_BOOL}.
@@ -2452,7 +2473,7 @@
 
     /**
      * When {@code true}, if the user is in an ongoing video call over WIFI and answers an incoming
-     * audio call, the video call will be disconnected before the audio call is answered.  This is
+     * audio call, the video call will be disconnected before the audio call is answered. This is
      * in contrast to the usual expected behavior where a foreground video call would be put into
      * the background and held when an incoming audio call is answered.
      */
@@ -2462,8 +2483,8 @@
     /**
      * Flag indicating whether the carrier supports merging wifi calls when VoWIFI is disabled.
      * This can happen in the case of a carrier which allows offloading video calls to WIFI
-     * separately of whether voice over wifi is enabled.  In such a scenario when two video calls
-     * are downgraded to voice, they remain over wifi.  However, if VoWIFI is disabled, these calls
+     * separately of whether voice over wifi is enabled. In such a scenario when two video calls
+     * are downgraded to voice, they remain over wifi. However, if VoWIFI is disabled, these calls
      * cannot be merged.
      */
     public static final String KEY_ALLOW_MERGE_WIFI_CALLS_WHEN_VOWIFI_OFF_BOOL =
@@ -2473,9 +2494,9 @@
      * Flag indicating whether the carrier supports the Hold command while in an IMS call.
      * <p>
      * The device configuration value {@code config_device_respects_hold_carrier_config} ultimately
-     * controls whether this carrier configuration option is used.  Where
-     * {@code config_device_respects_hold_carrier_config} is false, the value of the
-     * {@link #KEY_ALLOW_HOLD_IN_IMS_CALL_BOOL} carrier configuration option is ignored.
+     * controls whether this carrier configuration option is used.
+     * Where {@code config_device_respects_hold_carrier_config} is false, the value of
+     * this carrier configuration is ignored.
      * @hide
      */
     public static final String KEY_ALLOW_HOLD_IN_IMS_CALL_BOOL = "allow_hold_in_ims_call";
@@ -2530,8 +2551,7 @@
      * <p>
      * This is {@code true} by default.
      */
-    public static final String KEY_ALLOW_HOLD_VIDEO_CALL_BOOL =
-            "allow_hold_video_call_bool";
+    public static final String KEY_ALLOW_HOLD_VIDEO_CALL_BOOL = "allow_hold_video_call_bool";
 
     /**
      * When true, indicates that the HD audio icon in the in-call screen should not be shown for
@@ -2625,7 +2645,8 @@
      * is returned.
      * @hide
      */
-    public static final String KEY_FILTERED_CNAP_NAMES_STRING_ARRAY = "filtered_cnap_names_string_array";
+    public static final String KEY_FILTERED_CNAP_NAMES_STRING_ARRAY =
+            "filtered_cnap_names_string_array";
 
     /**
      * The RCS configuration server URL. This URL is used to initiate RCS provisioning.
@@ -2693,9 +2714,9 @@
             "emergency_notification_delay_int";
 
     /**
-     * When {@code true}, the carrier allows the user of the
-     * {@link TelephonyManager#sendUssdRequest(String, TelephonyManager.UssdResponseCallback,
-     * Handler)} API to perform USSD requests.  {@code True} by default.
+     * When {@code true}, the carrier allows the user of the {@link
+     * TelephonyManager#sendUssdRequest(String, TelephonyManager.UssdResponseCallback, Handler)}
+     * API to perform USSD requests. {@code True} by default.
      * @hide
      */
     public static final String KEY_ALLOW_USSD_REQUESTS_VIA_TELEPHONY_MANAGER_BOOL =
@@ -2707,7 +2728,7 @@
      * fails.
      */
     public static final String KEY_SUPPORT_3GPP_CALL_FORWARDING_WHILE_ROAMING_BOOL =
-        "support_3gpp_call_forwarding_while_roaming_bool";
+            "support_3gpp_call_forwarding_while_roaming_bool";
 
     /**
      * Boolean indicating whether to display voicemail number as default call forwarding number in
@@ -2773,8 +2794,7 @@
      * This setting may be still overridden by explicit user choice. By default,
      * {@link #DATA_CYCLE_USE_PLATFORM_DEFAULT} will be used.
      */
-    public static final String KEY_MONTHLY_DATA_CYCLE_DAY_INT =
-            "monthly_data_cycle_day_int";
+    public static final String KEY_MONTHLY_DATA_CYCLE_DAY_INT = "monthly_data_cycle_day_int";
 
     /**
      * When {@link #KEY_MONTHLY_DATA_CYCLE_DAY_INT}, {@link #KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG},
@@ -2820,7 +2840,7 @@
 
     /**
      * Controls if the device should automatically warn the user that sim voice & data function
-     * might be limited due to dual sim scenario. When set to {@true} display the notification,
+     * might be limited due to dual sim scenario. When set to {@code true} display the notification,
      * {@code false} otherwise.
      * @hide
      */
@@ -2846,16 +2866,14 @@
      * their cellular data limit. When set to {@code false} the carrier is
      * expected to have implemented their own notification mechanism. {@code true} by default.
      */
-    public static final String KEY_DATA_LIMIT_NOTIFICATION_BOOL =
-            "data_limit_notification_bool";
+    public static final String KEY_DATA_LIMIT_NOTIFICATION_BOOL = "data_limit_notification_bool";
 
     /**
      * Controls if the device should automatically notify the user when rapid
      * cellular data usage is observed. When set to {@code false} the carrier is
-     * expected to have implemented their own notification mechanism.  {@code true} by default.
+     * expected to have implemented their own notification mechanism. {@code true} by default.
      */
-    public static final String KEY_DATA_RAPID_NOTIFICATION_BOOL =
-            "data_rapid_notification_bool";
+    public static final String KEY_DATA_RAPID_NOTIFICATION_BOOL = "data_rapid_notification_bool";
 
     /**
      * Offset to be reduced from rsrp threshold while calculating signal strength level.
@@ -2888,8 +2906,7 @@
      * "nrarfcn2_start-nrarfcn2_end" ... }
      * @hide
      */
-    public static final String KEY_BOOSTED_NRARFCNS_STRING_ARRAY =
-            "boosted_nrarfcns_string_array";
+    public static final String KEY_BOOSTED_NRARFCNS_STRING_ARRAY = "boosted_nrarfcns_string_array";
 
     /**
      * Determine whether to use only RSRP for the number of LTE signal bars.
@@ -2996,8 +3013,8 @@
      * is set, the default value 2 is used.
      * @hide
      */
-    public static final String
-            KEY_NGRAN_SSRSRP_HYSTERESIS_DB_INT = "ngran_ssrsrp_hysteresis_db_int";
+    public static final String KEY_NGRAN_SSRSRP_HYSTERESIS_DB_INT =
+            "ngran_ssrsrp_hysteresis_db_int";
 
     /**
      * An interval in dB for {@link SignalThresholdInfo#SIGNAL_MEASUREMENT_TYPE_SSRSRQ} measurement
@@ -3005,10 +3022,10 @@
      *
      * <p>The default value is 2 and the minimum allowed value is 0. If no value or negative value
      * is set, the default value 2 is used.
-     *@hide
+     * @hide
      */
-    public static final String
-            KEY_NGRAN_SSRSRQ_HYSTERESIS_DB_INT = "ngran_ssrsrq_hysteresis_db_int";
+    public static final String KEY_NGRAN_SSRSRQ_HYSTERESIS_DB_INT =
+            "ngran_ssrsrq_hysteresis_db_int";
 
     /**
      * An interval in dB for {@link SignalThresholdInfo#SIGNAL_MEASUREMENT_TYPE_SSSINR} measurement
@@ -3018,8 +3035,8 @@
      * is set, the default value 2 is used.
      * @hide
      */
-    public static final String
-            KEY_NGRAN_SSSINR_HYSTERESIS_DB_INT = "ngran_sssinr_hysteresis_db_int";
+    public static final String KEY_NGRAN_SSSINR_HYSTERESIS_DB_INT =
+            "ngran_sssinr_hysteresis_db_int";
 
     /**
      * Bit-field integer to determine whether to use SS reference signal received power (SSRSRP),
@@ -3107,8 +3124,7 @@
      * A match on this supersedes a match on {@link #KEY_NON_ROAMING_OPERATOR_STRING_ARRAY}.
      * @hide
      */
-    public static final String KEY_ROAMING_OPERATOR_STRING_ARRAY =
-            "roaming_operator_string_array";
+    public static final String KEY_ROAMING_OPERATOR_STRING_ARRAY = "roaming_operator_string_array";
 
     /**
      * URL from which the proto containing the public key of the Carrier used for
@@ -3177,7 +3193,7 @@
      * Boolean flag indicating whether the carrier supports TTY.
      * <p>
      * Note that {@link #KEY_CARRIER_VOLTE_TTY_SUPPORTED_BOOL} controls availability of TTY over
-     * VoLTE; if {@link #KEY_TTY_SUPPORTED_BOOL} is disabled, then
+     * VoLTE; if this carrier configuration is disabled, then
      * {@link #KEY_CARRIER_VOLTE_TTY_SUPPORTED_BOOL} is also implicitly disabled.
      * <p>
      * {@link TelecomManager#isTtySupported()} should be used to determine if a device supports TTY,
@@ -3301,11 +3317,11 @@
     public static final String KEY_CHECK_PRICING_WITH_CARRIER_FOR_DATA_ROAMING_BOOL =
             "check_pricing_with_carrier_data_roaming_bool";
 
-     /**
-      * Determines whether we should show a notification when the phone established a data
-      * connection in roaming network, to warn users about possible roaming charges.
-      * @hide
-      */
+    /**
+     * Determines whether we should show a notification when the phone established a data
+     * connection in roaming network, to warn users about possible roaming charges.
+     * @hide
+     */
     public static final String KEY_SHOW_DATA_CONNECTED_ROAMING_NOTIFICATION_BOOL =
             "show_data_connected_roaming_notification";
 
@@ -3320,8 +3336,7 @@
      * these boundaries is considered invalid.
      * @hide
      */
-    public static final String KEY_LTE_RSRP_THRESHOLDS_INT_ARRAY =
-            "lte_rsrp_thresholds_int_array";
+    public static final String KEY_LTE_RSRP_THRESHOLDS_INT_ARRAY = "lte_rsrp_thresholds_int_array";
 
     /**
      * A list of 4 customized LTE Reference Signal Received Quality (RSRQ) thresholds.
@@ -3338,8 +3353,7 @@
      * This key is considered invalid if the format is violated. If the key is invalid or
      * not configured, a default value set will apply.
      */
-    public static final String KEY_LTE_RSRQ_THRESHOLDS_INT_ARRAY =
-            "lte_rsrq_thresholds_int_array";
+    public static final String KEY_LTE_RSRQ_THRESHOLDS_INT_ARRAY = "lte_rsrq_thresholds_int_array";
 
     /**
      * A list of 4 customized LTE Reference Signal Signal to Noise Ratio (RSSNR) thresholds.
@@ -3365,8 +3379,7 @@
      * is set, the default value 2 is used.
      * @hide
      */
-    public static final String
-            KEY_EUTRAN_RSRP_HYSTERESIS_DB_INT = "eutran_rsrp_hysteresis_db_int";
+    public static final String KEY_EUTRAN_RSRP_HYSTERESIS_DB_INT = "eutran_rsrp_hysteresis_db_int";
 
     /**
      * An interval in dB for {@link SignalThresholdInfo#SIGNAL_MEASUREMENT_TYPE_RSRQ} measurement
@@ -3386,8 +3399,8 @@
      * is set, the default value 2 is used.
      * @hide
      */
-    public static final String
-            KEY_EUTRAN_RSSNR_HYSTERESIS_DB_INT = "eutran_rssnr_hysteresis_db_int";
+    public static final String KEY_EUTRAN_RSSNR_HYSTERESIS_DB_INT =
+            "eutran_rssnr_hysteresis_db_int";
 
     /**
      * Decides when clients try to bind to iwlan network service, which package name will
@@ -3436,6 +3449,7 @@
      */
     public static final String KEY_CARRIER_QUALIFIED_NETWORKS_SERVICE_CLASS_OVERRIDE_STRING =
             "carrier_qualified_networks_service_class_override_string";
+
     /**
      * A list of 4 WCDMA RSCP thresholds above which a signal level is considered POOR,
      * MODERATE, GOOD, or EXCELLENT, to be used in SignalStrength reporting.
@@ -3511,7 +3525,7 @@
 
     /**
      * Specifies a carrier-defined {@link android.telecom.CallRedirectionService} which Telecom
-     * will bind to for outgoing calls.  An empty string indicates that no carrier-defined
+     * will bind to for outgoing calls. An empty string indicates that no carrier-defined
      * {@link android.telecom.CallRedirectionService} is specified.
      */
     public static final String KEY_CALL_REDIRECTION_SERVICE_COMPONENT_NAME_STRING =
@@ -3811,7 +3825,7 @@
      * This configuration allows the framework to use user data communication to detect Idle state,
      * and this is used on the 5G icon.
      *
-     * There is a new way for for RRC state detection at Android 12. If
+     * There is a new way for RRC state detection at Android 12. If
      * {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}(
      * {@link TelephonyManager#CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED}) returns true,
      * then framework can use PHYSICAL_CHANNEL_CONFIG for RRC state detection. Based on this
@@ -3967,8 +3981,7 @@
      * FQDN (Fully Qualified Domain Name) of the SM-DP+ (e.g., smdp.gsma.com) restricted to the
      * Alphanumeric mode character set defined in table 5 of ISO/IEC 18004 excluding '$'.
      */
-    public static final String KEY_SMDP_SERVER_ADDRESS_STRING =
-            "smdp_server_address_string";
+    public static final String KEY_SMDP_SERVER_ADDRESS_STRING = "smdp_server_address_string";
 
     /**
      * This timer value is used in the eSIM Exponential Backoff download retry algorithm.
@@ -4019,7 +4032,7 @@
     public static final String KEY_OPPORTUNISTIC_ESIM_DOWNLOAD_VIA_WIFI_ONLY_BOOL =
             "opportunistic_esim_download_via_wifi_only_bool";
 
-/**
+    /**
      * Controls RSRP threshold, in dBm, at which OpportunisticNetworkService will decide whether
      * the opportunistic network is good enough for internet data.
      *
@@ -4113,6 +4126,7 @@
      */
     public static final String KEY_OPPORTUNISTIC_NETWORK_PING_PONG_TIME_LONG =
             "opportunistic_network_ping_pong_time_long";
+
     /**
      * Controls back off time in milli seconds for switching back to
      * opportunistic subscription. This time will be added to
@@ -4332,7 +4346,7 @@
          * If opportunistic network is determined as out of service or below
          * {@link #KEY_EXIT_THRESHOLD_SS_RSRP_INT} or
          * {@link #KEY_EXIT_THRESHOLD_SS_RSRQ_DOUBLE} within
-         * {@link #KEY_5G_PING_PONG_TIME_LONG} of switching to opportunistic network,
+         * the time specified by this carrier config of switching to opportunistic network,
          * it will be determined as ping pong situation by system app or 1st party app.
          *
          * @hide
@@ -4388,29 +4402,30 @@
     public static final String KEY_ENABLE_4G_OPPORTUNISTIC_NETWORK_SCAN_BOOL =
             "enabled_4g_opportunistic_network_scan_bool";
 
-  /**
-   * Only relevant when the device supports opportunistic networks but does not support
-   * simultaneuous 5G+5G. Controls how long, in milliseconds, to wait before opportunistic network
-   * goes out of service before switching the 5G capability back to primary stack. The idea of
-   * waiting a few seconds is to minimize the calling of the expensive capability switching
-   * operation in the case where CBRS goes back into service shortly after going out of it.
-   *
-   * @hide
-   */
-  public static final String KEY_TIME_TO_SWITCH_BACK_TO_PRIMARY_IF_OPPORTUNISTIC_OOS_LONG =
+    /**
+     * Only relevant when the device supports opportunistic networks but does not support
+     * simultaneous 5G+5G. Controls how long, in milliseconds, to wait before opportunistic network
+     * goes out of service before switching the 5G capability back to primary stack. The idea of
+     * waiting a few seconds is to minimize the calling of the expensive capability switching
+     * operation in the case where CBRS goes back into service shortly after going out of it.
+     *
+     * @hide
+     */
+    public static final String KEY_TIME_TO_SWITCH_BACK_TO_PRIMARY_IF_OPPORTUNISTIC_OOS_LONG =
             "time_to_switch_back_to_primary_if_opportunistic_oos_long";
 
-  /**
-   * Only relevant when the device supports opportunistic networks but does not support
-   * simultaneuous 5G+5G. Controls how long, in milliseconds, after 5G capability has switched back
-   * to primary stack due to opportunistic network being OOS. The idea is to minimizing the
-   * 'ping-ponging' effect where device is constantly witching capability back and forth between
-   * primary and opportunistic stack.
-   *
-   * @hide
-   */
-  public static final String KEY_OPPORTUNISTIC_TIME_TO_SCAN_AFTER_CAPABILITY_SWITCH_TO_PRIMARY_LONG
-          = "opportunistic_time_to_scan_after_capability_switch_to_primary_long";
+    /**
+     * Only relevant when the device supports opportunistic networks but does not support
+     * simultaneous 5G+5G. Controls how long, in milliseconds, after 5G capability has switched back
+     * to primary stack due to opportunistic network being OOS. The idea is to minimizing the
+     * 'ping-ponging' effect where device is constantly witching capability back and forth between
+     * primary and opportunistic stack.
+     *
+     * @hide
+     */
+    public static final String
+            KEY_OPPORTUNISTIC_TIME_TO_SCAN_AFTER_CAPABILITY_SWITCH_TO_PRIMARY_LONG =
+            "opportunistic_time_to_scan_after_capability_switch_to_primary_long";
 
     /**
      * Indicates zero or more emergency number prefix(es), because some carrier requires
@@ -4537,8 +4552,7 @@
      * @hide
      */
     @SystemApi
-    public static final String KEY_GBA_UA_SECURITY_PROTOCOL_INT =
-            "gba_ua_security_protocol_int";
+    public static final String KEY_GBA_UA_SECURITY_PROTOCOL_INT = "gba_ua_security_protocol_int";
 
     /**
      * An integer representing the cipher suite to be used when building the
@@ -4548,8 +4562,7 @@
      * @hide
      */
     @SystemApi
-    public static final String KEY_GBA_UA_TLS_CIPHER_SUITE_INT =
-            "gba_ua_tls_cipher_suite_int";
+    public static final String KEY_GBA_UA_TLS_CIPHER_SUITE_INT = "gba_ua_tls_cipher_suite_int";
 
     /**
      * The data stall recovery timers array in milliseconds, each element is the delay before
@@ -4708,7 +4721,6 @@
          */
         public static final int SUPL_EMERGENCY_MODE_TYPE_DP_ONLY = 2;
 
-
         /**
          * Determine whether current lpp_mode used for E-911 needs to be kept persistently.
          * {@code false} - not keeping the lpp_mode means using default configuration of gps.conf
@@ -4826,8 +4838,8 @@
          * The default value for this configuration is {@link #SUPL_EMERGENCY_MODE_TYPE_CP_ONLY}.
          * @hide
          */
-        public static final String KEY_ES_SUPL_CONTROL_PLANE_SUPPORT_INT = KEY_PREFIX
-                + "es_supl_control_plane_support_int";
+        public static final String KEY_ES_SUPL_CONTROL_PLANE_SUPPORT_INT =
+                KEY_PREFIX + "es_supl_control_plane_support_int";
 
         /**
          * A list of roaming PLMNs where SUPL ES mode does not support a control-plane mechanism to
@@ -4862,13 +4874,14 @@
         }
     }
 
-   /**
-    * An int array containing CDMA enhanced roaming indicator values for Home (non-roaming) network.
-    * The default values come from 3GPP2 C.R1001 table 8.1-1.
-    * Enhanced Roaming Indicator Number Assignments
-    *
-    * @hide
-    */
+    /**
+     * An int array containing CDMA enhanced roaming indicator values for Home (non-roaming)
+     * network.
+     * The default values come from 3GPP2 C.R1001 table 8.1-1.
+     * Enhanced Roaming Indicator Number Assignments
+     *
+     * @hide
+     */
     public static final String KEY_CDMA_ENHANCED_ROAMING_INDICATOR_FOR_HOME_NETWORK_INT_ARRAY =
             "cdma_enhanced_roaming_indicator_for_home_network_int_array";
 
@@ -4880,7 +4893,7 @@
 
     /**
      * Indicates use 3GPP application to replace 3GPP2 application even if it's a CDMA/CDMA-LTE
-     * phone, becasue some carriers's CSIM application is present but not supported.
+     * phone, because some carriers' CSIM application is present but not supported.
      * @hide
      */
     public static final String KEY_USE_USIM_BOOL = "use_usim_bool";
@@ -4943,8 +4956,7 @@
      * {@see SubscriptionInfo#getUsageSetting}
      *
      */
-    public static final String KEY_CELLULAR_USAGE_SETTING_INT =
-            "cellular_usage_setting_int";
+    public static final String KEY_CELLULAR_USAGE_SETTING_INT = "cellular_usage_setting_int";
 
     /**
      * Data switch validation minimal gap time, in milliseconds.
@@ -5008,7 +5020,7 @@
      * "Carrier Provisioning Info" or "Trigger Carrier Provisioning" button clicked.
      *
      * <p>
-     * e.g, com.google.android.carrierPackageName/.CarrierReceiverName
+     * e.g., com.google.android.carrierPackageName/.CarrierReceiverName
      *
      * @hide
      */
@@ -5048,9 +5060,9 @@
          * Capability Exchange (UCE). See RCC.71, section 3 for more information.
          * <p>
          * If this key's value is set to false, the procedure for RCS contact capability exchange
-         * via SIP SUBSCRIBE/NOTIFY will also be disabled internally, and
-         * {@link Ims#KEY_ENABLE_PRESENCE_PUBLISH_BOOL} must also be set to false to ensure
-         * apps do not improperly think that capability exchange via SIP PUBLISH is enabled.
+         * via SIP SUBSCRIBE/NOTIFY will also be disabled internally, and this key must also be set
+         * to false to ensure apps do not improperly think that capability exchange via SIP PUBLISH
+         * is enabled.
          * <p> The default value for this key is {@code false}.
          */
         public static final String KEY_ENABLE_PRESENCE_PUBLISH_BOOL =
@@ -5106,7 +5118,6 @@
         public static final String KEY_ENABLE_PRESENCE_CAPABILITY_EXCHANGE_BOOL =
                 KEY_PREFIX + "enable_presence_capability_exchange_bool";
 
-
         /**
          * Flag indicating whether or not the carrier expects the RCS UCE service to periodically
          * refresh the RCS capabilities cache of the user's contacts as well as request the
@@ -5240,7 +5251,7 @@
                 KEY_PREFIX + "sip_timer_j_millis_int";
 
         /** Specifies the SIP Server default port. */
-        public static final String KEY_SIP_SERVER_PORT_NUMBER_INT  =
+        public static final String KEY_SIP_SERVER_PORT_NUMBER_INT =
                 KEY_PREFIX + "sip_server_port_number_int";
 
         /**
@@ -5252,7 +5263,6 @@
 
         /** @hide */
         @IntDef({REQUEST_URI_FORMAT_TEL, REQUEST_URI_FORMAT_SIP})
-
         public @interface RequestUriFormatType {}
 
         /**
@@ -5299,7 +5309,6 @@
             PREFERRED_TRANSPORT_DYNAMIC_UDP_TCP,
             PREFERRED_TRANSPORT_TLS
         })
-
         public @interface PreferredTransportType {}
 
         /** Preferred Transport is always UDP. */
@@ -5380,7 +5389,6 @@
 
         /** @hide */
         @IntDef({IPSEC_AUTHENTICATION_ALGORITHM_HMAC_MD5, IPSEC_AUTHENTICATION_ALGORITHM_HMAC_SHA1})
-
         public @interface IpsecAuthenticationAlgorithmType {}
 
         /** IPSec Authentication algorithm is HMAC-MD5. see Annex H of TS 33.203 */
@@ -5405,7 +5413,6 @@
             IPSEC_ENCRYPTION_ALGORITHM_DES_EDE3_CBC,
             IPSEC_ENCRYPTION_ALGORITHM_AES_CBC
         })
-
         public @interface IpsecEncryptionAlgorithmType {}
 
         /** IPSec Encryption algorithm is NULL. see Annex H of TS 33.203 */
@@ -5464,7 +5471,6 @@
             GEOLOCATION_PIDF_FOR_NON_EMERGENCY_ON_CELLULAR,
             GEOLOCATION_PIDF_FOR_EMERGENCY_ON_CELLULAR
         })
-
         public @interface GeolocationPidfAllowedType {}
 
         /**
@@ -5558,7 +5564,6 @@
             NETWORK_TYPE_HOME,
             NETWORK_TYPE_ROAMING
         })
-
         public @interface NetworkType {}
 
         /** Indicates HOME Network. */
@@ -5575,7 +5580,6 @@
             E911_RTCP_INACTIVITY_ON_CONNECTED,
             E911_RTP_INACTIVITY_ON_CONNECTED
         })
-
         public @interface MediaInactivityReason {}
 
         /**  RTCP inactivity occurred when call is on HOLD. */
@@ -5621,7 +5625,7 @@
          *     <li>{@link #KEY_CAPABILITY_TYPE_CALL_COMPOSER_INT_ARRAY}</li>
          * </ul>
          * <p> The values are defined in
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationTech}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech}
          *
          * changing mmtel_requires_provisioning_bundle requires changes to
          * carrier_volte_provisioning_required_bool and vice versa
@@ -5635,10 +5639,10 @@
          * is supported.
          * @see MmTelFeature.MmTelCapabilities#CAPABILITY_TYPE_VOICE
          * <p>Possible values are,
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
          */
         public static final String KEY_CAPABILITY_TYPE_VOICE_INT_ARRAY =
                 KEY_PREFIX + "capability_type_voice_int_array";
@@ -5648,10 +5652,10 @@
          * is supported.
          * @see MmTelFeature.MmTelCapabilities#CAPABILITY_TYPE_VIDEO
          * <p>Possible values are,
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
          */
         public static final String KEY_CAPABILITY_TYPE_VIDEO_INT_ARRAY =
                 KEY_PREFIX + "capability_type_video_int_array";
@@ -5661,10 +5665,10 @@
          * supplementary services. (IR.92) is supported.
          * @see MmTelFeature.MmTelCapabilities#CAPABILITY_TYPE_UT
          * <p>Possible values are,
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
          */
         public static final String KEY_CAPABILITY_TYPE_UT_INT_ARRAY =
                 KEY_PREFIX + "capability_type_ut_int_array";
@@ -5673,10 +5677,10 @@
          * List of different RAT technologies on which Provisioning for SMS (IR.92) is supported.
          * @see MmTelFeature.MmTelCapabilities#CAPABILITY_TYPE_SMS
          * <p>Possible values are,
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
          */
         public static final String KEY_CAPABILITY_TYPE_SMS_INT_ARRAY =
                 KEY_PREFIX + "capability_type_sms_int_array";
@@ -5686,10 +5690,10 @@
          * (section 2.4 of RCC.20) is supported.
          * @see MmTelFeature.MmTelCapabilities#CAPABILITY_TYPE_CALL_COMPOSER
          * <p>Possible values are,
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
          */
         public static final String KEY_CAPABILITY_TYPE_CALL_COMPOSER_INT_ARRAY =
                 KEY_PREFIX + "capability_type_call_composer_int_array";
@@ -5705,7 +5709,7 @@
          *     <li>{@link #KEY_CAPABILITY_TYPE_PRESENCE_UCE_INT_ARRAY}</li>
          * </ul>
          * <p> The values are defined in
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationTech}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech}
          */
         public static final String KEY_RCS_REQUIRES_PROVISIONING_BUNDLE =
                 KEY_PREFIX + "rcs_requires_provisioning_bundle";
@@ -5716,10 +5720,10 @@
          * If not set, this RcsFeature should not service capability requests.
          * @see RcsFeature.RcsImsCapabilities#CAPABILITY_TYPE_OPTIONS_UCE
          * <p>Possible values are,
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
          */
         public static final String KEY_CAPABILITY_TYPE_OPTIONS_UCE_INT_ARRAY =
                 KEY_PREFIX + "capability_type_options_uce_int_array";
@@ -5731,10 +5735,10 @@
          * requests using presence.
          * @see RcsFeature.RcsImsCapabilities#CAPABILITY_TYPE_PRESENCE_UCE
          * <p>Possible values are,
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
-         * {@link android.telephony.ims.stub.ImsRegistrationImplBase.ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_LTE}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_IWLAN}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_CROSS_SIM}
+         * {@link ImsRegistrationImplBase.ImsRegistrationTech#REGISTRATION_TECH_NR}
          */
         public static final String KEY_CAPABILITY_TYPE_PRESENCE_UCE_INT_ARRAY =
                 KEY_PREFIX + "capability_type_presence_uce_int_array";
@@ -5747,7 +5751,7 @@
             defaults.putBoolean(KEY_IMS_SINGLE_REGISTRATION_REQUIRED_BOOL, false);
             defaults.putBoolean(KEY_ENABLE_PRESENCE_PUBLISH_BOOL, false);
             defaults.putStringArray(KEY_PUBLISH_SERVICE_DESC_FEATURE_TAG_MAP_OVERRIDE_STRING_ARRAY,
-                    new String[] {});
+                    new String[0]);
             defaults.putBoolean(KEY_ENABLE_PRESENCE_CAPABILITY_EXCHANGE_BOOL, false);
             defaults.putBoolean(KEY_RCS_BULK_CAPABILITY_EXCHANGE_BOOL, false);
             defaults.putBoolean(KEY_ENABLE_PRESENCE_GROUP_SUBSCRIBE_BOOL, false);
@@ -5872,7 +5876,7 @@
          * <p>If {@code false}: hard disabled.
          * If {@code true}: then depends on availability, etc.
          */
-        public static final String KEY_CARRIER_VOLTE_ROAMING_AVAILABLE_BOOL  =
+        public static final String KEY_CARRIER_VOLTE_ROAMING_AVAILABLE_BOOL =
                 KEY_PREFIX + "carrier_volte_roaming_available_bool";
 
         /**
@@ -5883,7 +5887,7 @@
          * will be sent in the dialed string in the SIP:INVITE.
          * If {@code false}, *67 and *82 will be removed.
          */
-        public static final String KEY_INCLUDE_CALLER_ID_SERVICE_CODES_IN_SIP_INVITE_BOOL  =
+        public static final String KEY_INCLUDE_CALLER_ID_SERVICE_CODES_IN_SIP_INVITE_BOOL =
                 KEY_PREFIX + "include_caller_id_service_codes_in_sip_invite_bool";
 
         /**
@@ -5927,7 +5931,6 @@
             SESSION_REFRESHER_TYPE_UAC,
             SESSION_REFRESHER_TYPE_UAS
         })
-
         public @interface SessionRefresherType {}
 
         /**
@@ -5969,14 +5972,12 @@
         public static final String KEY_SESSION_REFRESHER_TYPE_INT =
                 KEY_PREFIX + "session_refresher_type_int";
 
-
         /** @hide */
         @IntDef({
             SESSION_PRIVACY_TYPE_HEADER,
             SESSION_PRIVACY_TYPE_NONE,
             SESSION_PRIVACY_TYPE_ID
         })
-
         public @interface SessionPrivacyType {}
 
         /**
@@ -6014,7 +6015,7 @@
          * If {@code true},  SIP 18x responses (other than SIP 183 response)
          * are sent reliably.
          */
-        public static final String KEY_PRACK_SUPPORTED_FOR_18X_BOOL  =
+        public static final String KEY_PRACK_SUPPORTED_FOR_18X_BOOL =
                 KEY_PREFIX + "prack_supported_for_18x_bool";
 
         /** @hide */
@@ -6022,7 +6023,6 @@
             CONFERENCE_SUBSCRIBE_TYPE_IN_DIALOG,
             CONFERENCE_SUBSCRIBE_TYPE_OUT_OF_DIALOG
         })
-
         public @interface ConferenceSubscribeType {}
 
         /**
@@ -6043,7 +6043,7 @@
 
         /**
          * This is used to specify whether the SIP SUBSCRIBE to conference state events,
-         * is sent in or out of the  SIP INVITE dialog between the UE and the
+         * is sent in or out of the SIP INVITE dialog between the UE and the
          * conference server.
          *
          * <p>Reference: IR.92 Section 2.3.3.
@@ -6068,7 +6068,7 @@
          *
          * <p>Reference: 3GPP TS 24.229
          */
-        public static final String KEY_VOICE_QOS_PRECONDITION_SUPPORTED_BOOL  =
+        public static final String KEY_VOICE_QOS_PRECONDITION_SUPPORTED_BOOL =
                 KEY_PREFIX + "voice_qos_precondition_supported_bool";
 
         /**
@@ -6076,7 +6076,7 @@
          *
          * <p>If {@code true}: voice packets can be sent on default bearer. {@code false} otherwise.
          */
-        public static final String KEY_VOICE_ON_DEFAULT_BEARER_SUPPORTED_BOOL  =
+        public static final String KEY_VOICE_ON_DEFAULT_BEARER_SUPPORTED_BOOL =
                 KEY_PREFIX + "voice_on_default_bearer_supported_bool";
 
         /**
@@ -6098,7 +6098,6 @@
             PREALERTING_SRVCC_SUPPORT,
             MIDCALL_SRVCC_SUPPORT
         })
-
         public @interface SrvccType {}
 
         /**
@@ -6196,7 +6195,6 @@
             SESSION_REFRESH_METHOD_INVITE,
             SESSION_REFRESH_METHOD_UPDATE_PREFERRED
         })
-
         public @interface SessionRefreshMethod {}
 
         /**
@@ -6231,7 +6229,7 @@
          * determination of the originating party identity in OIP.
          * {@code false} otherwise.
          */
-        public static final String KEY_OIP_SOURCE_FROM_HEADER_BOOL  =
+        public static final String KEY_OIP_SOURCE_FROM_HEADER_BOOL =
                 KEY_PREFIX + "oip_source_from_header_bool";
 
         /**
@@ -6319,7 +6317,7 @@
          * <p>Payload type is an integer in dynamic payload type range 96-127
          * as per RFC RFC 3551 Section 6.
          */
-        public static final String KEY_EVS_PAYLOAD_TYPE_INT_ARRAY  =
+        public static final String KEY_EVS_PAYLOAD_TYPE_INT_ARRAY =
                 KEY_PREFIX + "evs_payload_type_int_array";
 
         /**
@@ -6328,7 +6326,7 @@
          * <p>Payload type is an integer in dynamic payload type range 96-127
          * as per RFC RFC 3551 Section 6.
          */
-        public static final String KEY_AMRWB_PAYLOAD_TYPE_INT_ARRAY  =
+        public static final String KEY_AMRWB_PAYLOAD_TYPE_INT_ARRAY =
                 KEY_PREFIX + "amrwb_payload_type_int_array";
 
         /**
@@ -6337,7 +6335,7 @@
          * <p>Payload type is an integer in dynamic payload type range 96-127
          * as per RFC RFC 3551 Section 6.
          */
-        public static final String KEY_AMRNB_PAYLOAD_TYPE_INT_ARRAY  =
+        public static final String KEY_AMRNB_PAYLOAD_TYPE_INT_ARRAY =
                 KEY_PREFIX + "amrnb_payload_type_int_array";
 
         /**
@@ -6346,7 +6344,7 @@
          * <p>Payload type is an integer in dynamic payload type range 96-127
          * as per RFC RFC 3551 Section 6.
          */
-        public static final String KEY_DTMFWB_PAYLOAD_TYPE_INT_ARRAY  =
+        public static final String KEY_DTMFWB_PAYLOAD_TYPE_INT_ARRAY =
                 KEY_PREFIX + "dtmfwb_payload_type_int_array";
 
         /**
@@ -6355,7 +6353,7 @@
          * <p>Payload type is an integer in dynamic payload type range 96-127
          * as per RFC RFC 3551 Section 6.
          */
-        public static final String KEY_DTMFNB_PAYLOAD_TYPE_INT_ARRAY  =
+        public static final String KEY_DTMFNB_PAYLOAD_TYPE_INT_ARRAY =
                 KEY_PREFIX + "dtmfnb_payload_type_int_array";
 
         /**
@@ -6372,7 +6370,6 @@
         public static final String KEY_VOICE_RTP_PACKET_LOSS_RATE_THRESHOLD_INT =
                 KEY_PREFIX + "rtp_packet_loss_rate_threshold_int";
 
-
         /**
          * This indicates the threshold for RTP jitter value in milliseconds (RFC3550). If measured
          * jitter value crosses this, a callback with {@link MediaQualityStatus} will be invoked
@@ -6401,13 +6398,11 @@
         public static final String KEY_VOICE_RTP_INACTIVITY_TIME_THRESHOLD_MILLIS_LONG =
                 KEY_PREFIX + "rtp_inactivity_time_threshold_millis_long";
 
-
         /** @hide */
         @IntDef({
             BANDWIDTH_EFFICIENT,
             OCTET_ALIGNED
         })
-
         public @interface AmrPayloadFormat {}
 
         /** AMR NB/WB Payload format is bandwidth-efficient. */
@@ -6428,7 +6423,7 @@
          *
          * <p>Reference: RFC 4867 Section 8.1.
          */
-        public static final String KEY_AMR_CODEC_ATTRIBUTE_PAYLOAD_FORMAT_INT  =
+        public static final String KEY_AMR_CODEC_ATTRIBUTE_PAYLOAD_FORMAT_INT =
                 KEY_PREFIX + "amr_codec_attribute_payload_format_int";
 
         /**
@@ -6443,7 +6438,7 @@
          * <p>Possible values are subset of,
          * [0,1,2,3,4,5,6,7,8] - AMRWB with the modes representing nine speech codec modes
          * with bit rates of 6.6, 8.85, 12.65, 14.25,  15.85, 18.25, 19.85, 23.05, 23.85 kbps.
-         * [0,1,2,3,4,5,6,7] - AMRNB  with the modes representing eight speech codec modes
+         * [0,1,2,3,4,5,6,7] - AMRNB with the modes representing eight speech codec modes
          * with bit rates of 4.75, 5.15, 5.90, 6.70, 7.40, 7.95, 10.2, 12.2 kbps.
          *
          * <p>If value is not specified, then it means device supports all
@@ -6451,7 +6446,7 @@
          *
          * <p>Reference: RFC 4867 Section 8.1, 3GPP 26.445 A.3.1
          */
-        public static final String KEY_AMR_CODEC_ATTRIBUTE_MODESET_INT_ARRAY  =
+        public static final String KEY_AMR_CODEC_ATTRIBUTE_MODESET_INT_ARRAY =
                 KEY_PREFIX + "amr_codec_attribute_modeset_int_array";
 
         /**
@@ -6501,7 +6496,6 @@
             EVS_OPERATIONAL_MODE_PRIMARY,
             EVS_OPERATIONAL_MODE_AMRWB_IO
         })
-
         public @interface EvsOperationalMode {}
 
         /**  Indicates the EVS primary mode. 3GPP 26.445 Section 3.1 */
@@ -6536,7 +6530,6 @@
             EVS_ENCODED_BW_TYPE_WB_SWB,
             EVS_ENCODED_BW_TYPE_WB_SWB_FB
         })
-
         public @interface EvsEncodedBwType {}
 
         /**
@@ -6612,7 +6605,7 @@
          *
          * <p>Reference: 3GPP 26.441 Table 1.
          */
-        public static final String KEY_EVS_CODEC_ATTRIBUTE_BANDWIDTH_INT  =
+        public static final String KEY_EVS_CODEC_ATTRIBUTE_BANDWIDTH_INT =
                 KEY_PREFIX + "evs_codec_attribute_bandwidth_int";
 
         /** @hide */
@@ -6630,7 +6623,6 @@
             EVS_PRIMARY_MODE_BITRATE_96_0_KBPS,
             EVS_PRIMARY_MODE_BITRATE_128_0_KBPS
         })
-
         public @interface EvsPrimaryModeBitRate {}
 
         /** EVS primary mode with bitrate 5.9 kbps */
@@ -6696,14 +6688,14 @@
          *
          * <p>Reference: 3GPP 26.445 Section A.3.1
          */
-        public static final String KEY_EVS_CODEC_ATTRIBUTE_BITRATE_INT_ARRAY  =
+        public static final String KEY_EVS_CODEC_ATTRIBUTE_BITRATE_INT_ARRAY =
                 KEY_PREFIX + "evs_codec_attribute_bitrate_int_array";
 
         /**
          * Specifies the Channel aware mode (ch-aw-recv) for the receive direction.
          * This is applicable for EVS codec.
          *
-         * <p>Permissible values  are -1, 0, 2, 3, 5, and 7.
+         * <p> Permissible values are -1, 0, 2, 3, 5, and 7.
          * If this key is not specified, then the behavior is same as value 0
          * (channel aware mode disabled).
          * <p> If this key is configured, then device is expected to send
@@ -6711,7 +6703,7 @@
          *
          * <p>Reference: 3GPP TS 26.445 section 4.4.5, 3GPP 26.445 Section A.3.1
          */
-        public static final String KEY_EVS_CODEC_ATTRIBUTE_CH_AW_RECV_INT  =
+        public static final String KEY_EVS_CODEC_ATTRIBUTE_CH_AW_RECV_INT =
                 KEY_PREFIX + "evs_codec_attribute_ch_aw_recv_int";
 
         /**
@@ -6732,7 +6724,7 @@
          *
          * <p>Reference: 3GPP 26.445 Section A.3.1.
          */
-        public static final String KEY_EVS_CODEC_ATTRIBUTE_HF_ONLY_INT  =
+        public static final String KEY_EVS_CODEC_ATTRIBUTE_HF_ONLY_INT =
                 KEY_PREFIX + "evs_codec_attribute_hf_only_int";
 
         /**
@@ -6748,7 +6740,7 @@
          * will apply.
          * <p>Reference: 3GPP TS 26.445 Section A.3.1.
          */
-        public static final String KEY_EVS_CODEC_ATTRIBUTE_DTX_BOOL  =
+        public static final String KEY_EVS_CODEC_ATTRIBUTE_DTX_BOOL =
                 KEY_PREFIX + "evs_codec_attribute_dtx_bool";
 
         /**
@@ -6773,7 +6765,7 @@
          *
          * <p>Reference: RFC 3551
          */
-        public static final String KEY_EVS_CODEC_ATTRIBUTE_CHANNELS_INT  =
+        public static final String KEY_EVS_CODEC_ATTRIBUTE_CHANNELS_INT =
                 KEY_PREFIX + "evs_codec_attribute_channels_int";
 
         /**
@@ -6786,7 +6778,7 @@
          *
          * <p>Reference: 3GPP 26.445 Section A.3.1, 3GPP 26.114 Table 6.2a
          */
-        public static final String KEY_EVS_CODEC_ATTRIBUTE_CMR_INT  =
+        public static final String KEY_EVS_CODEC_ATTRIBUTE_CMR_INT =
                 KEY_PREFIX + "codec_attribute_cmr_int";
 
         /**
@@ -6800,7 +6792,7 @@
          *
          * <p>Reference: RFC 4867 Section 8.1.
          */
-        public static final String KEY_CODEC_ATTRIBUTE_MODE_CHANGE_PERIOD_INT  =
+        public static final String KEY_CODEC_ATTRIBUTE_MODE_CHANGE_PERIOD_INT =
                 KEY_PREFIX + "codec_attribute_mode_change_period_int";
 
         /**
@@ -6814,7 +6806,7 @@
          *
          * <p>Reference: RFC 4867 Section 8.1.
          */
-        public static final String KEY_CODEC_ATTRIBUTE_MODE_CHANGE_CAPABILITY_INT  =
+        public static final String KEY_CODEC_ATTRIBUTE_MODE_CHANGE_CAPABILITY_INT =
                 KEY_PREFIX + "codec_attribute_mode_change_capability_int";
 
         /**
@@ -6822,7 +6814,7 @@
          * This attribute is applicable for EVS codec in AMR-WB IO mode
          * and AMR-WB.
          *
-         * <p>Possible values are 0, 1.  If value is 1, then the sender should only
+         * <p>Possible values are 0, 1. If value is 1, then the sender should only
          * perform mode changes to the neighboring modes in the active codec mode set.
          * If value is 0, then mode changes between any two modes
          * in the active codec mode set is allowed.
@@ -6831,7 +6823,7 @@
          *
          * <p>Reference: RFC 4867 Section 8.1.
          */
-        public static final String KEY_CODEC_ATTRIBUTE_MODE_CHANGE_NEIGHBOR_INT  =
+        public static final String KEY_CODEC_ATTRIBUTE_MODE_CHANGE_NEIGHBOR_INT =
                 KEY_PREFIX + "codec_attribute_mode_change_neighbor_int";
 
         /**
@@ -6995,7 +6987,7 @@
          * <p>If {@code true}: SMS over IMS support available.
          * {@code false}: otherwise.
          */
-        public static final String KEY_SMS_OVER_IMS_SUPPORTED_BOOL  =
+        public static final String KEY_SMS_OVER_IMS_SUPPORTED_BOOL =
                 KEY_PREFIX + "sms_over_ims_supported_bool";
 
         /**
@@ -7005,7 +6997,7 @@
          * <p>If {@code true}: allow SMS CSFB in case of SMS over PS failure.
          * {@code false} otherwise.
          */
-        public static final String KEY_SMS_CSFB_RETRY_ON_FAILURE_BOOL  =
+        public static final String KEY_SMS_CSFB_RETRY_ON_FAILURE_BOOL =
                 KEY_PREFIX + "sms_csfb_retry_on_failure_bool";
 
         /** @hide */
@@ -7013,7 +7005,6 @@
             SMS_FORMAT_3GPP,
             SMS_FORMAT_3GPP2
         })
-
         public @interface SmsFormat {}
 
         /** SMS format is 3GPP. */
@@ -7192,7 +7183,7 @@
          * <p>If {@code true}: text media can be sent on default bearer.
          * {@code false} otherwise.
          */
-        public static final String KEY_TEXT_ON_DEFAULT_BEARER_SUPPORTED_BOOL  =
+        public static final String KEY_TEXT_ON_DEFAULT_BEARER_SUPPORTED_BOOL =
                 KEY_PREFIX + "text_on_default_bearer_supported_bool";
 
         /**
@@ -7202,7 +7193,7 @@
          * {@code false} otherwise.
          * <p>Reference: 3GPP TS 24.229
          */
-        public static final String KEY_TEXT_QOS_PRECONDITION_SUPPORTED_BOOL  =
+        public static final String KEY_TEXT_QOS_PRECONDITION_SUPPORTED_BOOL =
                 KEY_PREFIX + "text_qos_precondition_supported_bool";
 
         /**
@@ -7252,14 +7243,14 @@
          * <p>Payload type is an integer in dynamic payload type range 96-127
          * as per RFC RFC 3551 Section 6.
          */
-        public static final String KEY_T140_PAYLOAD_TYPE_INT  =
+        public static final String KEY_T140_PAYLOAD_TYPE_INT =
                 KEY_PREFIX + "t140_payload_type_int";
 
         /** Integer representing payload type for RED/redundancy codec.
          * <p>Payload type is an integer in dynamic payload type range 96-127
          * as per RFC RFC 3551 Section 6.
          */
-        public static final String KEY_RED_PAYLOAD_TYPE_INT  =
+        public static final String KEY_RED_PAYLOAD_TYPE_INT =
                 KEY_PREFIX + "red_payload_type_int";
 
         private static PersistableBundle getDefaults() {
@@ -7308,7 +7299,7 @@
          * <p>If {@code true}: Allow UE to retry emergency call on
          * IMS PDN if emergency PDN setup failed.{@code false} otherwise.
          */
-        public static final String KEY_RETRY_EMERGENCY_ON_IMS_PDN_BOOL  =
+        public static final String KEY_RETRY_EMERGENCY_ON_IMS_PDN_BOOL =
                 KEY_PREFIX + "retry_emergency_on_ims_pdn_bool";
 
         /**
@@ -7318,7 +7309,7 @@
          * <p>If {@code true}: Enter ECBM mode after E911 call is ended.
          * {@code false} otherwise.
          */
-        public static final String KEY_EMERGENCY_CALLBACK_MODE_SUPPORTED_BOOL  =
+        public static final String KEY_EMERGENCY_CALLBACK_MODE_SUPPORTED_BOOL =
                 KEY_PREFIX + "emergency_callback_mode_supported_bool";
 
         /**
@@ -7330,7 +7321,7 @@
          *
          * <p>Reference: 3GPP TS 24.229
          */
-        public static final String KEY_EMERGENCY_QOS_PRECONDITION_SUPPORTED_BOOL  =
+        public static final String KEY_EMERGENCY_QOS_PRECONDITION_SUPPORTED_BOOL =
                 KEY_PREFIX + "emergency_qos_precondition_supported_bool";
 
         /**
@@ -7737,7 +7728,7 @@
             defaults.putBoolean(KEY_EMERGENCY_LTE_PREFERRED_AFTER_NR_FAILED_BOOL, false);
             defaults.putBoolean(KEY_EMERGENCY_REQUIRES_VOLTE_ENABLED_BOOL, false);
             defaults.putStringArray(KEY_EMERGENCY_CDMA_PREFERRED_NUMBERS_STRING_ARRAY,
-                    new String[] {});
+                    new String[0]);
 
             return defaults;
         }
@@ -7758,7 +7749,7 @@
          * <p>If {@code true}: video media can be sent on default bearer.
          * {@code false} otherwise.
          */
-        public static final String KEY_VIDEO_ON_DEFAULT_BEARER_SUPPORTED_BOOL  =
+        public static final String KEY_VIDEO_ON_DEFAULT_BEARER_SUPPORTED_BOOL =
                 KEY_PREFIX + "video_on_default_bearer_supported_bool";
 
         /**
@@ -7824,7 +7815,7 @@
          * {@code false} otherwise.
          * <p>Reference: 3GPP TS 24.229
          */
-        public static final String KEY_VIDEO_QOS_PRECONDITION_SUPPORTED_BOOL  =
+        public static final String KEY_VIDEO_QOS_PRECONDITION_SUPPORTED_BOOL =
                 KEY_PREFIX + "video_qos_precondition_supported_bool";
 
         /**
@@ -7849,7 +7840,7 @@
          * <p>Payload type is an integer in dynamic payload type range 96-127
          * as per RFC RFC 3551 Section 6.
          */
-        public static final String KEY_H264_PAYLOAD_TYPE_INT_ARRAY  =
+        public static final String KEY_H264_PAYLOAD_TYPE_INT_ARRAY =
                 KEY_PREFIX + "h264_payload_type_int_array";
 
         /**
@@ -7891,7 +7882,7 @@
          *
          * <p>Reference: RFC 6184 Section 5.4
          */
-        public static final String KEY_VIDEO_CODEC_ATTRIBUTE_PACKETIZATION_MODE_INT  =
+        public static final String KEY_VIDEO_CODEC_ATTRIBUTE_PACKETIZATION_MODE_INT =
                 KEY_PREFIX + "video_codec_attribute_packetization_mode_int";
 
         /**
@@ -7905,7 +7896,7 @@
          * <UL>
          * <p>Reference: RFC 4566 Section 6, 3GPP 26.114 Section 6.2.3.2
          */
-        public static final String KEY_VIDEO_CODEC_ATTRIBUTE_FRAME_RATE_INT  =
+        public static final String KEY_VIDEO_CODEC_ATTRIBUTE_FRAME_RATE_INT =
                 KEY_PREFIX + "video_codec_attribute_frame_rate_int";
 
         /**
@@ -7924,7 +7915,7 @@
          * <p>Reference: RFC 4566 Section 6, 3GPP 26.114 Section 6.2.3.2
          *
          */
-        public static final String KEY_VIDEO_CODEC_ATTRIBUTE_RESOLUTION_INT_ARRAY  =
+        public static final String KEY_VIDEO_CODEC_ATTRIBUTE_RESOLUTION_INT_ARRAY =
                 KEY_PREFIX + "video_codec_attribute_resolution_int_array";
 
         /**
@@ -7937,7 +7928,7 @@
          *
          * <p>Reference: RFC 6184 Section 8.1, ITU-T Recommendation H.264
          */
-        public static final String KEY_H264_VIDEO_CODEC_ATTRIBUTE_PROFILE_LEVEL_ID_STRING  =
+        public static final String KEY_H264_VIDEO_CODEC_ATTRIBUTE_PROFILE_LEVEL_ID_STRING =
                 KEY_PREFIX + "h264_video_codec_attribute_profile_level_id_string";
 
         private static PersistableBundle getDefaults() {
@@ -8005,7 +7996,7 @@
          *  List of MDNs for which Geo-location PIDF XML with country info
          *  needs to included for normal calls involving short code.
          */
-        public static final String KEY_PIDF_SHORT_CODE_STRING_ARRAY  =
+        public static final String KEY_PIDF_SHORT_CODE_STRING_ARRAY =
                 KEY_PREFIX + "pidf_short_code_string_array";
 
         /**
@@ -8015,15 +8006,14 @@
          * <p>If {@code false}: E911 call uses IMS PDN for E911 call over VoWiFi.
          * If {@code true}: E911 call uses Emergency PDN for E911 call over VoWiFi.
          */
-        public static final String KEY_EMERGENCY_CALL_OVER_EMERGENCY_PDN_BOOL  =
+        public static final String KEY_EMERGENCY_CALL_OVER_EMERGENCY_PDN_BOOL =
                 KEY_PREFIX + "emergency_call_over_emergency_pdn_bool";
 
-
         private static PersistableBundle getDefaults() {
             PersistableBundle defaults = new PersistableBundle();
 
             defaults.putBoolean(KEY_EMERGENCY_CALL_OVER_EMERGENCY_PDN_BOOL, false);
-            defaults.putStringArray(KEY_PIDF_SHORT_CODE_STRING_ARRAY, new String[] {});
+            defaults.putStringArray(KEY_PIDF_SHORT_CODE_STRING_ARRAY, new String[0]);
 
             return defaults;
         }
@@ -8070,7 +8060,7 @@
          * If XCAP over UT fails, return error.
          * if {@code true}, Use CSFB if XCAP over UT fails.
          */
-        public static final String KEY_USE_CSFB_ON_XCAP_OVER_UT_FAILURE_BOOL  =
+        public static final String KEY_USE_CSFB_ON_XCAP_OVER_UT_FAILURE_BOOL =
                 KEY_PREFIX + "use_csfb_on_xcap_over_ut_failure_bool";
 
         /**
@@ -8082,7 +8072,7 @@
          *
          * Reference: IR.92 Section 5.5.1
          */
-        public static final String KEY_UT_SUPPORTED_WHEN_PS_DATA_OFF_BOOL  =
+        public static final String KEY_UT_SUPPORTED_WHEN_PS_DATA_OFF_BOOL =
                 KEY_PREFIX + "ut_supported_when_ps_data_off_bool";
 
         /**
@@ -8092,7 +8082,7 @@
          * <p>If {@code true}:  Support Available.{@code false}: Otherwise.
          * Reference: 3GPP 24.390.
          */
-        public static final String KEY_NETWORK_INITIATED_USSD_OVER_IMS_SUPPORTED_BOOL  =
+        public static final String KEY_NETWORK_INITIATED_USSD_OVER_IMS_SUPPORTED_BOOL =
                 KEY_PREFIX + "network_initiated_ussd_over_ims_supported_bool";
 
         /**
@@ -8176,7 +8166,6 @@
             SUPPLEMENTARY_SERVICE_CB_ACR,
             SUPPLEMENTARY_SERVICE_CB_BIL
         })
-
         public @interface SsType {}
 
         /** Communication Waiting (CW) support as per 3GPP 24.615. */
@@ -8415,7 +8404,6 @@
             CALL_WAITING_SYNC_FIRST_CHANGE,
             CALL_WAITING_SYNC_IMS_ONLY
         })
-
         public @interface CwSyncType {}
 
         /**
@@ -8540,9 +8528,7 @@
                         SUPPLEMENTARY_SERVICE_CB_ACR,
                         SUPPLEMENTARY_SERVICE_CB_BIL
                     });
-            defaults.putIntArray(
-                    KEY_UT_TERMINAL_BASED_SERVICES_INT_ARRAY,
-                    new int[] {});
+            defaults.putIntArray(KEY_UT_TERMINAL_BASED_SERVICES_INT_ARRAY, new int[0]);
 
             defaults.putIntArray(
                     KEY_XCAP_OVER_UT_SUPPORTED_RATS_INT_ARRAY,
@@ -8726,7 +8712,6 @@
         public static final String KEY_IKE_SESSION_AES_CBC_KEY_SIZE_INT_ARRAY =
                 KEY_PREFIX + "ike_session_encryption_aes_cbc_key_size_int_array";
 
-
         /**
          * List of supported key sizes for AES Counter (CTR) encryption mode of IKE session.
          * Possible values -
@@ -8861,7 +8846,7 @@
         public static final int EPDG_ADDRESS_PCO = 2;
         /** Use cellular location to chose epdg server */
         public static final int EPDG_ADDRESS_CELLULAR_LOC = 3;
-        /* Use Visited Country FQDN rule*/
+        /** Use Visited Country FQDN rule*/
         public static final int EPDG_ADDRESS_VISITED_COUNTRY = 4;
 
         /** @hide */
@@ -8999,7 +8984,7 @@
             defaults.putIntArray(
                     KEY_EPDG_ADDRESS_PRIORITY_INT_ARRAY,
                     new int[] {EPDG_ADDRESS_PLMN, EPDG_ADDRESS_STATIC});
-            defaults.putStringArray(KEY_MCC_MNCS_STRING_ARRAY, new String[] {});
+            defaults.putStringArray(KEY_MCC_MNCS_STRING_ARRAY, new String[0]);
             defaults.putInt(KEY_IKE_LOCAL_ID_TYPE_INT, ID_TYPE_RFC822_ADDR);
             defaults.putInt(KEY_IKE_REMOTE_ID_TYPE_INT, ID_TYPE_FQDN);
             defaults.putBoolean(KEY_ADD_KE_TO_CHILD_SESSION_REKEY_BOOL, false);
@@ -9022,8 +9007,7 @@
      * level outside these boundaries is considered invalid.
      * @hide
      */
-    public static final String KEY_GSM_RSSI_THRESHOLDS_INT_ARRAY =
-            "gsm_rssi_thresholds_int_array";
+    public static final String KEY_GSM_RSSI_THRESHOLDS_INT_ARRAY = "gsm_rssi_thresholds_int_array";
 
     /**
      * An interval in dB for {@link SignalThresholdInfo#SIGNAL_MEASUREMENT_TYPE_RSSI} measurement
@@ -9041,8 +9025,7 @@
      * See Wireless Priority Service from https://www.fcc.gov/general/wireless-priority-service-wps
      * @hide
      */
-    public static final String KEY_SUPPORT_WPS_OVER_IMS_BOOL =
-            "support_wps_over_ims_bool";
+    public static final String KEY_SUPPORT_WPS_OVER_IMS_BOOL = "support_wps_over_ims_bool";
 
     /**
      * The two digital number pattern of MMI code which is defined by carrier.
@@ -9090,8 +9073,7 @@
      * When true, forwarded number is shown.
      * When false, forwarded number is not shown.
      */
-    public static final String KEY_SHOW_FORWARDED_NUMBER_BOOL =
-            "show_forwarded_number_bool";
+    public static final String KEY_SHOW_FORWARDED_NUMBER_BOOL = "show_forwarded_number_bool";
 
     /**
      * The list of originating address of missed incoming call SMS. If the SMS has originator
@@ -9103,7 +9085,6 @@
     public static final String KEY_MISSED_INCOMING_CALL_SMS_ORIGINATOR_STRING_ARRAY =
             "missed_incoming_call_sms_originator_string_array";
 
-
     /**
      * String array of Apn Type configurations.
      * The entries should be of form "APN_TYPE_NAME:priority".
@@ -9251,8 +9232,7 @@
      *
      * @hide
      */
-    public static final String KEY_DEFAULT_RTT_MODE_INT =
-            "default_rtt_mode_int";
+    public static final String KEY_DEFAULT_RTT_MODE_INT = "default_rtt_mode_int";
 
     /**
      * Indicates whether RTT is supported while roaming.
@@ -9278,10 +9258,9 @@
      * seamlessly after an unattended reboot.
      *
      * The device configuration value {@code config_allow_pin_storage_for_unattended_reboot}
-     * ultimately controls whether this carrier configuration option is used.  Where
-     * {@code config_allow_pin_storage_for_unattended_reboot} is false, the value of the
-     * {@link #KEY_STORE_SIM_PIN_FOR_UNATTENDED_REBOOT_BOOL} carrier configuration option is
-     * ignored.
+     * ultimately controls whether this carrier configuration option is used. Where
+     * {@code config_allow_pin_storage_for_unattended_reboot} is false, the value of this
+     * carrier configuration is ignored.
      *
      * @hide
      */
@@ -9559,7 +9538,7 @@
             "iwlan_handover_policy_string_array";
 
     /** The default value for every variable. */
-    private final static PersistableBundle sDefaults;
+    private static final PersistableBundle sDefaults;
 
     static {
         sDefaults = new PersistableBundle();
@@ -9669,17 +9648,17 @@
         sDefaults.putBoolean(KEY_REQUIRE_ENTITLEMENT_CHECKS_BOOL, true);
         sDefaults.putBoolean(KEY_CARRIER_SUPPORTS_TETHERING_BOOL, true);
         sDefaults.putBoolean(KEY_RESTART_RADIO_ON_PDP_FAIL_REGULAR_DEACTIVATION_BOOL, false);
-        sDefaults.putIntArray(KEY_RADIO_RESTART_FAILURE_CAUSES_INT_ARRAY, new int[]{});
+        sDefaults.putIntArray(KEY_RADIO_RESTART_FAILURE_CAUSES_INT_ARRAY, new int[0]);
         sDefaults.putInt(KEY_VOLTE_REPLACEMENT_RAT_INT, 0);
         sDefaults.putString(KEY_DEFAULT_SIM_CALL_MANAGER_STRING, "");
         sDefaults.putString(KEY_VVM_DESTINATION_NUMBER_STRING, "");
         sDefaults.putInt(KEY_VVM_PORT_NUMBER_INT, 0);
         sDefaults.putString(KEY_VVM_TYPE_STRING, "");
         sDefaults.putBoolean(KEY_VVM_CELLULAR_DATA_REQUIRED_BOOL, false);
-        sDefaults.putString(KEY_VVM_CLIENT_PREFIX_STRING,"//VVM");
-        sDefaults.putBoolean(KEY_VVM_SSL_ENABLED_BOOL,false);
+        sDefaults.putString(KEY_VVM_CLIENT_PREFIX_STRING, "//VVM");
+        sDefaults.putBoolean(KEY_VVM_SSL_ENABLED_BOOL, false);
         sDefaults.putStringArray(KEY_VVM_DISABLED_CAPABILITIES_STRING_ARRAY, null);
-        sDefaults.putBoolean(KEY_VVM_LEGACY_MODE_ENABLED_BOOL,false);
+        sDefaults.putBoolean(KEY_VVM_LEGACY_MODE_ENABLED_BOOL, false);
         sDefaults.putBoolean(KEY_VVM_PREFETCH_BOOL, true);
         sDefaults.putString(KEY_CARRIER_VVM_PACKAGE_NAME_STRING, "");
         sDefaults.putStringArray(KEY_CARRIER_VVM_PACKAGE_NAME_STRING_ARRAY, null);
@@ -9836,7 +9815,6 @@
         sDefaults.putStringArray(KEY_CARRIER_APP_NO_WAKE_SIGNAL_CONFIG_STRING_ARRAY, null);
         sDefaults.putBoolean(KEY_CARRIER_APP_REQUIRED_DURING_SIM_SETUP_BOOL, false);
 
-
         // Default carrier app configurations
         sDefaults.putStringArray(KEY_CARRIER_DEFAULT_ACTIONS_ON_REDIRECTION_STRING_ARRAY,
                 new String[]{
@@ -9850,9 +9828,10 @@
                 //6: CARRIER_ACTION_CANCEL_ALL_NOTIFICATIONS
                 //8: CARRIER_ACTION_DISABLE_DEFAULT_URL_HANDLER
                 });
-        sDefaults.putStringArray(KEY_CARRIER_DEFAULT_ACTIONS_ON_DEFAULT_NETWORK_AVAILABLE, new String[] {
-                String.valueOf(false) + ": 7", //7: CARRIER_ACTION_ENABLE_DEFAULT_URL_HANDLER
-                String.valueOf(true) + ": 8"  //8: CARRIER_ACTION_DISABLE_DEFAULT_URL_HANDLER
+        sDefaults.putStringArray(KEY_CARRIER_DEFAULT_ACTIONS_ON_DEFAULT_NETWORK_AVAILABLE,
+                new String[] {
+                        false + ": 7", //7: CARRIER_ACTION_ENABLE_DEFAULT_URL_HANDLER
+                        true + ": 8"  //8: CARRIER_ACTION_DISABLE_DEFAULT_URL_HANDLER
                 });
         sDefaults.putStringArray(KEY_CARRIER_DEFAULT_REDIRECTION_URL_STRING_ARRAY, null);
 
@@ -9866,9 +9845,9 @@
 
         // Rat families: {GPRS, EDGE}, {EVDO, EVDO_A, EVDO_B}, {UMTS, HSPA, HSDPA, HSUPA, HSPAP},
         // {LTE, LTE_CA}
-        // Order is important - lowest precidence first
+        // Order is important - lowest precedence first
         sDefaults.putStringArray(KEY_RATCHET_RAT_FAMILIES,
-                new String[]{"1,2","7,8,12","3,11,9,10,15","14,19"});
+                new String[]{"1,2", "7,8,12", "3,11,9,10,15", "14,19"});
         sDefaults.putBoolean(KEY_TREAT_DOWNGRADED_VIDEO_CALLS_AS_VIDEO_CALLS_BOOL, false);
         sDefaults.putBoolean(KEY_DROP_VIDEO_CALL_WHEN_ANSWERING_AUDIO_CALL_BOOL, false);
         sDefaults.putBoolean(KEY_ALLOW_MERGE_WIFI_CALLS_WHEN_VOWIFI_OFF_BOOL, true);
@@ -9899,8 +9878,7 @@
         sDefaults.putBoolean(KEY_NOTIFY_INTERNATIONAL_CALL_ON_WFC_BOOL, false);
         sDefaults.putBoolean(KEY_HIDE_PRESET_APN_DETAILS_BOOL, false);
         sDefaults.putBoolean(KEY_SHOW_VIDEO_CALL_CHARGES_ALERT_DIALOG_BOOL, false);
-        sDefaults.putStringArray(KEY_CALL_FORWARDING_BLOCKS_WHILE_ROAMING_STRING_ARRAY,
-                null);
+        sDefaults.putStringArray(KEY_CALL_FORWARDING_BLOCKS_WHILE_ROAMING_STRING_ARRAY, null);
         sDefaults.putBoolean(KEY_SUPPORT_IMS_CALL_FORWARDING_WHILE_ROAMING_BOOL, true);
         sDefaults.putInt(KEY_LTE_EARFCNS_RSRP_BOOST_INT, 0);
         sDefaults.putStringArray(KEY_BOOSTED_LTE_EARFCNS_STRING_ARRAY, null);
@@ -9939,6 +9917,7 @@
         sDefaults.putInt(KEY_LTE_PLUS_THRESHOLD_BANDWIDTH_KHZ_INT, 20000);
         sDefaults.putInt(KEY_NR_ADVANCED_THRESHOLD_BANDWIDTH_KHZ_INT, 0);
         sDefaults.putBoolean(KEY_INCLUDE_LTE_FOR_NR_ADVANCED_THRESHOLD_BANDWIDTH_BOOL, false);
+        sDefaults.putBoolean(KEY_RATCHET_NR_ADVANCED_BANDWIDTH_IF_RRC_IDLE_BOOL, true);
         sDefaults.putIntArray(KEY_CARRIER_NR_AVAILABILITIES_INT_ARRAY,
                 new int[]{CARRIER_NR_AVAILABILITY_NSA, CARRIER_NR_AVAILABILITY_SA});
         sDefaults.putBoolean(KEY_LTE_ENABLED_BOOL, true);
@@ -9977,27 +9956,27 @@
         sDefaults.putIntArray(KEY_WCDMA_RSCP_THRESHOLDS_INT_ARRAY,
                 // Boundaries: [-120 dBm, -25 dBm]
                 new int[] {
-                        -115,  /* SIGNAL_STRENGTH_POOR */
+                        -115, /* SIGNAL_STRENGTH_POOR */
                         -105, /* SIGNAL_STRENGTH_MODERATE */
-                        -95, /* SIGNAL_STRENGTH_GOOD */
-                        -85  /* SIGNAL_STRENGTH_GREAT */
+                        -95,  /* SIGNAL_STRENGTH_GOOD */
+                        -85   /* SIGNAL_STRENGTH_GREAT */
                 });
         // TODO(b/249896055): On enabling ECNO measurement part for Signal Bar level indication
-        // system functionality,below values to be rechecked.
+        // system functionality, below values to be rechecked.
         sDefaults.putIntArray(KEY_WCDMA_ECNO_THRESHOLDS_INT_ARRAY,
                 // Boundaries: [-24 dBm, 1 dBm]
                 new int[] {
                         -24, /* SIGNAL_STRENGTH_POOR */
                         -14, /* SIGNAL_STRENGTH_MODERATE */
-                        -6, /* SIGNAL_STRENGTH_GOOD */
-                        1  /* SIGNAL_STRENGTH_GREAT */
+                        -6,  /* SIGNAL_STRENGTH_GOOD */
+                        1    /* SIGNAL_STRENGTH_GREAT */
                 });
         sDefaults.putIntArray(KEY_5G_NR_SSRSRP_THRESHOLDS_INT_ARRAY,
                 // Boundaries: [-140 dB, -44 dB]
                 new int[] {
                     -110, /* SIGNAL_STRENGTH_POOR */
-                    -90, /* SIGNAL_STRENGTH_MODERATE */
-                    -80, /* SIGNAL_STRENGTH_GOOD */
+                    -90,  /* SIGNAL_STRENGTH_MODERATE */
+                    -80,  /* SIGNAL_STRENGTH_GOOD */
                     -65,  /* SIGNAL_STRENGTH_GREAT */
                 });
         sDefaults.putIntArray(KEY_5G_NR_SSRSRQ_THRESHOLDS_INT_ARRAY,
@@ -10005,14 +9984,14 @@
                 new int[] {
                     -31, /* SIGNAL_STRENGTH_POOR */
                     -19, /* SIGNAL_STRENGTH_MODERATE */
-                    -7, /* SIGNAL_STRENGTH_GOOD */
-                    6  /* SIGNAL_STRENGTH_GREAT */
+                    -7,  /* SIGNAL_STRENGTH_GOOD */
+                    6    /* SIGNAL_STRENGTH_GREAT */
                 });
         sDefaults.putIntArray(KEY_5G_NR_SSSINR_THRESHOLDS_INT_ARRAY,
                 // Boundaries: [-23 dB, 40 dB]
                 new int[] {
                     -5, /* SIGNAL_STRENGTH_POOR */
-                    5, /* SIGNAL_STRENGTH_MODERATE */
+                    5,  /* SIGNAL_STRENGTH_MODERATE */
                     15, /* SIGNAL_STRENGTH_GOOD */
                     30  /* SIGNAL_STRENGTH_GREAT */
                 });
@@ -10106,8 +10085,7 @@
         sDefaults.putLong(KEY_OPPORTUNISTIC_NETWORK_MAX_BACKOFF_TIME_LONG, 60000);
         sDefaults.putBoolean(KEY_ENABLE_4G_OPPORTUNISTIC_NETWORK_SCAN_BOOL, true);
         sDefaults.putLong(KEY_TIME_TO_SWITCH_BACK_TO_PRIMARY_IF_OPPORTUNISTIC_OOS_LONG, 60000L);
-        sDefaults.putLong(
-                KEY_OPPORTUNISTIC_TIME_TO_SCAN_AFTER_CAPABILITY_SWITCH_TO_PRIMARY_LONG,
+        sDefaults.putLong(KEY_OPPORTUNISTIC_TIME_TO_SCAN_AFTER_CAPABILITY_SWITCH_TO_PRIMARY_LONG,
                 120000L);
         sDefaults.putAll(ImsServiceEntitlement.getDefaults());
         sDefaults.putAll(Gps.getDefaults());
@@ -10129,7 +10107,7 @@
                 new int[] {
                         -107, /* SIGNAL_STRENGTH_POOR */
                         -103, /* SIGNAL_STRENGTH_MODERATE */
-                        -97, /* SIGNAL_STRENGTH_GOOD */
+                        -97,  /* SIGNAL_STRENGTH_GOOD */
                         -89,  /* SIGNAL_STRENGTH_GREAT */
                 });
         sDefaults.putBoolean(KEY_SUPPORT_WPS_OVER_IMS_BOOL, true);
@@ -10221,7 +10199,7 @@
         sDefaults.putBoolean(KEY_VONR_SETTING_VISIBILITY_BOOL, true);
         sDefaults.putBoolean(KEY_VONR_ENABLED_BOOL, false);
         sDefaults.putBoolean(KEY_VONR_ON_BY_DEFAULT_BOOL, true);
-        sDefaults.putIntArray(KEY_SUPPORTED_PREMIUM_CAPABILITIES_INT_ARRAY, new int[] {});
+        sDefaults.putIntArray(KEY_SUPPORTED_PREMIUM_CAPABILITIES_INT_ARRAY, new int[0]);
         sDefaults.putLong(KEY_PREMIUM_CAPABILITY_NOTIFICATION_DISPLAY_TIMEOUT_MILLIS_LONG,
                 TimeUnit.MINUTES.toMillis(30));
         sDefaults.putLong(KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG,
@@ -10290,7 +10268,6 @@
         public static final String KEY_AVOID_5GHZ_WIFI_DIRECT_FOR_LAA_BOOL =
                 KEY_PREFIX + "avoid_5ghz_wifi_direct_for_laa_bool";
 
-
         private static PersistableBundle getDefaults() {
             PersistableBundle defaults = new PersistableBundle();
             defaults.putInt(KEY_HOTSPOT_MAX_CLIENT_COUNT, 0);
@@ -10337,8 +10314,7 @@
             return loader.getConfigForSubIdWithFeature(subId, mContext.getOpPackageName(),
                     mContext.getAttributionTag());
         } catch (RemoteException ex) {
-            Rlog.e(TAG, "Error getting config for subId " + subId + ": "
-                    + ex.toString());
+            Rlog.e(TAG, "Error getting config for subId " + subId + ": " + ex);
         }
         return null;
     }
@@ -10364,7 +10340,7 @@
      * {@link TelephonyManager#hasCarrierPrivileges()}).
      *
      * @param subId The subscription ID on which the carrier config should be retrieved.
-     * @param keys  The carrier config keys to retrieve values.
+     * @param keys The carrier config keys to retrieve values.
      * @return A {@link PersistableBundle} with key/value mapping for the specified configuration
      * on success, or an empty (but never null) bundle on failure (for example, when the calling app
      * has no permission).
@@ -10455,8 +10431,7 @@
             }
             loader.overrideConfig(subscriptionId, overrideValues, persistent);
         } catch (RemoteException ex) {
-            Rlog.e(TAG, "Error setting config for subId " + subscriptionId + ": "
-                    + ex.toString());
+            Rlog.e(TAG, "Error setting config for subId " + subscriptionId + ": " + ex);
         }
     }
 
@@ -10569,7 +10544,7 @@
             }
             loader.notifyConfigChangedForSubId(subId);
         } catch (RemoteException ex) {
-            Rlog.e(TAG, "Error reloading config for subId=" + subId + ": " + ex.toString());
+            Rlog.e(TAG, "Error reloading config for subId=" + subId + ": " + ex);
         }
     }
 
@@ -10593,7 +10568,7 @@
             }
             loader.updateConfigForPhoneId(phoneId, simState);
         } catch (RemoteException ex) {
-            Rlog.e(TAG, "Error updating config for phoneId=" + phoneId + ": " + ex.toString());
+            Rlog.e(TAG, "Error updating config for phoneId=" + phoneId + ": " + ex);
         }
     }
 
@@ -10615,8 +10590,7 @@
             }
             return loader.getDefaultCarrierServicePackageName();
         } catch (RemoteException ex) {
-            Rlog.e(TAG, "getDefaultCarrierServicePackageName ICarrierConfigLoader is null"
-                    + ex.toString());
+            Rlog.e(TAG, "getDefaultCarrierServicePackageName ICarrierConfigLoader is null" + ex);
             ex.rethrowAsRuntimeException();
         }
         return "";