Merge "Add flag for VDM dump_history feature" into main
diff --git a/cmds/idmap2/libidmap2/XmlParser.cpp b/cmds/idmap2/libidmap2/XmlParser.cpp
index 766ca56..1d78460 100644
--- a/cmds/idmap2/libidmap2/XmlParser.cpp
+++ b/cmds/idmap2/libidmap2/XmlParser.cpp
@@ -109,7 +109,7 @@
   switch (value.dataType) {
     case Res_value::TYPE_STRING: {
       if (auto str = parser.getStrings().string8ObjectAt(value.data); str.ok()) {
-        return std::string(str->string());
+        return std::string(str->c_str());
       }
       break;
     }
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 33b8b03..715edc5 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -16111,11 +16111,6 @@
      * Called by a profile owner of an organization-owned managed profile to suspend personal
      * apps on the device. When personal apps are suspended the device can only be used for calls.
      *
-     * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
-     * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
-     * in the profile owner package. Profile owner implementation that uses personal apps suspension
-     * must handle this intent.
-     *
      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
      * @param suspended Whether personal apps should be suspended.
      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
diff --git a/core/java/android/hardware/biometrics/BiometricPrompt.java b/core/java/android/hardware/biometrics/BiometricPrompt.java
index 912e8df..af448f0 100644
--- a/core/java/android/hardware/biometrics/BiometricPrompt.java
+++ b/core/java/android/hardware/biometrics/BiometricPrompt.java
@@ -466,6 +466,19 @@
         // LINT.ThenChange(frameworks/base/core/java/android/hardware/biometrics/PromptInfo.java)
 
         /**
+         * Set if emergency call button should show, for example if biometrics are
+         * required to access the dialer app
+         * @param showEmergencyCallButton if true, shows emergency call button
+         * @return This builder.
+         * @hide
+         */
+        @NonNull
+        public Builder setShowEmergencyCallButton(boolean showEmergencyCallButton) {
+            mPromptInfo.setShowEmergencyCallButton(showEmergencyCallButton);
+            return this;
+        }
+
+        /**
          * Creates a {@link BiometricPrompt}.
          *
          * @return An instance of {@link BiometricPrompt}.
diff --git a/core/java/android/hardware/biometrics/PromptInfo.java b/core/java/android/hardware/biometrics/PromptInfo.java
index e275078..24cfd164 100644
--- a/core/java/android/hardware/biometrics/PromptInfo.java
+++ b/core/java/android/hardware/biometrics/PromptInfo.java
@@ -48,6 +48,7 @@
     private boolean mAllowBackgroundAuthentication;
     private boolean mIgnoreEnrollmentState;
     private boolean mIsForLegacyFingerprintManager = false;
+    private boolean mShowEmergencyCallButton = false;
 
     public PromptInfo() {
 
@@ -72,6 +73,7 @@
         mAllowBackgroundAuthentication = in.readBoolean();
         mIgnoreEnrollmentState = in.readBoolean();
         mIsForLegacyFingerprintManager = in.readBoolean();
+        mShowEmergencyCallButton = in.readBoolean();
     }
 
     public static final Creator<PromptInfo> CREATOR = new Creator<PromptInfo>() {
@@ -111,6 +113,7 @@
         dest.writeBoolean(mAllowBackgroundAuthentication);
         dest.writeBoolean(mIgnoreEnrollmentState);
         dest.writeBoolean(mIsForLegacyFingerprintManager);
+        dest.writeBoolean(mShowEmergencyCallButton);
     }
 
     // LINT.IfChange
@@ -228,6 +231,10 @@
         mAllowedSensorIds.add(sensorId);
     }
 
+    public void setShowEmergencyCallButton(boolean showEmergencyCallButton) {
+        mShowEmergencyCallButton = showEmergencyCallButton;
+    }
+
     // Getters
 
     public CharSequence getTitle() {
@@ -309,4 +316,8 @@
     public boolean isForLegacyFingerprintManager() {
         return mIsForLegacyFingerprintManager;
     }
+
+    public boolean isShowEmergencyCallButton() {
+        return mShowEmergencyCallButton;
+    }
 }
diff --git a/core/java/android/hardware/camera2/CameraExtensionCharacteristics.java b/core/java/android/hardware/camera2/CameraExtensionCharacteristics.java
index 6baf91d7..ea951a5 100644
--- a/core/java/android/hardware/camera2/CameraExtensionCharacteristics.java
+++ b/core/java/android/hardware/camera2/CameraExtensionCharacteristics.java
@@ -236,9 +236,10 @@
         private static final CameraExtensionManagerGlobal GLOBAL_CAMERA_MANAGER =
                 new CameraExtensionManagerGlobal();
         private final Object mLock = new Object();
-        private final int PROXY_SERVICE_DELAY_MS = 1000;
+        private final int PROXY_SERVICE_DELAY_MS = 2000;
         private InitializerFuture mInitFuture = null;
         private ServiceConnection mConnection = null;
+        private int mConnectionCount = 0;
         private ICameraExtensionsProxyService mProxy = null;
         private boolean mSupportsAdvancedExtensions = false;
 
@@ -249,6 +250,15 @@
             return GLOBAL_CAMERA_MANAGER;
         }
 
+        private void releaseProxyConnectionLocked(Context ctx) {
+            if (mConnection != null ) {
+                ctx.unbindService(mConnection);
+                mConnection = null;
+                mProxy = null;
+                mConnectionCount = 0;
+            }
+        }
+
         private void connectToProxyLocked(Context ctx) {
             if (mConnection == null) {
                 Intent intent = new Intent();
@@ -270,7 +280,6 @@
                 mConnection = new ServiceConnection() {
                     @Override
                     public void onServiceDisconnected(ComponentName component) {
-                        mInitFuture.setStatus(false);
                         mConnection = null;
                         mProxy = null;
                     }
@@ -348,23 +357,32 @@
 
         public boolean registerClient(Context ctx, IBinder token) {
             synchronized (mLock) {
+                boolean ret = false;
                 connectToProxyLocked(ctx);
                 if (mProxy == null) {
                     return false;
                 }
+                mConnectionCount++;
 
                 try {
-                    return mProxy.registerClient(token);
+                    ret = mProxy.registerClient(token);
                 } catch (RemoteException e) {
                     Log.e(TAG, "Failed to initialize extension! Extension service does "
                             + " not respond!");
                 }
+                if (!ret) {
+                    mConnectionCount--;
+                }
 
-                return false;
+                if (mConnectionCount <= 0) {
+                    releaseProxyConnectionLocked(ctx);
+                }
+
+                return ret;
             }
         }
 
-        public void unregisterClient(IBinder token) {
+        public void unregisterClient(Context ctx, IBinder token) {
             synchronized (mLock) {
                 if (mProxy != null) {
                     try {
@@ -372,6 +390,11 @@
                     } catch (RemoteException e) {
                         Log.e(TAG, "Failed to de-initialize extension! Extension service does"
                                 + " not respond!");
+                    } finally {
+                        mConnectionCount--;
+                        if (mConnectionCount <= 0) {
+                            releaseProxyConnectionLocked(ctx);
+                        }
                     }
                 }
             }
@@ -446,8 +469,8 @@
     /**
      * @hide
      */
-    public static void unregisterClient(IBinder token) {
-        CameraExtensionManagerGlobal.get().unregisterClient(token);
+    public static void unregisterClient(Context ctx, IBinder token) {
+        CameraExtensionManagerGlobal.get().unregisterClient(ctx, token);
     }
 
     /**
@@ -578,7 +601,7 @@
                 }
             }
         } finally {
-            unregisterClient(token);
+            unregisterClient(mContext, token);
         }
 
         return Collections.unmodifiableList(ret);
@@ -626,7 +649,7 @@
             Log.e(TAG, "Failed to query the extension for postview availability! Extension "
                     + "service does not respond!");
         } finally {
-            unregisterClient(token);
+            unregisterClient(mContext, token);
         }
 
         return false;
@@ -722,7 +745,7 @@
                     + "service does not respond!");
             return Collections.emptyList();
         } finally {
-            unregisterClient(token);
+            unregisterClient(mContext, token);
         }
     }
 
@@ -791,7 +814,7 @@
                     + " not respond!");
             return new ArrayList<>();
         } finally {
-            unregisterClient(token);
+            unregisterClient(mContext, token);
         }
     }
 
@@ -872,7 +895,7 @@
                     }
                 }
             } finally {
-                unregisterClient(token);
+                unregisterClient(mContext, token);
             }
         } catch (RemoteException e) {
             Log.e(TAG, "Failed to query the extension supported sizes! Extension service does"
@@ -957,7 +980,7 @@
             Log.e(TAG, "Failed to query the extension capture latency! Extension service does"
                     + " not respond!");
         } finally {
-            unregisterClient(token);
+            unregisterClient(mContext, token);
         }
 
         return null;
@@ -998,7 +1021,7 @@
             Log.e(TAG, "Failed to query the extension progress callbacks! Extension service does"
                     + " not respond!");
         } finally {
-            unregisterClient(token);
+            unregisterClient(mContext, token);
         }
 
         return false;
@@ -1075,7 +1098,7 @@
         } catch (RemoteException e) {
             throw new IllegalStateException("Failed to query the available capture request keys!");
         } finally {
-            unregisterClient(token);
+            unregisterClient(mContext, token);
         }
 
         return Collections.unmodifiableSet(ret);
@@ -1155,7 +1178,7 @@
         } catch (RemoteException e) {
             throw new IllegalStateException("Failed to query the available capture result keys!");
         } finally {
-            unregisterClient(token);
+            unregisterClient(mContext, token);
         }
 
         return Collections.unmodifiableSet(ret);
diff --git a/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java
index e06699b..c7e74c0 100644
--- a/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java
@@ -90,7 +90,7 @@
     private final HashMap<Integer, ImageReader> mReaderMap = new HashMap<>();
     private RequestProcessor mRequestProcessor = new RequestProcessor();
     private final int mSessionId;
-    private final IBinder mToken;
+    private IBinder mToken = null;
 
     private Surface mClientRepeatingRequestSurface;
     private Surface mClientCaptureSurface;
@@ -103,6 +103,8 @@
     private boolean mInitialized;
     private boolean mSessionClosed;
 
+    private final Context mContext;
+
     // Lock to synchronize cross-thread access to device public interface
     final Object mInterfaceLock;
 
@@ -113,14 +115,9 @@
     public static CameraAdvancedExtensionSessionImpl createCameraAdvancedExtensionSession(
             @NonNull android.hardware.camera2.impl.CameraDeviceImpl cameraDevice,
             @NonNull Map<String, CameraCharacteristics> characteristicsMap,
-            @NonNull Context ctx, @NonNull ExtensionSessionConfiguration config, int sessionId)
+            @NonNull Context ctx, @NonNull ExtensionSessionConfiguration config, int sessionId,
+            @NonNull IBinder token)
             throws CameraAccessException, RemoteException {
-        final IBinder token = new Binder(TAG + " : " + sessionId);
-        boolean success = CameraExtensionCharacteristics.registerClient(ctx, token);
-        if (!success) {
-            throw new UnsupportedOperationException("Unsupported extension!");
-        }
-
         String cameraId = cameraDevice.getId();
         CameraExtensionCharacteristics extensionChars = new CameraExtensionCharacteristics(ctx,
                 cameraId, characteristicsMap);
@@ -204,8 +201,9 @@
         IAdvancedExtenderImpl extender = CameraExtensionCharacteristics.initializeAdvancedExtension(
                 config.getExtension());
         extender.init(cameraId, characteristicsMapNative);
-        CameraAdvancedExtensionSessionImpl ret = new CameraAdvancedExtensionSessionImpl(extender,
-                cameraDevice, characteristicsMapNative, repeatingRequestSurface,
+
+        CameraAdvancedExtensionSessionImpl ret = new CameraAdvancedExtensionSessionImpl(ctx,
+                extender, cameraDevice, characteristicsMapNative, repeatingRequestSurface,
                 burstCaptureSurface, postviewSurface, config.getStateCallback(),
                 config.getExecutor(), sessionId, token);
 
@@ -217,13 +215,16 @@
         return ret;
     }
 
-    private CameraAdvancedExtensionSessionImpl(@NonNull IAdvancedExtenderImpl extender,
+    private CameraAdvancedExtensionSessionImpl(Context ctx,
+            @NonNull IAdvancedExtenderImpl extender,
             @NonNull CameraDeviceImpl cameraDevice,
             Map<String, CameraMetadataNative> characteristicsMap,
             @Nullable Surface repeatingRequestSurface, @Nullable Surface burstCaptureSurface,
             @Nullable Surface postviewSurface,
             @NonNull StateCallback callback, @NonNull Executor executor,
-            int sessionId, @NonNull IBinder token) {
+            int sessionId,
+            @NonNull IBinder token) {
+        mContext = ctx;
         mAdvancedExtender = extender;
         mCameraDevice = cameraDevice;
         mCharacteristicsMap = characteristicsMap;
@@ -578,12 +579,16 @@
                 mSessionProcessor = null;
             }
 
-            CameraExtensionCharacteristics.unregisterClient(mToken);
-            if (mInitialized || (mCaptureSession != null)) {
-                notifyClose = true;
-                CameraExtensionCharacteristics.releaseSession();
+
+            if (mToken != null) {
+                if (mInitialized || (mCaptureSession != null)) {
+                    notifyClose = true;
+                    CameraExtensionCharacteristics.releaseSession();
+                }
+                CameraExtensionCharacteristics.unregisterClient(mContext, mToken);
             }
             mInitialized = false;
+            mToken = null;
 
             for (ImageReader reader : mReaderMap.values()) {
                 reader.close();
diff --git a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
index d3bde4b..181ab2c 100644
--- a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
@@ -2550,19 +2550,32 @@
         HashMap<String, CameraCharacteristics> characteristicsMap = new HashMap<>(
                 mPhysicalIdsToChars);
         characteristicsMap.put(mCameraId, mCharacteristics);
+        boolean initializationFailed = true;
+        IBinder token = new Binder(TAG + " : " + mNextSessionId++);
         try {
+            boolean ret = CameraExtensionCharacteristics.registerClient(mContext, token);
+            if (!ret) {
+                token = null;
+                throw new UnsupportedOperationException("Unsupported extension!");
+            }
+
             if (CameraExtensionCharacteristics.areAdvancedExtensionsSupported()) {
                 mCurrentAdvancedExtensionSession =
                         CameraAdvancedExtensionSessionImpl.createCameraAdvancedExtensionSession(
                                 this, characteristicsMap, mContext, extensionConfiguration,
-                                mNextSessionId++);
+                                mNextSessionId, token);
             } else {
                 mCurrentExtensionSession = CameraExtensionSessionImpl.createCameraExtensionSession(
                         this, characteristicsMap, mContext, extensionConfiguration,
-                        mNextSessionId++);
+                        mNextSessionId, token);
             }
+            initializationFailed = false;
         } catch (RemoteException e) {
             throw new CameraAccessException(CameraAccessException.CAMERA_ERROR);
+        } finally {
+            if (initializationFailed && (token != null)) {
+                CameraExtensionCharacteristics.unregisterClient(mContext, token);
+            }
         }
     }
 }
diff --git a/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java
index 5d25681..bf77681 100644
--- a/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java
@@ -91,7 +91,7 @@
     private final Set<CaptureRequest.Key> mSupportedRequestKeys;
     private final Set<CaptureResult.Key> mSupportedResultKeys;
     private final ExtensionSessionStatsAggregator mStatsAggregator;
-    private final IBinder mToken;
+    private IBinder mToken = null;
     private boolean mCaptureResultsSupported;
 
     private CameraCaptureSession mCaptureSession = null;
@@ -119,6 +119,8 @@
     // will do so internally.
     private boolean mInternalRepeatingRequestEnabled = true;
 
+    private final Context mContext;
+
     // Lock to synchronize cross-thread access to device public interface
     final Object mInterfaceLock;
 
@@ -135,14 +137,9 @@
             @NonNull Map<String, CameraCharacteristics> characteristicsMap,
             @NonNull Context ctx,
             @NonNull ExtensionSessionConfiguration config,
-            int sessionId)
+            int sessionId,
+            @NonNull IBinder token)
             throws CameraAccessException, RemoteException {
-        final IBinder token = new Binder(TAG + " : " + sessionId);
-        boolean success = CameraExtensionCharacteristics.registerClient(ctx, token);
-        if (!success) {
-            throw new UnsupportedOperationException("Unsupported extension!");
-        }
-
         String cameraId = cameraDevice.getId();
         CameraExtensionCharacteristics extensionChars = new CameraExtensionCharacteristics(ctx,
                 cameraId, characteristicsMap);
@@ -234,6 +231,7 @@
                 characteristicsMap.get(cameraId).getNativeMetadata());
 
         CameraExtensionSessionImpl session = new CameraExtensionSessionImpl(
+                ctx,
                 extenders.second,
                 extenders.first,
                 supportedPreviewSizes,
@@ -256,7 +254,7 @@
         return session;
     }
 
-    public CameraExtensionSessionImpl(@NonNull IImageCaptureExtenderImpl imageExtender,
+    public CameraExtensionSessionImpl(Context ctx, @NonNull IImageCaptureExtenderImpl imageExtender,
             @NonNull IPreviewExtenderImpl previewExtender,
             @NonNull List<Size> previewSizes,
             @NonNull android.hardware.camera2.impl.CameraDeviceImpl cameraDevice,
@@ -269,6 +267,7 @@
             @NonNull IBinder token,
             @NonNull Set<CaptureRequest.Key> requestKeys,
             @Nullable Set<CaptureResult.Key> resultKeys) {
+        mContext = ctx;
         mImageExtender = imageExtender;
         mPreviewExtender = previewExtender;
         mCameraDevice = cameraDevice;
@@ -878,12 +877,15 @@
                         + " respond!");
             }
 
-            CameraExtensionCharacteristics.unregisterClient(mToken);
-            if (mInitialized || (mCaptureSession != null)) {
-                notifyClose = true;
-                CameraExtensionCharacteristics.releaseSession();
+            if (mToken != null) {
+                if (mInitialized || (mCaptureSession != null)) {
+                    notifyClose = true;
+                    CameraExtensionCharacteristics.releaseSession();
+                }
+                CameraExtensionCharacteristics.unregisterClient(mContext, mToken);
             }
             mInitialized = false;
+            mToken = null;
 
             if (mRepeatingRequestImageCallback != null) {
                 mRepeatingRequestImageCallback.close();
diff --git a/core/java/android/hardware/display/DisplayManagerInternal.java b/core/java/android/hardware/display/DisplayManagerInternal.java
index 94bff89..4700720 100644
--- a/core/java/android/hardware/display/DisplayManagerInternal.java
+++ b/core/java/android/hardware/display/DisplayManagerInternal.java
@@ -370,8 +370,9 @@
 
     /**
      * Returns the default size of the surface associated with the display, or null if the surface
-     * is not provided for layer mirroring by SurfaceFlinger.
-     * Only used for mirroring started from MediaProjection.
+     * is not provided for layer mirroring by SurfaceFlinger. Size is rotated to reflect the current
+     * display device orientation.
+     * Used for mirroring from MediaProjection, or a physical display based on display flags.
      */
     public abstract Point getDisplaySurfaceDefaultSize(int displayId);
 
diff --git a/core/java/android/os/SystemVibrator.java b/core/java/android/os/SystemVibrator.java
index bf72b1d..2cda787 100644
--- a/core/java/android/os/SystemVibrator.java
+++ b/core/java/android/os/SystemVibrator.java
@@ -18,26 +18,19 @@
 
 import android.annotation.CallbackExecutor;
 import android.annotation.NonNull;
-import android.annotation.Nullable;
 import android.compat.annotation.UnsupportedAppUsage;
 import android.content.Context;
-import android.hardware.vibrator.IVibrator;
+import android.os.vibrator.VibratorInfoFactory;
 import android.util.ArrayMap;
 import android.util.Log;
-import android.util.Range;
-import android.util.Slog;
 import android.util.SparseArray;
-import android.util.SparseBooleanArray;
-import android.util.SparseIntArray;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
 
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Objects;
 import java.util.concurrent.Executor;
-import java.util.function.Function;
 
 /**
  * Vibrator implementation that controls the main system vibrator.
@@ -82,7 +75,7 @@
             if (vibratorIds.length == 0) {
                 // It is known that the device has no vibrator, so cache and return info that
                 // reflects the lack of support for effects/primitives.
-                return mVibratorInfo = new NoVibratorInfo();
+                return mVibratorInfo = VibratorInfo.EMPTY_VIBRATOR_INFO;
             }
             VibratorInfo[] vibratorInfos = new VibratorInfo[vibratorIds.length];
             for (int i = 0; i < vibratorIds.length; i++) {
@@ -96,12 +89,7 @@
                 }
                 vibratorInfos[i] = vibrator.getInfo();
             }
-            if (vibratorInfos.length == 1) {
-                // Device has a single vibrator info, cache and return successfully loaded info.
-                return mVibratorInfo = new VibratorInfo(/* id= */ -1, vibratorInfos[0]);
-            }
-            // Device has multiple vibrators, generate a single info representing all of them.
-            return mVibratorInfo = new MultiVibratorInfo(vibratorInfos);
+            return mVibratorInfo = VibratorInfoFactory.create(/* id= */ -1, vibratorInfos);
         }
     }
 
@@ -275,296 +263,6 @@
     }
 
     /**
-     * Represents a device with no vibrator as a single {@link VibratorInfo}.
-     *
-     * @hide
-     */
-    @VisibleForTesting
-    public static class NoVibratorInfo extends VibratorInfo {
-        public NoVibratorInfo() {
-            // Use empty arrays to indicate no support, while null would indicate support unknown.
-            super(/* id= */ -1,
-                    /* capabilities= */ 0,
-                    /* supportedEffects= */ new SparseBooleanArray(),
-                    /* supportedBraking= */ new SparseBooleanArray(),
-                    /* supportedPrimitives= */ new SparseIntArray(),
-                    /* primitiveDelayMax= */ 0,
-                    /* compositionSizeMax= */ 0,
-                    /* pwlePrimitiveDurationMax= */ 0,
-                    /* pwleSizeMax= */ 0,
-                    /* qFactor= */ Float.NaN,
-                    new FrequencyProfile(/* resonantFrequencyHz= */ Float.NaN,
-                            /* minFrequencyHz= */ Float.NaN,
-                            /* frequencyResolutionHz= */ Float.NaN,
-                            /* maxAmplitudes= */ null));
-        }
-    }
-
-    /**
-     * Represents multiple vibrator information as a single {@link VibratorInfo}.
-     *
-     * <p>This uses an intersection of all vibrators to decide the capabilities and effect/primitive
-     * support.
-     *
-     * @hide
-     */
-    @VisibleForTesting
-    public static class MultiVibratorInfo extends VibratorInfo {
-        // Epsilon used for float comparison applied in calculations for the merged info.
-        private static final float EPSILON = 1e-5f;
-
-        public MultiVibratorInfo(VibratorInfo[] vibrators) {
-            // Need to use an extra constructor to share the computation in super initialization.
-            this(vibrators, frequencyProfileIntersection(vibrators));
-        }
-
-        private MultiVibratorInfo(VibratorInfo[] vibrators,
-                VibratorInfo.FrequencyProfile mergedProfile) {
-            super(/* id= */ -1,
-                    capabilitiesIntersection(vibrators, mergedProfile.isEmpty()),
-                    supportedEffectsIntersection(vibrators),
-                    supportedBrakingIntersection(vibrators),
-                    supportedPrimitivesAndDurationsIntersection(vibrators),
-                    integerLimitIntersection(vibrators, VibratorInfo::getPrimitiveDelayMax),
-                    integerLimitIntersection(vibrators, VibratorInfo::getCompositionSizeMax),
-                    integerLimitIntersection(vibrators, VibratorInfo::getPwlePrimitiveDurationMax),
-                    integerLimitIntersection(vibrators, VibratorInfo::getPwleSizeMax),
-                    floatPropertyIntersection(vibrators, VibratorInfo::getQFactor),
-                    mergedProfile);
-        }
-
-        private static int capabilitiesIntersection(VibratorInfo[] infos,
-                boolean frequencyProfileIsEmpty) {
-            int intersection = ~0;
-            for (VibratorInfo info : infos) {
-                intersection &= info.getCapabilities();
-            }
-            if (frequencyProfileIsEmpty) {
-                // Revoke frequency control if the merged frequency profile ended up empty.
-                intersection &= ~IVibrator.CAP_FREQUENCY_CONTROL;
-            }
-            return intersection;
-        }
-
-        @Nullable
-        private static SparseBooleanArray supportedBrakingIntersection(VibratorInfo[] infos) {
-            for (VibratorInfo info : infos) {
-                if (!info.isBrakingSupportKnown()) {
-                    // If one vibrator support is unknown, then the intersection is also unknown.
-                    return null;
-                }
-            }
-
-            SparseBooleanArray intersection = new SparseBooleanArray();
-            SparseBooleanArray firstVibratorBraking = infos[0].getSupportedBraking();
-
-            brakingIdLoop:
-            for (int i = 0; i < firstVibratorBraking.size(); i++) {
-                int brakingId = firstVibratorBraking.keyAt(i);
-                if (!firstVibratorBraking.valueAt(i)) {
-                    // The first vibrator already doesn't support this braking, so skip it.
-                    continue brakingIdLoop;
-                }
-
-                for (int j = 1; j < infos.length; j++) {
-                    if (!infos[j].hasBrakingSupport(brakingId)) {
-                        // One vibrator doesn't support this braking, so the intersection doesn't.
-                        continue brakingIdLoop;
-                    }
-                }
-
-                intersection.put(brakingId, true);
-            }
-
-            return intersection;
-        }
-
-        @Nullable
-        private static SparseBooleanArray supportedEffectsIntersection(VibratorInfo[] infos) {
-            for (VibratorInfo info : infos) {
-                if (!info.isEffectSupportKnown()) {
-                    // If one vibrator support is unknown, then the intersection is also unknown.
-                    return null;
-                }
-            }
-
-            SparseBooleanArray intersection = new SparseBooleanArray();
-            SparseBooleanArray firstVibratorEffects = infos[0].getSupportedEffects();
-
-            effectIdLoop:
-            for (int i = 0; i < firstVibratorEffects.size(); i++) {
-                int effectId = firstVibratorEffects.keyAt(i);
-                if (!firstVibratorEffects.valueAt(i)) {
-                    // The first vibrator already doesn't support this effect, so skip it.
-                    continue effectIdLoop;
-                }
-
-                for (int j = 1; j < infos.length; j++) {
-                    if (infos[j].isEffectSupported(effectId) != VIBRATION_EFFECT_SUPPORT_YES) {
-                        // One vibrator doesn't support this effect, so the intersection doesn't.
-                        continue effectIdLoop;
-                    }
-                }
-
-                intersection.put(effectId, true);
-            }
-
-            return intersection;
-        }
-
-        @NonNull
-        private static SparseIntArray supportedPrimitivesAndDurationsIntersection(
-                VibratorInfo[] infos) {
-            SparseIntArray intersection = new SparseIntArray();
-            SparseIntArray firstVibratorPrimitives = infos[0].getSupportedPrimitives();
-
-            primitiveIdLoop:
-            for (int i = 0; i < firstVibratorPrimitives.size(); i++) {
-                int primitiveId = firstVibratorPrimitives.keyAt(i);
-                int primitiveDuration = firstVibratorPrimitives.valueAt(i);
-                if (primitiveDuration == 0) {
-                    // The first vibrator already doesn't support this primitive, so skip it.
-                    continue primitiveIdLoop;
-                }
-
-                for (int j = 1; j < infos.length; j++) {
-                    int vibratorPrimitiveDuration = infos[j].getPrimitiveDuration(primitiveId);
-                    if (vibratorPrimitiveDuration == 0) {
-                        // One vibrator doesn't support this primitive, so the intersection doesn't.
-                        continue primitiveIdLoop;
-                    } else {
-                        // The primitive vibration duration is the maximum among all vibrators.
-                        primitiveDuration = Math.max(primitiveDuration, vibratorPrimitiveDuration);
-                    }
-                }
-
-                intersection.put(primitiveId, primitiveDuration);
-            }
-            return intersection;
-        }
-
-        private static int integerLimitIntersection(VibratorInfo[] infos,
-                Function<VibratorInfo, Integer> propertyGetter) {
-            int limit = 0; // Limit 0 means unlimited
-            for (VibratorInfo info : infos) {
-                int vibratorLimit = propertyGetter.apply(info);
-                if ((limit == 0) || (vibratorLimit > 0 && vibratorLimit < limit)) {
-                    // This vibrator is limited and intersection is unlimited or has a larger limit:
-                    // use smaller limit here for the intersection.
-                    limit = vibratorLimit;
-                }
-            }
-            return limit;
-        }
-
-        private static float floatPropertyIntersection(VibratorInfo[] infos,
-                Function<VibratorInfo, Float> propertyGetter) {
-            float property = propertyGetter.apply(infos[0]);
-            if (Float.isNaN(property)) {
-                // If one vibrator is undefined then the intersection is undefined.
-                return Float.NaN;
-            }
-            for (int i = 1; i < infos.length; i++) {
-                if (Float.compare(property, propertyGetter.apply(infos[i])) != 0) {
-                    // If one vibrator has a different value then the intersection is undefined.
-                    return Float.NaN;
-                }
-            }
-            return property;
-        }
-
-        @NonNull
-        private static FrequencyProfile frequencyProfileIntersection(VibratorInfo[] infos) {
-            float freqResolution = floatPropertyIntersection(infos,
-                    info -> info.getFrequencyProfile().getFrequencyResolutionHz());
-            float resonantFreq = floatPropertyIntersection(infos,
-                    VibratorInfo::getResonantFrequencyHz);
-            Range<Float> freqRange = frequencyRangeIntersection(infos, freqResolution);
-
-            if ((freqRange == null) || Float.isNaN(freqResolution)) {
-                return new FrequencyProfile(resonantFreq, Float.NaN, freqResolution, null);
-            }
-
-            int amplitudeCount =
-                    Math.round(1 + (freqRange.getUpper() - freqRange.getLower()) / freqResolution);
-            float[] maxAmplitudes = new float[amplitudeCount];
-
-            // Use MAX_VALUE here to ensure that the FrequencyProfile constructor called with this
-            // will fail if the loop below is broken and do not replace filled values with actual
-            // vibrator measurements.
-            Arrays.fill(maxAmplitudes, Float.MAX_VALUE);
-
-            for (VibratorInfo info : infos) {
-                Range<Float> vibratorFreqRange = info.getFrequencyProfile().getFrequencyRangeHz();
-                float[] vibratorMaxAmplitudes = info.getFrequencyProfile().getMaxAmplitudes();
-                int vibratorStartIdx = Math.round(
-                        (freqRange.getLower() - vibratorFreqRange.getLower()) / freqResolution);
-                int vibratorEndIdx = vibratorStartIdx + maxAmplitudes.length - 1;
-
-                if ((vibratorStartIdx < 0) || (vibratorEndIdx >= vibratorMaxAmplitudes.length)) {
-                    Slog.w(TAG, "Error calculating the intersection of vibrator frequency"
-                            + " profiles: attempted to fetch from vibrator "
-                            + info.getId() + " max amplitude with bad index " + vibratorStartIdx);
-                    return new FrequencyProfile(resonantFreq, Float.NaN, Float.NaN, null);
-                }
-
-                for (int i = 0; i < maxAmplitudes.length; i++) {
-                    maxAmplitudes[i] = Math.min(maxAmplitudes[i],
-                            vibratorMaxAmplitudes[vibratorStartIdx + i]);
-                }
-            }
-
-            return new FrequencyProfile(resonantFreq, freqRange.getLower(),
-                    freqResolution, maxAmplitudes);
-        }
-
-        @Nullable
-        private static Range<Float> frequencyRangeIntersection(VibratorInfo[] infos,
-                float frequencyResolution) {
-            Range<Float> firstRange = infos[0].getFrequencyProfile().getFrequencyRangeHz();
-            if (firstRange == null) {
-                // If one vibrator is undefined then the intersection is undefined.
-                return null;
-            }
-            float intersectionLower = firstRange.getLower();
-            float intersectionUpper = firstRange.getUpper();
-
-            // Generate the intersection of all vibrator supported ranges, making sure that both
-            // min supported frequencies are aligned w.r.t. the frequency resolution.
-
-            for (int i = 1; i < infos.length; i++) {
-                Range<Float> vibratorRange = infos[i].getFrequencyProfile().getFrequencyRangeHz();
-                if (vibratorRange == null) {
-                    // If one vibrator is undefined then the intersection is undefined.
-                    return null;
-                }
-
-                if ((vibratorRange.getLower() >= intersectionUpper)
-                        || (vibratorRange.getUpper() <= intersectionLower)) {
-                    // If the range and intersection are disjoint then the intersection is undefined
-                    return null;
-                }
-
-                float frequencyDelta = Math.abs(intersectionLower - vibratorRange.getLower());
-                if ((frequencyDelta % frequencyResolution) > EPSILON) {
-                    // If the intersection is not aligned with one vibrator then it's undefined
-                    return null;
-                }
-
-                intersectionLower = Math.max(intersectionLower, vibratorRange.getLower());
-                intersectionUpper = Math.min(intersectionUpper, vibratorRange.getUpper());
-            }
-
-            if ((intersectionUpper - intersectionLower) < frequencyResolution) {
-                // If the intersection is empty then it's undefined.
-                return null;
-            }
-
-            return Range.create(intersectionLower, intersectionUpper);
-        }
-    }
-
-    /**
      * Listener for all vibrators state change.
      *
      * <p>This registers a listener to all vibrators to merge the callbacks into a single state
diff --git a/core/java/android/os/VibratorInfo.java b/core/java/android/os/VibratorInfo.java
index 0b7d7c3..4f8c24d 100644
--- a/core/java/android/os/VibratorInfo.java
+++ b/core/java/android/os/VibratorInfo.java
@@ -156,6 +156,16 @@
             return false;
         }
         VibratorInfo that = (VibratorInfo) o;
+        return mId == that.mId && equalContent(that);
+    }
+
+    /**
+     * Returns {@code true} only if the properties and capabilities of the provided info, except for
+     * the ID, equals to this info. Returns {@code false} otherwise.
+     *
+     * @hide
+     */
+    public boolean equalContent(VibratorInfo that) {
         int supportedPrimitivesCount = mSupportedPrimitives.size();
         if (supportedPrimitivesCount != that.mSupportedPrimitives.size()) {
             return false;
@@ -168,7 +178,7 @@
                 return false;
             }
         }
-        return mId == that.mId && mCapabilities == that.mCapabilities
+        return mCapabilities == that.mCapabilities
                 && mPrimitiveDelayMax == that.mPrimitiveDelayMax
                 && mCompositionSizeMax == that.mCompositionSizeMax
                 && mPwlePrimitiveDurationMax == that.mPwlePrimitiveDurationMax
@@ -445,7 +455,8 @@
         return mFrequencyProfile;
     }
 
-    protected long getCapabilities() {
+    /** Returns a single int representing all the capabilities of the vibrator. */
+    public long getCapabilities() {
         return mCapabilities;
     }
 
diff --git a/core/java/android/os/vibrator/MultiVibratorInfo.java b/core/java/android/os/vibrator/MultiVibratorInfo.java
new file mode 100644
index 0000000..5f32731
--- /dev/null
+++ b/core/java/android/os/vibrator/MultiVibratorInfo.java
@@ -0,0 +1,294 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.os.vibrator;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.hardware.vibrator.IVibrator;
+import android.os.Vibrator;
+import android.os.VibratorInfo;
+import android.util.Range;
+import android.util.Slog;
+import android.util.SparseBooleanArray;
+import android.util.SparseIntArray;
+
+import java.util.Arrays;
+import java.util.function.Function;
+
+/**
+ * Represents multiple vibrator information as a single {@link VibratorInfo}.
+ *
+ * <p>This uses an intersection of all vibrators to decide the capabilities and effect/primitive
+ * support.
+ *
+ * @hide
+ */
+public final class MultiVibratorInfo extends VibratorInfo {
+    private static final String TAG = "MultiVibratorInfo";
+
+    // Epsilon used for float comparison applied in calculations for the merged info.
+    private static final float EPSILON = 1e-5f;
+
+    public MultiVibratorInfo(int id, VibratorInfo[] vibrators) {
+        this(id, vibrators, frequencyProfileIntersection(vibrators));
+    }
+
+    private MultiVibratorInfo(
+            int id, VibratorInfo[] vibrators, VibratorInfo.FrequencyProfile mergedProfile) {
+        super(id,
+                capabilitiesIntersection(vibrators, mergedProfile.isEmpty()),
+                supportedEffectsIntersection(vibrators),
+                supportedBrakingIntersection(vibrators),
+                supportedPrimitivesAndDurationsIntersection(vibrators),
+                integerLimitIntersection(vibrators, VibratorInfo::getPrimitiveDelayMax),
+                integerLimitIntersection(vibrators, VibratorInfo::getCompositionSizeMax),
+                integerLimitIntersection(vibrators, VibratorInfo::getPwlePrimitiveDurationMax),
+                integerLimitIntersection(vibrators, VibratorInfo::getPwleSizeMax),
+                floatPropertyIntersection(vibrators, VibratorInfo::getQFactor),
+                mergedProfile);
+    }
+
+    private static int capabilitiesIntersection(VibratorInfo[] infos,
+            boolean frequencyProfileIsEmpty) {
+        int intersection = ~0;
+        for (VibratorInfo info : infos) {
+            intersection &= info.getCapabilities();
+        }
+        if (frequencyProfileIsEmpty) {
+            // Revoke frequency control if the merged frequency profile ended up empty.
+            intersection &= ~IVibrator.CAP_FREQUENCY_CONTROL;
+        }
+        return intersection;
+    }
+
+    @Nullable
+    private static SparseBooleanArray supportedBrakingIntersection(VibratorInfo[] infos) {
+        for (VibratorInfo info : infos) {
+            if (!info.isBrakingSupportKnown()) {
+                // If one vibrator support is unknown, then the intersection is also unknown.
+                return null;
+            }
+        }
+
+        SparseBooleanArray intersection = new SparseBooleanArray();
+        SparseBooleanArray firstVibratorBraking = infos[0].getSupportedBraking();
+
+        brakingIdLoop:
+        for (int i = 0; i < firstVibratorBraking.size(); i++) {
+            int brakingId = firstVibratorBraking.keyAt(i);
+            if (!firstVibratorBraking.valueAt(i)) {
+                // The first vibrator already doesn't support this braking, so skip it.
+                continue brakingIdLoop;
+            }
+
+            for (int j = 1; j < infos.length; j++) {
+                if (!infos[j].hasBrakingSupport(brakingId)) {
+                    // One vibrator doesn't support this braking, so the intersection doesn't.
+                    continue brakingIdLoop;
+                }
+            }
+
+            intersection.put(brakingId, true);
+        }
+
+        return intersection;
+    }
+
+    @Nullable
+    private static SparseBooleanArray supportedEffectsIntersection(VibratorInfo[] infos) {
+        for (VibratorInfo info : infos) {
+            if (!info.isEffectSupportKnown()) {
+                // If one vibrator support is unknown, then the intersection is also unknown.
+                return null;
+            }
+        }
+
+        SparseBooleanArray intersection = new SparseBooleanArray();
+        SparseBooleanArray firstVibratorEffects = infos[0].getSupportedEffects();
+
+        effectIdLoop:
+        for (int i = 0; i < firstVibratorEffects.size(); i++) {
+            int effectId = firstVibratorEffects.keyAt(i);
+            if (!firstVibratorEffects.valueAt(i)) {
+                // The first vibrator already doesn't support this effect, so skip it.
+                continue effectIdLoop;
+            }
+
+            for (int j = 1; j < infos.length; j++) {
+                if (infos[j].isEffectSupported(effectId) != Vibrator.VIBRATION_EFFECT_SUPPORT_YES) {
+                    // One vibrator doesn't support this effect, so the intersection doesn't.
+                    continue effectIdLoop;
+                }
+            }
+
+            intersection.put(effectId, true);
+        }
+
+        return intersection;
+    }
+
+    @NonNull
+    private static SparseIntArray supportedPrimitivesAndDurationsIntersection(
+            VibratorInfo[] infos) {
+        SparseIntArray intersection = new SparseIntArray();
+        SparseIntArray firstVibratorPrimitives = infos[0].getSupportedPrimitives();
+
+        primitiveIdLoop:
+        for (int i = 0; i < firstVibratorPrimitives.size(); i++) {
+            int primitiveId = firstVibratorPrimitives.keyAt(i);
+            int primitiveDuration = firstVibratorPrimitives.valueAt(i);
+            if (primitiveDuration == 0) {
+                // The first vibrator already doesn't support this primitive, so skip it.
+                continue primitiveIdLoop;
+            }
+
+            for (int j = 1; j < infos.length; j++) {
+                int vibratorPrimitiveDuration = infos[j].getPrimitiveDuration(primitiveId);
+                if (vibratorPrimitiveDuration == 0) {
+                    // One vibrator doesn't support this primitive, so the intersection doesn't.
+                    continue primitiveIdLoop;
+                } else {
+                    // The primitive vibration duration is the maximum among all vibrators.
+                    primitiveDuration = Math.max(primitiveDuration, vibratorPrimitiveDuration);
+                }
+            }
+
+            intersection.put(primitiveId, primitiveDuration);
+        }
+        return intersection;
+    }
+
+    private static int integerLimitIntersection(VibratorInfo[] infos,
+            Function<VibratorInfo, Integer> propertyGetter) {
+        int limit = 0; // Limit 0 means unlimited
+        for (VibratorInfo info : infos) {
+            int vibratorLimit = propertyGetter.apply(info);
+            if ((limit == 0) || (vibratorLimit > 0 && vibratorLimit < limit)) {
+                // This vibrator is limited and intersection is unlimited or has a larger limit:
+                // use smaller limit here for the intersection.
+                limit = vibratorLimit;
+            }
+        }
+        return limit;
+    }
+
+    private static float floatPropertyIntersection(VibratorInfo[] infos,
+            Function<VibratorInfo, Float> propertyGetter) {
+        float property = propertyGetter.apply(infos[0]);
+        if (Float.isNaN(property)) {
+            // If one vibrator is undefined then the intersection is undefined.
+            return Float.NaN;
+        }
+        for (int i = 1; i < infos.length; i++) {
+            if (Float.compare(property, propertyGetter.apply(infos[i])) != 0) {
+                // If one vibrator has a different value then the intersection is undefined.
+                return Float.NaN;
+            }
+        }
+        return property;
+    }
+
+    @NonNull
+    private static FrequencyProfile frequencyProfileIntersection(VibratorInfo[] infos) {
+        float freqResolution = floatPropertyIntersection(infos,
+                info -> info.getFrequencyProfile().getFrequencyResolutionHz());
+        float resonantFreq = floatPropertyIntersection(infos,
+                VibratorInfo::getResonantFrequencyHz);
+        Range<Float> freqRange = frequencyRangeIntersection(infos, freqResolution);
+
+        if ((freqRange == null) || Float.isNaN(freqResolution)) {
+            return new FrequencyProfile(resonantFreq, Float.NaN, freqResolution, null);
+        }
+
+        int amplitudeCount =
+                Math.round(1 + (freqRange.getUpper() - freqRange.getLower()) / freqResolution);
+        float[] maxAmplitudes = new float[amplitudeCount];
+
+        // Use MAX_VALUE here to ensure that the FrequencyProfile constructor called with this
+        // will fail if the loop below is broken and do not replace filled values with actual
+        // vibrator measurements.
+        Arrays.fill(maxAmplitudes, Float.MAX_VALUE);
+
+        for (VibratorInfo info : infos) {
+            Range<Float> vibratorFreqRange = info.getFrequencyProfile().getFrequencyRangeHz();
+            float[] vibratorMaxAmplitudes = info.getFrequencyProfile().getMaxAmplitudes();
+            int vibratorStartIdx = Math.round(
+                    (freqRange.getLower() - vibratorFreqRange.getLower()) / freqResolution);
+            int vibratorEndIdx = vibratorStartIdx + maxAmplitudes.length - 1;
+
+            if ((vibratorStartIdx < 0) || (vibratorEndIdx >= vibratorMaxAmplitudes.length)) {
+                Slog.w(TAG, "Error calculating the intersection of vibrator frequency"
+                        + " profiles: attempted to fetch from vibrator "
+                        + info.getId() + " max amplitude with bad index " + vibratorStartIdx);
+                return new FrequencyProfile(resonantFreq, Float.NaN, Float.NaN, null);
+            }
+
+            for (int i = 0; i < maxAmplitudes.length; i++) {
+                maxAmplitudes[i] = Math.min(maxAmplitudes[i],
+                        vibratorMaxAmplitudes[vibratorStartIdx + i]);
+            }
+        }
+
+        return new FrequencyProfile(resonantFreq, freqRange.getLower(),
+                freqResolution, maxAmplitudes);
+    }
+
+    @Nullable
+    private static Range<Float> frequencyRangeIntersection(VibratorInfo[] infos,
+            float frequencyResolution) {
+        Range<Float> firstRange = infos[0].getFrequencyProfile().getFrequencyRangeHz();
+        if (firstRange == null) {
+            // If one vibrator is undefined then the intersection is undefined.
+            return null;
+        }
+        float intersectionLower = firstRange.getLower();
+        float intersectionUpper = firstRange.getUpper();
+
+        // Generate the intersection of all vibrator supported ranges, making sure that both
+        // min supported frequencies are aligned w.r.t. the frequency resolution.
+
+        for (int i = 1; i < infos.length; i++) {
+            Range<Float> vibratorRange = infos[i].getFrequencyProfile().getFrequencyRangeHz();
+            if (vibratorRange == null) {
+                // If one vibrator is undefined then the intersection is undefined.
+                return null;
+            }
+
+            if ((vibratorRange.getLower() >= intersectionUpper)
+                    || (vibratorRange.getUpper() <= intersectionLower)) {
+                // If the range and intersection are disjoint then the intersection is undefined
+                return null;
+            }
+
+            float frequencyDelta = Math.abs(intersectionLower - vibratorRange.getLower());
+            if ((frequencyDelta % frequencyResolution) > EPSILON) {
+                // If the intersection is not aligned with one vibrator then it's undefined
+                return null;
+            }
+
+            intersectionLower = Math.max(intersectionLower, vibratorRange.getLower());
+            intersectionUpper = Math.min(intersectionUpper, vibratorRange.getUpper());
+        }
+
+        if ((intersectionUpper - intersectionLower) < frequencyResolution) {
+            // If the intersection is empty then it's undefined.
+            return null;
+        }
+
+        return Range.create(intersectionLower, intersectionUpper);
+    }
+}
diff --git a/core/java/android/os/vibrator/VibratorInfoFactory.java b/core/java/android/os/vibrator/VibratorInfoFactory.java
new file mode 100644
index 0000000..d10d7ec
--- /dev/null
+++ b/core/java/android/os/vibrator/VibratorInfoFactory.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.os.vibrator;
+
+import android.annotation.NonNull;
+import android.os.VibratorInfo;
+
+/**
+ * Factory for creating {@link VibratorInfo}s.
+ *
+ * @hide
+ */
+public final class VibratorInfoFactory {
+    /**
+     * Creates a single {@link VibratorInfo} that is an intersection of a given collection of
+     * {@link VibratorInfo}s. That is, the capabilities of the returned info will be an
+     * intersection of that of the provided infos.
+     *
+     * @param id the ID for the new {@link VibratorInfo}.
+     * @param vibratorInfos the {@link VibratorInfo}s from which to create a single
+     *      {@link VibratorInfo}.
+     * @return a {@link VibratorInfo} that represents the intersection of {@code vibratorInfos}.
+     */
+    @NonNull
+    public static VibratorInfo create(int id, @NonNull VibratorInfo[] vibratorInfos) {
+        if (vibratorInfos.length == 0) {
+            return new VibratorInfo.Builder(id).build();
+        }
+        if (vibratorInfos.length == 1) {
+            // Create an equivalent info with the requested ID.
+            return new VibratorInfo(id, vibratorInfos[0]);
+        }
+        // Create a MultiVibratorInfo that intersects all the given infos and has the requested ID.
+        return new MultiVibratorInfo(id, vibratorInfos);
+    }
+
+    private VibratorInfoFactory() {}
+}
diff --git a/core/java/android/service/notification/NotificationRankingUpdate.java b/core/java/android/service/notification/NotificationRankingUpdate.java
index 75640bd..f3b4c6d 100644
--- a/core/java/android/service/notification/NotificationRankingUpdate.java
+++ b/core/java/android/service/notification/NotificationRankingUpdate.java
@@ -92,6 +92,7 @@
                 mapParcel.recycle();
                 if (buffer != null) {
                     mRankingMapFd.unmap(buffer);
+                    mRankingMapFd.close();
                 }
             }
         } else {
diff --git a/core/java/android/service/quicksettings/Tile.java b/core/java/android/service/quicksettings/Tile.java
index 910fc44..c027981 100644
--- a/core/java/android/service/quicksettings/Tile.java
+++ b/core/java/android/service/quicksettings/Tile.java
@@ -64,6 +64,7 @@
     private IBinder mToken;
     private Icon mIcon;
     private CharSequence mLabel;
+    private CharSequence mDefaultLabel;
     private CharSequence mSubtitle;
     private CharSequence mContentDescription;
     private CharSequence mStateDescription;
@@ -142,10 +143,25 @@
      * Gets the current label for the tile.
      */
     public CharSequence getLabel() {
+        return mLabel != null ? mLabel : mDefaultLabel;
+    }
+
+    /**
+     * @hide
+     * @return
+     */
+    public CharSequence getCustomLabel() {
         return mLabel;
     }
 
     /**
+     * @hide
+     */
+    public void setDefaultLabel(CharSequence defaultLabel) {
+        mDefaultLabel = defaultLabel;
+    }
+
+    /**
      * Sets the current label for the tile.
      *
      * Does not take effect until {@link #updateTile()} is called.
@@ -267,6 +283,7 @@
         }
         dest.writeInt(mState);
         TextUtils.writeToParcel(mLabel, dest, flags);
+        TextUtils.writeToParcel(mDefaultLabel, dest, flags);
         TextUtils.writeToParcel(mSubtitle, dest, flags);
         TextUtils.writeToParcel(mContentDescription, dest, flags);
         TextUtils.writeToParcel(mStateDescription, dest, flags);
@@ -285,6 +302,7 @@
         }
         mState = source.readInt();
         mLabel = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
+        mDefaultLabel = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
         mSubtitle = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
         mContentDescription = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
         mStateDescription = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
diff --git a/core/java/android/view/InsetsAnimationControlImpl.java b/core/java/android/view/InsetsAnimationControlImpl.java
index 6c5f195..fabfed3 100644
--- a/core/java/android/view/InsetsAnimationControlImpl.java
+++ b/core/java/android/view/InsetsAnimationControlImpl.java
@@ -28,7 +28,6 @@
 import static android.view.InsetsAnimationControlImplProto.PENDING_INSETS;
 import static android.view.InsetsAnimationControlImplProto.SHOWN_ON_FINISH;
 import static android.view.InsetsAnimationControlImplProto.TMP_MATRIX;
-import static android.view.InsetsController.ANIMATION_TYPE_SHOW;
 import static android.view.InsetsController.AnimationType;
 import static android.view.InsetsController.DEBUG;
 import static android.view.InsetsController.LAYOUT_INSETS_DURING_ANIMATION_SHOWN;
@@ -285,15 +284,11 @@
             return false;
         }
         final Insets offset = Insets.subtract(mShownInsets, mPendingInsets);
-        ArrayList<SurfaceParams> params = new ArrayList<>();
-        updateLeashesForSide(ISIDE_LEFT, offset.left, mPendingInsets.left, params, outState,
-                mPendingAlpha);
-        updateLeashesForSide(ISIDE_TOP, offset.top, mPendingInsets.top, params, outState,
-                mPendingAlpha);
-        updateLeashesForSide(ISIDE_RIGHT, offset.right, mPendingInsets.right, params, outState,
-                mPendingAlpha);
-        updateLeashesForSide(ISIDE_BOTTOM, offset.bottom, mPendingInsets.bottom, params, outState,
-                mPendingAlpha);
+        final ArrayList<SurfaceParams> params = new ArrayList<>();
+        updateLeashesForSide(ISIDE_LEFT, offset.left, params, outState, mPendingAlpha);
+        updateLeashesForSide(ISIDE_TOP, offset.top, params, outState, mPendingAlpha);
+        updateLeashesForSide(ISIDE_RIGHT, offset.right, params, outState, mPendingAlpha);
+        updateLeashesForSide(ISIDE_BOTTOM, offset.bottom, params, outState, mPendingAlpha);
 
         mController.applySurfaceParams(params.toArray(new SurfaceParams[params.size()]));
         mCurrentInsets = mPendingInsets;
@@ -457,7 +452,7 @@
         return alpha >= 1 ? 1 : (alpha <= 0 ? 0 : alpha);
     }
 
-    private void updateLeashesForSide(@InternalInsetsSide int side, int offset, int inset,
+    private void updateLeashesForSide(@InternalInsetsSide int side, int offset,
             ArrayList<SurfaceParams> surfaceParams, @Nullable InsetsState outState, float alpha) {
         final ArraySet<InsetsSourceControl> controls = mSideControlsMap.get(side);
         if (controls == null) {
@@ -475,9 +470,9 @@
             }
             addTranslationToMatrix(side, offset, mTmpMatrix, mTmpFrame);
 
-            final boolean visible = mHasZeroInsetsIme && side == ISIDE_BOTTOM
-                    ? (mAnimationType == ANIMATION_TYPE_SHOW || !mFinished)
-                    : inset != 0;
+            final boolean visible = mPendingFraction == 0 && source != null
+                    ? source.isVisible()
+                    : !mFinished || mShownOnFinish;
 
             if (outState != null && source != null) {
                 outState.addSource(new InsetsSource(source)
diff --git a/core/java/android/view/InsetsController.java b/core/java/android/view/InsetsController.java
index c6d8bd1..8ec7d67 100644
--- a/core/java/android/view/InsetsController.java
+++ b/core/java/android/view/InsetsController.java
@@ -666,9 +666,6 @@
     /** Set of inset types for which an animation was started since last resetting this field */
     private @InsetsType int mLastStartedAnimTypes;
 
-    /** Set of inset types which cannot be controlled by the user animation */
-    private @InsetsType int mDisabledUserAnimationInsetsTypes;
-
     /** Set of inset types which are existing */
     private @InsetsType int mExistingTypes = 0;
 
@@ -887,21 +884,11 @@
         mState.set(newState, 0 /* types */);
         @InsetsType int existingTypes = 0;
         @InsetsType int visibleTypes = 0;
-        @InsetsType int disabledUserAnimationTypes = 0;
         @InsetsType int[] cancelledUserAnimationTypes = {0};
         for (int i = 0, size = newState.sourceSize(); i < size; i++) {
             final InsetsSource source = newState.sourceAt(i);
             @InsetsType int type = source.getType();
             @AnimationType int animationType = getAnimationType(type);
-            if (!source.isUserControllable()) {
-                // The user animation is not allowed when visible frame is empty.
-                disabledUserAnimationTypes |= type;
-                if (animationType == ANIMATION_TYPE_USER) {
-                    // Existing user animation needs to be cancelled.
-                    animationType = ANIMATION_TYPE_NONE;
-                    cancelledUserAnimationTypes[0] |= type;
-                }
-            }
             final InsetsSourceConsumer consumer = mSourceConsumers.get(source.getId());
             if (consumer != null) {
                 consumer.updateSource(source, animationType);
@@ -931,28 +918,11 @@
         }
         InsetsState.traverse(mState, newState, mRemoveGoneSources);
 
-        updateDisabledUserAnimationTypes(disabledUserAnimationTypes);
-
         if (cancelledUserAnimationTypes[0] != 0) {
             mHandler.post(() -> show(cancelledUserAnimationTypes[0]));
         }
     }
 
-    private void updateDisabledUserAnimationTypes(@InsetsType int disabledUserAnimationTypes) {
-        @InsetsType int diff = mDisabledUserAnimationInsetsTypes ^ disabledUserAnimationTypes;
-        if (diff != 0) {
-            for (int i = mSourceConsumers.size() - 1; i >= 0; i--) {
-                InsetsSourceConsumer consumer = mSourceConsumers.valueAt(i);
-                if (consumer.getControl() != null && (consumer.getType() & diff) != 0) {
-                    mHandler.removeCallbacks(mInvokeControllableInsetsChangedListeners);
-                    mHandler.post(mInvokeControllableInsetsChangedListeners);
-                    break;
-                }
-            }
-            mDisabledUserAnimationInsetsTypes = disabledUserAnimationTypes;
-        }
-    }
-
     private boolean captionInsetsUnchanged() {
         if (CAPTION_ON_SHELL) {
             return false;
@@ -1332,26 +1302,6 @@
                     + " while an existing " + Type.toString(mTypesBeingCancelled)
                     + " is being cancelled.");
         }
-        if (animationType == ANIMATION_TYPE_USER) {
-            final @InsetsType int disabledTypes = types & mDisabledUserAnimationInsetsTypes;
-            if (DEBUG) Log.d(TAG, "user animation disabled types: " + disabledTypes);
-            types &= ~mDisabledUserAnimationInsetsTypes;
-
-            if ((disabledTypes & ime()) != 0) {
-                ImeTracker.forLogging().onFailed(statsToken,
-                        ImeTracker.PHASE_CLIENT_DISABLED_USER_ANIMATION);
-
-                if (fromIme
-                        && !mState.isSourceOrDefaultVisible(mImeSourceConsumer.getId(), ime())) {
-                    // We've requested IMM to show IME, but the IME is not controllable. We need to
-                    // cancel the request.
-                    setRequestedVisibleTypes(0 /* visibleTypes */, ime());
-                    if (mImeSourceConsumer.onAnimationStateChanged(false /* running */)) {
-                        notifyVisibilityChanged();
-                    }
-                }
-            }
-        }
         if (types == 0) {
             // nothing to animate.
             listener.onCancelled(null);
@@ -1954,7 +1904,7 @@
         for (int i = mSourceConsumers.size() - 1; i >= 0; i--) {
             InsetsSourceConsumer consumer = mSourceConsumers.valueAt(i);
             InsetsSource source = mState.peekSource(consumer.getId());
-            if (consumer.getControl() != null && source != null && source.isUserControllable()) {
+            if (consumer.getControl() != null && source != null) {
                 result |= consumer.getType();
             }
         }
diff --git a/core/java/android/view/InsetsSource.java b/core/java/android/view/InsetsSource.java
index ff009ed..0d5704e 100644
--- a/core/java/android/view/InsetsSource.java
+++ b/core/java/android/view/InsetsSource.java
@@ -187,11 +187,6 @@
         return (mFlags & flags) == flags;
     }
 
-    boolean isUserControllable() {
-        // If mVisibleFrame is null, it will be the same area as mFrame.
-        return mVisibleFrame == null || !mVisibleFrame.isEmpty();
-    }
-
     /**
      * Calculates the insets this source will cause to a client window.
      *
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 92509c9..5e19c67 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -9279,8 +9279,8 @@
             }
 
             while (parentGroup != null && !parentGroup.isImportantForAutofill()) {
-                ignoredParentLeft += parentGroup.mLeft;
-                ignoredParentTop += parentGroup.mTop;
+                ignoredParentLeft += parentGroup.mLeft - parentGroup.mScrollX;
+                ignoredParentTop += parentGroup.mTop - parentGroup.mScrollY;
 
                 viewParent = parentGroup.getParent();
                 if (viewParent instanceof View) {
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index e6ecd6e..ddd3269 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -322,13 +322,6 @@
             SystemProperties.getBoolean("persist.wm.debug.client_immersive_confirmation", false);
 
     /**
-     * Whether the client should compute the window frame on its own.
-     * @hide
-     */
-    public static final boolean LOCAL_LAYOUT =
-            SystemProperties.getBoolean("persist.debug.local_layout", true);
-
-    /**
      * Set this system property to true to force the view hierarchy to render
      * at 60 Hz. This can be used to measure the potential framerate.
      */
@@ -1912,8 +1905,8 @@
         final float compatScale = frames.compatScale;
         final boolean frameChanged = !mWinFrame.equals(frame);
         final boolean configChanged = !mLastReportedMergedConfiguration.equals(mergedConfiguration);
-        final boolean attachedFrameChanged = LOCAL_LAYOUT
-                && !Objects.equals(mTmpFrames.attachedFrame, attachedFrame);
+        final boolean attachedFrameChanged =
+                !Objects.equals(mTmpFrames.attachedFrame, attachedFrame);
         final boolean displayChanged = mDisplay.getDisplayId() != displayId;
         final boolean compatScaleChanged = mTmpFrames.compatScale != compatScale;
         final boolean dragResizingChanged = mPendingDragResizing != dragResizing;
@@ -8309,8 +8302,7 @@
         final int measuredWidth = mMeasuredWidth;
         final int measuredHeight = mMeasuredHeight;
         final boolean relayoutAsync;
-        if (LOCAL_LAYOUT
-                && (mViewFrameInfo.flags & FrameInfo.FLAG_WINDOW_VISIBILITY_CHANGED) == 0
+        if ((mViewFrameInfo.flags & FrameInfo.FLAG_WINDOW_VISIBILITY_CHANGED) == 0
                 && mWindowAttributes.type != TYPE_APPLICATION_STARTING
                 && mSyncSeqId <= mLastSyncSeqId
                 && winConfigFromAm.diff(winConfigFromWm, false /* compareUndefined */) == 0) {
diff --git a/core/java/com/android/internal/os/OWNERS b/core/java/com/android/internal/os/OWNERS
index 0b9773e..e35b7f1 100644
--- a/core/java/com/android/internal/os/OWNERS
+++ b/core/java/com/android/internal/os/OWNERS
@@ -11,6 +11,7 @@
 per-file *ChargeCalculator* = file:/BATTERY_STATS_OWNERS
 per-file *PowerCalculator* = file:/BATTERY_STATS_OWNERS
 per-file *PowerEstimator* = file:/BATTERY_STATS_OWNERS
+per-file *PowerStats* = file:/BATTERY_STATS_OWNERS
 per-file *Kernel* = file:/BATTERY_STATS_OWNERS
 per-file *MultiState* = file:/BATTERY_STATS_OWNERS
 per-file *PowerProfile* = file:/BATTERY_STATS_OWNERS
diff --git a/core/java/com/android/internal/os/PowerStats.java b/core/java/com/android/internal/os/PowerStats.java
new file mode 100644
index 0000000..1169552
--- /dev/null
+++ b/core/java/com/android/internal/os/PowerStats.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.os;
+
+import android.os.BatteryConsumer;
+import android.util.IndentingPrintWriter;
+import android.util.SparseArray;
+
+import java.util.Arrays;
+
+/**
+ * Container for power stats, acquired by various PowerStatsCollector classes. See subclasses for
+ * details.
+ */
+public final class PowerStats {
+    /**
+     * Power component (e.g. CPU, WIFI etc) that this snapshot relates to.
+     */
+    public @BatteryConsumer.PowerComponent int powerComponentId;
+
+    /**
+     * Duration, in milliseconds, covered by this snapshot.
+     */
+    public long durationMs;
+
+    /**
+     * Device-wide stats.
+     */
+    public long[] stats;
+
+    /**
+     * Per-UID CPU stats.
+     */
+    public final SparseArray<long[]> uidStats = new SparseArray<>();
+
+    /**
+     * Prints the contents of the stats snapshot.
+     */
+    public void dump(IndentingPrintWriter pw) {
+        pw.print("PowerStats: ");
+        pw.println(BatteryConsumer.powerComponentIdToString(powerComponentId));
+        pw.increaseIndent();
+        pw.print("duration", durationMs).println();
+        for (int i = 0; i < uidStats.size(); i++) {
+            pw.print("UID ");
+            pw.print(uidStats.keyAt(i));
+            pw.print(": ");
+            pw.print(Arrays.toString(uidStats.valueAt(i)));
+            pw.println();
+        }
+        pw.decreaseIndent();
+    }
+}
diff --git a/core/java/com/android/internal/widget/BigPictureNotificationImageView.java b/core/java/com/android/internal/widget/BigPictureNotificationImageView.java
index 3a7cf74..f95f5db 100644
--- a/core/java/com/android/internal/widget/BigPictureNotificationImageView.java
+++ b/core/java/com/android/internal/widget/BigPictureNotificationImageView.java
@@ -37,13 +37,16 @@
  * Icon.loadDrawable().
  */
 @RemoteViews.RemoteView
-public class BigPictureNotificationImageView extends ImageView {
+public class BigPictureNotificationImageView extends ImageView implements
+        NotificationDrawableConsumer {
 
     private static final String TAG = BigPictureNotificationImageView.class.getSimpleName();
 
     private final int mMaximumDrawableWidth;
     private final int mMaximumDrawableHeight;
 
+    private NotificationIconManager mIconManager;
+
     public BigPictureNotificationImageView(@NonNull Context context) {
         this(context, null, 0, 0);
     }
@@ -69,6 +72,19 @@
                         : R.dimen.notification_big_picture_max_height);
     }
 
+
+    /**
+     * Sets an {@link NotificationIconManager} on this ImageView, which handles the loading of
+     * icons, instead of using the {@link LocalImageResolver} directly.
+     * If set, it overrides the behaviour of {@link #setImageIconAsync} and {@link #setImageIcon},
+     * and it expects that the content of this imageView is only updated calling these two methods.
+     *
+     * @param iconManager to be called, when the icon is updated
+     */
+    public void setIconManager(NotificationIconManager iconManager) {
+        mIconManager = iconManager;
+    }
+
     @Override
     @android.view.RemotableViewMethod(asyncImpl = "setImageURIAsync")
     public void setImageURI(@Nullable Uri uri) {
@@ -84,11 +100,20 @@
     @Override
     @android.view.RemotableViewMethod(asyncImpl = "setImageIconAsync")
     public void setImageIcon(@Nullable Icon icon) {
+        if (mIconManager != null) {
+            mIconManager.updateIcon(this, icon).run();
+            return;
+        }
+        // old code path
         setImageDrawable(loadImage(icon));
     }
 
     /** @hide **/
     public Runnable setImageIconAsync(@Nullable Icon icon) {
+        if (mIconManager != null) {
+            return mIconManager.updateIcon(this, icon);
+        }
+        // old code path
         final Drawable drawable = loadImage(icon);
         return () -> setImageDrawable(drawable);
     }
diff --git a/core/java/com/android/internal/widget/ConversationLayout.java b/core/java/com/android/internal/widget/ConversationLayout.java
index 5b6b360..42be784 100644
--- a/core/java/com/android/internal/widget/ConversationLayout.java
+++ b/core/java/com/android/internal/widget/ConversationLayout.java
@@ -149,6 +149,7 @@
     private View mAppNameDivider;
     private TouchDelegateComposite mTouchDelegate = new TouchDelegateComposite(this);
     private ArrayList<MessagingLinearLayout.MessagingChild> mToRecycle = new ArrayList<>();
+    private boolean mPrecomputedTextEnabled = false;
 
     public ConversationLayout(@NonNull Context context) {
         super(context);
@@ -389,36 +390,37 @@
      */
     @RemotableViewMethod(asyncImpl = "setDataAsync")
     public void setData(Bundle extras) {
+        bind(parseMessagingData(extras, /* usePrecomputedText= */ false));
+    }
+
+    @NonNull
+    private MessagingData parseMessagingData(Bundle extras, boolean usePrecomputedText) {
         Parcelable[] messages = extras.getParcelableArray(Notification.EXTRA_MESSAGES);
-        List<Notification.MessagingStyle.Message> newMessages
-                = Notification.MessagingStyle.Message.getMessagesFromBundleArray(messages);
+        List<Notification.MessagingStyle.Message> newMessages =
+                Notification.MessagingStyle.Message.getMessagesFromBundleArray(messages);
         Parcelable[] histMessages = extras.getParcelableArray(Notification.EXTRA_HISTORIC_MESSAGES);
-        List<Notification.MessagingStyle.Message> newHistoricMessages
-                = Notification.MessagingStyle.Message.getMessagesFromBundleArray(histMessages);
+        List<Notification.MessagingStyle.Message> newHistoricMessages =
+                Notification.MessagingStyle.Message.getMessagesFromBundleArray(histMessages);
 
         // mUser now set (would be nice to avoid the side effect but WHATEVER)
         final Person user = extras.getParcelable(Notification.EXTRA_MESSAGING_PERSON, Person.class);
         // Append remote input history to newMessages (again, side effect is lame but WHATEVS)
         RemoteInputHistoryItem[] history = (RemoteInputHistoryItem[])
-                extras.getParcelableArray(Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS, android.app.RemoteInputHistoryItem.class);
+                extras.getParcelableArray(Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS,
+                        RemoteInputHistoryItem.class);
         addRemoteInputHistoryToMessages(newMessages, history);
 
         boolean showSpinner =
                 extras.getBoolean(Notification.EXTRA_SHOW_REMOTE_INPUT_SPINNER, false);
         int unreadCount = extras.getInt(Notification.EXTRA_CONVERSATION_UNREAD_MESSAGE_COUNT);
 
-        // convert MessagingStyle.Message to MessagingMessage, re-using ones from a previous binding
-        // if they exist
         final List<MessagingMessage> newMessagingMessages =
-                createMessages(newMessages, /* isHistoric= */false,
-                        /* usePrecomputedText= */false);
+                createMessages(newMessages, /* isHistoric= */false, usePrecomputedText);
         final List<MessagingMessage> newHistoricMessagingMessages =
-                createMessages(newHistoricMessages, /* isHistoric= */true,
-                        /* usePrecomputedText= */false);
-        // bind it, baby
-        bindViews(user, showSpinner, unreadCount,
-                newMessagingMessages,
-                newHistoricMessagingMessages);
+                createMessages(newHistoricMessages, /* isHistoric= */true, usePrecomputedText);
+
+        return new MessagingData(user, showSpinner, unreadCount,
+                newHistoricMessagingMessages, newMessagingMessages);
     }
 
     /**
@@ -430,7 +432,33 @@
      */
     @NonNull
     public Runnable setDataAsync(Bundle extras) {
-        return () -> setData(extras);
+        if (!mPrecomputedTextEnabled) {
+            return () -> setData(extras);
+        }
+
+        final MessagingData messagingData =
+                parseMessagingData(extras, /* usePrecomputedText= */ true);
+
+        return () -> {
+            finalizeInflate(messagingData.getHistoricMessagingMessages());
+            finalizeInflate(messagingData.getNewMessagingMessages());
+
+            bind(messagingData);
+        };
+    }
+
+    /**
+     * enable/disable precomputed text usage
+     * @hide
+     */
+    public void setPrecomputedTextEnabled(boolean precomputedTextEnabled) {
+        mPrecomputedTextEnabled = precomputedTextEnabled;
+    }
+
+    private void finalizeInflate(List<MessagingMessage> historicMessagingMessages) {
+        for (MessagingMessage messagingMessage : historicMessagingMessages) {
+            messagingMessage.finalizeInflate();
+        }
     }
 
     @Override
@@ -460,17 +488,12 @@
         }
     }
 
+    private void bind(MessagingData messagingData) {
+        setUser(messagingData.getUser());
+        setUnreadCount(messagingData.getUnreadCount());
 
-    private void bindViews(Person user,
-            boolean showSpinner, int unreadCount, List<MessagingMessage> newMessagingMessages,
-            List<MessagingMessage> newHistoricMessagingMessages) {
-        setUser(user);
-        setUnreadCount(unreadCount);
-        bind(showSpinner, newMessagingMessages, newHistoricMessagingMessages);
-    }
-
-    private void bind(boolean showSpinner, List<MessagingMessage> messages,
-            List<MessagingMessage> historicMessages) {
+        List<MessagingMessage> messages = messagingData.getNewMessagingMessages();
+        List<MessagingMessage> historicMessages = messagingData.getHistoricMessagingMessages();
         // Copy our groups, before they get clobbered
         ArrayList<MessagingGroup> oldGroups = new ArrayList<>(mGroups);
 
@@ -483,7 +506,7 @@
 
         // Let's now create the views and reorder them accordingly
         //   side-effect: updates mGroups, mAddedGroups
-        createGroupViews(groups, senders, showSpinner);
+        createGroupViews(groups, senders, messagingData.getShowSpinner());
 
         // Let's first check which groups were removed altogether and remove them in one animation
         removeGroups(oldGroups);
@@ -585,7 +608,7 @@
 
             // When collapsed, we're displaying the image message in a dedicated container
             // on the right of the layout instead of inline. Let's add the isolated image there
-            MessagingGroup messagingGroup = mGroups.get(mGroups.size() -1);
+            MessagingGroup messagingGroup = mGroups.get(mGroups.size() - 1);
             MessagingImageMessage isolatedMessage = messagingGroup.getIsolatedMessage();
             if (isolatedMessage != null) {
                 newMessage = isolatedMessage.getView();
@@ -1042,7 +1065,7 @@
             }
             if (visibleChildren > 0 && group.getVisibility() == GONE) {
                 group.setVisibility(VISIBLE);
-            } else if (visibleChildren == 0 && group.getVisibility() != GONE)   {
+            } else if (visibleChildren == 0 && group.getVisibility() != GONE) {
                 group.setVisibility(GONE);
             }
         }
@@ -1259,7 +1282,7 @@
         public boolean onTouchEvent(MotionEvent event) {
             float x = event.getX();
             float y = event.getY();
-            for (TouchDelegate delegate: mDelegates) {
+            for (TouchDelegate delegate : mDelegates) {
                 event.setLocation(x, y);
                 if (delegate.onTouchEvent(event)) {
                     return true;
diff --git a/core/java/com/android/internal/widget/MessagingData.java b/core/java/com/android/internal/widget/MessagingData.java
new file mode 100644
index 0000000..85b0201
--- /dev/null
+++ b/core/java/com/android/internal/widget/MessagingData.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.widget;
+
+import android.app.Person;
+
+import java.util.List;
+
+/**
+ * @hide
+ */
+final class MessagingData {
+    private final Person mUser;
+    private final boolean mShowSpinner;
+    private final List<MessagingMessage> mHistoricMessagingMessages;
+    private final List<MessagingMessage> mNewMessagingMessages;
+    private final int mUnreadCount;
+
+    MessagingData(Person user, boolean showSpinner,
+            List<MessagingMessage> historicMessagingMessages,
+            List<MessagingMessage> newMessagingMessages) {
+        this(user, showSpinner, /* unreadCount= */0,
+                historicMessagingMessages, newMessagingMessages);
+    }
+
+    MessagingData(Person user, boolean showSpinner,
+            int unreadCount,
+            List<MessagingMessage> historicMessagingMessages,
+            List<MessagingMessage> newMessagingMessages) {
+        mUser = user;
+        mShowSpinner = showSpinner;
+        mUnreadCount = unreadCount;
+        mHistoricMessagingMessages = historicMessagingMessages;
+        mNewMessagingMessages = newMessagingMessages;
+    }
+
+    public Person getUser() {
+        return mUser;
+    }
+
+    public boolean getShowSpinner() {
+        return mShowSpinner;
+    }
+
+    public List<MessagingMessage> getHistoricMessagingMessages() {
+        return mHistoricMessagingMessages;
+    }
+
+    public List<MessagingMessage> getNewMessagingMessages() {
+        return mNewMessagingMessages;
+    }
+
+    public int getUnreadCount() {
+        return mUnreadCount;
+    }
+}
diff --git a/core/java/com/android/internal/widget/MessagingLayout.java b/core/java/com/android/internal/widget/MessagingLayout.java
index 83557cd..b6d7503 100644
--- a/core/java/com/android/internal/widget/MessagingLayout.java
+++ b/core/java/com/android/internal/widget/MessagingLayout.java
@@ -87,7 +87,7 @@
     private ImageResolver mImageResolver;
     private CharSequence mConversationTitle;
     private ArrayList<MessagingLinearLayout.MessagingChild> mToRecycle = new ArrayList<>();
-
+    private boolean mPrecomputedTextEnabled = false;
     public MessagingLayout(@NonNull Context context) {
         super(context);
     }
@@ -162,15 +162,23 @@
      */
     @RemotableViewMethod(asyncImpl = "setDataAsync")
     public void setData(Bundle extras) {
+        bind(parseMessagingData(extras, /* usePrecomputedText= */false));
+    }
+
+    @NonNull
+    private MessagingData parseMessagingData(Bundle extras, boolean usePrecomputedText) {
         Parcelable[] messages = extras.getParcelableArray(Notification.EXTRA_MESSAGES);
-        List<Notification.MessagingStyle.Message> newMessages
-                = Notification.MessagingStyle.Message.getMessagesFromBundleArray(messages);
+        List<Notification.MessagingStyle.Message> newMessages =
+                Notification.MessagingStyle.Message.getMessagesFromBundleArray(messages);
         Parcelable[] histMessages = extras.getParcelableArray(Notification.EXTRA_HISTORIC_MESSAGES);
-        List<Notification.MessagingStyle.Message> newHistoricMessages
-                = Notification.MessagingStyle.Message.getMessagesFromBundleArray(histMessages);
-        setUser(extras.getParcelable(Notification.EXTRA_MESSAGING_PERSON, android.app.Person.class));
-        RemoteInputHistoryItem[] history = (RemoteInputHistoryItem[])
-                extras.getParcelableArray(Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS, android.app.RemoteInputHistoryItem.class);
+        List<Notification.MessagingStyle.Message> newHistoricMessages =
+                Notification.MessagingStyle.Message.getMessagesFromBundleArray(histMessages);
+        setUser(extras.getParcelable(Notification.EXTRA_MESSAGING_PERSON,
+                Person.class));
+        RemoteInputHistoryItem[] history =
+                (RemoteInputHistoryItem[]) extras.getParcelableArray(
+                        Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS,
+                        RemoteInputHistoryItem.class);
         addRemoteInputHistoryToMessages(newMessages, history);
 
         final Person user = extras.getParcelable(Notification.EXTRA_MESSAGING_PERSON, Person.class);
@@ -178,10 +186,12 @@
                 extras.getBoolean(Notification.EXTRA_SHOW_REMOTE_INPUT_SPINNER, false);
 
         final List<MessagingMessage> historicMessagingMessages = createMessages(newHistoricMessages,
-                /* isHistoric= */true, /* usePrecomputedText= */ false);
+                /* isHistoric= */true, usePrecomputedText);
         final List<MessagingMessage> newMessagingMessages =
-                createMessages(newMessages, /* isHistoric= */false, /* usePrecomputedText= */false);
-        bindViews(user, showSpinner, historicMessagingMessages, newMessagingMessages);
+                createMessages(newMessages, /* isHistoric */false, usePrecomputedText);
+
+        return new MessagingData(user, showSpinner,
+                historicMessagingMessages, newMessagingMessages);
     }
 
     /**
@@ -193,7 +203,32 @@
      */
     @NonNull
     public Runnable setDataAsync(Bundle extras) {
-        return () -> setData(extras);
+        if (!mPrecomputedTextEnabled) {
+            return () -> setData(extras);
+        }
+
+        final MessagingData messagingData =
+                parseMessagingData(extras, /* usePrecomputedText= */true);
+
+        return () -> {
+            finalizeInflate(messagingData.getHistoricMessagingMessages());
+            finalizeInflate(messagingData.getNewMessagingMessages());
+            bind(messagingData);
+        };
+    }
+
+    /**
+     * enable/disable precomputed text usage
+     * @hide
+     */
+    public void setPrecomputedTextEnabled(boolean precomputedTextEnabled) {
+        mPrecomputedTextEnabled = precomputedTextEnabled;
+    }
+
+    private void finalizeInflate(List<MessagingMessage> historicMessagingMessages) {
+        for (MessagingMessage messagingMessage: historicMessagingMessages) {
+            messagingMessage.finalizeInflate();
+        }
     }
 
     @Override
@@ -218,17 +253,13 @@
         }
     }
 
-    private void bindViews(Person user, boolean showSpinner,
-            List<MessagingMessage> historicMessagingMessages,
-            List<MessagingMessage> newMessagingMessages) {
-        setUser(user);
-        bind(showSpinner, historicMessagingMessages, newMessagingMessages);
-    }
+    private void bind(MessagingData messagingData) {
+        setUser(messagingData.getUser());
 
-    private void bind(boolean showSpinner, List<MessagingMessage> historicMessages,
-            List<MessagingMessage> messages) {
+        List<MessagingMessage> historicMessages = messagingData.getHistoricMessagingMessages();
+        List<MessagingMessage> messages = messagingData.getNewMessagingMessages();
         ArrayList<MessagingGroup> oldGroups = new ArrayList<>(mGroups);
-        addMessagesToGroups(historicMessages, messages, showSpinner);
+        addMessagesToGroups(historicMessages, messages, messagingData.getShowSpinner());
 
         // Let's first check which groups were removed altogether and remove them in one animation
         removeGroups(oldGroups);
diff --git a/core/java/com/android/internal/widget/NotificationDrawableConsumer.java b/core/java/com/android/internal/widget/NotificationDrawableConsumer.java
new file mode 100644
index 0000000..7c4d929
--- /dev/null
+++ b/core/java/com/android/internal/widget/NotificationDrawableConsumer.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.widget;
+
+import android.graphics.drawable.Drawable;
+
+import androidx.annotation.Nullable;
+
+/**
+ * An interface for the class, who will use {@link NotificationIconManager} to load icons.
+ */
+public interface NotificationDrawableConsumer {
+
+    /**
+     * Sets a drawable as the content of this consumer.
+     *
+     * @param drawable the {@link Drawable} to set, or {@code null} to clear the content
+     */
+    void setImageDrawable(@Nullable Drawable drawable);
+}
diff --git a/core/java/com/android/internal/widget/NotificationIconManager.java b/core/java/com/android/internal/widget/NotificationIconManager.java
new file mode 100644
index 0000000..221845c
--- /dev/null
+++ b/core/java/com/android/internal/widget/NotificationIconManager.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.widget;
+
+import android.graphics.drawable.Icon;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+/**
+ * An interface used for Notification views to delegate handling the loading of icons.
+ */
+public interface NotificationIconManager {
+
+    /**
+     * Called when a new icon is provided to display.
+     *
+     * @param drawableConsumer a consumer, which can display the loaded drawable.
+     * @param icon             the updated icon to be displayed.
+     *
+     * @return a {@link Runnable} that sets the drawable on the consumer
+     */
+    @NonNull
+    Runnable updateIcon(
+            @NonNull NotificationDrawableConsumer drawableConsumer,
+            @Nullable Icon icon
+    );
+}
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 9aa992b..b5d70d3 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -353,7 +353,7 @@
     JNIEnv* env;
     jmethodID methodId;
 
-    ALOGD("Calling main entry %s", className.string());
+    ALOGD("Calling main entry %s", className.c_str());
 
     env = getJNIEnv();
     if (clazz == NULL || env == NULL) {
@@ -362,7 +362,7 @@
 
     methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V");
     if (methodId == NULL) {
-        ALOGE("ERROR: could not find method %s.main(String[])\n", className.string());
+        ALOGE("ERROR: could not find method %s.main(String[])\n", className.c_str());
         return UNKNOWN_ERROR;
     }
 
@@ -378,7 +378,7 @@
     strArray = env->NewObjectArray(numArgs, stringClass, NULL);
 
     for (size_t i = 0; i < numArgs; i++) {
-        jstring argStr = env->NewStringUTF(args[i].string());
+        jstring argStr = env->NewStringUTF(args[i].c_str());
         env->SetObjectArrayElement(strArray, i, argStr);
     }
 
@@ -1269,7 +1269,7 @@
     env->SetObjectArrayElement(strArray, 0, classNameStr);
 
     for (size_t i = 0; i < options.size(); ++i) {
-        jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
+        jstring optionsStr = env->NewStringUTF(options.itemAt(i).c_str());
         assert(optionsStr != NULL);
         env->SetObjectArrayElement(strArray, i + 1, optionsStr);
     }
diff --git a/core/jni/android_content_res_ObbScanner.cpp b/core/jni/android_content_res_ObbScanner.cpp
index de429a0..760037f 100644
--- a/core/jni/android_content_res_ObbScanner.cpp
+++ b/core/jni/android_content_res_ObbScanner.cpp
@@ -52,7 +52,7 @@
 
     env->ReleaseStringUTFChars(file, filePath);
 
-    const char* packageNameStr = obb->getPackageName().string();
+    const char* packageNameStr = obb->getPackageName().c_str();
 
     jstring packageName = env->NewStringUTF(packageNameStr);
     if (packageName == NULL) {
diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp
index 979c9e3..f04b901 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -295,7 +295,7 @@
   if (alloc.length() <= 0) {
     return nullptr;
   }
-  return env->NewStringUTF(alloc.string());
+  return env->NewStringUTF(alloc.c_str());
 }
 
 static jint NativeGetGlobalAssetManagerCount(JNIEnv* /*env*/, jobject /*clazz*/) {
@@ -456,7 +456,7 @@
   }
 
   for (size_t i = 0; i < file_count; i++) {
-    jstring java_string = env->NewStringUTF(asset_dir->getFileName(i).string());
+    jstring java_string = env->NewStringUTF(asset_dir->getFileName(i).c_str());
 
     // Check for errors creating the strings (if malformed or no memory).
     if (env->ExceptionCheck()) {
diff --git a/core/jni/android_view_DisplayEventReceiver.cpp b/core/jni/android_view_DisplayEventReceiver.cpp
index 624bd5f..69fc515 100644
--- a/core/jni/android_view_DisplayEventReceiver.cpp
+++ b/core/jni/android_view_DisplayEventReceiver.cpp
@@ -292,7 +292,7 @@
     if (status) {
         String8 message;
         message.appendFormat("Failed to initialize display event receiver.  status=%d", status);
-        jniThrowRuntimeException(env, message.string());
+        jniThrowRuntimeException(env, message.c_str());
         return 0;
     }
 
@@ -316,7 +316,7 @@
     if (status) {
         String8 message;
         message.appendFormat("Failed to schedule next vertical sync pulse.  status=%d", status);
-        jniThrowRuntimeException(env, message.string());
+        jniThrowRuntimeException(env, message.c_str());
     }
 }
 
diff --git a/core/jni/android_view_InputEventSender.cpp b/core/jni/android_view_InputEventSender.cpp
index 061f669..833952d 100644
--- a/core/jni/android_view_InputEventSender.cpp
+++ b/core/jni/android_view_InputEventSender.cpp
@@ -340,7 +340,7 @@
     if (status) {
         String8 message;
         message.appendFormat("Failed to initialize input event sender.  status=%d", status);
-        jniThrowRuntimeException(env, message.string());
+        jniThrowRuntimeException(env, message.c_str());
         return 0;
     }
 
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 2f0b390..aeeaaca 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -542,6 +542,9 @@
     <bool name="config_goToSleepOnButtonPressTheaterMode">true</bool>
     <!-- If this is true, long press on power button will be available from the non-interactive state -->
     <bool name="config_supportLongPressPowerWhenNonInteractive">false</bool>
+    <!-- If this is true, short press on power button will be available whenever the default display
+         is on even if the device is non-interactive (dreaming). -->
+    <bool name="config_supportShortPressPowerWhenDefaultDisplayOn">false</bool>
 
     <!-- If this is true, then keep dreaming when unplugging.
          This config was formerly known as config_keepDreamingWhenUndocking.
@@ -6621,11 +6624,6 @@
     <!-- Whether to show weather on the lock screen by default. -->
     <bool name="config_lockscreenWeatherEnabledByDefault">false</bool>
 
-    <!-- Whether to reset Battery Stats on unplug when the battery level is high. -->
-    <bool name="config_batteryStatsResetOnUnplugHighBatteryLevel">true</bool>
-    <!-- Whether to reset Battery Stats on unplug if the battery was significantly charged -->
-    <bool name="config_batteryStatsResetOnUnplugAfterSignificantCharge">true</bool>
-
     <!-- Whether we should persist the brightness value in nits for the default display even if
          the underlying display device changes. -->
     <bool name="config_persistBrightnessNitsForDefaultDisplay">false</bool>
diff --git a/core/res/res/values/config_battery_stats.xml b/core/res/res/values/config_battery_stats.xml
new file mode 100644
index 0000000..8fb48bc
--- /dev/null
+++ b/core/res/res/values/config_battery_stats.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright 2023 The Android Open Source Project
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+  -->
+
+<!-- These resources are around just to allow their values to be customized
+     for different hardware and product builds.  Do not translate.
+
+     NOTE: The naming convention is "config_camelCaseValue". -->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+
+    <!-- Whether to reset Battery Stats on unplug when the battery level is high. -->
+    <bool name="config_batteryStatsResetOnUnplugHighBatteryLevel">true</bool>
+    <!-- Whether to reset Battery Stats on unplug if the battery was significantly charged -->
+    <bool name="config_batteryStatsResetOnUnplugAfterSignificantCharge">true</bool>
+
+    <!-- CPU power stats collection throttle period in milliseconds.  Since power stats collection
+    is a relatively expensive operation, this throttle period may need to be adjusted for low-power
+    devices-->
+    <integer name="config_defaultPowerStatsThrottlePeriodCpu">60000</integer>
+</resources>
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 0dd6c74..207927a 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -5561,7 +5561,7 @@
     <!-- Title for the autofill update dialog shown when the the contents of the activity can be updated
          in an autofill service, and the service knows what the activity represents, and it represents 3 types of
          data (for example, username, password and credit card info) [CHAR LIMIT=NONE] -->
-    <string name="autofill_update_title_with_3types">Update these items in <b><xliff:g id="label" example="MyPass">%4$s</xliff:g></b>: <xliff:g id="type" example="Username">%1$s</xliff:g>, <xliff:g id="type" example="Password">%2$s</xliff:g>, and <xliff:g id="type" example="Credit Card">%3$s</xliff:g> ?</string>
+    <string name="autofill_update_title_with_3types">Update these items in <b><xliff:g id="label" example="MyPass">%4$s</xliff:g></b>: <xliff:g id="type" example="Username">%1$s</xliff:g>, <xliff:g id="type" example="Password">%2$s</xliff:g>, and <xliff:g id="type" example="Credit Card">%3$s</xliff:g>?</string>
 
     <!-- Label for the autofill save button [CHAR LIMIT=NONE] -->
     <string name="autofill_save_yes">Save</string>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index f1a78a6..8330f7b 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -1968,6 +1968,7 @@
   <java-symbol type="integer" name="config_keyguardDrawnTimeout" />
   <java-symbol type="bool" name="config_goToSleepOnButtonPressTheaterMode" />
   <java-symbol type="bool" name="config_supportLongPressPowerWhenNonInteractive" />
+  <java-symbol type="bool" name="config_supportShortPressPowerWhenDefaultDisplayOn" />
   <java-symbol type="bool" name="config_wimaxEnabled" />
   <java-symbol type="bool" name="show_ongoing_ime_switcher" />
   <java-symbol type="color" name="config_defaultNotificationColor" />
@@ -5088,6 +5089,7 @@
 
   <java-symbol type="bool" name="config_batteryStatsResetOnUnplugHighBatteryLevel" />
   <java-symbol type="bool" name="config_batteryStatsResetOnUnplugAfterSignificantCharge" />
+  <java-symbol type="integer" name="config_defaultPowerStatsThrottlePeriodCpu" />
 
   <java-symbol name="materialColorOnSecondaryFixedVariant" type="attr"/>
   <java-symbol name="materialColorOnTertiaryFixedVariant" type="attr"/>
diff --git a/core/tests/coretests/src/android/app/activity/BroadcastTest.java b/core/tests/coretests/src/android/app/activity/BroadcastTest.java
index 10452fd..bc69901 100644
--- a/core/tests/coretests/src/android/app/activity/BroadcastTest.java
+++ b/core/tests/coretests/src/android/app/activity/BroadcastTest.java
@@ -110,6 +110,7 @@
     public Intent makeBroadcastIntent(String action) {
         Intent intent = new Intent(action, null);
         intent.putExtra("caller", mCallTarget);
+        intent.setPackage(getContext().getPackageName());
         return intent;
     }
 
@@ -179,7 +180,8 @@
     public void registerMyReceiver(IntentFilter filter, String permission) {
         mReceiverRegistered = true;
         //System.out.println("Registering: " + mReceiver);
-        getContext().registerReceiver(mReceiver, filter, permission, null);
+        getContext().registerReceiver(mReceiver, filter, permission, null,
+                Context.RECEIVER_EXPORTED);
     }
 
     public void unregisterMyReceiver() {
@@ -255,7 +257,7 @@
     }
 
     @FlakyTest
-    public void testMulti() throws Exception {
+    public void ignore_testMulti() throws Exception {
         runLaunchpad(LaunchpadActivity.BROADCAST_MULTI);
     }
 
@@ -278,8 +280,11 @@
             Bundle map = new Bundle();
             map.putString("foo", "you");
             map.putString("remove", "me");
+            final Intent intent = new Intent(
+                    "com.android.frameworks.coretests.activity.BROADCAST_RESULT")
+                            .setPackage(getContext().getPackageName());
             getContext().sendOrderedBroadcast(
-                    new Intent("com.android.frameworks.coretests.activity.BROADCAST_RESULT"),
+                    intent,
                     null, broadcastReceiver, null, 1, "foo", map);
             while (!broadcastReceiver.mHaveResult) {
                 try {
@@ -313,7 +318,7 @@
         addIntermediate("finished-broadcast");
 
         IntentFilter filter = new IntentFilter(LaunchpadActivity.BROADCAST_STICKY1);
-        Intent sticky = getContext().registerReceiver(null, filter);
+        Intent sticky = getContext().registerReceiver(null, filter, Context.RECEIVER_EXPORTED);
         assertNotNull("Sticky not found", sticky);
         assertEquals(LaunchpadActivity.DATA_1, sticky.getStringExtra("test"));
     }
@@ -329,7 +334,7 @@
         addIntermediate("finished-unbroadcast");
 
         IntentFilter filter = new IntentFilter(LaunchpadActivity.BROADCAST_STICKY1);
-        Intent sticky = getContext().registerReceiver(null, filter);
+        Intent sticky = getContext().registerReceiver(null, filter, Context.RECEIVER_EXPORTED);
         assertNull("Sticky not found", sticky);
     }
 
@@ -343,7 +348,7 @@
         addIntermediate("finished-broadcast");
 
         IntentFilter filter = new IntentFilter(LaunchpadActivity.BROADCAST_STICKY1);
-        Intent sticky = getContext().registerReceiver(null, filter);
+        Intent sticky = getContext().registerReceiver(null, filter, Context.RECEIVER_EXPORTED);
         assertNotNull("Sticky not found", sticky);
         assertEquals(LaunchpadActivity.DATA_2, sticky.getStringExtra("test"));
     }
@@ -371,7 +376,7 @@
         runLaunchpad(LaunchpadActivity.BROADCAST_STICKY2);
     }
 
-    public void testRegisteredReceivePermissionGranted() throws Exception {
+    public void ignore_testRegisteredReceivePermissionGranted() throws Exception {
         setExpectedReceivers(new String[]{RECEIVER_REG});
         registerMyReceiver(new IntentFilter(BROADCAST_REGISTERED), PERMISSION_GRANTED);
         addIntermediate("after-register");
@@ -396,7 +401,7 @@
         waitForResultOrThrow(BROADCAST_TIMEOUT);
     }
 
-    public void testRegisteredBroadcastPermissionGranted() throws Exception {
+    public void ignore_testRegisteredBroadcastPermissionGranted() throws Exception {
         setExpectedReceivers(new String[]{RECEIVER_REG});
         registerMyReceiver(new IntentFilter(BROADCAST_REGISTERED), null);
         addIntermediate("after-register");
@@ -430,7 +435,7 @@
         waitForResultOrThrow(BROADCAST_TIMEOUT);
     }
 
-    public void testLocalReceivePermissionDenied() throws Exception {
+    public void ignore_testLocalReceivePermissionDenied() throws Exception {
         setExpectedReceivers(new String[]{RECEIVER_RESULTS});
 
         BroadcastReceiver finish = new BroadcastReceiver() {
@@ -446,7 +451,7 @@
         waitForResultOrThrow(BROADCAST_TIMEOUT);
     }
 
-    public void testLocalBroadcastPermissionGranted() throws Exception {
+    public void ignore_testLocalBroadcastPermissionGranted() throws Exception {
         setExpectedReceivers(new String[]{RECEIVER_LOCAL});
         getContext().sendBroadcast(
                 makeBroadcastIntent(BROADCAST_LOCAL),
@@ -476,7 +481,7 @@
         waitForResultOrThrow(BROADCAST_TIMEOUT);
     }
 
-    public void testRemoteReceivePermissionDenied() throws Exception {
+    public void ignore_testRemoteReceivePermissionDenied() throws Exception {
         setExpectedReceivers(new String[]{RECEIVER_RESULTS});
 
         BroadcastReceiver finish = new BroadcastReceiver() {
@@ -492,7 +497,7 @@
         waitForResultOrThrow(BROADCAST_TIMEOUT);
     }
 
-    public void testRemoteBroadcastPermissionGranted() throws Exception {
+    public void ignore_testRemoteBroadcastPermissionGranted() throws Exception {
         setExpectedReceivers(new String[]{RECEIVER_REMOTE});
         getContext().sendBroadcast(
                 makeBroadcastIntent(BROADCAST_REMOTE),
@@ -516,7 +521,7 @@
         waitForResultOrThrow(BROADCAST_TIMEOUT);
     }
 
-    public void testReceiverCanNotRegister() throws Exception {
+    public void ignore_testReceiverCanNotRegister() throws Exception {
         setExpectedReceivers(new String[]{RECEIVER_LOCAL});
         getContext().sendBroadcast(makeBroadcastIntent(BROADCAST_FAIL_REGISTER));
         waitForResultOrThrow(BROADCAST_TIMEOUT);
diff --git a/core/tests/coretests/src/android/app/activity/IntentSenderTest.java b/core/tests/coretests/src/android/app/activity/IntentSenderTest.java
index 1b52f80..a0645ce 100644
--- a/core/tests/coretests/src/android/app/activity/IntentSenderTest.java
+++ b/core/tests/coretests/src/android/app/activity/IntentSenderTest.java
@@ -27,7 +27,7 @@
 @LargeTest
 public class IntentSenderTest extends BroadcastTest {
 
-    public void testRegisteredReceivePermissionGranted() throws Exception {
+    public void ignore_testRegisteredReceivePermissionGranted() throws Exception {
         setExpectedReceivers(new String[]{RECEIVER_REG});
         registerMyReceiver(new IntentFilter(BROADCAST_REGISTERED), PERMISSION_GRANTED);
         addIntermediate("after-register");
@@ -71,7 +71,7 @@
         is.cancel();
     }
 
-    public void testLocalReceivePermissionDenied() throws Exception {
+    public void ignore_testLocalReceivePermissionDenied() throws Exception {
         final Intent intent = makeBroadcastIntent(BROADCAST_LOCAL_DENIED)
                 .setPackage(getContext().getPackageName());
 
diff --git a/core/tests/coretests/src/android/app/activity/LaunchpadActivity.java b/core/tests/coretests/src/android/app/activity/LaunchpadActivity.java
index 7662456..fda249f 100644
--- a/core/tests/coretests/src/android/app/activity/LaunchpadActivity.java
+++ b/core/tests/coretests/src/android/app/activity/LaunchpadActivity.java
@@ -438,6 +438,7 @@
     private Intent makeBroadcastIntent(String action) {
         Intent intent = new Intent(action, null);
         intent.putExtra("caller", mCallTarget);
+        intent.setPackage(getPackageName());
         return intent;
     }
 
@@ -466,7 +467,7 @@
     private void registerMyReceiver(IntentFilter filter) {
         mReceiverRegistered = true;
         //System.out.println("Registering: " + mReceiver);
-        registerReceiver(mReceiver, filter);
+        registerReceiver(mReceiver, filter, Context.RECEIVER_EXPORTED);
     }
 
     private void unregisterMyReceiver() {
diff --git a/core/tests/coretests/src/android/app/activity/LocalDeniedReceiver.java b/core/tests/coretests/src/android/app/activity/LocalDeniedReceiver.java
index 2120a1d..3271b8f 100644
--- a/core/tests/coretests/src/android/app/activity/LocalDeniedReceiver.java
+++ b/core/tests/coretests/src/android/app/activity/LocalDeniedReceiver.java
@@ -19,11 +19,11 @@
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
-import android.os.RemoteException;
 import android.os.IBinder;
 import android.os.Parcel;
+import android.os.RemoteException;
 
-class LocalDeniedReceiver extends BroadcastReceiver {
+public class LocalDeniedReceiver extends BroadcastReceiver {
     public LocalDeniedReceiver() {
     }
 
diff --git a/core/tests/coretests/src/android/service/notification/NotificationRankingUpdateTest.java b/core/tests/coretests/src/android/service/notification/NotificationRankingUpdateTest.java
index a84ac55..55ded9c 100644
--- a/core/tests/coretests/src/android/service/notification/NotificationRankingUpdateTest.java
+++ b/core/tests/coretests/src/android/service/notification/NotificationRankingUpdateTest.java
@@ -136,7 +136,11 @@
         NotificationListenerService.RankingMap retrievedRankings =
                 retrievedRankingUpdate.getRankingMap();
         assertNotNull(retrievedRankings);
-        assertTrue(retrievedRankingUpdate.isFdNotNullAndClosed());
+        // The rankingUpdate file descriptor is only non-null in the new path.
+        if (SystemUiSystemPropertiesFlags.getResolver().isEnabled(
+                SystemUiSystemPropertiesFlags.NotificationFlags.RANKING_UPDATE_ASHMEM)) {
+            assertTrue(retrievedRankingUpdate.isFdNotNullAndClosed());
+        }
         NotificationListenerService.Ranking retrievedRanking =
                 new NotificationListenerService.Ranking();
         assertTrue(retrievedRankings.getRanking(TEST_KEY, retrievedRanking));
diff --git a/core/tests/coretests/src/android/service/quicksettings/TileTest.java b/core/tests/coretests/src/android/service/quicksettings/TileTest.java
new file mode 100644
index 0000000..ca6c3b4
--- /dev/null
+++ b/core/tests/coretests/src/android/service/quicksettings/TileTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.service.quicksettings;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class TileTest {
+
+    private static final String DEFAULT_LABEL = "DEFAULT_LABEL";
+    private static final String CUSTOM_APP_LABEL = "CUSTOM_LABEL";
+
+    @Test
+    public void testGetLabel_labelSet_usesCustomLabel() {
+        Tile tile = new Tile();
+        tile.setDefaultLabel(DEFAULT_LABEL);
+        tile.setLabel(CUSTOM_APP_LABEL);
+
+        assertThat(tile.getLabel()).isEqualTo(CUSTOM_APP_LABEL);
+    }
+
+    @Test
+    public void testGetLabel_labelNotSet_usesDefaultLabel() {
+        Tile tile = new Tile();
+        tile.setDefaultLabel(DEFAULT_LABEL);
+
+        assertThat(tile.getLabel()).isEqualTo(DEFAULT_LABEL);
+    }
+
+    @Test
+    public void testGetCustomLabel_labelSet() {
+        Tile tile = new Tile();
+        tile.setDefaultLabel(DEFAULT_LABEL);
+        tile.setLabel(CUSTOM_APP_LABEL);
+
+        assertThat(tile.getCustomLabel()).isEqualTo(CUSTOM_APP_LABEL);
+    }
+
+    @Test
+    public void testGetCustomLabel_labelNotSet() {
+        Tile tile = new Tile();
+        tile.setDefaultLabel(DEFAULT_LABEL);
+
+        assertThat(tile.getCustomLabel()).isNull();
+    }
+}
diff --git a/core/tests/vibrator/src/android/os/VibratorInfoTest.java b/core/tests/vibrator/src/android/os/VibratorInfoTest.java
index 808c4ec..73cd464 100644
--- a/core/tests/vibrator/src/android/os/VibratorInfoTest.java
+++ b/core/tests/vibrator/src/android/os/VibratorInfoTest.java
@@ -257,8 +257,13 @@
 
     @Test
     public void testEquals() {
-        VibratorInfo.Builder completeBuilder = new VibratorInfo.Builder(TEST_VIBRATOR_ID)
-                .setCapabilities(IVibrator.CAP_AMPLITUDE_CONTROL)
+        VibratorInfo.Builder completeBuilder = new VibratorInfo.Builder(TEST_VIBRATOR_ID);
+        // Create a builder with a different ID, but same properties the same as the first one.
+        VibratorInfo.Builder completeBuilder2 = new VibratorInfo.Builder(TEST_VIBRATOR_ID + 2);
+
+        for (VibratorInfo.Builder builder :
+                new VibratorInfo.Builder[] {completeBuilder, completeBuilder2}) {
+            builder.setCapabilities(IVibrator.CAP_AMPLITUDE_CONTROL)
                 .setSupportedEffects(VibrationEffect.EFFECT_CLICK)
                 .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 20)
                 .setPrimitiveDelayMax(100)
@@ -268,31 +273,43 @@
                 .setPwleSizeMax(20)
                 .setQFactor(2f)
                 .setFrequencyProfile(TEST_FREQUENCY_PROFILE);
+        }
         VibratorInfo complete = completeBuilder.build();
 
         assertEquals(complete, complete);
+        assertTrue(complete.equalContent(complete));
         assertEquals(complete, completeBuilder.build());
+        assertTrue(complete.equalContent(completeBuilder.build()));
         assertEquals(complete.hashCode(), completeBuilder.build().hashCode());
 
+        // The infos from the two builders should have equal content, but should not be equal due to
+        // their different IDs.
+        assertNotEquals(complete, completeBuilder2.build());
+        assertTrue(complete.equalContent(completeBuilder2.build()));
+
         VibratorInfo completeWithComposeControl = completeBuilder
                 .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
                 .build();
         assertNotEquals(complete, completeWithComposeControl);
+        assertFalse(complete.equalContent(completeWithComposeControl));
 
         VibratorInfo completeWithNoEffects = completeBuilder
                 .setSupportedEffects(new int[0])
                 .build();
         assertNotEquals(complete, completeWithNoEffects);
+        assertFalse(complete.equalContent(completeWithNoEffects));
 
         VibratorInfo completeWithUnknownEffects = completeBuilder
                 .setSupportedEffects(null)
                 .build();
         assertNotEquals(complete, completeWithUnknownEffects);
+        assertFalse(complete.equalContent(completeWithUnknownEffects));
 
         VibratorInfo completeWithDifferentPrimitiveDuration = completeBuilder
                 .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
                 .build();
         assertNotEquals(complete, completeWithDifferentPrimitiveDuration);
+        assertFalse(complete.equalContent(completeWithDifferentPrimitiveDuration));
 
         VibratorInfo completeWithDifferentFrequencyProfile = completeBuilder
                 .setFrequencyProfile(new VibratorInfo.FrequencyProfile(
@@ -302,31 +319,37 @@
                         TEST_AMPLITUDE_MAP))
                 .build();
         assertNotEquals(complete, completeWithDifferentFrequencyProfile);
+        assertFalse(complete.equalContent(completeWithDifferentFrequencyProfile));
 
         VibratorInfo completeWithEmptyFrequencyProfile = completeBuilder
                 .setFrequencyProfile(EMPTY_FREQUENCY_PROFILE)
                 .build();
         assertNotEquals(complete, completeWithEmptyFrequencyProfile);
+        assertFalse(complete.equalContent(completeWithEmptyFrequencyProfile));
 
         VibratorInfo completeWithUnknownQFactor = completeBuilder.setQFactor(Float.NaN).build();
         assertNotEquals(complete, completeWithUnknownQFactor);
+        assertFalse(complete.equalContent(completeWithUnknownQFactor));
 
         VibratorInfo completeWithDifferentQFactor = completeBuilder
                 .setQFactor(complete.getQFactor() + 3f)
                 .build();
         assertNotEquals(complete, completeWithDifferentQFactor);
+        assertFalse(complete.equalContent(completeWithDifferentQFactor));
 
         VibratorInfo unknownEffectSupport = new VibratorInfo.Builder(TEST_VIBRATOR_ID).build();
         VibratorInfo knownEmptyEffectSupport = new VibratorInfo.Builder(TEST_VIBRATOR_ID)
                 .setSupportedEffects(new int[0])
                 .build();
         assertNotEquals(unknownEffectSupport, knownEmptyEffectSupport);
+        assertFalse(unknownEffectSupport.equalContent(knownEmptyEffectSupport));
 
         VibratorInfo unknownBrakingSupport = new VibratorInfo.Builder(TEST_VIBRATOR_ID).build();
         VibratorInfo knownEmptyBrakingSupport = new VibratorInfo.Builder(TEST_VIBRATOR_ID)
                 .setSupportedBraking(new int[0])
                 .build();
         assertNotEquals(unknownBrakingSupport, knownEmptyBrakingSupport);
+        assertFalse(unknownBrakingSupport.equalContent(knownEmptyBrakingSupport));
     }
 
     @Test
diff --git a/core/tests/vibrator/src/android/os/VibratorTest.java b/core/tests/vibrator/src/android/os/VibratorTest.java
index 8141ca4..cfa12bb 100644
--- a/core/tests/vibrator/src/android/os/VibratorTest.java
+++ b/core/tests/vibrator/src/android/os/VibratorTest.java
@@ -37,7 +37,6 @@
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.ContextWrapper;
-import android.hardware.vibrator.IVibrator;
 import android.media.AudioAttributes;
 import android.os.test.TestLooper;
 
@@ -60,8 +59,6 @@
     @Rule
     public FakeSettingsProviderRule mSettingsProviderRule = FakeSettingsProvider.rule();
 
-    private static final float TEST_TOLERANCE = 1e-5f;
-
     private Context mContextSpy;
     private Vibrator mVibratorSpy;
     private TestLooper mTestLooper;
@@ -79,9 +76,6 @@
     @Test
     public void getId_returnsDefaultId() {
         assertEquals(-1, mVibratorSpy.getId());
-        assertEquals(-1, new SystemVibrator.NoVibratorInfo().getId());
-        assertEquals(-1, new SystemVibrator.MultiVibratorInfo(new VibratorInfo[] {
-                VibratorInfo.EMPTY_VIBRATOR_INFO, VibratorInfo.EMPTY_VIBRATOR_INFO }).getId());
     }
 
     @Test
@@ -95,53 +89,6 @@
     }
 
     @Test
-    public void areEffectsSupported_noVibrator_returnsAlwaysNo() {
-        VibratorInfo info = new SystemVibrator.NoVibratorInfo();
-        assertEquals(Vibrator.VIBRATION_EFFECT_SUPPORT_NO,
-                info.isEffectSupported(VibrationEffect.EFFECT_CLICK));
-    }
-
-    @Test
-    public void areEffectsSupported_unsupportedInOneVibrator_returnsNo() {
-        VibratorInfo supportedVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setSupportedEffects(VibrationEffect.EFFECT_CLICK)
-                .build();
-        VibratorInfo unsupportedVibrator = new VibratorInfo.Builder(/* id= */ 2)
-                .setSupportedEffects(new int[0])
-                .build();
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{supportedVibrator, unsupportedVibrator});
-        assertEquals(Vibrator.VIBRATION_EFFECT_SUPPORT_NO,
-                info.isEffectSupported(VibrationEffect.EFFECT_CLICK));
-    }
-
-    @Test
-    public void areEffectsSupported_unknownInOneVibrator_returnsUnknown() {
-        VibratorInfo supportedVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setSupportedEffects(VibrationEffect.EFFECT_CLICK)
-                .build();
-        VibratorInfo unknownSupportVibrator = VibratorInfo.EMPTY_VIBRATOR_INFO;
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{supportedVibrator, unknownSupportVibrator});
-        assertEquals(Vibrator.VIBRATION_EFFECT_SUPPORT_UNKNOWN,
-                info.isEffectSupported(VibrationEffect.EFFECT_CLICK));
-    }
-
-    @Test
-    public void arePrimitivesSupported_supportedInAllVibrators_returnsYes() {
-        VibratorInfo firstVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setSupportedEffects(VibrationEffect.EFFECT_CLICK)
-                .build();
-        VibratorInfo secondVibrator = new VibratorInfo.Builder(/* id= */ 2)
-                .setSupportedEffects(VibrationEffect.EFFECT_CLICK)
-                .build();
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, secondVibrator});
-        assertEquals(Vibrator.VIBRATION_EFFECT_SUPPORT_YES,
-                info.isEffectSupported(VibrationEffect.EFFECT_CLICK));
-    }
-
-    @Test
     public void arePrimitivesSupported_returnsArrayOfSameSize() {
         assertEquals(0, mVibratorSpy.arePrimitivesSupported(new int[0]).length);
         assertEquals(1, mVibratorSpy.arePrimitivesSupported(
@@ -152,39 +99,6 @@
     }
 
     @Test
-    public void arePrimitivesSupported_noVibrator_returnsAlwaysFalse() {
-        VibratorInfo info = new SystemVibrator.NoVibratorInfo();
-        assertFalse(info.isPrimitiveSupported(VibrationEffect.Composition.PRIMITIVE_CLICK));
-    }
-
-    @Test
-    public void arePrimitivesSupported_unsupportedInOneVibrator_returnsFalse() {
-        VibratorInfo supportedVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
-                .build();
-        VibratorInfo unsupportedVibrator = VibratorInfo.EMPTY_VIBRATOR_INFO;
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{supportedVibrator, unsupportedVibrator});
-        assertFalse(info.isPrimitiveSupported(VibrationEffect.Composition.PRIMITIVE_CLICK));
-    }
-
-    @Test
-    public void arePrimitivesSupported_supportedInAllVibrators_returnsTrue() {
-        VibratorInfo firstVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 5)
-                .build();
-        VibratorInfo secondVibrator = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 15)
-                .build();
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, secondVibrator});
-        assertTrue(info.isPrimitiveSupported(VibrationEffect.Composition.PRIMITIVE_CLICK));
-    }
-
-    @Test
     public void getPrimitivesDurations_returnsArrayOfSameSize() {
         assertEquals(0, mVibratorSpy.getPrimitiveDurations(new int[0]).length);
         assertEquals(1, mVibratorSpy.getPrimitiveDurations(
@@ -195,245 +109,6 @@
     }
 
     @Test
-    public void getPrimitivesDurations_noVibrator_returnsAlwaysZero() {
-        VibratorInfo info = new SystemVibrator.NoVibratorInfo();
-        assertEquals(0, info.getPrimitiveDuration(VibrationEffect.Composition.PRIMITIVE_CLICK));
-    }
-
-    @Test
-    public void getPrimitivesDurations_unsupportedInOneVibrator_returnsZero() {
-        VibratorInfo supportedVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
-                .build();
-        VibratorInfo unsupportedVibrator = VibratorInfo.EMPTY_VIBRATOR_INFO;
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{supportedVibrator, unsupportedVibrator});
-        assertEquals(0, info.getPrimitiveDuration(VibrationEffect.Composition.PRIMITIVE_CLICK));
-    }
-
-    @Test
-    public void getPrimitivesDurations_supportedInAllVibrators_returnsMaxDuration() {
-        VibratorInfo firstVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
-                .build();
-        VibratorInfo secondVibrator = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
-                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 20)
-                .build();
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, secondVibrator});
-        assertEquals(20, info.getPrimitiveDuration(VibrationEffect.Composition.PRIMITIVE_CLICK));
-    }
-
-    @Test
-    public void getQFactorAndResonantFrequency_noVibrator_returnsNaN() {
-        VibratorInfo info = new SystemVibrator.NoVibratorInfo();
-
-        assertTrue(Float.isNaN(info.getQFactor()));
-        assertTrue(Float.isNaN(info.getResonantFrequencyHz()));
-    }
-
-    @Test
-    public void getQFactorAndResonantFrequency_differentValues_returnsNaN() {
-        VibratorInfo firstVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setQFactor(1f)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, 1, null))
-                .build();
-        VibratorInfo secondVibrator = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setQFactor(2f)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(2, 2, 2, null))
-                .build();
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, secondVibrator});
-
-        assertTrue(Float.isNaN(info.getQFactor()));
-        assertTrue(Float.isNaN(info.getResonantFrequencyHz()));
-        assertEmptyFrequencyProfileAndControl(info);
-
-        // One vibrator with values undefined.
-        VibratorInfo thirdVibrator = new VibratorInfo.Builder(/* id= */ 3).build();
-        info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, thirdVibrator});
-
-        assertTrue(Float.isNaN(info.getQFactor()));
-        assertTrue(Float.isNaN(info.getResonantFrequencyHz()));
-        assertEmptyFrequencyProfileAndControl(info);
-    }
-
-    @Test
-    public void getQFactorAndResonantFrequency_sameValues_returnsValue() {
-        VibratorInfo firstVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setQFactor(10f)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(
-                        /* resonantFrequencyHz= */ 11, 10, 0.5f, null))
-                .build();
-        VibratorInfo secondVibrator = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setQFactor(10f)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(
-                        /* resonantFrequencyHz= */ 11, 5, 1, null))
-                .build();
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, secondVibrator});
-
-        assertEquals(10f, info.getQFactor(), TEST_TOLERANCE);
-        assertEquals(11f, info.getResonantFrequencyHz(), TEST_TOLERANCE);
-
-        // No frequency range defined.
-        assertTrue(info.getFrequencyProfile().isEmpty());
-        assertEquals(false, info.hasCapability(IVibrator.CAP_FREQUENCY_CONTROL));
-    }
-
-    @Test
-    public void getFrequencyProfile_noVibrator_returnsEmpty() {
-        VibratorInfo info = new SystemVibrator.NoVibratorInfo();
-
-        assertEmptyFrequencyProfileAndControl(info);
-    }
-
-    @Test
-    public void getFrequencyProfile_differentResonantFrequencyOrResolutionValues_returnsEmpty() {
-        VibratorInfo firstVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, 1,
-                        new float[] { 0, 1 }))
-                .build();
-        VibratorInfo differentResonantFrequency = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(2, 1, 1,
-                        new float[] { 0, 1 }))
-                .build();
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, differentResonantFrequency});
-
-        assertEmptyFrequencyProfileAndControl(info);
-
-        VibratorInfo differentFrequencyResolution = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, 2,
-                        new float[] { 0, 1 }))
-                .build();
-        info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, differentFrequencyResolution});
-
-        assertEmptyFrequencyProfileAndControl(info);
-    }
-
-    @Test
-    public void getFrequencyProfile_missingValues_returnsEmpty() {
-        VibratorInfo firstVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, 1,
-                        new float[] { 0, 1 }))
-                .build();
-        VibratorInfo missingResonantFrequency = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(Float.NaN, 1, 1,
-                        new float[] { 0, 1 }))
-                .build();
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, missingResonantFrequency});
-
-        assertEmptyFrequencyProfileAndControl(info);
-
-        VibratorInfo missingMinFrequency = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, Float.NaN, 1,
-                        new float[] { 0, 1 }))
-                .build();
-        info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, missingMinFrequency});
-
-        assertEmptyFrequencyProfileAndControl(info);
-
-        VibratorInfo missingFrequencyResolution = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, Float.NaN,
-                        new float[] { 0, 1 }))
-                .build();
-        info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, missingFrequencyResolution});
-
-        assertEmptyFrequencyProfileAndControl(info);
-
-        VibratorInfo missingMaxAmplitudes = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, 1, null))
-                .build();
-        info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, missingMaxAmplitudes});
-
-        assertEmptyFrequencyProfileAndControl(info);
-    }
-
-    @Test
-    public void getFrequencyProfile_unalignedMaxAmplitudes_returnsEmpty() {
-        VibratorInfo firstVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10, 0.5f,
-                        new float[] { 0, 1, 1, 0 }))
-                .build();
-        VibratorInfo unalignedMinFrequency = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10.1f, 0.5f,
-                        new float[] { 0, 1, 1, 0 }))
-                .build();
-        VibratorInfo thirdVibrator = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f,
-                        new float[] { 0, 1, 1, 0 }))
-                .build();
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, unalignedMinFrequency, thirdVibrator});
-
-        assertEmptyFrequencyProfileAndControl(info);
-    }
-
-    @Test
-    public void getFrequencyProfile_alignedProfiles_returnsIntersection() {
-        VibratorInfo firstVibrator = new VibratorInfo.Builder(/* id= */ 1)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10, 0.5f,
-                        new float[] { 0.5f, 1, 1, 0.5f }))
-                .build();
-        VibratorInfo secondVibrator = new VibratorInfo.Builder(/* id= */ 2)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f,
-                        new float[] { 1, 1, 1 }))
-                .build();
-        VibratorInfo thirdVibrator = new VibratorInfo.Builder(/* id= */ 3)
-                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f,
-                        new float[] { 0.8f, 1, 0.8f, 0.5f }))
-                .build();
-        VibratorInfo info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, secondVibrator, thirdVibrator});
-
-        assertEquals(
-                new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f, new float[] { 0.8f, 1, 0.5f }),
-                info.getFrequencyProfile());
-        assertEquals(true, info.hasCapability(IVibrator.CAP_FREQUENCY_CONTROL));
-
-        // Third vibrator without frequency control capability.
-        thirdVibrator = new VibratorInfo.Builder(/* id= */ 3)
-                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f,
-                        new float[] { 0.8f, 1, 0.8f, 0.5f }))
-                .build();
-        info = new SystemVibrator.MultiVibratorInfo(
-                new VibratorInfo[]{firstVibrator, secondVibrator, thirdVibrator});
-
-        assertEquals(
-                new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f, new float[] { 0.8f, 1, 0.5f }),
-                info.getFrequencyProfile());
-        assertEquals(false, info.hasCapability(IVibrator.CAP_FREQUENCY_CONTROL));
-    }
-
-    @Test
     public void onVibratorStateChanged_noVibrator_registersNoListenerToVibratorManager() {
         VibratorManager mockVibratorManager = mock(VibratorManager.class);
         when(mockVibratorManager.getVibratorIds()).thenReturn(new int[0]);
@@ -577,12 +252,4 @@
         VibrationAttributes vibrationAttributes = captor.getValue();
         assertEquals(new VibrationAttributes.Builder().build(), vibrationAttributes);
     }
-
-    /**
-     * Asserts that the frequency profile is empty, and therefore frequency control isn't supported.
-     */
-    void assertEmptyFrequencyProfileAndControl(VibratorInfo info) {
-        assertTrue(info.getFrequencyProfile().isEmpty());
-        assertEquals(false, info.hasCapability(IVibrator.CAP_FREQUENCY_CONTROL));
-    }
 }
diff --git a/core/tests/vibrator/src/android/os/vibrator/MultiVibratorInfoTest.java b/core/tests/vibrator/src/android/os/vibrator/MultiVibratorInfoTest.java
new file mode 100644
index 0000000..fc31ac4
--- /dev/null
+++ b/core/tests/vibrator/src/android/os/vibrator/MultiVibratorInfoTest.java
@@ -0,0 +1,361 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.os.vibrator;
+
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+import static junit.framework.TestCase.assertEquals;
+
+import android.hardware.vibrator.IVibrator;
+import android.os.VibrationEffect;
+import android.os.Vibrator;
+import android.os.VibratorInfo;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class MultiVibratorInfoTest {
+    private static final float TEST_TOLERANCE = 1e-5f;
+
+    @Test
+    public void testGetId() {
+        VibratorInfo firstInfo = new VibratorInfo.Builder(/* id= */ 1)
+                .setSupportedEffects(VibrationEffect.EFFECT_CLICK)
+                .build();
+        VibratorInfo secondInfo = new VibratorInfo.Builder(/* id= */ 2)
+                .setSupportedEffects(new int[0])
+                .build();
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 3,
+                new VibratorInfo[]{firstInfo, secondInfo});
+
+        assertEquals(3, info.getId());
+    }
+
+    @Test
+    public void testIsEffectSupported_supportedInAllVibrators_returnsYes() {
+        VibratorInfo firstInfo = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedEffects(VibrationEffect.EFFECT_CLICK)
+                .build();
+        VibratorInfo secondInfo = new VibratorInfo.Builder(/* id= */ 2)
+                .setSupportedEffects(VibrationEffect.EFFECT_CLICK, VibrationEffect.EFFECT_TICK)
+                .build();
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, secondInfo});
+
+        assertEquals(Vibrator.VIBRATION_EFFECT_SUPPORT_YES,
+                info.isEffectSupported(VibrationEffect.EFFECT_CLICK));
+    }
+
+    @Test
+    public void testIsEffectSupported_unsupportedInOneVibrator_returnsNo() {
+        VibratorInfo supportedVibrator = new VibratorInfo.Builder(/* id= */ 1)
+                .setSupportedEffects(VibrationEffect.EFFECT_CLICK)
+                .build();
+        VibratorInfo unsupportedVibrator = new VibratorInfo.Builder(/* id= */ 2)
+                .setSupportedEffects(new int[0])
+                .build();
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{supportedVibrator, unsupportedVibrator});
+
+        assertEquals(Vibrator.VIBRATION_EFFECT_SUPPORT_NO,
+                info.isEffectSupported(VibrationEffect.EFFECT_CLICK));
+    }
+
+    @Test
+    public void testIsEffectSupported_unknownInOneVibrator_returnsUnknown() {
+        VibratorInfo supportedVibrator = new VibratorInfo.Builder(/* id= */ 1)
+                .setSupportedEffects(VibrationEffect.EFFECT_CLICK)
+                .build();
+        VibratorInfo unknownSupportVibrator = VibratorInfo.EMPTY_VIBRATOR_INFO;
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{supportedVibrator, unknownSupportVibrator});
+        assertEquals(Vibrator.VIBRATION_EFFECT_SUPPORT_UNKNOWN,
+                info.isEffectSupported(VibrationEffect.EFFECT_CLICK));
+    }
+
+    @Test
+    public void testIsPrimitiveSupported_unsupportedInOneVibrator_returnsFalse() {
+        VibratorInfo supportedVibrator = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
+                .build();
+        VibratorInfo unsupportedVibrator = VibratorInfo.EMPTY_VIBRATOR_INFO;
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{supportedVibrator, unsupportedVibrator});
+
+        assertFalse(info.isPrimitiveSupported(VibrationEffect.Composition.PRIMITIVE_CLICK));
+    }
+
+    @Test
+    public void testIsPrimitiveSupported_supportedInAllVibrators_returnsTrue() {
+        VibratorInfo firstInfo = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 5)
+                .build();
+        VibratorInfo secondInfo = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 15)
+                .build();
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, secondInfo});
+
+        assertTrue(info.isPrimitiveSupported(VibrationEffect.Composition.PRIMITIVE_CLICK));
+    }
+
+    @Test
+    public void testGetPrimitiveDuration_unsupportedInOneVibrator_returnsZero() {
+        VibratorInfo supportedVibrator = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
+                .build();
+        VibratorInfo unsupportedVibrator = VibratorInfo.EMPTY_VIBRATOR_INFO;
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{supportedVibrator, unsupportedVibrator});
+
+        assertEquals(0, info.getPrimitiveDuration(VibrationEffect.Composition.PRIMITIVE_CLICK));
+    }
+
+    @Test
+    public void testGetPrimitiveDuration_supportedInAllVibrators_returnsMaxDuration() {
+        VibratorInfo firstInfo = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
+                .build();
+        VibratorInfo secondInfo = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 20)
+                .build();
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, secondInfo});
+
+        assertEquals(20, info.getPrimitiveDuration(VibrationEffect.Composition.PRIMITIVE_CLICK));
+    }
+
+    @Test
+    public void testGetQFactorAndResonantFrequency_differentValues_returnsNaN() {
+        VibratorInfo firstInfo = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setQFactor(1f)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, 1, null))
+                .build();
+        VibratorInfo secondInfo = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setQFactor(2f)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(2, 2, 2, null))
+                .build();
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, secondInfo});
+
+        assertTrue(Float.isNaN(info.getQFactor()));
+        assertTrue(Float.isNaN(info.getResonantFrequencyHz()));
+        assertEmptyFrequencyProfileAndControl(info);
+
+        // One vibrator with values undefined.
+        VibratorInfo thirdVibrator = new VibratorInfo.Builder(/* id= */ 3).build();
+        info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, thirdVibrator});
+
+        assertTrue(Float.isNaN(info.getQFactor()));
+        assertTrue(Float.isNaN(info.getResonantFrequencyHz()));
+        assertEmptyFrequencyProfileAndControl(info);
+    }
+
+    @Test
+    public void testGetQFactorAndResonantFrequency_sameValues_returnsValue() {
+        VibratorInfo firstInfo = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setQFactor(10f)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(
+                        /* resonantFrequencyHz= */ 11, 10, 0.5f, null))
+                .build();
+        VibratorInfo secondInfo = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setQFactor(10f)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(
+                        /* resonantFrequencyHz= */ 11, 5, 1, null))
+                .build();
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, secondInfo});
+
+        assertEquals(10f, info.getQFactor(), TEST_TOLERANCE);
+        assertEquals(11f, info.getResonantFrequencyHz(), TEST_TOLERANCE);
+        // No frequency range defined.
+        assertTrue(info.getFrequencyProfile().isEmpty());
+        assertEquals(false, info.hasCapability(IVibrator.CAP_FREQUENCY_CONTROL));
+    }
+
+    @Test
+    public void testGetFrequencyProfile_differentResonantFrequencyOrResolutions_returnsEmpty() {
+        VibratorInfo firstInfo = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, 1,
+                        new float[] { 0, 1 }))
+                .build();
+        VibratorInfo differentResonantFrequency = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(2, 1, 1,
+                        new float[] { 0, 1 }))
+                .build();
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, differentResonantFrequency});
+
+        assertEmptyFrequencyProfileAndControl(info);
+
+        VibratorInfo differentFrequencyResolution = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, 2,
+                        new float[] { 0, 1 }))
+                .build();
+        info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, differentFrequencyResolution});
+
+        assertEmptyFrequencyProfileAndControl(info);
+    }
+
+    @Test
+    public void testGetFrequencyProfile_missingValues_returnsEmpty() {
+        VibratorInfo firstInfo = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, 1,
+                        new float[] { 0, 1 }))
+                .build();
+        VibratorInfo missingResonantFrequency = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(Float.NaN, 1, 1,
+                        new float[] { 0, 1 }))
+                .build();
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, missingResonantFrequency});
+
+        assertEmptyFrequencyProfileAndControl(info);
+
+        VibratorInfo missingMinFrequency = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, Float.NaN, 1,
+                        new float[] { 0, 1 }))
+                .build();
+        info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, missingMinFrequency});
+
+        assertEmptyFrequencyProfileAndControl(info);
+
+        VibratorInfo missingFrequencyResolution = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, Float.NaN,
+                        new float[] { 0, 1 }))
+                .build();
+        info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, missingFrequencyResolution});
+
+        assertEmptyFrequencyProfileAndControl(info);
+
+        VibratorInfo missingMaxAmplitudes = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(1, 1, 1, null))
+                .build();
+        info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, missingMaxAmplitudes});
+
+        assertEmptyFrequencyProfileAndControl(info);
+    }
+
+    @Test
+    public void testGetFrequencyProfile_unalignedMaxAmplitudes_returnsEmpty() {
+        VibratorInfo firstInfo = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10, 0.5f,
+                        new float[] { 0, 1, 1, 0 }))
+                .build();
+        VibratorInfo unalignedMinFrequency = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10.1f, 0.5f,
+                        new float[] { 0, 1, 1, 0 }))
+                .build();
+        VibratorInfo thirdVibrator = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f,
+                        new float[] { 0, 1, 1, 0 }))
+                .build();
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, unalignedMinFrequency, thirdVibrator});
+
+        assertEmptyFrequencyProfileAndControl(info);
+    }
+
+    @Test
+    public void testGetFrequencyProfile_alignedProfiles_returnsIntersection() {
+        VibratorInfo firstInfo = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10, 0.5f,
+                        new float[] { 0.5f, 1, 1, 0.5f }))
+                .build();
+        VibratorInfo secondInfo = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f,
+                        new float[] { 1, 1, 1 }))
+                .build();
+        VibratorInfo thirdVibrator = new VibratorInfo.Builder(/* id= */ 3)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f,
+                        new float[] { 0.8f, 1, 0.8f, 0.5f }))
+                .build();
+
+        VibratorInfo info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, secondInfo, thirdVibrator});
+
+        assertEquals(
+                new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f, new float[] { 0.8f, 1, 0.5f }),
+                info.getFrequencyProfile());
+        assertEquals(true, info.hasCapability(IVibrator.CAP_FREQUENCY_CONTROL));
+
+        // Third vibrator without frequency control capability.
+        thirdVibrator = new VibratorInfo.Builder(/* id= */ 3)
+                .setFrequencyProfile(new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f,
+                        new float[] { 0.8f, 1, 0.8f, 0.5f }))
+                .build();
+        info = new MultiVibratorInfo(/* id= */ 1,
+                new VibratorInfo[]{firstInfo, secondInfo, thirdVibrator});
+
+        assertEquals(
+                new VibratorInfo.FrequencyProfile(11, 10.5f, 0.5f, new float[] { 0.8f, 1, 0.5f }),
+                info.getFrequencyProfile());
+        assertEquals(false, info.hasCapability(IVibrator.CAP_FREQUENCY_CONTROL));
+    }
+
+    /**
+     * Asserts that the frequency profile is empty, and therefore frequency control isn't supported.
+     */
+    private void assertEmptyFrequencyProfileAndControl(VibratorInfo info) {
+        assertTrue(info.getFrequencyProfile().isEmpty());
+        assertEquals(false, info.hasCapability(IVibrator.CAP_FREQUENCY_CONTROL));
+    }
+}
diff --git a/core/tests/vibrator/src/android/os/vibrator/VibratorInfoFactoryTest.java b/core/tests/vibrator/src/android/os/vibrator/VibratorInfoFactoryTest.java
new file mode 100644
index 0000000..df4822f
--- /dev/null
+++ b/core/tests/vibrator/src/android/os/vibrator/VibratorInfoFactoryTest.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.os.vibrator;
+
+import static junit.framework.Assert.assertTrue;
+import static junit.framework.TestCase.assertEquals;
+
+import android.hardware.vibrator.IVibrator;
+import android.os.VibrationEffect;
+import android.os.VibratorInfo;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class VibratorInfoFactoryTest {
+
+    @Test
+    public void testCreatedInfo_hasTheRequestedId() {
+        // Empty info list.
+        VibratorInfo infoFromEmptyInfos =
+                VibratorInfoFactory.create(/* id= */ 3, new VibratorInfo[] {});
+        VibratorInfo info1 = new VibratorInfo.Builder(/* id= */ 1)
+                .setSupportedEffects(VibrationEffect.EFFECT_CLICK)
+                .build();
+        VibratorInfo info2 = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
+                .build();
+        VibratorInfo infoFromOneInfo =
+                VibratorInfoFactory.create(/* id= */ -1, new VibratorInfo[] {info1});
+        VibratorInfo infoFromTwoInfos =
+                VibratorInfoFactory.create(/* id= */ -3, new VibratorInfo[] {info1, info2});
+
+        assertEquals(3, infoFromEmptyInfos.getId());
+        assertEquals(-1, infoFromOneInfo.getId());
+        assertEquals(-3, infoFromTwoInfos.getId());
+    }
+
+    @Test
+    public void testCreatedInfo_fromEmptyVibratorInfos_returnsEmptyVibratorInfo() {
+        VibratorInfo info = VibratorInfoFactory.create(/* id= */ 2, new VibratorInfo[] {});
+
+        assertEqualContent(VibratorInfo.EMPTY_VIBRATOR_INFO, info);
+    }
+
+    @Test
+    public void testCreatedInfo_fromSingleVibratorInfo_hasEqualContent() {
+        VibratorInfo info = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS | IVibrator.CAP_FREQUENCY_CONTROL)
+                .setSupportedEffects(VibrationEffect.EFFECT_TICK, VibrationEffect.EFFECT_THUD)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 20)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_TICK, 30)
+                .build();
+
+        VibratorInfo createdInfo =
+                VibratorInfoFactory.create(/* id= */ -1, new VibratorInfo[] {info});
+
+        assertEqualContent(info, createdInfo);
+    }
+
+    @Test
+    public void testCreatedInfo_hasEqualContentRegardlessOfSourceInfoOrder() {
+        VibratorInfo info1 = new VibratorInfo.Builder(/* id= */ 1)
+                .setCapabilities(IVibrator.CAP_FREQUENCY_CONTROL)
+                .setSupportedEffects(VibrationEffect.EFFECT_CLICK)
+                .build();
+        VibratorInfo info2 = new VibratorInfo.Builder(/* id= */ 2)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
+                .build();
+
+        assertEqualContent(
+                VibratorInfoFactory.create(/* id= */ -1, new VibratorInfo[] {info1, info2}),
+                VibratorInfoFactory.create(/* id= */ -1, new VibratorInfo[] {info2, info1}));
+    }
+
+    @Test
+    public void testCreatedInfoContents() {
+        VibratorInfo info1 = new VibratorInfo.Builder(/* id= */ -1)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS | IVibrator.CAP_FREQUENCY_CONTROL)
+                .setSupportedEffects(VibrationEffect.EFFECT_CLICK, VibrationEffect.EFFECT_POP)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD, 5)
+                .build();
+        VibratorInfo info2 = new VibratorInfo.Builder(/* id= */ -2)
+                .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS | IVibrator.CAP_AMPLITUDE_CONTROL)
+                .setSupportedEffects(VibrationEffect.EFFECT_POP, VibrationEffect.EFFECT_THUD)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 10)
+                .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD, 20)
+                .build();
+        VibratorInfo info3 = new VibratorInfo.Builder(/* id= */ -3)
+                .setCapabilities(IVibrator.CAP_AMPLITUDE_CONTROL)
+                .build();
+
+        assertEquals(
+                new VibratorInfo.Builder(/* id= */ 3)
+                        .setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS)
+                        .setSupportedEffects(VibrationEffect.EFFECT_POP)
+                        .setSupportedPrimitive(VibrationEffect.Composition.PRIMITIVE_THUD, 20)
+                        .build(),
+                VibratorInfoFactory.create(/* id= */ 3, new VibratorInfo[] {info1, info2}));
+        assertEquals(
+                new VibratorInfo.Builder(/* id= */ 3)
+                        .setCapabilities(IVibrator.CAP_AMPLITUDE_CONTROL)
+                        .build(),
+                VibratorInfoFactory.create(/* id= */ 3, new VibratorInfo[] {info2, info3}));
+        assertEquals(
+                new VibratorInfo.Builder(/* id= */ 3).build(),
+                VibratorInfoFactory.create(/* id= */ 3, new VibratorInfo[] {info1, info3}));
+    }
+
+    private static void assertEqualContent(VibratorInfo info1, VibratorInfo info2) {
+        assertTrue(info1.equalContent(info2));
+    }
+}
diff --git a/libs/WindowManager/Shell/res/layout/bubble_bar_manage_education.xml b/libs/WindowManager/Shell/res/layout/bubble_bar_manage_education.xml
new file mode 100644
index 0000000..a0a06f1
--- /dev/null
+++ b/libs/WindowManager/Shell/res/layout/bubble_bar_manage_education.xml
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2023 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License
+  -->
+<com.android.wm.shell.common.bubbles.BubblePopupView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:layout_gravity="center_horizontal"
+    android:layout_marginHorizontal="@dimen/bubble_popup_margin_horizontal"
+    android:layout_marginTop="@dimen/bubble_popup_margin_top"
+    android:elevation="@dimen/bubble_manage_menu_elevation"
+    android:gravity="center_horizontal"
+    android:orientation="vertical">
+
+    <ImageView
+        android:layout_width="32dp"
+        android:layout_height="32dp"
+        android:tint="?android:attr/colorAccent"
+        android:contentDescription="@null"
+        android:src="@drawable/pip_ic_settings"/>
+
+    <TextView
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginTop="16dp"
+        android:maxWidth="@dimen/bubble_popup_content_max_width"
+        android:maxLines="1"
+        android:ellipsize="end"
+        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Headline"
+        android:textColor="?android:attr/textColorPrimary"
+        android:text="@string/bubble_bar_education_manage_title"/>
+
+    <TextView
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginTop="16dp"
+        android:maxWidth="@dimen/bubble_popup_content_max_width"
+        android:textAppearance="@android:style/TextAppearance.DeviceDefault"
+        android:textColor="?android:attr/textColorSecondary"
+        android:textAlignment="center"
+        android:text="@string/bubble_bar_education_manage_text"/>
+
+</com.android.wm.shell.common.bubbles.BubblePopupView>
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/res/values/dimen.xml b/libs/WindowManager/Shell/res/values/dimen.xml
index 597e899d..20bf81d 100644
--- a/libs/WindowManager/Shell/res/values/dimen.xml
+++ b/libs/WindowManager/Shell/res/values/dimen.xml
@@ -226,6 +226,20 @@
     <dimen name="bubble_user_education_padding_end">58dp</dimen>
     <!-- Padding between the bubble and the user education text. -->
     <dimen name="bubble_user_education_stack_padding">16dp</dimen>
+    <!-- Max width for the bubble popup view. -->
+    <dimen name="bubble_popup_content_max_width">300dp</dimen>
+    <!-- Horizontal margin for the bubble popup view. -->
+    <dimen name="bubble_popup_margin_horizontal">32dp</dimen>
+    <!-- Top margin for the bubble popup view. -->
+    <dimen name="bubble_popup_margin_top">16dp</dimen>
+    <!-- Width for the bubble popup view arrow. -->
+    <dimen name="bubble_popup_arrow_width">12dp</dimen>
+    <!-- Height for the bubble popup view arrow. -->
+    <dimen name="bubble_popup_arrow_height">10dp</dimen>
+    <!-- Corner radius for the bubble popup view arrow. -->
+    <dimen name="bubble_popup_arrow_corner_radius">2dp</dimen>
+    <!-- Padding for the bubble popup view contents. -->
+    <dimen name="bubble_popup_padding">24dp</dimen>
     <!-- The size of the caption bar inset at the top of bubble bar expanded view. -->
     <dimen name="bubble_bar_expanded_view_caption_height">32dp</dimen>
     <!-- The height of the dots shown for the caption menu in the bubble bar expanded view.. -->
diff --git a/libs/WindowManager/Shell/res/values/strings.xml b/libs/WindowManager/Shell/res/values/strings.xml
index 8cbc3d0..00c63d7 100644
--- a/libs/WindowManager/Shell/res/values/strings.xml
+++ b/libs/WindowManager/Shell/res/values/strings.xml
@@ -163,6 +163,11 @@
     <!-- [CHAR LIMIT=NONE] Empty overflow subtitle -->
     <string name="bubble_overflow_empty_subtitle">Recent bubbles and dismissed bubbles will appear here</string>
 
+    <!-- Title text for the bubble bar "manage" button tool tip highlighting where users can go to control bubble settings. [CHAR LIMIT=60]-->
+    <string name="bubble_bar_education_manage_title">Control bubbles anytime</string>
+    <!-- Descriptive text for the bubble bar "manage" button tool tip highlighting where users can go to control bubble settings. [CHAR LIMIT=80]-->
+    <string name="bubble_bar_education_manage_text">Tap here to manage which apps and conversations can bubble</string>
+
     <!-- [CHAR LIMIT=100] Notification Importance title -->
     <string name="notification_bubble_title">Bubble</string>
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubble.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubble.java
index 7e09c98..ff67110 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubble.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubble.java
@@ -60,7 +60,6 @@
 /**
  * Encapsulates the data and UI elements of a bubble.
  */
-@VisibleForTesting
 public class Bubble implements BubbleViewProvider {
     private static final String TAG = "Bubble";
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleEducationController.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleEducationController.kt
new file mode 100644
index 0000000..e57f02c
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleEducationController.kt
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.bubbles
+
+import android.content.Context
+import android.util.Log
+import androidx.core.content.edit
+import com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_USER_EDUCATION
+import com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES
+import com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME
+
+/** Manages bubble education flags. Provides convenience methods to check the education state */
+class BubbleEducationController(private val context: Context) {
+    private val prefs = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
+
+    /** Whether the user has seen the stack education */
+    @get:JvmName(name = "hasSeenStackEducation")
+    var hasSeenStackEducation: Boolean
+        get() = prefs.getBoolean(PREF_STACK_EDUCATION, false)
+        set(value) = prefs.edit { putBoolean(PREF_STACK_EDUCATION, value) }
+
+    /** Whether the user has seen the expanded view "manage" menu education */
+    @get:JvmName(name = "hasSeenManageEducation")
+    var hasSeenManageEducation: Boolean
+        get() = prefs.getBoolean(PREF_MANAGED_EDUCATION, false)
+        set(value) = prefs.edit { putBoolean(PREF_MANAGED_EDUCATION, value) }
+
+    /** Whether education view should show for the collapsed stack. */
+    fun shouldShowStackEducation(bubble: BubbleViewProvider?): Boolean {
+        val shouldShow = bubble != null &&
+                bubble.isConversationBubble && // show education for conversation bubbles only
+                (!hasSeenStackEducation || BubbleDebugConfig.forceShowUserEducation(context))
+        logDebug("Show stack edu: $shouldShow")
+        return shouldShow
+    }
+
+    /** Whether the educational view should show for the expanded view "manage" menu. */
+    fun shouldShowManageEducation(bubble: BubbleViewProvider?): Boolean {
+        val shouldShow = bubble != null &&
+                bubble.isConversationBubble && // show education for conversation bubbles only
+                (!hasSeenManageEducation || BubbleDebugConfig.forceShowUserEducation(context))
+        logDebug("Show manage edu: $shouldShow")
+        return shouldShow
+    }
+
+    private fun logDebug(message: String) {
+        if (DEBUG_USER_EDUCATION) {
+            Log.d(TAG, message)
+        }
+    }
+
+    companion object {
+        private val TAG = if (TAG_WITH_CLASS_NAME) "BubbleEducationController" else TAG_BUBBLES
+        const val PREF_STACK_EDUCATION: String = "HasSeenBubblesOnboarding"
+        const val PREF_MANAGED_EDUCATION: String = "HasSeenBubblesManageOnboarding"
+    }
+}
+
+/** Convenience extension method to check if the bubble is a conversation bubble */
+private val BubbleViewProvider.isConversationBubble: Boolean
+    get() = if (this is Bubble) isConversation else false
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePopupViewExt.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePopupViewExt.kt
new file mode 100644
index 0000000..bdb09e1
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePopupViewExt.kt
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.bubbles
+
+import android.graphics.Color
+import com.android.wm.shell.R
+import com.android.wm.shell.common.bubbles.BubblePopupDrawable
+import com.android.wm.shell.common.bubbles.BubblePopupView
+
+/**
+ * A convenience method to setup the [BubblePopupView] with the correct config using local resources
+ */
+fun BubblePopupView.setup() {
+    val attrs =
+        context.obtainStyledAttributes(
+            intArrayOf(
+                com.android.internal.R.attr.materialColorSurface,
+                android.R.attr.dialogCornerRadius
+            )
+        )
+
+    val res = context.resources
+    val config =
+        BubblePopupDrawable.Config(
+            color = attrs.getColor(0, Color.WHITE),
+            cornerRadius = attrs.getDimension(1, 0f),
+            contentPadding = res.getDimensionPixelSize(R.dimen.bubble_popup_padding),
+            arrowWidth = res.getDimension(R.dimen.bubble_popup_arrow_width),
+            arrowHeight = res.getDimension(R.dimen.bubble_popup_arrow_height),
+            arrowRadius = res.getDimension(R.dimen.bubble_popup_arrow_corner_radius)
+        )
+    attrs.recycle()
+    setupBackground(config)
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
index da5974f..74f830e 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
@@ -46,7 +46,6 @@
 import android.graphics.RectF;
 import android.graphics.drawable.ColorDrawable;
 import android.os.Bundle;
-import android.os.SystemProperties;
 import android.provider.Settings;
 import android.util.Log;
 import android.view.Choreographer;
@@ -108,12 +107,6 @@
  */
 public class BubbleStackView extends FrameLayout
         implements ViewTreeObserver.OnComputeInternalInsetsListener {
-
-    // LINT.IfChange
-    public static final boolean ENABLE_FLING_TO_DISMISS_BUBBLE =
-            SystemProperties.getBoolean("persist.wm.debug.fling_to_dismiss_bubble", true);
-    // LINT.ThenChange(com/android/launcher3/taskbar/bubbles/BubbleDismissController.java)
-
     private static final String TAG = TAG_WITH_CLASS_NAME ? "BubbleStackView" : TAG_BUBBLES;
 
     /** How far the flyout needs to be dragged before it's dismissed regardless of velocity. */
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java
index 33629f9..c20733a 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java
@@ -19,7 +19,6 @@
 import static android.view.View.LAYOUT_DIRECTION_RTL;
 
 import static com.android.wm.shell.bubbles.BubblePositioner.NUM_VISIBLE_WHEN_RESTING;
-import static com.android.wm.shell.bubbles.BubbleStackView.ENABLE_FLING_TO_DISMISS_BUBBLE;
 
 import android.content.res.Resources;
 import android.graphics.Path;
@@ -355,7 +354,6 @@
         mMagnetizedBubbleDraggingOut.setMagnetListener(listener);
         mMagnetizedBubbleDraggingOut.setHapticsEnabled(true);
         mMagnetizedBubbleDraggingOut.setFlingToTargetMinVelocity(FLING_TO_DISMISS_MIN_VELOCITY);
-        mMagnetizedBubbleDraggingOut.setFlingToTargetEnabled(ENABLE_FLING_TO_DISMISS_BUBBLE);
     }
 
     private void springBubbleTo(View bubble, float x, float y) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java
index 5533842..4bb1ab4 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java
@@ -17,7 +17,6 @@
 package com.android.wm.shell.bubbles.animation;
 
 import static com.android.wm.shell.bubbles.BubblePositioner.NUM_VISIBLE_WHEN_RESTING;
-import static com.android.wm.shell.bubbles.BubbleStackView.ENABLE_FLING_TO_DISMISS_BUBBLE;
 
 import android.content.ContentResolver;
 import android.content.res.Resources;
@@ -1026,7 +1025,6 @@
             };
             mMagnetizedStack.setHapticsEnabled(true);
             mMagnetizedStack.setFlingToTargetMinVelocity(FLING_TO_DISMISS_MIN_VELOCITY);
-            mMagnetizedStack.setFlingToTargetEnabled(ENABLE_FLING_TO_DISMISS_BUBBLE);
         }
 
         final ContentResolver contentResolver = mLayout.getContext().getContentResolver();
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarExpandedView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarExpandedView.java
index 6b6d6ba..79f188a 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarExpandedView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarExpandedView.java
@@ -39,7 +39,6 @@
 import com.android.wm.shell.bubbles.Bubbles;
 import com.android.wm.shell.taskview.TaskView;
 
-import java.util.function.Consumer;
 import java.util.function.Supplier;
 
 /**
@@ -48,6 +47,18 @@
  * {@link BubbleController#isShowingAsBubbleBar()}
  */
 public class BubbleBarExpandedView extends FrameLayout implements BubbleTaskViewHelper.Listener {
+    /**
+     * The expanded view listener notifying the {@link BubbleBarLayerView} about the internal
+     * actions and events
+     */
+    public interface Listener {
+        /** Called when the task view task is first created. */
+        void onTaskCreated();
+        /** Called when expanded view needs to un-bubble the given conversation */
+        void onUnBubbleConversation(String bubbleKey);
+        /** Called when expanded view task view back button pressed */
+        void onBackPressed();
+    }
 
     private static final String TAG = BubbleBarExpandedView.class.getSimpleName();
     private static final int INVALID_TASK_ID = -1;
@@ -57,7 +68,7 @@
     private BubbleTaskViewHelper mBubbleTaskViewHelper;
     private BubbleBarMenuViewController mMenuViewController;
     private @Nullable Supplier<Rect> mLayerBoundsSupplier;
-    private @Nullable Consumer<String> mUnBubbleConversationCallback;
+    private @Nullable Listener mListener;
 
     private BubbleBarHandleView mHandleView = new BubbleBarHandleView(getContext());
     private @Nullable TaskView mTaskView;
@@ -145,15 +156,13 @@
         mMenuViewController.setListener(new BubbleBarMenuViewController.Listener() {
             @Override
             public void onMenuVisibilityChanged(boolean visible) {
-                if (mTaskView == null || mLayerBoundsSupplier == null) return;
-                // Updates the obscured touchable region for the task surface.
-                mTaskView.setObscuredTouchRect(visible ? mLayerBoundsSupplier.get() : null);
+                setObscured(visible);
             }
 
             @Override
             public void onUnBubbleConversation(Bubble bubble) {
-                if (mUnBubbleConversationCallback != null) {
-                    mUnBubbleConversationCallback.accept(bubble.getKey());
+                if (mListener != null) {
+                    mListener.onUnBubbleConversation(bubble.getKey());
                 }
             }
 
@@ -231,6 +240,9 @@
     public void onTaskCreated() {
         setContentVisibility(true);
         updateHandleColor(false /* animated */);
+        if (mListener != null) {
+            mListener.onTaskCreated();
+        }
     }
 
     @Override
@@ -240,7 +252,8 @@
 
     @Override
     public void onBackPressed() {
-        mController.collapseStack();
+        if (mListener == null) return;
+        mListener.onBackPressed();
     }
 
     /** Cleans up task view, should be called when the bubble is no longer active. */
@@ -254,6 +267,18 @@
         mMenuViewController.hideMenu(false /* animated */);
     }
 
+    /**
+     * Hides the current modal menu view or collapses the bubble stack.
+     * Called from {@link BubbleBarLayerView}
+     */
+    public void hideMenuOrCollapse() {
+        if (mMenuViewController.isMenuVisible()) {
+            mMenuViewController.hideMenu(/* animated = */ true);
+        } else {
+            mController.collapseStack();
+        }
+    }
+
     /** Updates the bubble shown in the expanded view. */
     public void update(Bubble bubble) {
         mBubbleTaskViewHelper.update(bubble);
@@ -270,10 +295,16 @@
         mLayerBoundsSupplier = supplier;
     }
 
-    /** Sets the function to call to un-bubble the given conversation. */
-    public void setUnBubbleConversationCallback(
-            @Nullable Consumer<String> unBubbleConversationCallback) {
-        mUnBubbleConversationCallback = unBubbleConversationCallback;
+    /** Sets expanded view listener */
+    void setListener(@Nullable Listener listener) {
+        mListener = listener;
+    }
+
+    /** Sets whether the view is obscured by some modal view */
+    void setObscured(boolean obscured) {
+        if (mTaskView == null || mLayerBoundsSupplier == null) return;
+        // Updates the obscured touchable region for the task surface.
+        mTaskView.setObscuredTouchRect(obscured ? mLayerBoundsSupplier.get() : null);
     }
 
     /**
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java
index bc04bfc..8f11253 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java
@@ -52,6 +52,7 @@
     private final BubbleController mBubbleController;
     private final BubblePositioner mPositioner;
     private final BubbleBarAnimationHelper mAnimationHelper;
+    private final BubbleEducationViewController mEducationViewController;
     private final View mScrimView;
 
     @Nullable
@@ -80,6 +81,10 @@
 
         mAnimationHelper = new BubbleBarAnimationHelper(context,
                 this, mPositioner);
+        mEducationViewController = new BubbleEducationViewController(context, (boolean visible) -> {
+            if (mExpandedView == null) return;
+            mExpandedView.setObscured(visible);
+        });
 
         mScrimView = new View(getContext());
         mScrimView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
@@ -90,9 +95,7 @@
         mScrimView.setBackgroundDrawable(new ColorDrawable(
                 getResources().getColor(android.R.color.system_neutral1_1000)));
 
-        setOnClickListener(view -> {
-            mBubbleController.collapseStack();
-        });
+        setOnClickListener(view -> hideMenuOrCollapse());
     }
 
     @Override
@@ -108,6 +111,7 @@
         getViewTreeObserver().removeOnComputeInternalInsetsListener(this);
 
         if (mExpandedView != null) {
+            mEducationViewController.hideManageEducation(/* animated = */ false);
             removeView(mExpandedView);
             mExpandedView = null;
         }
@@ -162,14 +166,27 @@
             final int width = mPositioner.getExpandedViewWidthForBubbleBar(isOverflowExpanded);
             final int height = mPositioner.getExpandedViewHeightForBubbleBar(isOverflowExpanded);
             mExpandedView.setVisibility(GONE);
-            mExpandedView.setUnBubbleConversationCallback(mUnBubbleConversationCallback);
+            mExpandedView.setY(mPositioner.getExpandedViewBottomForBubbleBar() - height);
             mExpandedView.setLayerBoundsSupplier(() -> new Rect(0, 0, getWidth(), getHeight()));
-            mExpandedView.setUnBubbleConversationCallback(bubbleKey -> {
-                if (mUnBubbleConversationCallback != null) {
-                    mUnBubbleConversationCallback.accept(bubbleKey);
+            mExpandedView.setListener(new BubbleBarExpandedView.Listener() {
+                @Override
+                public void onTaskCreated() {
+                    mEducationViewController.maybeShowManageEducation(b, mExpandedView);
+                }
+
+                @Override
+                public void onUnBubbleConversation(String bubbleKey) {
+                    if (mUnBubbleConversationCallback != null) {
+                        mUnBubbleConversationCallback.accept(bubbleKey);
+                    }
+                }
+
+                @Override
+                public void onBackPressed() {
+                    hideMenuOrCollapse();
                 }
             });
-            mExpandedView.setY(mPositioner.getExpandedViewBottomForBubbleBar() - height);
+
             addView(mExpandedView, new FrameLayout.LayoutParams(width, height));
         }
 
@@ -193,6 +210,7 @@
     public void collapse() {
         mIsExpanded = false;
         final BubbleBarExpandedView viewToRemove = mExpandedView;
+        mEducationViewController.hideManageEducation(/* animated = */ true);
         mAnimationHelper.animateCollapse(() -> removeView(viewToRemove));
         mBubbleController.getSysuiProxy().onStackExpandChanged(false);
         mExpandedView = null;
@@ -206,6 +224,17 @@
         mUnBubbleConversationCallback = unBubbleConversationCallback;
     }
 
+    /** Hides the current modal education/menu view, expanded view or collapses the bubble stack */
+    private void hideMenuOrCollapse() {
+        if (mEducationViewController.isManageEducationVisible()) {
+            mEducationViewController.hideManageEducation(/* animated = */ true);
+        } else if (isExpanded() && mExpandedView != null) {
+            mExpandedView.hideMenuOrCollapse();
+        } else {
+            mBubbleController.collapseStack();
+        }
+    }
+
     /** Updates the expanded view size and position. */
     private void updateExpandedView() {
         if (mExpandedView == null) return;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarMenuViewController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarMenuViewController.java
index 8be140c..81e7582 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarMenuViewController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarMenuViewController.java
@@ -56,6 +56,11 @@
                 SpringForce.STIFFNESS_MEDIUM, SpringForce.DAMPING_RATIO_LOW_BOUNCY);
     }
 
+    /** Tells if the menu is visible or being animated */
+    boolean isMenuVisible() {
+        return mMenuView != null && mMenuView.getVisibility() == View.VISIBLE;
+    }
+
     /** Sets menu actions listener */
     void setListener(@Nullable Listener listener) {
         mListener = listener;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleEducationViewController.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleEducationViewController.kt
new file mode 100644
index 0000000..7b39c6f
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleEducationViewController.kt
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.bubbles.bar
+
+import android.content.Context
+import android.view.LayoutInflater
+import android.view.ViewGroup
+import androidx.core.view.doOnLayout
+import androidx.dynamicanimation.animation.DynamicAnimation
+import androidx.dynamicanimation.animation.SpringForce
+import com.android.wm.shell.R
+import com.android.wm.shell.animation.PhysicsAnimator
+import com.android.wm.shell.bubbles.BubbleEducationController
+import com.android.wm.shell.bubbles.BubbleViewProvider
+import com.android.wm.shell.bubbles.setup
+import com.android.wm.shell.common.bubbles.BubblePopupView
+
+/** Manages bubble education presentation and animation */
+class BubbleEducationViewController(private val context: Context, private val listener: Listener) {
+    interface Listener {
+        fun onManageEducationVisibilityChanged(isVisible: Boolean)
+    }
+
+    private var rootView: ViewGroup? = null
+    private var educationView: BubblePopupView? = null
+    private var animator: PhysicsAnimator<BubblePopupView>? = null
+
+    private val springConfig by lazy {
+        PhysicsAnimator.SpringConfig(
+            SpringForce.STIFFNESS_MEDIUM,
+            SpringForce.DAMPING_RATIO_LOW_BOUNCY
+        )
+    }
+
+    private val controller by lazy { BubbleEducationController(context) }
+
+    /** Whether the education view is visible or being animated */
+    val isManageEducationVisible: Boolean
+        get() = educationView != null && rootView != null
+
+    /**
+     * Show manage bubble education if hasn't been shown before
+     *
+     * @param bubble the bubble used for the manage education check
+     * @param root the view to show manage education in
+     */
+    fun maybeShowManageEducation(bubble: BubbleViewProvider, root: ViewGroup) {
+        if (!controller.shouldShowManageEducation(bubble)) return
+        showManageEducation(root)
+    }
+
+    /**
+     * Hide the manage education view if visible
+     *
+     * @param animated whether should hide with animation
+     */
+    fun hideManageEducation(animated: Boolean) {
+        rootView?.let {
+            fun cleanUp() {
+                it.removeView(educationView)
+                rootView = null
+                listener.onManageEducationVisibilityChanged(isVisible = false)
+            }
+
+            if (animated) {
+                animateTransition(show = false, ::cleanUp)
+            } else {
+                cleanUp()
+            }
+        }
+    }
+
+    /**
+     * Show manage education with animation
+     *
+     * @param root the view to show manage education in
+     */
+    private fun showManageEducation(root: ViewGroup) {
+        hideManageEducation(animated = false)
+        if (educationView == null) {
+            val eduView = createEducationView(root)
+            educationView = eduView
+            animator = createAnimation(eduView)
+        }
+        root.addView(educationView)
+        rootView = root
+        animateTransition(show = true) {
+            controller.hasSeenManageEducation = true
+            listener.onManageEducationVisibilityChanged(isVisible = true)
+        }
+    }
+
+    /**
+     * Animate show/hide transition for the education view
+     *
+     * @param show whether to show or hide the view
+     * @param endActions a closure to be called when the animation completes
+     */
+    private fun animateTransition(show: Boolean, endActions: () -> Unit) {
+        animator?.let { animator ->
+            animator
+                .spring(DynamicAnimation.ALPHA, if (show) 1f else 0f)
+                .spring(DynamicAnimation.SCALE_X, if (show) 1f else EDU_SCALE_HIDDEN)
+                .spring(DynamicAnimation.SCALE_Y, if (show) 1f else EDU_SCALE_HIDDEN)
+                .withEndActions(endActions)
+                .start()
+        } ?: endActions()
+    }
+
+    private fun createEducationView(root: ViewGroup): BubblePopupView {
+        val view =
+            LayoutInflater.from(context).inflate(R.layout.bubble_bar_manage_education, root, false)
+                as BubblePopupView
+
+        return view.apply {
+            setup()
+            alpha = 0f
+            pivotY = 0f
+            scaleX = EDU_SCALE_HIDDEN
+            scaleY = EDU_SCALE_HIDDEN
+            doOnLayout { it.pivotX = it.width / 2f }
+            setOnClickListener { hideManageEducation(animated = true) }
+        }
+    }
+
+    private fun createAnimation(view: BubblePopupView): PhysicsAnimator<BubblePopupView> {
+        val animator = PhysicsAnimator.getInstance(view)
+        animator.setDefaultSpringConfig(springConfig)
+        return animator
+    }
+
+    companion object {
+        private const val EDU_SCALE_HIDDEN = 0.5f
+    }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/bubbles/BubblePopupDrawable.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/common/bubbles/BubblePopupDrawable.kt
new file mode 100644
index 0000000..8b5283d
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/bubbles/BubblePopupDrawable.kt
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.common.bubbles
+
+import android.annotation.ColorInt
+import android.graphics.Canvas
+import android.graphics.ColorFilter
+import android.graphics.Matrix
+import android.graphics.Outline
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.Rect
+import android.graphics.RectF
+import android.graphics.drawable.Drawable
+import kotlin.math.atan
+import kotlin.math.cos
+import kotlin.math.sin
+import kotlin.properties.Delegates
+
+/** A drawable for the [BubblePopupView] that draws a popup background with a directional arrow */
+class BubblePopupDrawable(private val config: Config) : Drawable() {
+    /** The direction of the arrow in the popup drawable */
+    enum class ArrowDirection {
+        UP,
+        DOWN
+    }
+
+    /** The arrow position on the side of the popup bubble */
+    sealed class ArrowPosition {
+        object Start : ArrowPosition()
+        object Center : ArrowPosition()
+        object End : ArrowPosition()
+        class Custom(val value: Float) : ArrowPosition()
+    }
+
+    /** The configuration for drawable features */
+    data class Config(
+        @ColorInt val color: Int,
+        val cornerRadius: Float,
+        val contentPadding: Int,
+        val arrowWidth: Float,
+        val arrowHeight: Float,
+        val arrowRadius: Float
+    )
+
+    /**
+     * The direction of the arrow in the popup drawable. It affects the content padding and requires
+     * it to be updated in the view.
+     */
+    var arrowDirection: ArrowDirection by
+        Delegates.observable(ArrowDirection.UP) { _, _, _ -> requestPathUpdate() }
+
+    /**
+     * Arrow position along the X axis and its direction. The position is adjusted to the content
+     * corner radius when applied so it doesn't go into rounded corner area
+     */
+    var arrowPosition: ArrowPosition by
+        Delegates.observable(ArrowPosition.Center) { _, _, _ -> requestPathUpdate() }
+
+    private val path = Path()
+    private val paint = Paint()
+    private var shouldUpdatePath = true
+
+    init {
+        paint.color = config.color
+        paint.style = Paint.Style.FILL
+        paint.isAntiAlias = true
+    }
+
+    override fun draw(canvas: Canvas) {
+        updatePathIfNeeded()
+        canvas.drawPath(path, paint)
+    }
+
+    override fun onBoundsChange(bounds: Rect?) {
+        requestPathUpdate()
+    }
+
+    /** Should be applied to the view padding if arrow direction changes */
+    override fun getPadding(padding: Rect): Boolean {
+        padding.set(
+            config.contentPadding,
+            config.contentPadding,
+            config.contentPadding,
+            config.contentPadding
+        )
+        when (arrowDirection) {
+            ArrowDirection.UP -> padding.top += config.arrowHeight.toInt()
+            ArrowDirection.DOWN -> padding.bottom += config.arrowHeight.toInt()
+        }
+        return true
+    }
+
+    override fun getOutline(outline: Outline) {
+        updatePathIfNeeded()
+        outline.setPath(path)
+    }
+
+    override fun getOpacity(): Int {
+        return paint.alpha
+    }
+
+    override fun setAlpha(alpha: Int) {
+        paint.alpha = alpha
+    }
+
+    override fun setColorFilter(colorFilter: ColorFilter?) {
+        paint.colorFilter = colorFilter
+    }
+
+    /** Schedules path update for the next redraw */
+    private fun requestPathUpdate() {
+        shouldUpdatePath = true
+    }
+
+    /** Updates the path if required, when bounds or arrow direction/position changes */
+    private fun updatePathIfNeeded() {
+        if (shouldUpdatePath) {
+            updatePath()
+            shouldUpdatePath = false
+        }
+    }
+
+    /** Updates the path value using the current bounds, config, arrow direction and position */
+    private fun updatePath() {
+        if (bounds.isEmpty) return
+        // Reset the path state
+        path.reset()
+        // The content rect where the filled rounded rect will be drawn
+        val contentRect = RectF(bounds)
+        when (arrowDirection) {
+            ArrowDirection.UP -> {
+                // Add rounded arrow pointing up to the path
+                addRoundedArrowPositioned(path, arrowPosition)
+                // Inset content rect by the arrow size from the top
+                contentRect.top += config.arrowHeight
+            }
+            ArrowDirection.DOWN -> {
+                val matrix = Matrix()
+                // Flip the path with the matrix to draw arrow pointing down
+                matrix.setScale(1f, -1f, bounds.width() / 2f, bounds.height() / 2f)
+                path.transform(matrix)
+                // Add rounded arrow with the flipped matrix applied, will point down
+                addRoundedArrowPositioned(path, arrowPosition)
+                // Restore the path matrix to the original state with inverted matrix
+                matrix.invert(matrix)
+                path.transform(matrix)
+                // Inset content rect by the arrow size from the bottom
+                contentRect.bottom -= config.arrowHeight
+            }
+        }
+        // Add the content area rounded rect
+        path.addRoundRect(contentRect, config.cornerRadius, config.cornerRadius, Path.Direction.CW)
+    }
+
+    /** Add a rounded arrow pointing up in the horizontal position on the canvas */
+    private fun addRoundedArrowPositioned(path: Path, position: ArrowPosition) {
+        val matrix = Matrix()
+        var translationX = positionValue(position) - config.arrowWidth / 2
+        // Offset to position between rounded corners of the content view
+        translationX = translationX.coerceIn(config.cornerRadius,
+                bounds.width() - config.cornerRadius - config.arrowWidth)
+        // Translate to add the arrow in the center horizontally
+        matrix.setTranslate(-translationX, 0f)
+        path.transform(matrix)
+        // Add rounded arrow
+        addRoundedArrow(path)
+        // Restore the path matrix to the original state with inverted matrix
+        matrix.invert(matrix)
+        path.transform(matrix)
+    }
+
+    /** Adds a rounded arrow pointing up to the path, can be flipped if needed */
+    private fun addRoundedArrow(path: Path) {
+        // Theta is half of the angle inside the triangle tip
+        val thetaTan = config.arrowWidth / (config.arrowHeight * 2f)
+        val theta = atan(thetaTan)
+        val thetaDeg = Math.toDegrees(theta.toDouble()).toFloat()
+        // The center Y value of the circle for the triangle tip
+        val tipCircleCenterY = config.arrowRadius / sin(theta)
+        // The length from triangle tip to intersection point with the circle
+        val tipIntersectionSideLength = config.arrowRadius / thetaTan
+        // The offset from the top to the point of intersection
+        val intersectionTopOffset = tipIntersectionSideLength * cos(theta)
+        // The offset from the center to the point of intersection
+        val intersectionCenterOffset = tipIntersectionSideLength * sin(theta)
+        // The center X of the triangle
+        val arrowCenterX = config.arrowWidth / 2f
+
+        // Set initial position in bottom left of the arrow
+        path.moveTo(0f, config.arrowHeight)
+        // Add the left side of the triangle
+        path.lineTo(arrowCenterX - intersectionCenterOffset, intersectionTopOffset)
+        // Add the arc from the left to the right side of the triangle
+        path.arcTo(
+            /* left = */ arrowCenterX - config.arrowRadius,
+            /* top = */ tipCircleCenterY - config.arrowRadius,
+            /* right = */ arrowCenterX + config.arrowRadius,
+            /* bottom = */ tipCircleCenterY + config.arrowRadius,
+            /* startAngle = */ 180 + thetaDeg,
+            /* sweepAngle = */ 180 - (2 * thetaDeg),
+            /* forceMoveTo = */ false
+        )
+        // Add the right side of the triangle
+        path.lineTo(config.arrowWidth, config.arrowHeight)
+        // Close the path
+        path.close()
+    }
+
+    /** The value of the arrow position provided the position and current bounds */
+    private fun positionValue(position: ArrowPosition): Float {
+        return when (position) {
+            is ArrowPosition.Start -> 0f
+            is ArrowPosition.Center -> bounds.width().toFloat() / 2f
+            is ArrowPosition.End -> bounds.width().toFloat()
+            is ArrowPosition.Custom -> position.value
+        }
+    }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/bubbles/BubblePopupView.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/common/bubbles/BubblePopupView.kt
new file mode 100644
index 0000000..f8a4946
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/bubbles/BubblePopupView.kt
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.common.bubbles
+
+import android.content.Context
+import android.graphics.Rect
+import android.util.AttributeSet
+import android.widget.LinearLayout
+
+/** A popup container view that uses [BubblePopupDrawable] as a background */
+open class BubblePopupView
+@JvmOverloads
+constructor(
+    context: Context,
+    attrs: AttributeSet? = null,
+    defStyleAttr: Int = 0,
+    defStyleRes: Int = 0
+) : LinearLayout(context, attrs, defStyleAttr, defStyleRes) {
+    private var popupDrawable: BubblePopupDrawable? = null
+
+    /**
+     * Sets up the popup drawable with the config provided. Required to remove dependency on local
+     * resources
+     */
+    fun setupBackground(config: BubblePopupDrawable.Config) {
+        popupDrawable = BubblePopupDrawable(config)
+        background = popupDrawable
+        forceLayout()
+    }
+
+    /**
+     * Sets the arrow direction for the background drawable and updates the padding to fit the
+     * content inside of the popup drawable
+     */
+    fun setArrowDirection(direction: BubblePopupDrawable.ArrowDirection) {
+        popupDrawable?.let {
+            it.arrowDirection = direction
+            val padding = Rect()
+            if (it.getPadding(padding)) {
+                setPadding(padding.left, padding.top, padding.right, padding.bottom)
+            }
+        }
+    }
+
+    /** Sets the arrow position for the background drawable and triggers redraw */
+    fun setArrowPosition(position: BubblePopupDrawable.ArrowPosition) {
+        popupDrawable?.let {
+            it.arrowPosition = position
+            invalidate()
+        }
+    }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PipUiEventLogger.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PipUiEventLogger.kt
new file mode 100644
index 0000000..642dacc
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PipUiEventLogger.kt
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.common.pip
+
+import android.app.TaskInfo
+import android.content.pm.PackageManager
+import com.android.internal.logging.UiEvent
+import com.android.internal.logging.UiEventLogger
+
+/**
+ * Helper class that ends PiP log to UiEvent, see also go/uievent
+ */
+class PipUiEventLogger(
+    private val mUiEventLogger: UiEventLogger,
+    private val mPackageManager: PackageManager
+) {
+    private var mPackageName: String? = null
+    private var mPackageUid = INVALID_PACKAGE_UID
+    fun setTaskInfo(taskInfo: TaskInfo?) {
+        if (taskInfo?.topActivity != null) {
+            // safe because topActivity is guaranteed non-null here
+            mPackageName = taskInfo.topActivity!!.packageName
+            mPackageUid = getUid(mPackageName!!, taskInfo.userId)
+        } else {
+            mPackageName = null
+            mPackageUid = INVALID_PACKAGE_UID
+        }
+    }
+
+    /**
+     * Sends log via UiEvent, reference go/uievent for how to debug locally
+     */
+    fun log(event: PipUiEventEnum?) {
+        if (mPackageName == null || mPackageUid == INVALID_PACKAGE_UID) {
+            return
+        }
+        mUiEventLogger.log(event!!, mPackageUid, mPackageName)
+    }
+
+    private fun getUid(packageName: String, userId: Int): Int {
+        var uid = INVALID_PACKAGE_UID
+        try {
+            uid = mPackageManager.getApplicationInfoAsUser(
+                packageName, 0 /* ApplicationInfoFlags */, userId
+            ).uid
+        } catch (e: PackageManager.NameNotFoundException) {
+            // do nothing.
+        }
+        return uid
+    }
+
+    /**
+     * Enums for logging the PiP events to UiEvent
+     */
+    enum class PipUiEventEnum(private val mId: Int) : UiEventLogger.UiEventEnum {
+        @UiEvent(doc = "Activity enters picture-in-picture mode")
+        PICTURE_IN_PICTURE_ENTER(603),
+
+        @UiEvent(doc = "Activity enters picture-in-picture mode with auto-enter-pip API")
+        PICTURE_IN_PICTURE_AUTO_ENTER(1313),
+
+        @UiEvent(doc = "Activity enters picture-in-picture mode from content-pip API")
+        PICTURE_IN_PICTURE_ENTER_CONTENT_PIP(1314),
+
+        @UiEvent(doc = "Expands from picture-in-picture to fullscreen")
+        PICTURE_IN_PICTURE_EXPAND_TO_FULLSCREEN(604),
+
+        @UiEvent(doc = "Removes picture-in-picture by tap close button")
+        PICTURE_IN_PICTURE_TAP_TO_REMOVE(605),
+
+        @UiEvent(doc = "Removes picture-in-picture by drag to dismiss area")
+        PICTURE_IN_PICTURE_DRAG_TO_REMOVE(606),
+
+        @UiEvent(doc = "Shows picture-in-picture menu")
+        PICTURE_IN_PICTURE_SHOW_MENU(607),
+
+        @UiEvent(doc = "Hides picture-in-picture menu")
+        PICTURE_IN_PICTURE_HIDE_MENU(608),
+
+        @UiEvent(
+            doc = "Changes the aspect ratio of picture-in-picture window. This is inherited" +
+                    " from previous Tron-based logging and currently not in use."
+        )
+        PICTURE_IN_PICTURE_CHANGE_ASPECT_RATIO(609),
+
+        @UiEvent(doc = "User resize of the picture-in-picture window")
+        PICTURE_IN_PICTURE_RESIZE(610),
+
+        @UiEvent(doc = "User unstashed picture-in-picture")
+        PICTURE_IN_PICTURE_STASH_UNSTASHED(709),
+
+        @UiEvent(doc = "User stashed picture-in-picture to the left side")
+        PICTURE_IN_PICTURE_STASH_LEFT(710),
+
+        @UiEvent(doc = "User stashed picture-in-picture to the right side")
+        PICTURE_IN_PICTURE_STASH_RIGHT(711),
+
+        @UiEvent(doc = "User taps on the settings button in PiP menu")
+        PICTURE_IN_PICTURE_SHOW_SETTINGS(933),
+
+        @UiEvent(doc = "Closes PiP with app-provided close action")
+        PICTURE_IN_PICTURE_CUSTOM_CLOSE(1058);
+
+        override fun getId(): Int {
+            return mId
+        }
+    }
+
+    companion object {
+        private const val INVALID_PACKAGE_UID = -1
+    }
+}
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
index c06b22c..a2eabb1 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
@@ -20,6 +20,7 @@
 
 import android.app.ActivityTaskManager;
 import android.content.Context;
+import android.content.pm.PackageManager;
 import android.os.Handler;
 import android.os.SystemProperties;
 import android.view.IWindowManager;
@@ -57,6 +58,7 @@
 import com.android.wm.shell.common.annotations.ShellBackgroundThread;
 import com.android.wm.shell.common.annotations.ShellMainThread;
 import com.android.wm.shell.common.annotations.ShellSplashscreenThread;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.compatui.CompatUIConfiguration;
 import com.android.wm.shell.compatui.CompatUIController;
 import com.android.wm.shell.compatui.CompatUIShellCommandHandler;
@@ -331,6 +333,18 @@
     abstract ShellBackAnimationRegistry optionalBackAnimationRegistry();
 
     //
+    // PiP (optional feature)
+    //
+
+    @WMSingleton
+    @Provides
+    static PipUiEventLogger providePipUiEventLogger(UiEventLogger uiEventLogger,
+            PackageManager packageManager) {
+        return new PipUiEventLogger(uiEventLogger, packageManager);
+    }
+
+
+    //
     // Bubbles (optional feature)
     //
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java
index 9bf973f..5fd4f24 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java
@@ -32,6 +32,7 @@
 import com.android.wm.shell.common.annotations.ShellMainThread;
 import com.android.wm.shell.common.pip.PhoneSizeSpecSource;
 import com.android.wm.shell.common.pip.PipAppOpsListener;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.dagger.WMShellBaseModule;
 import com.android.wm.shell.dagger.WMSingleton;
@@ -49,7 +50,6 @@
 import com.android.wm.shell.pip.PipTransition;
 import com.android.wm.shell.pip.PipTransitionController;
 import com.android.wm.shell.pip.PipTransitionState;
-import com.android.wm.shell.pip.PipUiEventLogger;
 import com.android.wm.shell.pip.PipUtils;
 import com.android.wm.shell.pip.phone.PhonePipKeepClearAlgorithm;
 import com.android.wm.shell.pip.phone.PhonePipMenuController;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1SharedModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1SharedModule.java
index e8fae24..55a810a 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1SharedModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1SharedModule.java
@@ -17,15 +17,12 @@
 package com.android.wm.shell.dagger.pip;
 
 import android.content.Context;
-import android.content.pm.PackageManager;
 import android.os.Handler;
 
-import com.android.internal.logging.UiEventLogger;
 import com.android.wm.shell.common.annotations.ShellMainThread;
 import com.android.wm.shell.dagger.WMSingleton;
 import com.android.wm.shell.pip.PipMediaController;
 import com.android.wm.shell.pip.PipSurfaceTransactionHelper;
-import com.android.wm.shell.pip.PipUiEventLogger;
 
 import dagger.Module;
 import dagger.Provides;
@@ -49,11 +46,4 @@
     static PipSurfaceTransactionHelper providePipSurfaceTransactionHelper(Context context) {
         return new PipSurfaceTransactionHelper(context);
     }
-
-    @WMSingleton
-    @Provides
-    static PipUiEventLogger providePipUiEventLogger(UiEventLogger uiEventLogger,
-            PackageManager packageManager) {
-        return new PipUiEventLogger(uiEventLogger, packageManager);
-    }
 }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip2Module.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip2Module.java
index c7c6e8a..8dec4ea 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip2Module.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip2Module.java
@@ -18,6 +18,7 @@
 
 import android.annotation.Nullable;
 
+import com.android.wm.shell.dagger.WMShellBaseModule;
 import com.android.wm.shell.dagger.WMSingleton;
 import com.android.wm.shell.pip2.PipTransition;
 
@@ -26,9 +27,9 @@
 
 /**
  * Provides dependencies from {@link com.android.wm.shell.pip2}, this implementation is meant to be
- * the successor of its sibling {@link Pip1SharedModule}.
+ * the successor of its sibling {@link Pip1Module}.
  */
-@Module
+@Module(includes = WMShellBaseModule.class)
 public abstract class Pip2Module {
     @WMSingleton
     @Provides
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java
index 80ffbb0..4e332be 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java
@@ -30,6 +30,7 @@
 import com.android.wm.shell.common.annotations.ShellMainThread;
 import com.android.wm.shell.common.pip.LegacySizeSpecSource;
 import com.android.wm.shell.common.pip.PipAppOpsListener;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.dagger.WMShellBaseModule;
 import com.android.wm.shell.dagger.WMSingleton;
@@ -43,7 +44,6 @@
 import com.android.wm.shell.pip.PipTaskOrganizer;
 import com.android.wm.shell.pip.PipTransitionController;
 import com.android.wm.shell.pip.PipTransitionState;
-import com.android.wm.shell.pip.PipUiEventLogger;
 import com.android.wm.shell.pip.tv.TvPipBoundsAlgorithm;
 import com.android.wm.shell.pip.tv.TvPipBoundsController;
 import com.android.wm.shell.pip.tv.TvPipBoundsState;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
index 19c60c2..296857b 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
@@ -82,6 +82,7 @@
 import com.android.wm.shell.common.ShellExecutor;
 import com.android.wm.shell.common.SyncTransactionQueue;
 import com.android.wm.shell.common.annotations.ShellMainThread;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.pip.phone.PipMotionHelper;
 import com.android.wm.shell.protolog.ShellProtoLogGroup;
 import com.android.wm.shell.splitscreen.SplitScreenController;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipUiEventLogger.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipUiEventLogger.java
deleted file mode 100644
index 3e5a19b..0000000
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipUiEventLogger.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.pip;
-
-import android.app.TaskInfo;
-import android.content.pm.PackageManager;
-
-import com.android.internal.logging.UiEvent;
-import com.android.internal.logging.UiEventLogger;
-
-/**
- * Helper class that ends PiP log to UiEvent, see also go/uievent
- */
-public class PipUiEventLogger {
-
-    private static final int INVALID_PACKAGE_UID = -1;
-
-    private final UiEventLogger mUiEventLogger;
-    private final PackageManager mPackageManager;
-
-    private String mPackageName;
-    private int mPackageUid = INVALID_PACKAGE_UID;
-
-    public PipUiEventLogger(UiEventLogger uiEventLogger, PackageManager packageManager) {
-        mUiEventLogger = uiEventLogger;
-        mPackageManager = packageManager;
-    }
-
-    public void setTaskInfo(TaskInfo taskInfo) {
-        if (taskInfo != null && taskInfo.topActivity != null) {
-            mPackageName = taskInfo.topActivity.getPackageName();
-            mPackageUid = getUid(mPackageName, taskInfo.userId);
-        } else {
-            mPackageName = null;
-            mPackageUid = INVALID_PACKAGE_UID;
-        }
-    }
-
-    /**
-     * Sends log via UiEvent, reference go/uievent for how to debug locally
-     */
-    public void log(PipUiEventEnum event) {
-        if (mPackageName == null || mPackageUid == INVALID_PACKAGE_UID) {
-            return;
-        }
-        mUiEventLogger.log(event, mPackageUid, mPackageName);
-    }
-
-    private int getUid(String packageName, int userId) {
-        int uid = INVALID_PACKAGE_UID;
-        try {
-            uid = mPackageManager.getApplicationInfoAsUser(
-                    packageName, 0 /* ApplicationInfoFlags */, userId).uid;
-        } catch (PackageManager.NameNotFoundException e) {
-            // do nothing.
-        }
-        return uid;
-    }
-
-    /**
-     * Enums for logging the PiP events to UiEvent
-     */
-    public enum PipUiEventEnum implements UiEventLogger.UiEventEnum {
-        @UiEvent(doc = "Activity enters picture-in-picture mode")
-        PICTURE_IN_PICTURE_ENTER(603),
-
-        @UiEvent(doc = "Activity enters picture-in-picture mode with auto-enter-pip API")
-        PICTURE_IN_PICTURE_AUTO_ENTER(1313),
-
-        @UiEvent(doc = "Activity enters picture-in-picture mode from content-pip API")
-        PICTURE_IN_PICTURE_ENTER_CONTENT_PIP(1314),
-
-        @UiEvent(doc = "Expands from picture-in-picture to fullscreen")
-        PICTURE_IN_PICTURE_EXPAND_TO_FULLSCREEN(604),
-
-        @UiEvent(doc = "Removes picture-in-picture by tap close button")
-        PICTURE_IN_PICTURE_TAP_TO_REMOVE(605),
-
-        @UiEvent(doc = "Removes picture-in-picture by drag to dismiss area")
-        PICTURE_IN_PICTURE_DRAG_TO_REMOVE(606),
-
-        @UiEvent(doc = "Shows picture-in-picture menu")
-        PICTURE_IN_PICTURE_SHOW_MENU(607),
-
-        @UiEvent(doc = "Hides picture-in-picture menu")
-        PICTURE_IN_PICTURE_HIDE_MENU(608),
-
-        @UiEvent(doc = "Changes the aspect ratio of picture-in-picture window. This is inherited"
-                + " from previous Tron-based logging and currently not in use.")
-        PICTURE_IN_PICTURE_CHANGE_ASPECT_RATIO(609),
-
-        @UiEvent(doc = "User resize of the picture-in-picture window")
-        PICTURE_IN_PICTURE_RESIZE(610),
-
-        @UiEvent(doc = "User unstashed picture-in-picture")
-        PICTURE_IN_PICTURE_STASH_UNSTASHED(709),
-
-        @UiEvent(doc = "User stashed picture-in-picture to the left side")
-        PICTURE_IN_PICTURE_STASH_LEFT(710),
-
-        @UiEvent(doc = "User stashed picture-in-picture to the right side")
-        PICTURE_IN_PICTURE_STASH_RIGHT(711),
-
-        @UiEvent(doc = "User taps on the settings button in PiP menu")
-        PICTURE_IN_PICTURE_SHOW_SETTINGS(933),
-
-        @UiEvent(doc = "Closes PiP with app-provided close action")
-        PICTURE_IN_PICTURE_CUSTOM_CLOSE(1058);
-
-        private final int mId;
-
-        PipUiEventEnum(int id) {
-            mId = id;
-        }
-
-        @Override
-        public int getId() {
-            return mId;
-        }
-    }
-}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PhonePipMenuController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PhonePipMenuController.java
index 5e1b6be..c93d850 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PhonePipMenuController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PhonePipMenuController.java
@@ -38,12 +38,12 @@
 import com.android.internal.protolog.common.ProtoLog;
 import com.android.wm.shell.common.ShellExecutor;
 import com.android.wm.shell.common.SystemWindows;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.pip.PipBoundsState;
 import com.android.wm.shell.pip.PipMediaController;
 import com.android.wm.shell.pip.PipMediaController.ActionListener;
 import com.android.wm.shell.pip.PipMenuController;
 import com.android.wm.shell.pip.PipSurfaceTransactionHelper;
-import com.android.wm.shell.pip.PipUiEventLogger;
 import com.android.wm.shell.protolog.ShellProtoLogGroup;
 import com.android.wm.shell.splitscreen.SplitScreenController;
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipDismissTargetHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipDismissTargetHandler.java
index da455f8..4e75847 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipDismissTargetHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipDismissTargetHandler.java
@@ -38,7 +38,7 @@
 import com.android.wm.shell.common.bubbles.DismissCircleView;
 import com.android.wm.shell.common.bubbles.DismissView;
 import com.android.wm.shell.common.magnetictarget.MagnetizedObject;
-import com.android.wm.shell.pip.PipUiEventLogger;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 
 import kotlin.Unit;
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMenuView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMenuView.java
index 779c539..837426a 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMenuView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMenuView.java
@@ -66,7 +66,7 @@
 import com.android.wm.shell.R;
 import com.android.wm.shell.animation.Interpolators;
 import com.android.wm.shell.common.ShellExecutor;
-import com.android.wm.shell.pip.PipUiEventLogger;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.pip.PipUtils;
 import com.android.wm.shell.protolog.ShellProtoLogGroup;
 import com.android.wm.shell.splitscreen.SplitScreenController;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java
index b251f6f..8f0a8e1 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java
@@ -33,7 +33,6 @@
 import android.graphics.PointF;
 import android.graphics.Rect;
 import android.os.Debug;
-import android.os.SystemProperties;
 
 import com.android.internal.protolog.common.ProtoLog;
 import com.android.wm.shell.R;
@@ -48,19 +47,16 @@
 import com.android.wm.shell.pip.PipTransitionController;
 import com.android.wm.shell.protolog.ShellProtoLogGroup;
 
-import java.util.function.Consumer;
-
 import kotlin.Unit;
 import kotlin.jvm.functions.Function0;
 
+import java.util.function.Consumer;
+
 /**
  * A helper to animate and manipulate the PiP.
  */
 public class PipMotionHelper implements PipAppOpsListener.Callback,
         FloatingContentCoordinator.FloatingContent {
-
-    public static final boolean ENABLE_FLING_TO_DISMISS_PIP =
-            SystemProperties.getBoolean("persist.wm.debug.fling_to_dismiss_pip", false);
     private static final String TAG = "PipMotionHelper";
     private static final boolean DEBUG = false;
 
@@ -707,7 +703,7 @@
                     loc[1] = animatedPipBounds.top;
                 }
             };
-            mMagnetizedPip.setFlingToTargetEnabled(ENABLE_FLING_TO_DISMISS_PIP);
+            mMagnetizedPip.setFlingToTargetEnabled(false);
         }
 
         return mMagnetizedPip;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipResizeGestureHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipResizeGestureHandler.java
index abe2db0..4e687dd 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipResizeGestureHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipResizeGestureHandler.java
@@ -46,11 +46,11 @@
 import com.android.internal.policy.TaskResizingAlgorithm;
 import com.android.wm.shell.R;
 import com.android.wm.shell.common.ShellExecutor;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.pip.PipAnimationController;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
 import com.android.wm.shell.pip.PipTaskOrganizer;
-import com.android.wm.shell.pip.PipUiEventLogger;
 
 import java.io.PrintWriter;
 import java.util.function.Consumer;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipTouchHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipTouchHandler.java
index 9f7dee7..6055fd9 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipTouchHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipTouchHandler.java
@@ -50,13 +50,13 @@
 import com.android.wm.shell.R;
 import com.android.wm.shell.common.FloatingContentCoordinator;
 import com.android.wm.shell.common.ShellExecutor;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.PipAnimationController;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
 import com.android.wm.shell.pip.PipTaskOrganizer;
 import com.android.wm.shell.pip.PipTransitionController;
-import com.android.wm.shell.pip.PipUiEventLogger;
 import com.android.wm.shell.pip.PipUtils;
 import com.android.wm.shell.protolog.ShellProtoLogGroup;
 import com.android.wm.shell.sysui.ShellInit;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipTaskOrganizer.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipTaskOrganizer.java
index 4819f66..dbec607 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipTaskOrganizer.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipTaskOrganizer.java
@@ -25,6 +25,7 @@
 import com.android.wm.shell.common.DisplayController;
 import com.android.wm.shell.common.ShellExecutor;
 import com.android.wm.shell.common.SyncTransactionQueue;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.pip.PipAnimationController;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
@@ -35,7 +36,6 @@
 import com.android.wm.shell.pip.PipTaskOrganizer;
 import com.android.wm.shell.pip.PipTransitionController;
 import com.android.wm.shell.pip.PipTransitionState;
-import com.android.wm.shell.pip.PipUiEventLogger;
 import com.android.wm.shell.pip.PipUtils;
 import com.android.wm.shell.splitscreen.SplitScreenController;
 
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/service/Utils.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/service/Utils.kt
index 610cede..fa723e3 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/service/Utils.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/service/Utils.kt
@@ -23,6 +23,7 @@
 import android.tools.common.NavBar
 import android.tools.common.Rotation
 import android.tools.device.apphelpers.MessagingAppHelper
+import android.tools.device.flicker.rules.ArtifactSaverRule
 import android.tools.device.flicker.rules.ChangeDisplayOrientationRule
 import android.tools.device.flicker.rules.LaunchAppRule
 import android.tools.device.flicker.rules.RemoveAllTasksButHomeRule
@@ -33,9 +34,10 @@
     private val instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation()
 
     fun testSetupRule(navigationMode: NavBar, rotation: Rotation): RuleChain {
-        return RuleChain.outerRule(UnlockScreenRule())
+        return RuleChain.outerRule(ArtifactSaverRule())
+            .around(UnlockScreenRule())
             .around(
-                NavigationModeRule(navigationMode.value, /* changeNavigationModeAfterTest */ false)
+                NavigationModeRule(navigationMode.value, false)
             )
             .around(
                 LaunchAppRule(MessagingAppHelper(instrumentation), clearCacheAfterParsing = false)
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
index 1e3fe42..248d665 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
@@ -53,6 +53,7 @@
 import com.android.wm.shell.common.DisplayLayout;
 import com.android.wm.shell.common.SyncTransactionQueue;
 import com.android.wm.shell.common.pip.PhoneSizeSpecSource;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.phone.PhonePipMenuController;
 import com.android.wm.shell.splitscreen.SplitScreenController;
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java
index 689b5c5..12b4f3e 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java
@@ -37,6 +37,7 @@
 import com.android.wm.shell.common.FloatingContentCoordinator;
 import com.android.wm.shell.common.ShellExecutor;
 import com.android.wm.shell.common.pip.PhoneSizeSpecSource;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
@@ -45,7 +46,6 @@
 import com.android.wm.shell.pip.PipSnapAlgorithm;
 import com.android.wm.shell.pip.PipTaskOrganizer;
 import com.android.wm.shell.pip.PipTransitionController;
-import com.android.wm.shell.pip.PipUiEventLogger;
 
 import org.junit.Before;
 import org.junit.Test;
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipTouchHandlerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipTouchHandlerTest.java
index f65d7af..314f195d 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipTouchHandlerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipTouchHandlerTest.java
@@ -33,6 +33,7 @@
 import com.android.wm.shell.common.FloatingContentCoordinator;
 import com.android.wm.shell.common.ShellExecutor;
 import com.android.wm.shell.common.pip.PhoneSizeSpecSource;
+import com.android.wm.shell.common.pip.PipUiEventLogger;
 import com.android.wm.shell.common.pip.SizeSpecSource;
 import com.android.wm.shell.pip.PipBoundsAlgorithm;
 import com.android.wm.shell.pip.PipBoundsState;
@@ -41,7 +42,6 @@
 import com.android.wm.shell.pip.PipSnapAlgorithm;
 import com.android.wm.shell.pip.PipTaskOrganizer;
 import com.android.wm.shell.pip.PipTransitionController;
-import com.android.wm.shell.pip.PipUiEventLogger;
 import com.android.wm.shell.sysui.ShellInit;
 
 import org.junit.Before;
diff --git a/libs/androidfw/AssetManager.cpp b/libs/androidfw/AssetManager.cpp
index fb2b571..795bb3c 100644
--- a/libs/androidfw/AssetManager.cpp
+++ b/libs/androidfw/AssetManager.cpp
@@ -91,7 +91,7 @@
     path.appendPath(kResourceCache);
 
     char buf[256]; // 256 chars should be enough for anyone...
-    strncpy(buf, pkgPath.string(), 255);
+    strncpy(buf, pkgPath.c_str(), 255);
     buf[255] = '\0';
     char* filename = buf;
     while (*filename && *filename == '/') {
@@ -183,15 +183,15 @@
     if (kAppZipName) {
         realPath.appendPath(kAppZipName);
     }
-    ap.type = ::getFileType(realPath.string());
+    ap.type = ::getFileType(realPath.c_str());
     if (ap.type == kFileTypeRegular) {
         ap.path = realPath;
     } else {
         ap.path = path;
-        ap.type = ::getFileType(path.string());
+        ap.type = ::getFileType(path.c_str());
         if (ap.type != kFileTypeDirectory && ap.type != kFileTypeRegular) {
             ALOGW("Asset path %s is neither a directory nor file (type=%d).",
-                 path.string(), (int)ap.type);
+                 path.c_str(), (int)ap.type);
             return false;
         }
     }
@@ -207,7 +207,7 @@
     }
 
     ALOGV("In %p Asset %s path: %s", this,
-         ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.string());
+         ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.c_str());
 
     ap.isSystemAsset = isSystemAsset;
     ssize_t apPos = mAssetPaths.add(ap);
@@ -248,7 +248,7 @@
 
     Asset* idmap = NULL;
     if ((idmap = openAssetFromFileLocked(idmapPath, Asset::ACCESS_BUFFER)) == NULL) {
-        ALOGW("failed to open idmap file %s\n", idmapPath.string());
+        ALOGW("failed to open idmap file %s\n", idmapPath.c_str());
         return false;
     }
 
@@ -256,7 +256,7 @@
     String8 overlayPath;
     if (!ResTable::getIdmapInfo(idmap->getBuffer(false), idmap->getLength(),
                 NULL, NULL, NULL, &targetPath, &overlayPath)) {
-        ALOGW("failed to read idmap file %s\n", idmapPath.string());
+        ALOGW("failed to read idmap file %s\n", idmapPath.c_str());
         delete idmap;
         return false;
     }
@@ -264,29 +264,29 @@
 
     if (overlayPath != packagePath) {
         ALOGW("idmap file %s inconcistent: expected path %s does not match actual path %s\n",
-                idmapPath.string(), packagePath.string(), overlayPath.string());
+                idmapPath.c_str(), packagePath.c_str(), overlayPath.c_str());
         return false;
     }
-    if (access(targetPath.string(), R_OK) != 0) {
-        ALOGW("failed to access file %s: %s\n", targetPath.string(), strerror(errno));
+    if (access(targetPath.c_str(), R_OK) != 0) {
+        ALOGW("failed to access file %s: %s\n", targetPath.c_str(), strerror(errno));
         return false;
     }
-    if (access(idmapPath.string(), R_OK) != 0) {
-        ALOGW("failed to access file %s: %s\n", idmapPath.string(), strerror(errno));
+    if (access(idmapPath.c_str(), R_OK) != 0) {
+        ALOGW("failed to access file %s: %s\n", idmapPath.c_str(), strerror(errno));
         return false;
     }
-    if (access(overlayPath.string(), R_OK) != 0) {
-        ALOGW("failed to access file %s: %s\n", overlayPath.string(), strerror(errno));
+    if (access(overlayPath.c_str(), R_OK) != 0) {
+        ALOGW("failed to access file %s: %s\n", overlayPath.c_str(), strerror(errno));
         return false;
     }
 
     asset_path oap;
     oap.path = overlayPath;
-    oap.type = ::getFileType(overlayPath.string());
+    oap.type = ::getFileType(overlayPath.c_str());
     oap.idmap = idmapPath;
 #if 0
     ALOGD("Overlay added: targetPath=%s overlayPath=%s idmapPath=%s\n",
-            targetPath.string(), overlayPath.string(), idmapPath.string());
+            targetPath.c_str(), overlayPath.c_str(), idmapPath.c_str());
 #endif
     mAssetPaths.add(oap);
     *cookie = static_cast<int32_t>(mAssetPaths.size());
@@ -310,7 +310,7 @@
     ap.type = kFileTypeRegular;
     ap.assumeOwnership = assume_ownership;
 
-    ALOGV("In %p Asset fd %d name: %s", this, fd, ap.path.string());
+    ALOGV("In %p Asset fd %d name: %s", this, fd, ap.path.c_str());
 
     ssize_t apPos = mAssetPaths.add(ap);
 
@@ -343,11 +343,11 @@
             assets[i] = openNonAssetInPathLocked("resources.arsc",
                     Asset::ACCESS_BUFFER, ap);
             if (assets[i] == NULL) {
-                ALOGW("failed to find resources.arsc in %s\n", ap.path.string());
+                ALOGW("failed to find resources.arsc in %s\n", ap.path.c_str());
                 goto exit;
             }
             if (tables[i].add(assets[i]) != NO_ERROR) {
-                ALOGW("failed to add %s to resource table", paths[i].string());
+                ALOGW("failed to add %s to resource table", paths[i].c_str());
                 goto exit;
             }
         }
@@ -449,8 +449,8 @@
     while (i > 0) {
         i--;
         ALOGV("Looking for asset '%s' in '%s'\n",
-                assetName.string(), mAssetPaths.itemAt(i).path.string());
-        Asset* pAsset = openNonAssetInPathLocked(assetName.string(), mode,
+                assetName.c_str(), mAssetPaths.itemAt(i).path.c_str());
+        Asset* pAsset = openNonAssetInPathLocked(assetName.c_str(), mode,
                 mAssetPaths.editItemAt(i));
         if (pAsset != NULL) {
             return pAsset != kExcludedAsset ? pAsset : NULL;
@@ -478,7 +478,7 @@
     size_t i = mAssetPaths.size();
     while (i > 0) {
         i--;
-        ALOGV("Looking for non-asset '%s' in '%s'\n", fileName, mAssetPaths.itemAt(i).path.string());
+        ALOGV("Looking for non-asset '%s' in '%s'\n", fileName, mAssetPaths.itemAt(i).path.c_str());
         Asset* pAsset = openNonAssetInPathLocked(
             fileName, mode, mAssetPaths.editItemAt(i));
         if (pAsset != NULL) {
@@ -500,7 +500,7 @@
 
     if (which < mAssetPaths.size()) {
         ALOGV("Looking for non-asset '%s' in '%s'\n", fileName,
-                mAssetPaths.itemAt(which).path.string());
+                mAssetPaths.itemAt(which).path.c_str());
         Asset* pAsset = openNonAssetInPathLocked(
             fileName, mode, mAssetPaths.editItemAt(which));
         if (pAsset != NULL) {
@@ -546,10 +546,10 @@
     ResTable* sharedRes = NULL;
     bool shared = true;
     bool onlyEmptyResources = true;
-    ATRACE_NAME(ap.path.string());
+    ATRACE_NAME(ap.path.c_str());
     Asset* idmap = openIdmapLocked(ap);
     size_t nextEntryIdx = mResources->getTableCount();
-    ALOGV("Looking for resource asset in '%s'\n", ap.path.string());
+    ALOGV("Looking for resource asset in '%s'\n", ap.path.c_str());
     if (ap.type != kFileTypeDirectory && ap.rawFd < 0) {
         if (nextEntryIdx == 0) {
             // The first item is typically the framework resources,
@@ -565,7 +565,7 @@
             ass = const_cast<AssetManager*>(this)->
                 mZipSet.getZipResourceTableAsset(ap.path);
             if (ass == NULL) {
-                ALOGV("loading resource table %s\n", ap.path.string());
+                ALOGV("loading resource table %s\n", ap.path.c_str());
                 ass = const_cast<AssetManager*>(this)->
                     openNonAssetInPathLocked("resources.arsc",
                                              Asset::ACCESS_BUFFER,
@@ -580,7 +580,7 @@
                 // If this is the first resource table in the asset
                 // manager, then we are going to cache it so that we
                 // can quickly copy it out for others.
-                ALOGV("Creating shared resources for %s", ap.path.string());
+                ALOGV("Creating shared resources for %s", ap.path.c_str());
                 sharedRes = new ResTable();
                 sharedRes->add(ass, idmap, nextEntryIdx + 1, false);
 #ifdef __ANDROID__
@@ -589,14 +589,14 @@
                 String8 overlaysListPath(data);
                 overlaysListPath.appendPath(kResourceCache);
                 overlaysListPath.appendPath("overlays.list");
-                addSystemOverlays(overlaysListPath.string(), ap.path, sharedRes, nextEntryIdx);
+                addSystemOverlays(overlaysListPath.c_str(), ap.path, sharedRes, nextEntryIdx);
 #endif
                 sharedRes = const_cast<AssetManager*>(this)->
                     mZipSet.setZipResourceTable(ap.path, sharedRes);
             }
         }
     } else {
-        ALOGV("loading resource table %s\n", ap.path.string());
+        ALOGV("loading resource table %s\n", ap.path.c_str());
         ass = const_cast<AssetManager*>(this)->
             openNonAssetInPathLocked("resources.arsc",
                                      Asset::ACCESS_BUFFER,
@@ -607,10 +607,10 @@
     if ((ass != NULL || sharedRes != NULL) && ass != kExcludedAsset) {
         ALOGV("Installing resource asset %p in to table %p\n", ass, mResources);
         if (sharedRes != NULL) {
-            ALOGV("Copying existing resources for %s", ap.path.string());
+            ALOGV("Copying existing resources for %s", ap.path.c_str());
             mResources->add(sharedRes, ap.isSystemAsset);
         } else {
-            ALOGV("Parsing resources for %s", ap.path.string());
+            ALOGV("Parsing resources for %s", ap.path.c_str());
             mResources->add(ass, idmap, nextEntryIdx + 1, !shared, appAsLib, ap.isSystemAsset);
         }
         onlyEmptyResources = false;
@@ -692,9 +692,9 @@
         ass = const_cast<AssetManager*>(this)->
             openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
         if (ass) {
-            ALOGV("loading idmap %s\n", ap.idmap.string());
+            ALOGV("loading idmap %s\n", ap.idmap.c_str());
         } else {
-            ALOGW("failed to load idmap %s\n", ap.idmap.string());
+            ALOGW("failed to load idmap %s\n", ap.idmap.c_str());
         }
     }
     return ass;
@@ -812,7 +812,7 @@
         ZipFileRO* pZip = getZipFileLocked(ap);
         if (pZip != NULL) {
             ALOGV("GOT zip, checking NA '%s'", (const char*) path);
-            ZipEntryRO entry = pZip->findEntryByName(path.string());
+            ZipEntryRO entry = pZip->findEntryByName(path.c_str());
             if (entry != NULL) {
                 ALOGV("FOUND NA in Zip file for %s", (const char*) path);
                 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
@@ -823,7 +823,7 @@
         if (pAsset != NULL) {
             /* create a "source" name, for debug/display */
             pAsset->setAssetSource(
-                    createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
+                    createZipSourceNameLocked(ZipSet::getPathName(ap.path.c_str()), String8(""),
                                                 String8(fileName)));
         }
     }
@@ -870,7 +870,7 @@
     }
 
     if (ap.rawFd < 0) {
-        ALOGV("getZipFileLocked: Creating new zip from path %s", ap.path.string());
+        ALOGV("getZipFileLocked: Creating new zip from path %s", ap.path.c_str());
         ap.zip = mZipSet.getSharedZip(ap.path);
     } else {
         ALOGV("getZipFileLocked: Creating new zip from fd %d", ap.rawFd);
@@ -897,12 +897,12 @@
 {
     Asset* pAsset = NULL;
 
-    if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
+    if (strcasecmp(pathName.getPathExtension().c_str(), ".gz") == 0) {
         //printf("TRYING '%s'\n", (const char*) pathName);
-        pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
+        pAsset = Asset::createFromCompressedFile(pathName.c_str(), mode);
     } else {
         //printf("TRYING '%s'\n", (const char*) pathName);
-        pAsset = Asset::createFromFile(pathName.string(), mode);
+        pAsset = Asset::createFromFile(pathName.c_str(), mode);
     }
 
     return pAsset;
@@ -940,12 +940,12 @@
 
     if (method == ZipFileRO::kCompressStored) {
         pAsset = Asset::createFromUncompressedMap(std::move(*dataMap), mode);
-        ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
+        ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.c_str(),
                 dataMap->file_name(), mode, pAsset.get());
     } else {
         pAsset = Asset::createFromCompressedMap(std::move(*dataMap),
             static_cast<size_t>(uncompressedLen), mode);
-        ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
+        ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.c_str(),
                 dataMap->file_name(), mode, pAsset.get());
     }
     if (pAsset == NULL) {
@@ -993,10 +993,10 @@
         i--;
         const asset_path& ap = mAssetPaths.itemAt(i);
         if (ap.type == kFileTypeRegular) {
-            ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
+            ALOGV("Adding directory %s from zip %s", dirName, ap.path.c_str());
             scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
         } else {
-            ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
+            ALOGV("Adding directory %s from dir %s", dirName, ap.path.c_str());
             scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
         }
     }
@@ -1042,10 +1042,10 @@
     if (which < mAssetPaths.size()) {
         const asset_path& ap = mAssetPaths.itemAt(which);
         if (ap.type == kFileTypeRegular) {
-            ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
+            ALOGV("Adding directory %s from zip %s", dirName, ap.path.c_str());
             scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
         } else {
-            ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
+            ALOGV("Adding directory %s from dir %s", dirName, ap.path.c_str());
             scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
         }
     }
@@ -1075,7 +1075,7 @@
 {
     assert(pMergedInfo != NULL);
 
-    //printf("scanAndMergeDir: %s %s %s\n", ap.path.string(), rootDir, dirName);
+    //printf("scanAndMergeDir: %s %s %s\n", ap.path.c_str(), rootDir, dirName);
 
     String8 path = createPathNameLocked(ap, rootDir);
     if (dirName[0] != '\0')
@@ -1100,7 +1100,7 @@
         const char* name;
         int nameLen;
 
-        name = pContents->itemAt(i).getFileName().string();
+        name = pContents->itemAt(i).getFileName().c_str();
         nameLen = strlen(name);
         if (nameLen > exclExtLen &&
             strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
@@ -1111,8 +1111,8 @@
             matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
             if (matchIdx > 0) {
                 ALOGV("Excluding '%s' [%s]\n",
-                    pMergedInfo->itemAt(matchIdx).getFileName().string(),
-                    pMergedInfo->itemAt(matchIdx).getSourceName().string());
+                    pMergedInfo->itemAt(matchIdx).getFileName().c_str(),
+                    pMergedInfo->itemAt(matchIdx).getSourceName().c_str());
                 pMergedInfo->removeAt(matchIdx);
             } else {
                 //printf("+++ no match on '%s'\n", (const char*) match);
@@ -1150,9 +1150,9 @@
     struct dirent* entry;
     FileType fileType;
 
-    ALOGV("Scanning dir '%s'\n", path.string());
+    ALOGV("Scanning dir '%s'\n", path.c_str());
 
-    dir = opendir(path.string());
+    dir = opendir(path.c_str());
     if (dir == NULL)
         return NULL;
 
@@ -1176,7 +1176,7 @@
             fileType = kFileTypeUnknown;
 #else
         // stat the file
-        fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
+        fileType = ::getFileType(path.appendPathCopy(entry->d_name).c_str());
 #endif
 
         if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
@@ -1184,7 +1184,7 @@
 
         AssetDir::FileInfo info;
         info.set(String8(entry->d_name), fileType);
-        if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
+        if (strcasecmp(info.getFileName().getPathExtension().c_str(), ".gz") == 0)
             info.setFileName(info.getFileName().getBasePath());
         info.setSourceName(path.appendPathCopy(info.getFileName()));
         pContents->add(info);
@@ -1212,11 +1212,11 @@
 
     pZip = mZipSet.getZip(ap.path);
     if (pZip == NULL) {
-        ALOGW("Failure opening zip %s\n", ap.path.string());
+        ALOGW("Failure opening zip %s\n", ap.path.c_str());
         return false;
     }
 
-    zipName = ZipSet::getPathName(ap.path.string());
+    zipName = ZipSet::getPathName(ap.path.c_str());
 
     /* convert "sounds" to "rootDir/sounds" */
     if (rootDir != NULL) dirName = rootDir;
@@ -1240,7 +1240,7 @@
      */
     int dirNameLen = dirName.length();
     void *iterationCookie;
-    if (!pZip->startIteration(&iterationCookie, dirName.string(), NULL)) {
+    if (!pZip->startIteration(&iterationCookie, dirName.c_str(), NULL)) {
         ALOGW("ZipFileRO::startIteration returned false");
         return false;
     }
@@ -1254,7 +1254,7 @@
             ALOGE("ARGH: name too long?\n");
             continue;
         }
-        //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
+        //printf("Comparing %s in %s?\n", nameBuf, dirName.c_str());
         if (dirNameLen == 0 || nameBuf[dirNameLen] == '/')
         {
             const char* cp;
@@ -1275,7 +1275,7 @@
                     createZipSourceNameLocked(zipName, dirName, info.getFileName()));
 
                 contents.add(info);
-                //printf("FOUND: file '%s'\n", info.getFileName().string());
+                //printf("FOUND: file '%s'\n", info.getFileName().c_str());
             } else {
                 /* this is a subdir; add it if we don't already have it*/
                 String8 subdirName(cp, nextSlash - cp);
@@ -1291,7 +1291,7 @@
                     dirs.add(subdirName);
                 }
 
-                //printf("FOUND: dir '%s'\n", subdirName.string());
+                //printf("FOUND: dir '%s'\n", subdirName.c_str());
             }
         }
     }
@@ -1427,10 +1427,10 @@
     if (kIsDebug) {
         ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
     }
-    ALOGV("+++ opening zip '%s'\n", mPath.string());
-    mZipFile = ZipFileRO::open(mPath.string());
+    ALOGV("+++ opening zip '%s'\n", mPath.c_str());
+    mZipFile = ZipFileRO::open(mPath.c_str());
     if (mZipFile == NULL) {
-        ALOGD("failed to open Zip archive '%s'\n", mPath.string());
+        ALOGD("failed to open Zip archive '%s'\n", mPath.c_str());
     }
 }
 
@@ -1441,11 +1441,11 @@
     if (kIsDebug) {
         ALOGI("Creating SharedZip %p fd=%d %s\n", this, fd, (const char*)mPath);
     }
-    ALOGV("+++ opening zip fd=%d '%s'\n", fd, mPath.string());
-    mZipFile = ZipFileRO::openFd(fd, mPath.string());
+    ALOGV("+++ opening zip fd=%d '%s'\n", fd, mPath.c_str());
+    mZipFile = ZipFileRO::openFd(fd, mPath.c_str());
     if (mZipFile == NULL) {
         ::close(fd);
-        ALOGD("failed to open Zip archive fd=%d '%s'\n", fd, mPath.string());
+        ALOGD("failed to open Zip archive fd=%d '%s'\n", fd, mPath.c_str());
     }
 }
 
@@ -1520,7 +1520,7 @@
 
 bool AssetManager::SharedZip::isUpToDate()
 {
-    time_t modWhen = getFileModDate(mPath.string());
+    time_t modWhen = getFileModDate(mPath.c_str());
     return mModWhen == modWhen;
 }
 
@@ -1551,7 +1551,7 @@
     }
     if (mZipFile != NULL) {
         delete mZipFile;
-        ALOGV("Closed '%s'\n", mPath.string());
+        ALOGV("Closed '%s'\n", mPath.c_str());
     }
 }
 
diff --git a/libs/androidfw/BackupData.cpp b/libs/androidfw/BackupData.cpp
index 76a430e..fec0e77 100644
--- a/libs/androidfw/BackupData.cpp
+++ b/libs/androidfw/BackupData.cpp
@@ -106,8 +106,8 @@
         k = key;
     }
     if (kIsDebug) {
-        ALOGD("Writing header: prefix='%s' key='%s' dataSize=%zu", m_keyPrefix.string(),
-                key.string(), dataSize);
+        ALOGD("Writing header: prefix='%s' key='%s' dataSize=%zu", m_keyPrefix.c_str(),
+                key.c_str(), dataSize);
     }
 
     entity_header_v1 header;
@@ -128,7 +128,7 @@
     m_pos += amt;
 
     if (kIsDebug) ALOGI("writing entity header key, %zd bytes", keyLen+1);
-    amt = write(m_fd, k.string(), keyLen+1);
+    amt = write(m_fd, k.c_str(), keyLen+1);
     if (amt != keyLen+1) {
         m_status = errno;
         return m_status;
diff --git a/libs/androidfw/BackupHelpers.cpp b/libs/androidfw/BackupHelpers.cpp
index e80e948..3582609 100644
--- a/libs/androidfw/BackupHelpers.cpp
+++ b/libs/androidfw/BackupHelpers.cpp
@@ -179,7 +179,7 @@
             }
 
             // filename is not NULL terminated, but it is padded
-            amt = write(fd, name.string(), nameLen);
+            amt = write(fd, name.c_str(), nameLen);
             if (amt != nameLen) {
                 ALOGW("write_snapshot_file error writing filename %s", strerror(errno));
                 return 1;
@@ -203,7 +203,7 @@
 static int
 write_delete_file(BackupDataWriter* dataStream, const String8& key)
 {
-    LOGP("write_delete_file %s\n", key.string());
+    LOGP("write_delete_file %s\n", key.c_str());
     return dataStream->WriteEntityHeader(key, -1);
 }
 
@@ -211,7 +211,7 @@
 write_update_file(BackupDataWriter* dataStream, int fd, int mode, const String8& key,
         char const* realFilename)
 {
-    LOGP("write_update_file %s (%s) : mode 0%o\n", realFilename, key.string(), mode);
+    LOGP("write_update_file %s (%s) : mode 0%o\n", realFilename, key.c_str(), mode);
 
     const int bufsize = 4*1024;
     int err;
@@ -365,7 +365,7 @@
             r.s.size = st.st_size;
 
             if (newSnapshot.indexOfKey(key) >= 0) {
-                LOGP("back_up_files key already in use '%s'", key.string());
+                LOGP("back_up_files key already in use '%s'", key.c_str());
                 return -1;
             }
 
@@ -390,30 +390,30 @@
         int cmp = p.compare(q);
         if (cmp < 0) {
             // file present in oldSnapshot, but not present in newSnapshot
-            LOGP("file removed: %s", p.string());
+            LOGP("file removed: %s", p.c_str());
             write_delete_file(dataStream, p);
             n++;
         } else if (cmp > 0) {
             // file added
-            LOGP("file added: %s crc=0x%08x", g.file.string(), g.s.crc32);
-            write_update_file(dataStream, q, g.file.string());
+            LOGP("file added: %s crc=0x%08x", g.file.c_str(), g.s.crc32);
+            write_update_file(dataStream, q, g.file.c_str());
             m++;
         } else {
             // same file exists in both old and new; check whether to update
             const FileState& f = oldSnapshot.valueAt(n);
 
-            LOGP("%s", q.string());
+            LOGP("%s", q.c_str());
             LOGP("  old: modTime=%d,%d mode=%04o size=%-3d crc32=0x%08x",
                     f.modTime_sec, f.modTime_nsec, f.mode, f.size, f.crc32);
             LOGP("  new: modTime=%d,%d mode=%04o size=%-3d crc32=0x%08x",
                     g.s.modTime_sec, g.s.modTime_nsec, g.s.mode, g.s.size, g.s.crc32);
             if (f.modTime_sec != g.s.modTime_sec || f.modTime_nsec != g.s.modTime_nsec
                     || f.mode != g.s.mode || f.size != g.s.size || f.crc32 != g.s.crc32) {
-                int fd = open(g.file.string(), O_RDONLY);
+                int fd = open(g.file.c_str(), O_RDONLY);
                 if (fd < 0) {
-                    ALOGE("Unable to read file for backup: %s", g.file.string());
+                    ALOGE("Unable to read file for backup: %s", g.file.c_str());
                 } else {
-                    write_update_file(dataStream, fd, g.s.mode, p, g.file.string());
+                    write_update_file(dataStream, fd, g.s.mode, p, g.file.c_str());
                     close(fd);
                 }
             }
@@ -432,7 +432,7 @@
     while (m<M) {
         const String8& q = newSnapshot.keyAt(m);
         FileRec& g = newSnapshot.editValueAt(m);
-        write_update_file(dataStream, q, g.file.string());
+        write_update_file(dataStream, q, g.file.c_str());
         m++;
     }
 
@@ -483,7 +483,7 @@
         BackupDataWriter* writer)
 {
     // In the output stream everything is stored relative to the root
-    const char* relstart = filepath.string() + rootpath.length();
+    const char* relstart = filepath.c_str() + rootpath.length();
     if (*relstart == '/') relstart++;     // won't be true when path == rootpath
     String8 relpath(relstart);
 
@@ -514,9 +514,9 @@
 
     int err = 0;
     struct stat64 s;
-    if (lstat64(filepath.string(), &s) != 0) {
+    if (lstat64(filepath.c_str(), &s) != 0) {
         err = errno;
-        ALOGE("Error %d (%s) from lstat64(%s)", err, strerror(err), filepath.string());
+        ALOGE("Error %d (%s) from lstat64(%s)", err, strerror(err), filepath.c_str());
         return err;
     }
 
@@ -541,10 +541,10 @@
 
     // !!! TODO: use mmap when possible to avoid churning the buffer cache
     // !!! TODO: this will break with symlinks; need to use readlink(2)
-    int fd = open(filepath.string(), O_RDONLY);
+    int fd = open(filepath.c_str(), O_RDONLY);
     if (fd < 0) {
         err = errno;
-        ALOGE("Error %d (%s) from open(%s)", err, strerror(err), filepath.string());
+        ALOGE("Error %d (%s) from open(%s)", err, strerror(err), filepath.c_str());
         return err;
     }
 
@@ -592,7 +592,7 @@
     } else if (S_ISREG(s.st_mode)) {
         type = '0';     // tar magic: '0' == normal file
     } else {
-        ALOGW("Error: unknown file mode 0%o [%s]", s.st_mode, filepath.string());
+        ALOGW("Error: unknown file mode 0%o [%s]", s.st_mode, filepath.c_str());
         goto cleanup;
     }
     buf[156] = type;
@@ -620,16 +620,16 @@
         //    [ 345 : 155 ] filename path prefix
         // We only use the prefix area if fullname won't fit in the path
         if (fullname.length() > 100) {
-            strncpy(buf, relpath.string(), 100);
-            strncpy(buf + 345, prefix.string(), 155);
+            strncpy(buf, relpath.c_str(), 100);
+            strncpy(buf + 345, prefix.c_str(), 155);
         } else {
-            strncpy(buf, fullname.string(), 100);
+            strncpy(buf, fullname.c_str(), 100);
         }
     }
 
     // [ 329 : 8 ] and [ 337 : 8 ] devmajor/devminor, not used
 
-    ALOGI("   Name: %s", fullname.string());
+    ALOGI("   Name: %s", fullname.c_str());
 
     // If we're using a pax extended header, build & write that here; lengths are
     // already preflighted
@@ -647,7 +647,7 @@
 
         // fullname was generated above with the ustar paths
         paxLen += write_pax_header_entry(paxData + paxLen, PAXDATA_SIZE - paxLen,
-                "path", fullname.string());
+                "path", fullname.c_str());
 
         // Now we know how big the pax data is
 
@@ -656,9 +656,9 @@
 
         String8 leaf = fullname.getPathLeaf();
         memset(paxHeader, 0, 100);                  // rewrite the name area
-        snprintf(paxHeader, 100, "PaxHeader/%s", leaf.string());
+        snprintf(paxHeader, 100, "PaxHeader/%s", leaf.c_str());
         memset(paxHeader + 345, 0, 155);            // rewrite the prefix area
-        strncpy(paxHeader + 345, prefix.string(), 155);
+        strncpy(paxHeader + 345, prefix.c_str(), 155);
 
         paxHeader[156] = 'x';                       // mark it as a pax extended header
 
@@ -691,12 +691,12 @@
             ssize_t nRead = read(fd, buf, toRead);
             if (nRead < 0) {
                 err = errno;
-                ALOGE("Unable to read file [%s], err=%d (%s)", filepath.string(),
+                ALOGE("Unable to read file [%s], err=%d (%s)", filepath.c_str(),
                         err, strerror(err));
                 break;
             } else if (nRead == 0) {
                 ALOGE("EOF but expect %lld more bytes in [%s]", (long long) toWrite,
-                        filepath.string());
+                        filepath.c_str());
                 err = EIO;
                 break;
             }
@@ -762,7 +762,7 @@
     file_metadata_v1 metadata;
     amt = in->ReadEntityData(&metadata, sizeof(metadata));
     if (amt != sizeof(metadata)) {
-        ALOGW("Could not read metadata for %s -- %ld / %s", filename.string(),
+        ALOGW("Could not read metadata for %s -- %ld / %s", filename.c_str(),
                 (long)amt, strerror(errno));
         return EIO;
     }
@@ -779,9 +779,9 @@
 
     // Write the file and compute the crc
     crc = crc32(0L, Z_NULL, 0);
-    fd = open(filename.string(), O_CREAT|O_RDWR|O_TRUNC, mode);
+    fd = open(filename.c_str(), O_CREAT|O_RDWR|O_TRUNC, mode);
     if (fd == -1) {
-        ALOGW("Could not open file %s -- %s", filename.string(), strerror(errno));
+        ALOGW("Could not open file %s -- %s", filename.c_str(), strerror(errno));
         return errno;
     }
 
@@ -789,7 +789,7 @@
         err = write(fd, buf, amt);
         if (err != amt) {
             close(fd);
-            ALOGW("Error '%s' writing '%s'", strerror(errno), filename.string());
+            ALOGW("Error '%s' writing '%s'", strerror(errno), filename.c_str());
             return errno;
         }
         crc = crc32(crc, (Bytef*)buf, amt);
@@ -798,9 +798,9 @@
     close(fd);
 
     // Record for the snapshot
-    err = stat(filename.string(), &st);
+    err = stat(filename.c_str(), &st);
     if (err != 0) {
-        ALOGW("Error stating file that we just created %s", filename.string());
+        ALOGW("Error stating file that we just created %s", filename.c_str());
         return errno;
     }
 
@@ -1104,9 +1104,9 @@
             fprintf(stderr, "state %zu expected={%d/%d, %04o, 0x%08x, 0x%08x, %3zu} '%s'\n"
                             "          actual={%d/%d, %04o, 0x%08x, 0x%08x, %3d} '%s'\n", i,
                     states[i].modTime_sec, states[i].modTime_nsec, states[i].mode, states[i].size,
-                    states[i].crc32, name.length(), filenames[i].string(),
+                    states[i].crc32, name.length(), filenames[i].c_str(),
                     state.modTime_sec, state.modTime_nsec, state.mode, state.size, state.crc32,
-                    state.nameLen, name.string());
+                    state.nameLen, name.c_str());
             matched = false;
         }
     }
@@ -1152,9 +1152,9 @@
         return err;
     }
 
-    err = writer.WriteEntityData(text.string(), text.length()+1);
+    err = writer.WriteEntityData(text.c_str(), text.length()+1);
     if (err != 0) {
-        fprintf(stderr, "write failed for data '%s'\n", text.string());
+        fprintf(stderr, "write failed for data '%s'\n", text.c_str());
         return errno;
     }
 
@@ -1230,7 +1230,7 @@
         goto finished;
     }
     if (string != str) {
-        fprintf(stderr, "ReadEntityHeader expected key '%s' got '%s'\n", str, string.string());
+        fprintf(stderr, "ReadEntityHeader expected key '%s' got '%s'\n", str, string.c_str());
         err = EINVAL;
         goto finished;
     }
diff --git a/libs/androidfw/ConfigDescription.cpp b/libs/androidfw/ConfigDescription.cpp
index cf2fd6f..e08030c 100644
--- a/libs/androidfw/ConfigDescription.cpp
+++ b/libs/androidfw/ConfigDescription.cpp
@@ -905,7 +905,7 @@
 
 std::string ConfigDescription::to_string() const {
   const String8 str = toString();
-  return std::string(str.string(), str.size());
+  return std::string(str.c_str(), str.size());
 }
 
 bool ConfigDescription::Dominates(const ConfigDescription& o) const {
diff --git a/libs/androidfw/CursorWindow.cpp b/libs/androidfw/CursorWindow.cpp
index 2a6dc7b..5e645cc 100644
--- a/libs/androidfw/CursorWindow.cpp
+++ b/libs/androidfw/CursorWindow.cpp
@@ -84,7 +84,7 @@
     String8 ashmemName("CursorWindow: ");
     ashmemName.append(mName);
 
-    ashmemFd = ashmem_create_region(ashmemName.string(), mInflatedSize);
+    ashmemFd = ashmem_create_region(ashmemName.c_str(), mInflatedSize);
     if (ashmemFd < 0) {
         PLOG(ERROR) << "Failed ashmem_create_region";
         goto fail_silent;
diff --git a/libs/androidfw/ObbFile.cpp b/libs/androidfw/ObbFile.cpp
index 95332a3..c6a9632 100644
--- a/libs/androidfw/ObbFile.cpp
+++ b/libs/androidfw/ObbFile.cpp
@@ -217,7 +217,7 @@
     free(scanBuf);
 
 #ifdef DEBUG
-    ALOGI("Obb scan succeeded: packageName=%s, version=%d\n", mPackageName.string(), mVersion);
+    ALOGI("Obb scan succeeded: packageName=%s, version=%d\n", mPackageName.c_str(), mVersion);
 #endif
 
     return true;
@@ -288,7 +288,7 @@
         return false;
     }
 
-    if (write(fd, mPackageName.string(), packageNameLen) != (ssize_t)packageNameLen) {
+    if (write(fd, mPackageName.c_str(), packageNameLen) != (ssize_t)packageNameLen) {
         ALOGW("couldn't write package name: %s\n", strerror(errno));
         return false;
     }
diff --git a/libs/androidfw/ResourceTypes.cpp b/libs/androidfw/ResourceTypes.cpp
index 5a63612..112058f 100644
--- a/libs/androidfw/ResourceTypes.cpp
+++ b/libs/androidfw/ResourceTypes.cpp
@@ -1042,7 +1042,7 @@
 
     if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0) {
         if (kDebugStringPoolNoisy) {
-            ALOGI("indexOfString UTF-8: %s", String8(str, strLen).string());
+            ALOGI("indexOfString UTF-8: %s", String8(str, strLen).c_str());
         }
 
         // The string pool contains UTF 8 strings; we don't want to cause
@@ -1103,7 +1103,7 @@
                         ALOGI("Looking at %s, i=%d\n", s->data(), i);
                     }
                     if (str8Len == s->size()
-                            && memcmp(s->data(), str8.string(), str8Len) == 0) {
+                            && memcmp(s->data(), str8.c_str(), str8Len) == 0) {
                         if (kDebugStringPoolNoisy) {
                             ALOGI("MATCH!");
                         }
@@ -1115,7 +1115,7 @@
 
     } else {
         if (kDebugStringPoolNoisy) {
-            ALOGI("indexOfString UTF-16: %s", String8(str, strLen).string());
+            ALOGI("indexOfString UTF-16: %s", String8(str, strLen).c_str());
         }
 
         if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
@@ -1133,7 +1133,7 @@
                 int c = s.has_value() ? strzcmp16(s->data(), s->size(), str, strLen) : -1;
                 if (kDebugStringPoolNoisy) {
                     ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
-                          String8(s->data(), s->size()).string(), c, (int)l, (int)mid, (int)h);
+                          String8(s->data(), s->size()).c_str(), c, (int)l, (int)mid, (int)h);
                 }
                 if (c == 0) {
                     if (kDebugStringPoolNoisy) {
@@ -1157,7 +1157,7 @@
                     return base::unexpected(s.error());
                 }
                 if (kDebugStringPoolNoisy) {
-                    ALOGI("Looking at %s, i=%d\n", String8(s->data(), s->size()).string(), i);
+                    ALOGI("Looking at %s, i=%d\n", String8(s->data(), s->size()).c_str(), i);
                 }
                 if (s.has_value() && strLen == s->size() &&
                         strzcmp16(s->data(), s->size(), str, strLen) == 0) {
@@ -1525,8 +1525,8 @@
 {
     String16 nsStr(ns != NULL ? ns : "");
     String16 attrStr(attr);
-    return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
-                            attrStr.string(), attrStr.size());
+    return indexOfAttribute(ns ? nsStr.c_str() : NULL, ns ? nsStr.size() : 0,
+                            attrStr.c_str(), attrStr.size());
 }
 
 ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
@@ -1544,8 +1544,8 @@
             }
             attr8 = String8(attr, attrLen);
             if (kDebugStringPoolNoisy) {
-                ALOGI("indexOfAttribute UTF8 %s (%zu) / %s (%zu)", ns8.string(), nsLen,
-                        attr8.string(), attrLen);
+                ALOGI("indexOfAttribute UTF8 %s (%zu) / %s (%zu)", ns8.c_str(), nsLen,
+                        attr8.c_str(), attrLen);
             }
             for (size_t i=0; i<N; i++) {
                 size_t curNsLen = 0, curAttrLen = 0;
@@ -1555,7 +1555,7 @@
                     ALOGI("  curNs=%s (%zu), curAttr=%s (%zu)", curNs, curNsLen, curAttr, curAttrLen);
                 }
                 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
-                        && memcmp(attr8.string(), curAttr, attrLen) == 0) {
+                        && memcmp(attr8.c_str(), curAttr, attrLen) == 0) {
                     if (ns == NULL) {
                         if (curNs == NULL) {
                             if (kDebugStringPoolNoisy) {
@@ -1565,8 +1565,8 @@
                         }
                     } else if (curNs != NULL) {
                         //printf(" --> ns=%s, curNs=%s\n",
-                        //       String8(ns).string(), String8(curNs).string());
-                        if (memcmp(ns8.string(), curNs, nsLen) == 0) {
+                        //       String8(ns).c_str(), String8(curNs).c_str());
+                        if (memcmp(ns8.c_str(), curNs, nsLen) == 0) {
                             if (kDebugStringPoolNoisy) {
                                 ALOGI("  FOUND!");
                             }
@@ -1578,8 +1578,8 @@
         } else {
             if (kDebugStringPoolNoisy) {
                 ALOGI("indexOfAttribute UTF16 %s (%zu) / %s (%zu)",
-                        String8(ns, nsLen).string(), nsLen,
-                        String8(attr, attrLen).string(), attrLen);
+                        String8(ns, nsLen).c_str(), nsLen,
+                        String8(attr, attrLen).c_str(), attrLen);
             }
             for (size_t i=0; i<N; i++) {
                 size_t curNsLen = 0, curAttrLen = 0;
@@ -1587,8 +1587,8 @@
                 const char16_t* curAttr = getAttributeName(i, &curAttrLen);
                 if (kDebugStringPoolNoisy) {
                     ALOGI("  curNs=%s (%zu), curAttr=%s (%zu)",
-                            String8(curNs, curNsLen).string(), curNsLen,
-                            String8(curAttr, curAttrLen).string(), curAttrLen);
+                            String8(curNs, curNsLen).c_str(), curNsLen,
+                            String8(curAttr, curAttrLen).c_str(), curAttrLen);
                 }
                 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
                         && (memcmp(attr, curAttr, attrLen*sizeof(char16_t)) == 0)) {
@@ -1601,7 +1601,7 @@
                         }
                     } else if (curNs != NULL) {
                         //printf(" --> ns=%s, curNs=%s\n",
-                        //       String8(ns).string(), String8(curNs).string());
+                        //       String8(ns).c_str(), String8(curNs).c_str());
                         if (memcmp(ns, curNs, nsLen*sizeof(char16_t)) == 0) {
                             if (kDebugStringPoolNoisy) {
                                 ALOGI("  FOUND!");
@@ -4475,7 +4475,7 @@
         return false;
     }
 
-    outName->package = grp->name.string();
+    outName->package = grp->name.c_str();
     outName->packageLen = grp->name.size();
     if (allowUtf8) {
         outName->type8 = UnpackOptionalString(entry.typeStr.string8(), &outName->typeLen);
@@ -4575,7 +4575,7 @@
                 outValue->dataType,
                 outValue->dataType == Res_value::TYPE_STRING ?
                     String8(UnpackOptionalString(
-                        entry.package->header->values.stringAt(outValue->data), &len)).string() :
+                        entry.package->header->values.stringAt(outValue->data), &len)).c_str() :
                     "",
                 outValue->data);
     }
@@ -4944,7 +4944,7 @@
     AutoMutex _lock2(mFilteredConfigLock);
 
     if (kDebugTableGetEntry) {
-        ALOGI("Setting parameters: %s\n", params->toString().string());
+        ALOGI("Setting parameters: %s\n", params->toString().c_str());
     }
     mParams = *params;
     for (size_t p = 0; p < mPackageGroups.size(); p++) {
@@ -5055,7 +5055,7 @@
             if (name[1] == 'i' && name[2] == 'n'
                 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
                 && name[6] == '_') {
-                int index = atoi(String8(name + 7, nameLen - 7).string());
+                int index = atoi(String8(name + 7, nameLen - 7).c_str());
                 if (Res_CHECKID(index)) {
                     ALOGW("Array resource index: %d is too large.",
                          index);
@@ -5121,9 +5121,9 @@
 
     if (kDebugTableNoisy) {
         printf("Looking for identifier: type=%s, name=%s, package=%s\n",
-                String8(type, typeLen).string(),
-                String8(name, nameLen).string(),
-                String8(package, packageLen).string());
+                String8(type, typeLen).c_str(),
+                String8(name, nameLen).c_str(),
+                String8(package, packageLen).c_str());
     }
 
     const String16 attr("attr");
@@ -5134,9 +5134,9 @@
         const PackageGroup* group = mPackageGroups[ig];
 
         if (strzcmp16(package, packageLen,
-                      group->name.string(), group->name.size())) {
+                      group->name.c_str(), group->name.size())) {
             if (kDebugTableNoisy) {
-                printf("Skipping package group: %s\n", String8(group->name).string());
+                printf("Skipping package group: %s\n", String8(group->name).c_str());
             }
             continue;
         }
@@ -5161,8 +5161,8 @@
                     }
                     return identifier;
                 }
-            } while (strzcmp16(attr.string(), attr.size(), targetType, targetTypeLen) == 0
-                    && (targetType = attrPrivate.string())
+            } while (strzcmp16(attr.c_str(), attr.size(), targetType, targetTypeLen) == 0
+                    && (targetType = attrPrivate.c_str())
                     && (targetTypeLen = attrPrivate.size())
             );
         }
@@ -5610,7 +5610,7 @@
         }
     }
 
-    //printf("Value for: %s\n", String8(s, len).string());
+    //printf("Value for: %s\n", String8(s, len).c_str());
 
     uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
     uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
@@ -5665,7 +5665,7 @@
         // be to any other type; we just need to count on the client making
         // sure the referenced type is correct.
 
-        //printf("Looking up ref: %s\n", String8(s, len).string());
+        //printf("Looking up ref: %s\n", String8(s, len).c_str());
 
         // It's a reference!
         if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
@@ -5705,8 +5705,8 @@
             }
 
             uint32_t specFlags = 0;
-            uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
-                    type.size(), package.string(), package.size(), &specFlags);
+            uint32_t rid = identifierForName(name.c_str(), name.size(), type.c_str(),
+                    type.size(), package.c_str(), package.size(), &specFlags);
             if (rid != 0) {
                 if (enforcePrivate) {
                     if (accessor == NULL || accessor->getAssetsPackage() != package) {
@@ -5725,8 +5725,8 @@
                         Res_GETTYPE(rid), Res_GETENTRY(rid));
                     if (kDebugTableNoisy) {
                         ALOGI("Incl %s:%s/%s: 0x%08x\n",
-                                String8(package).string(), String8(type).string(),
-                                String8(name).string(), rid);
+                                String8(package).c_str(), String8(type).c_str(),
+                                String8(name).c_str(), rid);
                     }
                 }
 
@@ -5744,8 +5744,8 @@
                 if (rid != 0) {
                     if (kDebugTableNoisy) {
                         ALOGI("Pckg %s:%s/%s: 0x%08x\n",
-                                String8(package).string(), String8(type).string(),
-                                String8(name).string(), rid);
+                                String8(package).c_str(), String8(type).c_str(),
+                                String8(name).c_str(), rid);
                     }
                     uint32_t packageId = Res_GETPACKAGE(rid) + 1;
                     if (packageId == 0x00) {
@@ -5834,7 +5834,7 @@
                 }
             } else {
                 outValue->data = color;
-                //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
+                //printf("Color input=%s, output=0x%x\n", String8(s, len).c_str(), color);
                 return true;
             }
         } else {
@@ -5846,8 +5846,8 @@
                 #if 0
                 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
                         "Resource File", //(const char*)in->getPrintableSource(),
-                        String8(*curTag).string(),
-                        String8(s, len).string());
+                        String8(*curTag).c_str(),
+                        String8(s, len).c_str());
                 #endif
                 return false;
             }
@@ -5861,7 +5861,7 @@
         // be to any other type; we just need to count on the client making
         // sure the referenced type is correct.
 
-        //printf("Looking up attr: %s\n", String8(s, len).string());
+        //printf("Looking up attr: %s\n", String8(s, len).c_str());
 
         static const String16 attr16("attr");
         String16 package, type, name;
@@ -5874,13 +5874,13 @@
         }
 
         //printf("Pkg: %s, Type: %s, Name: %s\n",
-        //       String8(package).string(), String8(type).string(),
-        //       String8(name).string());
+        //       String8(package).c_str(), String8(type).c_str(),
+        //       String8(name).c_str());
         uint32_t specFlags = 0;
         uint32_t rid =
-            identifierForName(name.string(), name.size(),
-                              type.string(), type.size(),
-                              package.string(), package.size(), &specFlags);
+            identifierForName(name.c_str(), name.size(),
+                              type.c_str(), type.size(),
+                              package.c_str(), package.size(), &specFlags);
         if (rid != 0) {
             if (enforcePrivate) {
                 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
@@ -6038,8 +6038,8 @@
                     if (getResourceName(bag->map.name.ident, false, &rname)) {
                         #if 0
                         printf("Matching %s against %s (0x%08x)\n",
-                               String8(s, len).string(),
-                               String8(rname.name, rname.nameLen).string(),
+                               String8(s, len).c_str(),
+                               String8(rname.name, rname.nameLen).c_str(),
                                bag->map.name.ident);
                         #endif
                         if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
@@ -6082,7 +6082,7 @@
                 while (pos < end && *pos != '|') {
                     pos++;
                 }
-                //printf("Looking for: %s\n", String8(start, pos-start).string());
+                //printf("Looking for: %s\n", String8(start, pos-start).c_str());
                 const bag_entry* bagi = bag;
                 ssize_t i;
                 for (i=0; i<cnt; i++, bagi++) {
@@ -6091,8 +6091,8 @@
                         if (getResourceName(bagi->map.name.ident, false, &rname)) {
                             #if 0
                             printf("Matching %s against %s (0x%08x)\n",
-                                   String8(start,pos-start).string(),
-                                   String8(rname.name, rname.nameLen).string(),
+                                   String8(start,pos-start).c_str(),
+                                   String8(rname.name, rname.nameLen).c_str(),
                                    bagi->map.name.ident);
                             #endif
                             if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
@@ -6419,7 +6419,7 @@
 }
 
 static bool compareString8AndCString(const String8& str, const char* cStr) {
-    return strcmp(str.string(), cStr) < 0;
+    return strcmp(str.c_str(), cStr) < 0;
 }
 
 void ResTable::getLocales(Vector<String8>* locales, bool includeSystemLocales,
@@ -6433,7 +6433,7 @@
         const auto endIter = locales->end();
 
         auto iter = std::lower_bound(beginIter, endIter, locale, compareString8AndCString);
-        if (iter == endIter || strcmp(iter->string(), locale) != 0) {
+        if (iter == endIter || strcmp(iter->c_str(), locale) != 0) {
             locales->insertAt(String8(locale), std::distance(beginIter, iter));
         }
     });
@@ -7030,7 +7030,7 @@
                         ResTable_config thisConfig;
                         thisConfig.copyFromDtoH(type->config);
                         ALOGI("Adding config to type %d: %s\n", type->id,
-                                thisConfig.toString().string());
+                                thisConfig.toString().c_str());
                     }
                 }
             } else {
@@ -7107,7 +7107,7 @@
         char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)];
         strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t));
         if (kDebugLibNoisy) {
-            ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(),
+            ALOGV("Found lib entry %s with id %d\n", String8(tmpName).c_str(),
                     dtohl(entry->packageId));
         }
         if (packageId >= 256) {
@@ -7386,7 +7386,7 @@
                     current_res.nameLen,
                     current_res.type,
                     current_res.typeLen,
-                    targetPackageName.string(),
+                    targetPackageName.c_str(),
                     targetPackageName.size(),
                     &typeSpecFlags);
 
@@ -7493,7 +7493,7 @@
 }
 
 
-#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
+#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).c_str())
 
 #define CHAR16_ARRAY_EQ(constant, var, len) \
         (((len) == (sizeof(constant)/sizeof((constant)[0]))) && (0 == memcmp((var), (constant), (len))))
@@ -7588,13 +7588,13 @@
         const char* str8 = UnpackOptionalString(pkg->header->values.string8At(
                 value.data), &len);
         if (str8 != NULL) {
-            printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
+            printf("(string8) \"%s\"\n", normalizeForOutput(str8).c_str());
         } else {
             const char16_t* str16 = UnpackOptionalString(pkg->header->values.stringAt(
                     value.data), &len);
             if (str16 != NULL) {
                 printf("(string16) \"%s\"\n",
-                    normalizeForOutput(String8(str16, len).string()).string());
+                    normalizeForOutput(String8(str16, len).c_str()).c_str());
             } else {
                 printf("(string) null\n");
             }
@@ -7635,7 +7635,7 @@
         const PackageGroup* pg = mPackageGroups[pgIndex];
         printf("Package Group %d id=0x%02x packageCount=%d name=%s\n",
                 (int)pgIndex, pg->id, (int)pg->packages.size(),
-                String8(pg->name).string());
+                String8(pg->name).c_str());
 
         const KeyedVector<String16, uint8_t>& refEntries = pg->dynamicRefTable.entries();
         const size_t refEntryCount = refEntries.size();
@@ -7644,7 +7644,7 @@
             for (size_t refIndex = 0; refIndex < refEntryCount; refIndex++) {
                 printf("    0x%02x -> %s\n",
                         refEntries.valueAt(refIndex),
-                        String8(refEntries.keyAt(refIndex)).string());
+                        String8(refEntries.keyAt(refIndex)).c_str());
             }
             printf("\n");
         }
@@ -7670,7 +7670,7 @@
                 strcpy16_dtoh(tmpName, pkg->package->name,
                               sizeof(pkg->package->name)/sizeof(pkg->package->name[0]));
                 printf("  Package %d id=0x%02x name=%s\n", (int)pkgIndex,
-                        pkg->package->id, String8(tmpName).string());
+                        pkg->package->id, String8(tmpName).c_str());
             }
 
             for (size_t typeIndex = 0; typeIndex < pg->types.size(); typeIndex++) {
@@ -7712,7 +7712,7 @@
                             printf("      spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
                                 resID,
                                 CHAR16_TO_CSTR(resName.package, resName.packageLen),
-                                type8.string(), name8.string(),
+                                type8.c_str(), name8.c_str(),
                                 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
                         } else {
                             printf("      INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
@@ -7733,7 +7733,7 @@
 
                     String8 configStr = thisConfig.toString();
                     printf("      config %s", configStr.size() > 0
-                            ? configStr.string() : "(default)");
+                            ? configStr.c_str() : "(default)");
                     if (type->flags != 0u) {
                         printf(" flags=0x%02x", type->flags);
                         if (type->flags & ResTable_type::FLAG_SPARSE) {
@@ -7807,7 +7807,7 @@
                             }
                             printf("        resource 0x%08x %s:%s/%s: ", resID,
                                     CHAR16_TO_CSTR(resName.package, resName.packageLen),
-                                    type8.string(), name8.string());
+                                    type8.c_str(), name8.c_str());
                         } else {
                             printf("        INVALID RESOURCE 0x%08x: ", resID);
                         }
diff --git a/libs/androidfw/include/androidfw/Asset.h b/libs/androidfw/include/androidfw/Asset.h
index 19febcd..f3776b5 100644
--- a/libs/androidfw/include/androidfw/Asset.h
+++ b/libs/androidfw/include/androidfw/Asset.h
@@ -135,7 +135,7 @@
      * This is NOT intended to be used for anything except debug output.
      * DO NOT try to parse this or use it to open a file.
      */
-    const char* getAssetSource(void) const { return mAssetSource.string(); }
+    const char* getAssetSource(void) const { return mAssetSource.c_str(); }
 
     /*
      * Create the asset from a file descriptor.
diff --git a/libs/androidfw/include/androidfw/ConfigDescription.h b/libs/androidfw/include/androidfw/ConfigDescription.h
index 7fbd7c0..83a80ce 100644
--- a/libs/androidfw/include/androidfw/ConfigDescription.h
+++ b/libs/androidfw/include/androidfw/ConfigDescription.h
@@ -213,7 +213,7 @@
 
 inline ::std::ostream& operator<<(::std::ostream& out,
                                   const ConfigDescription& o) {
-  return out << o.toString().string();
+  return out << o.toString().c_str();
 }
 
 }  // namespace android
diff --git a/libs/androidfw/tests/BackupData_test.cpp b/libs/androidfw/tests/BackupData_test.cpp
index e25b616..7d3a341 100644
--- a/libs/androidfw/tests/BackupData_test.cpp
+++ b/libs/androidfw/tests/BackupData_test.cpp
@@ -56,10 +56,10 @@
         mFilename.append(m_external_storage);
         mFilename.append(TEST_FILENAME);
 
-        ::unlink(mFilename.string());
-        int fd = ::open(mFilename.string(), O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
+        ::unlink(mFilename.c_str());
+        int fd = ::open(mFilename.c_str(), O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
         if (fd < 0) {
-            FAIL() << "Couldn't create " << mFilename.string() << " for writing";
+            FAIL() << "Couldn't create " << mFilename.c_str() << " for writing";
         }
         mKey1 = String8(KEY1);
         mKey2 = String8(KEY2);
@@ -72,7 +72,7 @@
 };
 
 TEST_F(BackupDataTest, WriteAndReadSingle) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
 
   EXPECT_EQ(NO_ERROR, writer->WriteEntityHeader(mKey1, sizeof(DATA1)))
@@ -81,7 +81,7 @@
           << "WriteEntityData returned an error";
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
   EXPECT_EQ(NO_ERROR, reader->Status())
           << "Reader ctor failed";
@@ -114,7 +114,7 @@
 }
 
 TEST_F(BackupDataTest, WriteAndReadMultiple) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, sizeof(DATA1));
   writer->WriteEntityData(DATA1, sizeof(DATA1));
@@ -122,7 +122,7 @@
   writer->WriteEntityData(DATA2, sizeof(DATA2));
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
@@ -162,7 +162,7 @@
 }
 
 TEST_F(BackupDataTest, SkipEntity) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, sizeof(DATA1));
   writer->WriteEntityData(DATA1, sizeof(DATA1));
@@ -172,7 +172,7 @@
   writer->WriteEntityData(DATA3, sizeof(DATA3));
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
@@ -217,14 +217,14 @@
 }
 
 TEST_F(BackupDataTest, DeleteEntity) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, sizeof(DATA1));
   writer->WriteEntityData(DATA1, sizeof(DATA1));
   writer->WriteEntityHeader(mKey2, -1);
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
@@ -256,7 +256,7 @@
 }
 
 TEST_F(BackupDataTest, EneityAfterDelete) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, sizeof(DATA1));
   writer->WriteEntityData(DATA1, sizeof(DATA1));
@@ -265,7 +265,7 @@
   writer->WriteEntityData(DATA3, sizeof(DATA3));
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
@@ -317,7 +317,7 @@
 }
 
 TEST_F(BackupDataTest, OnlyDeleteEntities) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, -1);
   writer->WriteEntityHeader(mKey2, -1);
@@ -325,7 +325,7 @@
   writer->WriteEntityHeader(mKey4, -1);
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
@@ -385,13 +385,13 @@
 }
 
 TEST_F(BackupDataTest, ReadDeletedEntityData) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, -1);
   writer->WriteEntityHeader(mKey2, -1);
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
diff --git a/libs/androidfw/tests/CommonHelpers.cpp b/libs/androidfw/tests/CommonHelpers.cpp
index 3396729..10138de 100644
--- a/libs/androidfw/tests/CommonHelpers.cpp
+++ b/libs/androidfw/tests/CommonHelpers.cpp
@@ -60,7 +60,7 @@
 std::string GetStringFromPool(const ResStringPool* pool, uint32_t idx) {
   auto str = pool->string8ObjectAt(idx);
   CHECK(str.has_value()) << "failed to find string entry";
-  return std::string(str->string(), str->length());
+  return std::string(str->c_str(), str->length());
 }
 
 }  // namespace android
diff --git a/libs/androidfw/tests/ConfigDescription_test.cpp b/libs/androidfw/tests/ConfigDescription_test.cpp
index f5c01e5..ec478b0 100644
--- a/libs/androidfw/tests/ConfigDescription_test.cpp
+++ b/libs/androidfw/tests/ConfigDescription_test.cpp
@@ -50,10 +50,10 @@
 TEST(ConfigDescriptionTest, ParseBasicQualifiers) {
   ConfigDescription config;
   EXPECT_TRUE(TestParse("", &config));
-  EXPECT_EQ(std::string(""), config.toString().string());
+  EXPECT_EQ(std::string(""), config.toString().c_str());
 
   EXPECT_TRUE(TestParse("fr-land", &config));
-  EXPECT_EQ(std::string("fr-land"), config.toString().string());
+  EXPECT_EQ(std::string("fr-land"), config.toString().c_str());
 
   EXPECT_TRUE(
       TestParse("mcc310-pl-sw720dp-normal-long-port-night-"
@@ -61,22 +61,22 @@
                 &config));
   EXPECT_EQ(std::string("mcc310-pl-sw720dp-normal-long-port-night-"
                         "xhdpi-keyssoft-qwerty-navexposed-nonav-v13"),
-            config.toString().string());
+            config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, ParseLocales) {
   ConfigDescription config;
   EXPECT_TRUE(TestParse("en-rUS", &config));
-  EXPECT_EQ(std::string("en-rUS"), config.toString().string());
+  EXPECT_EQ(std::string("en-rUS"), config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, ParseQualifierAddedInApi13) {
   ConfigDescription config;
   EXPECT_TRUE(TestParse("sw600dp", &config));
-  EXPECT_EQ(std::string("sw600dp-v13"), config.toString().string());
+  EXPECT_EQ(std::string("sw600dp-v13"), config.toString().c_str());
 
   EXPECT_TRUE(TestParse("sw600dp-v8", &config));
-  EXPECT_EQ(std::string("sw600dp-v13"), config.toString().string());
+  EXPECT_EQ(std::string("sw600dp-v13"), config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, ParseCarAttribute) {
@@ -91,13 +91,13 @@
   EXPECT_EQ(android::ResTable_config::SCREENROUND_YES,
             config.screenLayout2 & android::ResTable_config::MASK_SCREENROUND);
   EXPECT_EQ(SDK_MARSHMALLOW, config.sdkVersion);
-  EXPECT_EQ(std::string("round-v23"), config.toString().string());
+  EXPECT_EQ(std::string("round-v23"), config.toString().c_str());
 
   EXPECT_TRUE(TestParse("notround", &config));
   EXPECT_EQ(android::ResTable_config::SCREENROUND_NO,
             config.screenLayout2 & android::ResTable_config::MASK_SCREENROUND);
   EXPECT_EQ(SDK_MARSHMALLOW, config.sdkVersion);
-  EXPECT_EQ(std::string("notround-v23"), config.toString().string());
+  EXPECT_EQ(std::string("notround-v23"), config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, TestWideColorGamutQualifier) {
@@ -106,13 +106,13 @@
   EXPECT_EQ(android::ResTable_config::WIDE_COLOR_GAMUT_YES,
             config.colorMode & android::ResTable_config::MASK_WIDE_COLOR_GAMUT);
   EXPECT_EQ(SDK_O, config.sdkVersion);
-  EXPECT_EQ(std::string("widecg-v26"), config.toString().string());
+  EXPECT_EQ(std::string("widecg-v26"), config.toString().c_str());
 
   EXPECT_TRUE(TestParse("nowidecg", &config));
   EXPECT_EQ(android::ResTable_config::WIDE_COLOR_GAMUT_NO,
             config.colorMode & android::ResTable_config::MASK_WIDE_COLOR_GAMUT);
   EXPECT_EQ(SDK_O, config.sdkVersion);
-  EXPECT_EQ(std::string("nowidecg-v26"), config.toString().string());
+  EXPECT_EQ(std::string("nowidecg-v26"), config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, TestHdrQualifier) {
@@ -121,13 +121,13 @@
   EXPECT_EQ(android::ResTable_config::HDR_YES,
             config.colorMode & android::ResTable_config::MASK_HDR);
   EXPECT_EQ(SDK_O, config.sdkVersion);
-  EXPECT_EQ(std::string("highdr-v26"), config.toString().string());
+  EXPECT_EQ(std::string("highdr-v26"), config.toString().c_str());
 
   EXPECT_TRUE(TestParse("lowdr", &config));
   EXPECT_EQ(android::ResTable_config::HDR_NO,
             config.colorMode & android::ResTable_config::MASK_HDR);
   EXPECT_EQ(SDK_O, config.sdkVersion);
-  EXPECT_EQ(std::string("lowdr-v26"), config.toString().string());
+  EXPECT_EQ(std::string("lowdr-v26"), config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, ParseVrAttribute) {
@@ -135,7 +135,7 @@
   EXPECT_TRUE(TestParse("vrheadset", &config));
   EXPECT_EQ(android::ResTable_config::UI_MODE_TYPE_VR_HEADSET, config.uiMode);
   EXPECT_EQ(SDK_O, config.sdkVersion);
-  EXPECT_EQ(std::string("vrheadset-v26"), config.toString().string());
+  EXPECT_EQ(std::string("vrheadset-v26"), config.toString().c_str());
 }
 
 static inline ConfigDescription ParseConfigOrDie(android::StringPiece str) {
diff --git a/libs/androidfw/tests/ObbFile_test.cpp b/libs/androidfw/tests/ObbFile_test.cpp
index 1151121..ba818c4 100644
--- a/libs/androidfw/tests/ObbFile_test.cpp
+++ b/libs/androidfw/tests/ObbFile_test.cpp
@@ -43,9 +43,9 @@
         mFileName.append(externalStorage);
         mFileName.append(TEST_FILENAME);
 
-        int fd = ::open(mFileName.string(), O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
+        int fd = ::open(mFileName.c_str(), O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
         if (fd < 0) {
-            FAIL() << "Couldn't create " << mFileName.string() << " for tests";
+            FAIL() << "Couldn't create " << mFileName.c_str() << " for tests";
         }
     }
 
@@ -69,17 +69,17 @@
     EXPECT_TRUE(mObbFile->setSalt(salt, SALT_SIZE))
             << "Salt should be successfully set";
 
-    EXPECT_TRUE(mObbFile->writeTo(mFileName.string()))
+    EXPECT_TRUE(mObbFile->writeTo(mFileName.c_str()))
             << "couldn't write to fake .obb file";
 
     mObbFile = new ObbFile();
 
-    EXPECT_TRUE(mObbFile->readFrom(mFileName.string()))
+    EXPECT_TRUE(mObbFile->readFrom(mFileName.c_str()))
             << "couldn't read from fake .obb file";
 
     EXPECT_EQ(versionNum, mObbFile->getVersion())
             << "version didn't come out the same as it went in";
-    const char* currentPackageName = mObbFile->getPackageName().string();
+    const char* currentPackageName = mObbFile->getPackageName().c_str();
     EXPECT_STREQ(packageName, currentPackageName)
             << "package name didn't come out the same as it went in";
 
diff --git a/libs/androidfw/tests/ResTable_test.cpp b/libs/androidfw/tests/ResTable_test.cpp
index fbf7098..945981b 100644
--- a/libs/androidfw/tests/ResTable_test.cpp
+++ b/libs/androidfw/tests/ResTable_test.cpp
@@ -64,8 +64,8 @@
   String16 defPackage("com.android.basic");
   String16 testName("@string/test1");
   uint32_t resID =
-      table.identifierForName(testName.string(), testName.size(), 0, 0,
-                              defPackage.string(), defPackage.size());
+      table.identifierForName(testName.c_str(), testName.size(), 0, 0,
+                              defPackage.c_str(), defPackage.size());
   ASSERT_NE(uint32_t(0x00000000), resID);
   ASSERT_EQ(basic::R::string::test1, resID);
 }
diff --git a/libs/androidfw/tests/Split_test.cpp b/libs/androidfw/tests/Split_test.cpp
index 2c242db..3d88577 100644
--- a/libs/androidfw/tests/Split_test.cpp
+++ b/libs/androidfw/tests/Split_test.cpp
@@ -261,8 +261,8 @@
   const String16 package("com.android.basic");
   ASSERT_EQ(
       R::string::test3,
-      table.identifierForName(name.string(), name.size(), type.string(),
-                              type.size(), package.string(), package.size()));
+      table.identifierForName(name.c_str(), name.size(), type.c_str(),
+                              type.size(), package.c_str(), package.size()));
 }
 
 }  // namespace
diff --git a/libs/androidfw/tests/TestHelpers.cpp b/libs/androidfw/tests/TestHelpers.cpp
index 10c0a4f..c6f657c 100644
--- a/libs/androidfw/tests/TestHelpers.cpp
+++ b/libs/androidfw/tests/TestHelpers.cpp
@@ -79,9 +79,9 @@
   }
 
   if (String8(expected_str) != *actual_str) {
-    return AssertionFailure() << actual_str->string();
+    return AssertionFailure() << actual_str->c_str();
   }
-  return AssertionSuccess() << actual_str->string();
+  return AssertionSuccess() << actual_str->c_str();
 }
 
 }  // namespace android
diff --git a/libs/hwui/RenderNode.h b/libs/hwui/RenderNode.h
index b5b828e..529a49e9 100644
--- a/libs/hwui/RenderNode.h
+++ b/libs/hwui/RenderNode.h
@@ -114,7 +114,7 @@
         return mDisplayList.containsProjectionReceiver();
     }
 
-    const char* getName() const { return mName.string(); }
+    const char* getName() const { return mName.c_str(); }
 
     void setName(const char* name) {
         if (name) {
diff --git a/libs/hwui/pipeline/skia/SkiaPipeline.cpp b/libs/hwui/pipeline/skia/SkiaPipeline.cpp
index 3d77877..6679f8f 100644
--- a/libs/hwui/pipeline/skia/SkiaPipeline.cpp
+++ b/libs/hwui/pipeline/skia/SkiaPipeline.cpp
@@ -201,7 +201,7 @@
             String8 cachesOutput;
             mRenderThread.cacheManager().dumpMemoryUsage(cachesOutput,
                                                          &mRenderThread.renderState());
-            ALOGE("%s", cachesOutput.string());
+            ALOGE("%s", cachesOutput.c_str());
             if (errorHandler) {
                 std::ostringstream err;
                 err << "Unable to create layer for " << node->getName();
diff --git a/libs/hwui/renderthread/RenderThread.cpp b/libs/hwui/renderthread/RenderThread.cpp
index c740074..94ed06c 100644
--- a/libs/hwui/renderthread/RenderThread.cpp
+++ b/libs/hwui/renderthread/RenderThread.cpp
@@ -357,7 +357,7 @@
 
     String8 cachesOutput;
     mCacheManager->dumpMemoryUsage(cachesOutput, mRenderState);
-    dprintf(fd, "\nPipeline=%s\n%s", pipelineToString(), cachesOutput.string());
+    dprintf(fd, "\nPipeline=%s\n%s", pipelineToString(), cachesOutput.c_str());
     for (auto&& context : mCacheManager->mCanvasContexts) {
         context->visitAllRenderNodes([&](const RenderNode& node) {
             if (node.isTextureView()) {
diff --git a/libs/input/Android.bp b/libs/input/Android.bp
index 6c0fd5f..5ce990f 100644
--- a/libs/input/Android.bp
+++ b/libs/input/Android.bp
@@ -23,6 +23,12 @@
 
 cc_library_shared {
     name: "libinputservice",
+    defaults: [
+        // Build using the same flags and configurations as inputflinger.
+        "inputflinger_defaults",
+    ],
+    host_supported: false,
+
     srcs: [
         "PointerController.cpp",
         "PointerControllerContext.cpp",
@@ -50,12 +56,4 @@
     ],
 
     include_dirs: ["frameworks/native/services"],
-
-    cflags: [
-        "-Wall",
-        "-Wextra",
-        "-Werror",
-        "-Wthread-safety",
-    ],
-
 }
diff --git a/libs/input/MouseCursorController.cpp b/libs/input/MouseCursorController.cpp
index c3ad767..6a46544 100644
--- a/libs/input/MouseCursorController.cpp
+++ b/libs/input/MouseCursorController.cpp
@@ -47,7 +47,7 @@
     mLocked.pointerX = 0;
     mLocked.pointerY = 0;
     mLocked.pointerAlpha = 0.0f; // pointer is initially faded
-    mLocked.pointerSprite = mContext.getSpriteController()->createSprite();
+    mLocked.pointerSprite = mContext.getSpriteController().createSprite();
     mLocked.updatePointerIcon = false;
     mLocked.requestedPointerType = PointerIconStyle::TYPE_NOT_SPECIFIED;
     mLocked.resolvedPointerType = PointerIconStyle::TYPE_NOT_SPECIFIED;
@@ -325,8 +325,8 @@
     }
 
     if (timestamp - mLocked.lastFrameUpdatedTime > iter->second.durationPerFrame) {
-        sp<SpriteController> spriteController = mContext.getSpriteController();
-        spriteController->openTransaction();
+        auto& spriteController = mContext.getSpriteController();
+        spriteController.openTransaction();
 
         int incr = (timestamp - mLocked.lastFrameUpdatedTime) / iter->second.durationPerFrame;
         mLocked.animationFrameIndex += incr;
@@ -336,7 +336,7 @@
         }
         mLocked.pointerSprite->setIcon(iter->second.animationFrames[mLocked.animationFrameIndex]);
 
-        spriteController->closeTransaction();
+        spriteController.closeTransaction();
     }
     // Keep animating.
     return true;
@@ -346,8 +346,8 @@
     if (!mLocked.viewport.isValid()) {
         return;
     }
-    sp<SpriteController> spriteController = mContext.getSpriteController();
-    spriteController->openTransaction();
+    auto& spriteController = mContext.getSpriteController();
+    spriteController.openTransaction();
 
     mLocked.pointerSprite->setLayer(Sprite::BASE_LAYER_POINTER);
     mLocked.pointerSprite->setPosition(mLocked.pointerX, mLocked.pointerY);
@@ -392,7 +392,7 @@
         mLocked.updatePointerIcon = false;
     }
 
-    spriteController->closeTransaction();
+    spriteController.closeTransaction();
 }
 
 void MouseCursorController::loadResourcesLocked(bool getAdditionalMouseResources) REQUIRES(mLock) {
diff --git a/libs/input/PointerController.cpp b/libs/input/PointerController.cpp
index e21d6fb..435452c 100644
--- a/libs/input/PointerController.cpp
+++ b/libs/input/PointerController.cpp
@@ -63,7 +63,7 @@
 
 std::shared_ptr<PointerController> PointerController::create(
         const sp<PointerControllerPolicyInterface>& policy, const sp<Looper>& looper,
-        const sp<SpriteController>& spriteController) {
+        SpriteController& spriteController) {
     // using 'new' to access non-public constructor
     std::shared_ptr<PointerController> controller = std::shared_ptr<PointerController>(
             new PointerController(policy, looper, spriteController));
@@ -85,8 +85,7 @@
 }
 
 PointerController::PointerController(const sp<PointerControllerPolicyInterface>& policy,
-                                     const sp<Looper>& looper,
-                                     const sp<SpriteController>& spriteController)
+                                     const sp<Looper>& looper, SpriteController& spriteController)
       : PointerController(
                 policy, looper, spriteController,
                 [](const sp<android::gui::WindowInfosListener>& listener) {
@@ -97,13 +96,12 @@
                 }) {}
 
 PointerController::PointerController(const sp<PointerControllerPolicyInterface>& policy,
-                                     const sp<Looper>& looper,
-                                     const sp<SpriteController>& spriteController,
+                                     const sp<Looper>& looper, SpriteController& spriteController,
                                      WindowListenerConsumer registerListener,
                                      WindowListenerConsumer unregisterListener)
       : mContext(policy, looper, spriteController, *this),
         mCursorController(mContext),
-        mDisplayInfoListener(new DisplayInfoListener(this)),
+        mDisplayInfoListener(sp<DisplayInfoListener>::make(this)),
         mUnregisterWindowInfosListener(std::move(unregisterListener)) {
     std::scoped_lock lock(getLock());
     mLocked.presentation = Presentation::SPOT;
diff --git a/libs/input/PointerController.h b/libs/input/PointerController.h
index 62ee743..c7e772d 100644
--- a/libs/input/PointerController.h
+++ b/libs/input/PointerController.h
@@ -47,7 +47,7 @@
 public:
     static std::shared_ptr<PointerController> create(
             const sp<PointerControllerPolicyInterface>& policy, const sp<Looper>& looper,
-            const sp<SpriteController>& spriteController);
+            SpriteController& spriteController);
 
     ~PointerController() override;
 
@@ -83,13 +83,12 @@
 
     // Constructor used to test WindowInfosListener registration.
     PointerController(const sp<PointerControllerPolicyInterface>& policy, const sp<Looper>& looper,
-                      const sp<SpriteController>& spriteController,
-                      WindowListenerConsumer registerListener,
+                      SpriteController& spriteController, WindowListenerConsumer registerListener,
                       WindowListenerConsumer unregisterListener);
 
 private:
     PointerController(const sp<PointerControllerPolicyInterface>& policy, const sp<Looper>& looper,
-                      const sp<SpriteController>& spriteController);
+                      SpriteController& spriteController);
 
     friend PointerControllerContext::LooperCallback;
     friend PointerControllerContext::MessageHandler;
diff --git a/libs/input/PointerControllerContext.cpp b/libs/input/PointerControllerContext.cpp
index f30e8d8..15c3517 100644
--- a/libs/input/PointerControllerContext.cpp
+++ b/libs/input/PointerControllerContext.cpp
@@ -32,12 +32,12 @@
 
 PointerControllerContext::PointerControllerContext(
         const sp<PointerControllerPolicyInterface>& policy, const sp<Looper>& looper,
-        const sp<SpriteController>& spriteController, PointerController& controller)
+        SpriteController& spriteController, PointerController& controller)
       : mPolicy(policy),
         mLooper(looper),
         mSpriteController(spriteController),
-        mHandler(new MessageHandler()),
-        mCallback(new LooperCallback()),
+        mHandler(sp<MessageHandler>::make()),
+        mCallback(sp<LooperCallback>::make()),
         mController(controller),
         mAnimator(*this) {
     std::scoped_lock lock(mLock);
@@ -93,7 +93,7 @@
     return mPolicy;
 }
 
-sp<SpriteController> PointerControllerContext::getSpriteController() {
+SpriteController& PointerControllerContext::getSpriteController() {
     return mSpriteController;
 }
 
diff --git a/libs/input/PointerControllerContext.h b/libs/input/PointerControllerContext.h
index f6f5d3b..98c3988 100644
--- a/libs/input/PointerControllerContext.h
+++ b/libs/input/PointerControllerContext.h
@@ -92,7 +92,7 @@
 class PointerControllerContext {
 public:
     PointerControllerContext(const sp<PointerControllerPolicyInterface>& policy,
-                             const sp<Looper>& looper, const sp<SpriteController>& spriteController,
+                             const sp<Looper>& looper, SpriteController& spriteController,
                              PointerController& controller);
     ~PointerControllerContext();
 
@@ -109,7 +109,7 @@
     void setCallbackController(std::shared_ptr<PointerController> controller);
 
     sp<PointerControllerPolicyInterface> getPolicy();
-    sp<SpriteController> getSpriteController();
+    SpriteController& getSpriteController();
 
     void handleDisplayEvents();
 
@@ -163,7 +163,7 @@
 
     sp<PointerControllerPolicyInterface> mPolicy;
     sp<Looper> mLooper;
-    sp<SpriteController> mSpriteController;
+    SpriteController& mSpriteController;
     sp<MessageHandler> mHandler;
     sp<LooperCallback> mCallback;
 
diff --git a/libs/input/SpriteController.cpp b/libs/input/SpriteController.cpp
index 130b204..6dc45a6 100644
--- a/libs/input/SpriteController.cpp
+++ b/libs/input/SpriteController.cpp
@@ -31,12 +31,19 @@
                                    ParentSurfaceProvider parentSurfaceProvider)
       : mLooper(looper),
         mOverlayLayer(overlayLayer),
+        mHandler(sp<Handler>::make()),
         mParentSurfaceProvider(std::move(parentSurfaceProvider)) {
-    mHandler = new WeakMessageHandler(this);
     mLocked.transactionNestingCount = 0;
     mLocked.deferredSpriteUpdate = false;
 }
 
+void SpriteController::setHandlerController(
+        const std::shared_ptr<android::SpriteController>& controller) {
+    // Initialize the weak message handler outside the constructor, because we cannot get a shared
+    // pointer to self in the constructor.
+    mHandler->spriteController = controller;
+}
+
 SpriteController::~SpriteController() {
     mLooper->removeMessages(mHandler);
 
@@ -47,7 +54,7 @@
 }
 
 sp<Sprite> SpriteController::createSprite() {
-    return new SpriteImpl(this);
+    return sp<SpriteImpl>::make(*this);
 }
 
 void SpriteController::openTransaction() {
@@ -65,7 +72,7 @@
     mLocked.transactionNestingCount -= 1;
     if (mLocked.transactionNestingCount == 0 && mLocked.deferredSpriteUpdate) {
         mLocked.deferredSpriteUpdate = false;
-        mLooper->sendMessage(mHandler, Message(MSG_UPDATE_SPRITES));
+        mLooper->sendMessage(mHandler, Message(Handler::MSG_UPDATE_SPRITES));
     }
 }
 
@@ -76,7 +83,7 @@
         if (mLocked.transactionNestingCount != 0) {
             mLocked.deferredSpriteUpdate = true;
         } else {
-            mLooper->sendMessage(mHandler, Message(MSG_UPDATE_SPRITES));
+            mLooper->sendMessage(mHandler, Message(Handler::MSG_UPDATE_SPRITES));
         }
     }
 }
@@ -85,18 +92,7 @@
     bool wasEmpty = mLocked.disposedSurfaces.empty();
     mLocked.disposedSurfaces.push_back(surfaceControl);
     if (wasEmpty) {
-        mLooper->sendMessage(mHandler, Message(MSG_DISPOSE_SURFACES));
-    }
-}
-
-void SpriteController::handleMessage(const Message& message) {
-    switch (message.what) {
-    case MSG_UPDATE_SPRITES:
-        doUpdateSprites();
-        break;
-    case MSG_DISPOSE_SURFACES:
-        doDisposeSurfaces();
-        break;
+        mLooper->sendMessage(mHandler, Message(Handler::MSG_DISPOSE_SURFACES));
     }
 }
 
@@ -327,7 +323,7 @@
 
 void SpriteController::ensureSurfaceComposerClient() {
     if (mSurfaceComposerClient == NULL) {
-        mSurfaceComposerClient = new SurfaceComposerClient();
+        mSurfaceComposerClient = sp<SurfaceComposerClient>::make();
     }
 }
 
@@ -353,25 +349,41 @@
     return surfaceControl;
 }
 
-// --- SpriteController::SpriteImpl ---
+// --- SpriteController::Handler ---
 
-SpriteController::SpriteImpl::SpriteImpl(const sp<SpriteController> controller) :
-        mController(controller) {
+void SpriteController::Handler::handleMessage(const android::Message& message) {
+    auto controller = spriteController.lock();
+    if (!controller) {
+        return;
+    }
+
+    switch (message.what) {
+        case MSG_UPDATE_SPRITES:
+            controller->doUpdateSprites();
+            break;
+        case MSG_DISPOSE_SURFACES:
+            controller->doDisposeSurfaces();
+            break;
+    }
 }
 
+// --- SpriteController::SpriteImpl ---
+
+SpriteController::SpriteImpl::SpriteImpl(SpriteController& controller) : mController(controller) {}
+
 SpriteController::SpriteImpl::~SpriteImpl() {
-    AutoMutex _m(mController->mLock);
+    AutoMutex _m(mController.mLock);
 
     // Let the controller take care of deleting the last reference to sprite
     // surfaces so that we do not block the caller on an IPC here.
     if (mLocked.state.surfaceControl != NULL) {
-        mController->disposeSurfaceLocked(mLocked.state.surfaceControl);
+        mController.disposeSurfaceLocked(mLocked.state.surfaceControl);
         mLocked.state.surfaceControl.clear();
     }
 }
 
 void SpriteController::SpriteImpl::setIcon(const SpriteIcon& icon) {
-    AutoMutex _l(mController->mLock);
+    AutoMutex _l(mController.mLock);
 
     uint32_t dirty;
     if (icon.isValid()) {
@@ -401,7 +413,7 @@
 }
 
 void SpriteController::SpriteImpl::setVisible(bool visible) {
-    AutoMutex _l(mController->mLock);
+    AutoMutex _l(mController.mLock);
 
     if (mLocked.state.visible != visible) {
         mLocked.state.visible = visible;
@@ -410,7 +422,7 @@
 }
 
 void SpriteController::SpriteImpl::setPosition(float x, float y) {
-    AutoMutex _l(mController->mLock);
+    AutoMutex _l(mController.mLock);
 
     if (mLocked.state.positionX != x || mLocked.state.positionY != y) {
         mLocked.state.positionX = x;
@@ -420,7 +432,7 @@
 }
 
 void SpriteController::SpriteImpl::setLayer(int32_t layer) {
-    AutoMutex _l(mController->mLock);
+    AutoMutex _l(mController.mLock);
 
     if (mLocked.state.layer != layer) {
         mLocked.state.layer = layer;
@@ -429,7 +441,7 @@
 }
 
 void SpriteController::SpriteImpl::setAlpha(float alpha) {
-    AutoMutex _l(mController->mLock);
+    AutoMutex _l(mController.mLock);
 
     if (mLocked.state.alpha != alpha) {
         mLocked.state.alpha = alpha;
@@ -439,7 +451,7 @@
 
 void SpriteController::SpriteImpl::setTransformationMatrix(
         const SpriteTransformationMatrix& matrix) {
-    AutoMutex _l(mController->mLock);
+    AutoMutex _l(mController.mLock);
 
     if (mLocked.state.transformationMatrix != matrix) {
         mLocked.state.transformationMatrix = matrix;
@@ -448,7 +460,7 @@
 }
 
 void SpriteController::SpriteImpl::setDisplayId(int32_t displayId) {
-    AutoMutex _l(mController->mLock);
+    AutoMutex _l(mController.mLock);
 
     if (mLocked.state.displayId != displayId) {
         mLocked.state.displayId = displayId;
@@ -461,7 +473,7 @@
     mLocked.state.dirty |= dirty;
 
     if (!wasDirty) {
-        mController->invalidateSpriteLocked(this);
+        mController.invalidateSpriteLocked(sp<SpriteImpl>::fromExisting(this));
     }
 }
 
diff --git a/libs/input/SpriteController.h b/libs/input/SpriteController.h
index 1f113c0..04ecb38 100644
--- a/libs/input/SpriteController.h
+++ b/libs/input/SpriteController.h
@@ -109,15 +109,19 @@
  *
  * Clients are responsible for animating sprites by periodically updating their properties.
  */
-class SpriteController : public MessageHandler {
-protected:
-    virtual ~SpriteController();
-
+class SpriteController {
 public:
     using ParentSurfaceProvider = std::function<sp<SurfaceControl>(int /*displayId*/)>;
     SpriteController(const sp<Looper>& looper, int32_t overlayLayer, ParentSurfaceProvider parent);
+    SpriteController(const SpriteController&) = delete;
+    SpriteController& operator=(const SpriteController&) = delete;
+    virtual ~SpriteController();
 
-    /* Creates a new sprite, initially invisible. */
+    /* Initialize the callback for the message handler. */
+    void setHandlerController(const std::shared_ptr<SpriteController>& controller);
+
+    /* Creates a new sprite, initially invisible. The lifecycle of the sprite must not extend beyond
+     * the lifecycle of this SpriteController. */
     virtual sp<Sprite> createSprite();
 
     /* Opens or closes a transaction to perform a batch of sprite updates as part of
@@ -129,9 +133,12 @@
     virtual void closeTransaction();
 
 private:
-    enum {
-        MSG_UPDATE_SPRITES,
-        MSG_DISPOSE_SURFACES,
+    class Handler : public virtual android::MessageHandler {
+    public:
+        enum { MSG_UPDATE_SPRITES, MSG_DISPOSE_SURFACES };
+
+        void handleMessage(const Message& message) override;
+        std::weak_ptr<SpriteController> spriteController;
     };
 
     enum {
@@ -192,7 +199,7 @@
         virtual ~SpriteImpl();
 
     public:
-        explicit SpriteImpl(const sp<SpriteController> controller);
+        explicit SpriteImpl(SpriteController& controller);
 
         virtual void setIcon(const SpriteIcon& icon);
         virtual void setVisible(bool visible);
@@ -220,7 +227,7 @@
         }
 
     private:
-        sp<SpriteController> mController;
+        SpriteController& mController;
 
         struct Locked {
             SpriteState state;
@@ -245,7 +252,7 @@
 
     sp<Looper> mLooper;
     const int32_t mOverlayLayer;
-    sp<WeakMessageHandler> mHandler;
+    sp<Handler> mHandler;
     ParentSurfaceProvider mParentSurfaceProvider;
 
     sp<SurfaceComposerClient> mSurfaceComposerClient;
@@ -260,7 +267,6 @@
     void invalidateSpriteLocked(const sp<SpriteImpl>& sprite);
     void disposeSurfaceLocked(const sp<SurfaceControl>& surfaceControl);
 
-    void handleMessage(const Message& message);
     void doUpdateSprites();
     void doDisposeSurfaces();
 
diff --git a/libs/input/TouchSpotController.cpp b/libs/input/TouchSpotController.cpp
index d9fe599..b8de919 100644
--- a/libs/input/TouchSpotController.cpp
+++ b/libs/input/TouchSpotController.cpp
@@ -39,15 +39,15 @@
 
 // --- Spot ---
 
-void TouchSpotController::Spot::updateSprite(const SpriteIcon* icon, float x, float y,
+void TouchSpotController::Spot::updateSprite(const SpriteIcon* icon, float newX, float newY,
                                              int32_t displayId) {
     sprite->setLayer(Sprite::BASE_LAYER_SPOT + id);
     sprite->setAlpha(alpha);
     sprite->setTransformationMatrix(SpriteTransformationMatrix(scale, 0.0f, 0.0f, scale));
-    sprite->setPosition(x, y);
+    sprite->setPosition(newX, newY);
     sprite->setDisplayId(displayId);
-    this->x = x;
-    this->y = y;
+    x = newX;
+    y = newY;
 
     if (icon != mLastIcon) {
         mLastIcon = icon;
@@ -98,8 +98,8 @@
 #endif
 
     std::scoped_lock lock(mLock);
-    sp<SpriteController> spriteController = mContext.getSpriteController();
-    spriteController->openTransaction();
+    auto& spriteController = mContext.getSpriteController();
+    spriteController.openTransaction();
 
     // Add or move spots for fingers that are down.
     for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
@@ -125,7 +125,7 @@
         }
     }
 
-    spriteController->closeTransaction();
+    spriteController.closeTransaction();
 }
 
 void TouchSpotController::clearSpots() {
@@ -167,7 +167,7 @@
         sprite = mLocked.recycledSprites.back();
         mLocked.recycledSprites.pop_back();
     } else {
-        sprite = mContext.getSpriteController()->createSprite();
+        sprite = mContext.getSpriteController().createSprite();
     }
 
     // Return the new spot.
diff --git a/libs/input/tests/PointerController_test.cpp b/libs/input/tests/PointerController_test.cpp
index 8574751..3e2e43f 100644
--- a/libs/input/tests/PointerController_test.cpp
+++ b/libs/input/tests/PointerController_test.cpp
@@ -157,7 +157,7 @@
 
     sp<MockSprite> mPointerSprite;
     sp<MockPointerControllerPolicyInterface> mPolicy;
-    sp<MockSpriteController> mSpriteController;
+    std::unique_ptr<MockSpriteController> mSpriteController;
     std::shared_ptr<PointerController> mPointerController;
 
 private:
@@ -175,14 +175,13 @@
 
 PointerControllerTest::PointerControllerTest() : mPointerSprite(new NiceMock<MockSprite>),
         mLooper(new MyLooper), mThread(&PointerControllerTest::loopThread, this) {
-
-    mSpriteController = new NiceMock<MockSpriteController>(mLooper);
+    mSpriteController.reset(new NiceMock<MockSpriteController>(mLooper));
     mPolicy = new MockPointerControllerPolicyInterface();
 
     EXPECT_CALL(*mSpriteController, createSprite())
             .WillOnce(Return(mPointerSprite));
 
-    mPointerController = PointerController::create(mPolicy, mLooper, mSpriteController);
+    mPointerController = PointerController::create(mPolicy, mLooper, *mSpriteController);
 }
 
 PointerControllerTest::~PointerControllerTest() {
@@ -319,10 +318,9 @@
 class TestPointerController : public PointerController {
 public:
     TestPointerController(sp<android::gui::WindowInfosListener>& registeredListener,
-                          const sp<Looper>& looper)
+                          const sp<Looper>& looper, SpriteController& spriteController)
           : PointerController(
-                    new MockPointerControllerPolicyInterface(), looper,
-                    new NiceMock<MockSpriteController>(looper),
+                    new MockPointerControllerPolicyInterface(), looper, spriteController,
                     [&registeredListener](const sp<android::gui::WindowInfosListener>& listener) {
                         // Register listener
                         registeredListener = listener;
@@ -335,10 +333,12 @@
 
 TEST_F(PointerControllerWindowInfoListenerTest,
        doesNotCrashIfListenerCalledAfterPointerControllerDestroyed) {
+    sp<Looper> looper = new Looper(false);
+    auto spriteController = NiceMock<MockSpriteController>(looper);
     sp<android::gui::WindowInfosListener> registeredListener;
     sp<android::gui::WindowInfosListener> localListenerCopy;
     {
-        TestPointerController pointerController(registeredListener, new Looper(false));
+        TestPointerController pointerController(registeredListener, looper, spriteController);
         ASSERT_NE(nullptr, registeredListener) << "WindowInfosListener was not registered";
         localListenerCopy = registeredListener;
     }
diff --git a/media/java/android/media/projection/IMediaProjectionManager.aidl b/media/java/android/media/projection/IMediaProjectionManager.aidl
index 304eecb..d294601 100644
--- a/media/java/android/media/projection/IMediaProjectionManager.aidl
+++ b/media/java/android/media/projection/IMediaProjectionManager.aidl
@@ -108,6 +108,7 @@
                 + ".permission.MANAGE_MEDIA_PROJECTION)")
     void notifyActiveProjectionCapturedContentVisibilityChanged(boolean isVisible);
 
+    @EnforcePermission("MANAGE_MEDIA_PROJECTION")
     @JavaPassthrough(annotation = "@android.annotation.RequiresPermission(android.Manifest"
                 + ".permission.MANAGE_MEDIA_PROJECTION)")
     void addCallback(IMediaProjectionWatcherCallback callback);
diff --git a/packages/CtsShim/build/Android.bp b/packages/CtsShim/build/Android.bp
index d778feb..d6b7ecf 100644
--- a/packages/CtsShim/build/Android.bp
+++ b/packages/CtsShim/build/Android.bp
@@ -208,3 +208,22 @@
     ],
     min_sdk_version: "24",
 }
+
+//##########################################################
+// Variant: Add apk to an apex
+android_app {
+    name: "CtsShimAddApkToApex",
+    sdk_version: "current",
+    srcs: ["shim_add_apk_to_apex/src/android/addapktoapex/app/AddApkToApexDeviceActivity.java"],
+    optimize: {
+        enabled: false,
+    },
+    dex_preopt: {
+        enabled: false,
+    },
+    manifest: "shim_add_apk_to_apex/AndroidManifestAddApkToApex.xml",
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.apex.cts.shim.v2_add_apk_to_apex",
+    ],
+}
diff --git a/packages/CtsShim/build/shim_add_apk_to_apex/AndroidManifestAddApkToApex.xml b/packages/CtsShim/build/shim_add_apk_to_apex/AndroidManifestAddApkToApex.xml
new file mode 100644
index 0000000..0e620b0
--- /dev/null
+++ b/packages/CtsShim/build/shim_add_apk_to_apex/AndroidManifestAddApkToApex.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+     package="android.addapktoapex.app">
+
+    <application>
+        <activity android:name=".AddApkToApexDeviceActivity"
+             android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
\ No newline at end of file
diff --git a/packages/CtsShim/build/shim_add_apk_to_apex/src/android/addapktoapex/app/AddApkToApexDeviceActivity.java b/packages/CtsShim/build/shim_add_apk_to_apex/src/android/addapktoapex/app/AddApkToApexDeviceActivity.java
new file mode 100644
index 0000000..c68904b
--- /dev/null
+++ b/packages/CtsShim/build/shim_add_apk_to_apex/src/android/addapktoapex/app/AddApkToApexDeviceActivity.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.addapktoapex.app;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.util.Log;
+
+/**
+ * A simple activity which logs to Logcat.
+ */
+public class AddApkToApexDeviceActivity extends Activity {
+
+    private static final String TAG = AddApkToApexDeviceActivity.class.getSimpleName();
+
+    /**
+     * The test string to log.
+     */
+    private static final String TEST_STRING = "AddApkToApexTestString";
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+        // Log the test string to Logcat.
+        Log.i(TAG, TEST_STRING);
+    }
+
+}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/Keyboards.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/Keyboards.kt
index 3f7cc19..b650034 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/Keyboards.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/Keyboards.kt
@@ -21,7 +21,6 @@
 import androidx.compose.runtime.Composable
 import androidx.compose.runtime.LaunchedEffect
 import androidx.compose.runtime.snapshotFlow
-import androidx.compose.ui.ExperimentalComposeUiApi
 import androidx.compose.ui.platform.LocalSoftwareKeyboardController
 import kotlinx.coroutines.flow.distinctUntilChanged
 import kotlinx.coroutines.flow.filter
@@ -29,7 +28,6 @@
 /**
  * An action when run, hides the keyboard if it's open.
  */
-@OptIn(ExperimentalComposeUiApi::class)
 @Composable
 fun hideKeyboardAction(): () -> Unit {
     val keyboardController = LocalSoftwareKeyboardController.current
@@ -41,7 +39,6 @@
  *
  * And when user scrolling the lazy list, hides the keyboard if it's open.
  */
-@OptIn(ExperimentalComposeUiApi::class)
 @Composable
 fun rememberLazyListStateAndHideKeyboardWhenStartScroll(): LazyListState {
     val listState = rememberLazyListState()
diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/compose/KeyboardsTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/compose/KeyboardsTest.kt
index 944ef7f..e9b3109 100644
--- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/compose/KeyboardsTest.kt
+++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/compose/KeyboardsTest.kt
@@ -21,7 +21,6 @@
 import androidx.compose.material3.Text
 import androidx.compose.runtime.CompositionLocalProvider
 import androidx.compose.runtime.LaunchedEffect
-import androidx.compose.ui.ExperimentalComposeUiApi
 import androidx.compose.ui.Modifier
 import androidx.compose.ui.platform.LocalSoftwareKeyboardController
 import androidx.compose.ui.platform.SoftwareKeyboardController
@@ -32,12 +31,11 @@
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.mockito.Mock
-import org.mockito.Mockito.never
-import org.mockito.Mockito.verify
 import org.mockito.junit.MockitoJUnit
 import org.mockito.junit.MockitoRule
+import org.mockito.kotlin.never
+import org.mockito.kotlin.verify
 
-@OptIn(ExperimentalComposeUiApi::class)
 @RunWith(AndroidJUnit4::class)
 class KeyboardsTest {
     @get:Rule
diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/theme/SettingsThemeTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/theme/SettingsThemeTest.kt
index 2ff3039..bd8a54b 100644
--- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/theme/SettingsThemeTest.kt
+++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/theme/SettingsThemeTest.kt
@@ -31,10 +31,10 @@
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.mockito.Mock
-import org.mockito.Mockito.anyInt
 import org.mockito.junit.MockitoJUnit
 import org.mockito.junit.MockitoRule
-import org.mockito.Mockito.`when` as whenever
+import org.mockito.kotlin.any
+import org.mockito.kotlin.whenever
 
 @RunWith(AndroidJUnit4::class)
 class SettingsThemeTest {
@@ -55,7 +55,7 @@
     @Before
     fun setUp() {
         whenever(context.resources).thenReturn(resources)
-        whenever(resources.getString(anyInt())).thenReturn("")
+        whenever(resources.getString(any())).thenReturn("")
     }
 
     private fun mockAndroidConfig(configName: String, configValue: String) {
diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/AnnotatedTextTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/AnnotatedTextTest.kt
index 2c218e3..5e59620 100644
--- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/AnnotatedTextTest.kt
+++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/AnnotatedTextTest.kt
@@ -32,9 +32,9 @@
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.mockito.Mock
-import org.mockito.Mockito.verify
 import org.mockito.junit.MockitoJUnit
 import org.mockito.junit.MockitoRule
+import org.mockito.kotlin.verify
 
 @RunWith(AndroidJUnit4::class)
 class AnnotatedTextTest {
diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsScaffoldTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsScaffoldTest.kt
index 872d957..3e8fdec 100644
--- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsScaffoldTest.kt
+++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsScaffoldTest.kt
@@ -33,9 +33,9 @@
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.mockito.Mock
-import org.mockito.Mockito.verify
 import org.mockito.junit.MockitoJUnit
 import org.mockito.junit.MockitoRule
+import org.mockito.kotlin.verify
 
 @RunWith(AndroidJUnit4::class)
 class SettingsScaffoldTest {
diff --git a/packages/SettingsLib/Spa/testutils/Android.bp b/packages/SettingsLib/Spa/testutils/Android.bp
index 65f5d34..4031cd7 100644
--- a/packages/SettingsLib/Spa/testutils/Android.bp
+++ b/packages/SettingsLib/Spa/testutils/Android.bp
@@ -30,7 +30,7 @@
         "androidx.compose.ui_ui-test-junit4",
         "androidx.compose.ui_ui-test-manifest",
         "androidx.lifecycle_lifecycle-runtime-testing",
-        "mockito",
+        "mockito-kotlin2",
         "truth-prebuilt",
     ],
     kotlincflags: [
diff --git a/packages/SettingsLib/Spa/testutils/build.gradle.kts b/packages/SettingsLib/Spa/testutils/build.gradle.kts
index f5a22c9..50243dc 100644
--- a/packages/SettingsLib/Spa/testutils/build.gradle.kts
+++ b/packages/SettingsLib/Spa/testutils/build.gradle.kts
@@ -41,7 +41,12 @@
     api("androidx.arch.core:core-testing:2.2.0-alpha01")
     api("androidx.compose.ui:ui-test-junit4:$jetpackComposeVersion")
     api("androidx.lifecycle:lifecycle-runtime-testing")
+    api("org.mockito.kotlin:mockito-kotlin:5.1.0")
+    api("org.mockito:mockito-core") {
+        version {
+            strictly("2.28.2")
+        }
+    }
     api(libs.truth)
-    api("org.mockito:mockito-core:2.21.0")
     debugApi("androidx.compose.ui:ui-test-manifest:$jetpackComposeVersion")
 }
diff --git a/packages/SettingsLib/Spa/testutils/src/com/android/settingslib/spa/testutils/MockitoHelper.kt b/packages/SettingsLib/Spa/testutils/src/com/android/settingslib/spa/testutils/MockitoHelper.kt
deleted file mode 100644
index 5ba54c1..0000000
--- a/packages/SettingsLib/Spa/testutils/src/com/android/settingslib/spa/testutils/MockitoHelper.kt
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.settingslib.spa.testutils
-
-import org.mockito.Mockito
-
-/**
- * Returns Mockito.any() as nullable type to avoid java.lang.IllegalStateException when null is
- * returned.
- *
- * Generic T is nullable because implicitly bounded by Any?.
- */
-fun <T> any(type: Class<T>): T = Mockito.any(type)
-
-inline fun <reified T> any(): T = any(T::class.java)
diff --git a/packages/SettingsLib/tests/robotests/Android.bp b/packages/SettingsLib/tests/robotests/Android.bp
index 5c55a43..c037c40 100644
--- a/packages/SettingsLib/tests/robotests/Android.bp
+++ b/packages/SettingsLib/tests/robotests/Android.bp
@@ -42,7 +42,10 @@
     name: "SettingsLibRoboTests",
     srcs: ["src/**/*.java"],
     static_libs: [
+        "Settings_robolectric_meta_service_file",
+        "Robolectric_shadows_androidx_fragment_upstream",
         "SettingsLib-robo-testutils",
+        "androidx.fragment_fragment",
         "androidx.test.core",
         "androidx.core_core",
         "testng", // TODO: remove once JUnit on Android provides assertThrows
@@ -53,6 +56,20 @@
     test_options: {
         timeout: 36000,
     },
+    upstream: true,
+}
+
+java_genrule {
+    name: "Settings_robolectric_meta_service_file",
+    out: ["robolectric_meta_service_file.jar"],
+    tools: ["soong_zip"],
+    cmd: "mkdir -p $(genDir)/META-INF/services/ && touch $(genDir)/META-INF/services/org.robolectric.internal.ShadowProvider &&" +
+        "echo -e 'org.robolectric.Shadows' >> $(genDir)/META-INF/services/org.robolectric.internal.ShadowProvider && " +
+        "echo -e 'org.robolectric.shadows.multidex.Shadows' >> $(genDir)/META-INF/services/org.robolectric.internal.ShadowProvider && " +
+        "echo -e 'org.robolectric.shadows.httpclient.Shadows' >> $(genDir)/META-INF/services/org.robolectric.internal.ShadowProvider && " +
+        //"echo -e 'com.android.settings.testutils.shadow.Shadows' >> $(genDir)/META-INF/services/org.robolectric.internal.ShadowProvider && " +
+        "echo -e 'com.android.settingslib.testutils.shadow.Shadows' >> $(genDir)/META-INF/services/org.robolectric.internal.ShadowProvider && " +
+        "$(location soong_zip) -o $(out) -C $(genDir) -D $(genDir)/META-INF/services/",
 }
 
 java_library {
@@ -60,9 +77,23 @@
     srcs: [
         "testutils/com/android/settingslib/testutils/**/*.java",
     ],
-
+    javacflags: [
+        "-Aorg.robolectric.annotation.processing.shadowPackage=com.android.settingslib.testutils.shadow",
+        "-Aorg.robolectric.annotation.processing.sdkCheckMode=ERROR",
+        // Uncomment the below to debug annotation processors not firing.
+        //"-verbose",
+        //"-XprintRounds",
+        //"-XprintProcessorInfo",
+        //"-Xlint",
+        //"-J-verbose",
+    ],
+    plugins: [
+        "auto_value_plugin_1.9",
+        "auto_value_builder_plugin_1.9",
+        "Robolectric_processor_upstream",
+    ],
     libs: [
-        "Robolectric_all-target",
+        "Robolectric_all-target_upstream",
         "mockito-robolectric-prebuilt",
         "truth-prebuilt",
     ],
diff --git a/packages/SettingsLib/tests/robotests/config/robolectric.properties b/packages/SettingsLib/tests/robotests/config/robolectric.properties
index fab7251..2a9e50d 100644
--- a/packages/SettingsLib/tests/robotests/config/robolectric.properties
+++ b/packages/SettingsLib/tests/robotests/config/robolectric.properties
@@ -1 +1,2 @@
 sdk=NEWEST_SDK
+instrumentedPackages=androidx.preference
diff --git a/packages/SettingsLib/tests/robotests/fragment/Android.bp b/packages/SettingsLib/tests/robotests/fragment/Android.bp
new file mode 100644
index 0000000..3e67156
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/fragment/Android.bp
@@ -0,0 +1,40 @@
+//#############################################
+// Compile Robolectric shadows framework misapplied to androidx
+//#############################################
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_base_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_base_license"],
+}
+
+java_library {
+    name: "Robolectric_shadows_androidx_fragment_upstream",
+    srcs: [
+        "src/main/java/**/*.java",
+        "src/main/java/**/*.kt",
+    ],
+    javacflags: [
+        "-Aorg.robolectric.annotation.processing.shadowPackage=org.robolectric.shadows.androidx.fragment",
+        "-Aorg.robolectric.annotation.processing.sdkCheckMode=ERROR",
+        // Uncomment the below to debug annotation processors not firing.
+        //"-verbose",
+        //"-XprintRounds",
+        //"-XprintProcessorInfo",
+        //"-Xlint",
+        //"-J-verbose",
+    ],
+    libs: [
+        "Robolectric_all-target_upstream",
+        "androidx.fragment_fragment",
+    ],
+    plugins: [
+        "auto_value_plugin_1.9",
+        "auto_value_builder_plugin_1.9",
+        "Robolectric_processor_upstream",
+    ],
+
+}
diff --git a/packages/SettingsLib/tests/robotests/fragment/BUILD b/packages/SettingsLib/tests/robotests/fragment/BUILD
new file mode 100644
index 0000000..393a02e
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/fragment/BUILD
@@ -0,0 +1,69 @@
+load("//third_party/java/android/android_sdk_linux/extras/android/compatibility/jetify:jetify.bzl", "jetify_android_library", "jetify_android_local_test")
+
+package(
+    default_applicable_licenses = ["//third_party/java_src/robolectric:license"],
+    default_visibility = ["//third_party/java_src/robolectric:__subpackages__"],
+)
+
+licenses(["notice"])
+
+#==============================================================================
+# Test resources library
+#==============================================================================
+jetify_android_library(
+    name = "test_resources",
+    custom_package = "org.robolectric.shadows.androidx.fragment",
+    manifest = "src/test/AndroidManifest.xml",
+    resource_files = glob(
+        ["src/test/resources/**/*"],
+    ),
+)
+
+#==============================================================================
+# AndroidX fragment module library
+#==============================================================================
+jetify_android_library(
+    name = "androidx_fragment",
+    testonly = 1,
+    srcs = glob(
+        ["src/main/java/**"],
+    ),
+    custom_package = "org.robolectric.shadows.androidx.fragment",
+    javacopts = [
+        "-Aorg.robolectric.annotation.processing.shadowPackage=org.robolectric.shadows.androidx.fragment",
+    ],
+    jetify_sources = True,
+    plugins = [
+        "//java/com/google/thirdparty/robolectric/processor",
+    ],
+    deps = [
+        "//third_party/java/androidx/core",
+        "//third_party/java/androidx/fragment",
+        "//third_party/java/androidx/lifecycle",
+        "//third_party/java_src/robolectric/shadowapi",
+        "//third_party/java_src/robolectric/shadows/framework",
+    ],
+)
+
+[
+    jetify_android_local_test(
+        name = "test_" + src.rstrip(".java"),
+        size = "small",
+        srcs = glob(
+            ["src/test/java/**/*.java"],
+        ),
+        jetify_sources = True,
+        deps = [
+            ":androidx_fragment",
+            ":test_resources",
+            "//third_party/java/androidx/fragment",
+            "//third_party/java/androidx/loader",
+            "//third_party/java/mockito",
+            "//third_party/java/robolectric",
+            "//third_party/java/truth",
+        ],
+    )
+    for src in glob(
+        ["src/test/java/**/*Test.java"],
+    )
+]
diff --git a/packages/SettingsLib/tests/robotests/fragment/build.gradle b/packages/SettingsLib/tests/robotests/fragment/build.gradle
new file mode 100644
index 0000000..d9dcd84
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/fragment/build.gradle
@@ -0,0 +1,48 @@
+plugins {
+    id "net.ltgt.errorprone" version "0.0.13"
+}
+
+apply plugin: 'com.android.library'
+
+android {
+    compileSdkVersion 28
+
+    android {
+        sourceSets {
+            main {
+                res.srcDirs = ['src/test/resources/res']
+            }
+        }
+        testOptions {
+            unitTests {
+                includeAndroidResources = true
+            }
+        }
+    }
+}
+
+dependencies {
+    // Project dependencies
+    compileOnly project(":robolectric")
+
+    // Compile dependencies
+    compileOnly AndroidSdk.MAX_SDK.coordinates
+    compileOnly "androidx.core:core:1.0.0-rc02"
+    compileOnly 'androidx.fragment:fragment:1.0.0-rc02'
+    compileOnly "androidx.lifecycle:lifecycle-viewmodel:2.0.0-rc01"
+    compileOnly "androidx.lifecycle:lifecycle-common:2.0.0-beta01"
+
+    // Testing dependencies
+    testImplementation "com.google.truth:truth:0.44"
+    testImplementation "org.mockito:mockito-core:2.5.4"
+    testImplementation "androidx.arch.core:core-common:2.0.0-beta01"
+    testImplementation "androidx.arch.core:core-runtime:2.0.0-rc01"
+    testImplementation "androidx.collection:collection:1.0.0-rc01"
+    testImplementation "androidx.core:core:1.0.0-rc02"
+    testImplementation 'androidx.fragment:fragment:1.0.0-rc02'
+    testImplementation "androidx.lifecycle:lifecycle-viewmodel:2.0.0-rc01"
+    testImplementation "androidx.lifecycle:lifecycle-common:2.0.0-beta01"
+    testImplementation "androidx.lifecycle:lifecycle-runtime:2.0.0-rc01"
+    testImplementation "androidx.lifecycle:lifecycle-livedata-core:2.0.0-rc01"
+    testImplementation "androidx.loader:loader:1.0.0-rc02"
+}
diff --git a/packages/SettingsLib/tests/robotests/fragment/src/main/java/org/robolectric/shadows/androidx/fragment/FragmentController.java b/packages/SettingsLib/tests/robotests/fragment/src/main/java/org/robolectric/shadows/androidx/fragment/FragmentController.java
new file mode 100644
index 0000000..c688683
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/fragment/src/main/java/org/robolectric/shadows/androidx/fragment/FragmentController.java
@@ -0,0 +1,348 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.robolectric.shadows.androidx.fragment;
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.widget.LinearLayout;
+
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentActivity;
+
+import org.robolectric.android.controller.ActivityController;
+import org.robolectric.android.controller.ComponentController;
+import org.robolectric.util.ReflectionHelpers;
+
+/** A Controller that can be used to drive the lifecycle of a {@link Fragment} */
+public class FragmentController<F extends Fragment>
+        extends ComponentController<FragmentController<F>, F> {
+
+    private final F mFragment;
+    private final ActivityController<? extends FragmentActivity> mActivityController;
+
+    private FragmentController(F fragment, Class<? extends FragmentActivity> activityClass) {
+        this(fragment, activityClass, null /*intent*/, null /*arguments*/);
+    }
+
+    private FragmentController(
+            F fragment, Class<? extends FragmentActivity> activityClass, Intent intent) {
+        this(fragment, activityClass, intent, null /*arguments*/);
+    }
+
+    private FragmentController(
+            F fragment, Class<? extends FragmentActivity> activityClass, Bundle arguments) {
+        this(fragment, activityClass, null /*intent*/, arguments);
+    }
+
+    private FragmentController(
+            F fragment,
+            Class<? extends FragmentActivity> activityClass,
+            Intent intent,
+            Bundle arguments) {
+        super(fragment, intent);
+        this.mFragment = fragment;
+        if (arguments != null) {
+            this.mFragment.setArguments(arguments);
+        }
+        this.mActivityController =
+                ActivityController.of(ReflectionHelpers.callConstructor(activityClass), intent);
+    }
+
+    /**
+     * Generate the {@link FragmentController} for specific fragment.
+     *
+     * @param fragment the fragment which you'd like to drive lifecycle
+     * @return {@link FragmentController}
+     */
+    public static <F extends Fragment> FragmentController<F> of(F fragment) {
+        return new FragmentController<>(fragment, FragmentControllerActivity.class);
+    }
+
+    /**
+     * Generate the {@link FragmentController} for specific fragment and intent.
+     *
+     * @param fragment the fragment which you'd like to drive lifecycle
+     * @param intent   the intent which will be retained by activity
+     * @return {@link FragmentController}
+     */
+    public static <F extends Fragment> FragmentController<F> of(F fragment, Intent intent) {
+        return new FragmentController<>(fragment, FragmentControllerActivity.class, intent);
+    }
+
+    /**
+     * Generate the {@link FragmentController} for specific fragment and arguments.
+     *
+     * @param fragment  the fragment which you'd like to drive lifecycle
+     * @param arguments the arguments which will be retained by fragment
+     * @return {@link FragmentController}
+     */
+    public static <F extends Fragment> FragmentController<F> of(F fragment, Bundle arguments) {
+        return new FragmentController<>(fragment, FragmentControllerActivity.class, arguments);
+    }
+
+    /**
+     * Generate the {@link FragmentController} for specific fragment and activity class.
+     *
+     * @param fragment      the fragment which you'd like to drive lifecycle
+     * @param activityClass the activity which will be attached by fragment
+     * @return {@link FragmentController}
+     */
+    public static <F extends Fragment> FragmentController<F> of(
+            F fragment, Class<? extends FragmentActivity> activityClass) {
+        return new FragmentController<>(fragment, activityClass);
+    }
+
+    /**
+     * Generate the {@link FragmentController} for specific fragment, intent and arguments.
+     *
+     * @param fragment  the fragment which you'd like to drive lifecycle
+     * @param intent    the intent which will be retained by activity
+     * @param arguments the arguments which will be retained by fragment
+     * @return {@link FragmentController}
+     */
+    public static <F extends Fragment> FragmentController<F> of(
+            F fragment, Intent intent, Bundle arguments) {
+        return new FragmentController<>(fragment, FragmentControllerActivity.class, intent,
+                arguments);
+    }
+
+    /**
+     * Generate the {@link FragmentController} for specific fragment, activity class and intent.
+     *
+     * @param fragment      the fragment which you'd like to drive lifecycle
+     * @param activityClass the activity which will be attached by fragment
+     * @param intent        the intent which will be retained by activity
+     * @return {@link FragmentController}
+     */
+    public static <F extends Fragment> FragmentController<F> of(
+            F fragment, Class<? extends FragmentActivity> activityClass, Intent intent) {
+        return new FragmentController<>(fragment, activityClass, intent);
+    }
+
+    /**
+     * Generate the {@link FragmentController} for specific fragment, activity class and arguments.
+     *
+     * @param fragment      the fragment which you'd like to drive lifecycle
+     * @param activityClass the activity which will be attached by fragment
+     * @param arguments     the arguments which will be retained by fragment
+     * @return {@link FragmentController}
+     */
+    public static <F extends Fragment> FragmentController<F> of(
+            F fragment, Class<? extends FragmentActivity> activityClass, Bundle arguments) {
+        return new FragmentController<>(fragment, activityClass, arguments);
+    }
+
+    /**
+     * Generate the {@link FragmentController} for specific fragment, activity class, intent and
+     * arguments.
+     *
+     * @param fragment      the fragment which you'd like to drive lifecycle
+     * @param activityClass the activity which will be attached by fragment
+     * @param intent        the intent which will be retained by activity
+     * @param arguments     the arguments which will be retained by fragment
+     * @return {@link FragmentController}
+     */
+    public static <F extends Fragment> FragmentController<F> of(
+            F fragment,
+            Class<? extends FragmentActivity> activityClass,
+            Intent intent,
+            Bundle arguments) {
+        return new FragmentController<>(fragment, activityClass, intent, arguments);
+    }
+
+    /**
+     * Sets up the given fragment by attaching it to an activity, calling its onCreate() through
+     * onResume() lifecycle methods, and then making it visible. Note that the fragment will be
+     * added
+     * to the view with ID 1.
+     */
+    public static <F extends Fragment> F setupFragment(F fragment) {
+        return FragmentController.of(fragment).create().start().resume().visible().get();
+    }
+
+    /**
+     * Sets up the given fragment by attaching it to an activity, calling its onCreate() through
+     * onResume() lifecycle methods, and then making it visible. Note that the fragment will be
+     * added
+     * to the view with ID 1.
+     */
+    public static <F extends Fragment> F setupFragment(
+            F fragment, Class<? extends FragmentActivity> fragmentActivityClass) {
+        return FragmentController.of(fragment, fragmentActivityClass)
+                .create()
+                .start()
+                .resume()
+                .visible()
+                .get();
+    }
+
+    /**
+     * Sets up the given fragment by attaching it to an activity created with the given bundle,
+     * calling its onCreate() through onResume() lifecycle methods, and then making it visible. Note
+     * that the fragment will be added to the view with ID 1.
+     */
+    public static <F extends Fragment> F setupFragment(
+            F fragment, Class<? extends FragmentActivity> fragmentActivityClass, Bundle bundle) {
+        return FragmentController.of(fragment, fragmentActivityClass)
+                .create(bundle)
+                .start()
+                .resume()
+                .visible()
+                .get();
+    }
+
+    /**
+     * Sets up the given fragment by attaching it to an activity created with the given bundle and
+     * container id, calling its onCreate() through onResume() lifecycle methods, and then making it
+     * visible.
+     */
+    public static <F extends Fragment> F setupFragment(
+            F fragment,
+            Class<? extends FragmentActivity> fragmentActivityClass,
+            int containerViewId,
+            Bundle bundle) {
+        return FragmentController.of(fragment, fragmentActivityClass)
+                .create(containerViewId, bundle)
+                .start()
+                .resume()
+                .visible()
+                .get();
+    }
+
+    /**
+     * Creates the activity with {@link Bundle} and adds the fragment to the view with ID {@code
+     * contentViewId}.
+     */
+    public FragmentController<F> create(final int contentViewId, final Bundle bundle) {
+        shadowMainLooper.runPaused(
+                new Runnable() {
+                    @Override
+                    public void run() {
+                        mActivityController
+                                .create(bundle)
+                                .get()
+                                .getSupportFragmentManager()
+                                .beginTransaction()
+                                .add(contentViewId, mFragment)
+                                .commit();
+                    }
+                });
+        return this;
+    }
+
+    /**
+     * Creates the activity with {@link Bundle} and adds the fragment to it. Note that the fragment
+     * will be added to the view with ID 1.
+     */
+    public FragmentController<F> create(final Bundle bundle) {
+        return create(1, bundle);
+    }
+
+    /**
+     * Creates the {@link Fragment} in a newly initialized state and hence will receive a null
+     * savedInstanceState {@link Bundle parameter}
+     */
+    @Override
+    public FragmentController<F> create() {
+        return create(null);
+    }
+
+    /** Drive lifecycle of activity to Start lifetime */
+    public FragmentController<F> start() {
+        shadowMainLooper.runPaused(
+                new Runnable() {
+                    @Override
+                    public void run() {
+                        mActivityController.start();
+                    }
+                });
+        return this;
+    }
+
+    /** Drive lifecycle of activity to Resume lifetime */
+    public FragmentController<F> resume() {
+        shadowMainLooper.runPaused(
+                new Runnable() {
+                    @Override
+                    public void run() {
+                        mActivityController.resume();
+                    }
+                });
+        return this;
+    }
+
+    /** Drive lifecycle of activity to Pause lifetime */
+    public FragmentController<F> pause() {
+        shadowMainLooper.runPaused(
+                new Runnable() {
+                    @Override
+                    public void run() {
+                        mActivityController.pause();
+                    }
+                });
+        return this;
+    }
+
+    /** Drive lifecycle of activity to Stop lifetime */
+    public FragmentController<F> stop() {
+        shadowMainLooper.runPaused(
+                new Runnable() {
+                    @Override
+                    public void run() {
+                        mActivityController.stop();
+                    }
+                });
+        return this;
+    }
+
+    /** Drive lifecycle of activity to Destroy lifetime */
+    @Override
+    public FragmentController<F> destroy() {
+        shadowMainLooper.runPaused(
+                new Runnable() {
+                    @Override
+                    public void run() {
+                        mActivityController.destroy();
+                    }
+                });
+        return this;
+    }
+
+    /** Let activity can be visible lifetime */
+    public FragmentController<F> visible() {
+        shadowMainLooper.runPaused(
+                new Runnable() {
+                    @Override
+                    public void run() {
+                        mActivityController.visible();
+                    }
+                });
+        return this;
+    }
+
+    private static class FragmentControllerActivity extends FragmentActivity {
+
+        @Override
+        protected void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            LinearLayout view = new LinearLayout(this);
+            view.setId(1);
+
+            setContentView(view);
+        }
+    }
+}
diff --git a/packages/SettingsLib/tests/robotests/fragment/src/main/java/org/robolectric/shadows/androidx/fragment/package-info.java b/packages/SettingsLib/tests/robotests/fragment/src/main/java/org/robolectric/shadows/androidx/fragment/package-info.java
new file mode 100644
index 0000000..dd89441
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/fragment/src/main/java/org/robolectric/shadows/androidx/fragment/package-info.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Testing infrastructure for androidx.fragment library.
+ *
+ * <p>To use this in your project, add the artifact {@code
+ * org.robolectric:shadows-androidx-fragment} to your project.
+ */
+package org.robolectric.shadows.androidx.fragment;
diff --git a/packages/SettingsLib/tests/robotests/fragment/src/test/AndroidManifest.xml b/packages/SettingsLib/tests/robotests/fragment/src/test/AndroidManifest.xml
new file mode 100644
index 0000000..8493c02
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/fragment/src/test/AndroidManifest.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="org.robolectric.shadows.androidx.fragment">
+
+    <uses-sdk android:targetSdkVersion="28"/>
+</manifest>
diff --git a/packages/SettingsLib/tests/robotests/fragment/src/test/java/org/robolectric/shadows/androidx/fragment/FragmentControllerTest.java b/packages/SettingsLib/tests/robotests/fragment/src/test/java/org/robolectric/shadows/androidx/fragment/FragmentControllerTest.java
new file mode 100644
index 0000000..ef63058
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/fragment/src/test/java/org/robolectric/shadows/androidx/fragment/FragmentControllerTest.java
@@ -0,0 +1,360 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.robolectric.shadows.androidx.fragment;
+
+import static android.os.Looper.getMainLooper;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.robolectric.Shadows.shadowOf;
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentActivity;
+
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Tests for {@link FragmentController} */
+@RunWith(RobolectricTestRunner.class)
+public class FragmentControllerTest {
+
+    @After
+    public void tearDown() {
+        TranscriptFragment.clearLifecycleEvents();
+    }
+
+    @Test
+    public void initialNotAttached() {
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment());
+
+        assertThat(controller.get().getView()).isNull();
+        assertThat(controller.get().getActivity()).isNull();
+        assertThat(controller.get().isAdded()).isFalse();
+    }
+
+    @Test
+    public void initialNotAttached_customActivity() {
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment(), TestActivity.class);
+
+        assertThat(controller.get().getView()).isNull();
+        assertThat(controller.get().getActivity()).isNull();
+        assertThat(controller.get().isAdded()).isFalse();
+    }
+
+    @Test
+    public void attachedAfterCreate() {
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment());
+
+        controller.create();
+        shadowOf(getMainLooper()).idle();
+
+        assertThat(controller.get().getActivity()).isNotNull();
+        assertThat(controller.get().isAdded()).isTrue();
+        assertThat(controller.get().isResumed()).isFalse();
+    }
+
+    @Test
+    public void attachedAfterCreate_customActivity() {
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment(), TestActivity.class);
+
+        controller.create();
+        shadowOf(getMainLooper()).idle();
+
+        assertThat(controller.get().getActivity()).isNotNull();
+        assertThat(controller.get().getActivity()).isInstanceOf(TestActivity.class);
+        assertThat(controller.get().isAdded()).isTrue();
+        assertThat(controller.get().isResumed()).isFalse();
+    }
+
+    @Test
+    public void attachedAfterCreate_customizedViewId() {
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment(), CustomizedViewIdTestActivity.class);
+
+        controller.create(R.id.custom_activity_view, null).start();
+
+        assertThat(controller.get().getView()).isNotNull();
+        assertThat(controller.get().getActivity()).isNotNull();
+        assertThat(controller.get().isAdded()).isTrue();
+        assertThat(controller.get().isResumed()).isFalse();
+        assertThat((TextView) controller.get().getView().findViewById(R.id.tacos)).isNotNull();
+    }
+
+    @Test
+    public void hasViewAfterStart() {
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment());
+
+        controller.create().start();
+
+        assertThat(controller.get().getView()).isNotNull();
+    }
+
+    @Test
+    public void isResumed() {
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment(), TestActivity.class);
+
+        controller.create().start().resume();
+
+        assertThat(controller.get().getView()).isNotNull();
+        assertThat(controller.get().getActivity()).isNotNull();
+        assertThat(controller.get().isAdded()).isTrue();
+        assertThat(controller.get().isResumed()).isTrue();
+        assertThat((TextView) controller.get().getView().findViewById(R.id.tacos)).isNotNull();
+    }
+
+    @Test
+    public void isPaused() {
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment(), TestActivity.class);
+
+        controller.create().start().resume().pause();
+
+        assertThat(controller.get().getView()).isNotNull();
+        assertThat(controller.get().getActivity()).isNotNull();
+        assertThat(controller.get().isAdded()).isTrue();
+        assertThat(controller.get().isResumed()).isFalse();
+        assertThat(controller.get().getLifecycleEvents())
+                .containsExactly("onCreate", "onStart", "onResume", "onPause")
+                .inOrder();
+    }
+
+    @Test
+    public void isStopped() {
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment(), TestActivity.class);
+
+        controller.create().start().resume().pause().stop();
+
+        assertThat(controller.get().getView()).isNotNull();
+        assertThat(controller.get().getActivity()).isNotNull();
+        assertThat(controller.get().isAdded()).isTrue();
+        assertThat(controller.get().isResumed()).isFalse();
+        assertThat(controller.get().getLifecycleEvents())
+                .containsExactly("onCreate", "onStart", "onResume", "onPause", "onStop")
+                .inOrder();
+    }
+
+    @Test
+    public void withIntent() {
+        final Intent intent = generateTestIntent();
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment(), TestActivity.class, intent);
+
+        controller.create();
+        shadowOf(getMainLooper()).idle();
+        final Intent intentInFragment = controller.get().getActivity().getIntent();
+
+        assertThat(intentInFragment.getAction()).isEqualTo("test_action");
+        assertThat(intentInFragment.getExtras().getString("test_key")).isEqualTo("test_value");
+    }
+
+    @Test
+    public void withArguments() {
+        final Bundle bundle = generateTestBundle();
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment(), TestActivity.class, bundle);
+
+        controller.create();
+        final Bundle args = controller.get().getArguments();
+
+        assertThat(args.getString("test_key")).isEqualTo("test_value");
+    }
+
+    @Test
+    public void withIntentAndArguments() {
+        final Bundle bundle = generateTestBundle();
+        final Intent intent = generateTestIntent();
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment(), TestActivity.class, intent, bundle);
+
+        controller.create();
+        shadowOf(getMainLooper()).idle();
+        final Intent intentInFragment = controller.get().getActivity().getIntent();
+        final Bundle args = controller.get().getArguments();
+
+        assertThat(intentInFragment.getAction()).isEqualTo("test_action");
+        assertThat(intentInFragment.getExtras().getString("test_key")).isEqualTo("test_value");
+        assertThat(args.getString("test_key")).isEqualTo("test_value");
+    }
+
+    @Test
+    public void visible() {
+        final FragmentController<TranscriptFragment> controller =
+                FragmentController.of(new TranscriptFragment(), TestActivity.class);
+
+        controller.create().start().resume();
+
+        assertThat(controller.get().isVisible()).isFalse();
+
+        controller.visible();
+
+        assertThat(controller.get().isVisible()).isTrue();
+    }
+
+    @Test
+    public void setupFragmentWithFragment_fragmentHasCorrectLifecycle() {
+        TranscriptFragment fragment = FragmentController.setupFragment(new TranscriptFragment());
+
+        assertThat(fragment.getLifecycleEvents())
+                .containsExactly("onCreate", "onStart", "onResume")
+                .inOrder();
+        assertThat(fragment.isVisible()).isTrue();
+    }
+
+    @Test
+    public void setupFragmentWithFragmentAndActivity_fragmentHasCorrectLifecycle() {
+        TranscriptFragment fragment =
+                FragmentController.setupFragment(new TranscriptFragment(), TestActivity.class);
+
+        assertThat(fragment.getLifecycleEvents())
+                .containsExactly("onCreate", "onStart", "onResume")
+                .inOrder();
+        assertThat(fragment.isVisible()).isTrue();
+    }
+
+    @Test
+    public void setupFragmentWithFragmentAndActivityAndBundle_HasCorrectLifecycle() {
+        Bundle testBundle = generateTestBundle();
+        TranscriptFragment fragment =
+                FragmentController.setupFragment(new TranscriptFragment(), TestActivity.class,
+                        testBundle);
+
+        assertThat(fragment.getLifecycleEvents())
+                .containsExactly("onCreate", "onStart", "onResume")
+                .inOrder();
+        assertThat(fragment.isVisible()).isTrue();
+    }
+
+    @Test
+    public void
+            setupFragmentWithFragment_Activity_ContainViewIdAndBundle_HasCorrectLifecycle() {
+        Bundle testBundle = generateTestBundle();
+        TranscriptFragment fragment =
+                FragmentController.setupFragment(
+                        new TranscriptFragment(),
+                        CustomizedViewIdTestActivity.class,
+                        R.id.custom_activity_view,
+                        testBundle);
+
+        assertThat(fragment.getLifecycleEvents())
+                .containsExactly("onCreate", "onStart", "onResume")
+                .inOrder();
+        assertThat(fragment.isVisible()).isTrue();
+    }
+
+    private Intent generateTestIntent() {
+        final Intent testIntent = new Intent("test_action").putExtra("test_key", "test_value");
+        return testIntent;
+    }
+
+    private Bundle generateTestBundle() {
+        final Bundle testBundle = new Bundle();
+        testBundle.putString("test_key", "test_value");
+
+        return testBundle;
+    }
+
+    /** A Fragment which can record lifecycle status for test. */
+    public static class TranscriptFragment extends Fragment {
+
+        public static final List<String> sLifecycleEvents = new ArrayList<>();
+
+        @Override
+        public void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            sLifecycleEvents.add("onCreate");
+        }
+
+        @Override
+        public void onStart() {
+            super.onStart();
+            sLifecycleEvents.add("onStart");
+        }
+
+        @Override
+        public void onResume() {
+            super.onResume();
+            sLifecycleEvents.add("onResume");
+        }
+
+        @Override
+        public void onPause() {
+            super.onPause();
+            sLifecycleEvents.add("onPause");
+        }
+
+        @Override
+        public void onStop() {
+            super.onStop();
+            sLifecycleEvents.add("onStop");
+        }
+
+        @Override
+        public View onCreateView(
+                LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+            return inflater.inflate(R.layout.fragment_contents, container, false);
+        }
+
+        public List<String> getLifecycleEvents() {
+            return sLifecycleEvents;
+        }
+
+        public static void clearLifecycleEvents() {
+            sLifecycleEvents.clear();
+        }
+    }
+
+    /** A Activity which set a default view for test. */
+    public static class TestActivity extends FragmentActivity {
+        @Override
+        protected void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            LinearLayout view = new LinearLayout(this);
+            view.setId(1);
+
+            setContentView(view);
+        }
+    }
+
+    /** A Activity which has a custom view for test. */
+    public static class CustomizedViewIdTestActivity extends FragmentActivity {
+        @Override
+        protected void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            setContentView(R.layout.custom_activity_view);
+        }
+    }
+}
diff --git a/packages/SettingsLib/tests/robotests/fragment/src/test/resources/res/layout/custom_activity_view.xml b/packages/SettingsLib/tests/robotests/fragment/src/test/resources/res/layout/custom_activity_view.xml
new file mode 100644
index 0000000..c074f30
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/fragment/src/test/resources/res/layout/custom_activity_view.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/custom_activity_view"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:orientation="vertical">
+
+</LinearLayout>
diff --git a/packages/SettingsLib/tests/robotests/fragment/src/test/resources/res/layout/fragment_contents.xml b/packages/SettingsLib/tests/robotests/fragment/src/test/resources/res/layout/fragment_contents.xml
new file mode 100644
index 0000000..425b2bb
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/fragment/src/test/resources/res/layout/fragment_contents.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:orientation="vertical">
+
+  <TextView
+      android:id="@+id/tacos"
+      android:layout_width="wrap_content"
+      android:layout_height="wrap_content"
+      android:text="TACOS"/>
+
+  <TextView
+      android:id="@+id/burritos"
+      android:layout_width="wrap_content"
+      android:layout_height="wrap_content"
+      android:text="BURRITOS"/>
+
+</LinearLayout>
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java
index 4a913c8..bb72375 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java
@@ -25,7 +25,6 @@
 import static org.mockito.Mockito.when;
 
 import android.app.ActivityManager;
-import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.res.Resources;
@@ -58,12 +57,10 @@
 import org.robolectric.shadows.ShadowSettings;
 
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
 
 @RunWith(RobolectricTestRunner.class)
-@Config(shadows = {UtilsTest.ShadowSecure.class, UtilsTest.ShadowLocationManager.class})
+@Config(shadows = {UtilsTest.ShadowLocationManager.class})
 public class UtilsTest {
     private static final double[] TEST_PERCENTAGES = {0, 0.4, 0.5, 0.6, 49, 49.3, 49.8, 50, 100};
     private static final String TAG = "UtilsTest";
@@ -94,7 +91,7 @@
         mContext = spy(RuntimeEnvironment.application);
         when(mContext.getSystemService(Context.LOCATION_SERVICE)).thenReturn(mLocationManager);
         when(mContext.getSystemService(UsbManager.class)).thenReturn(mUsbManager);
-        ShadowSecure.reset();
+        ShadowSettings.ShadowSecure.reset();
         mAudioManager = mContext.getSystemService(AudioManager.class);
     }
 
@@ -111,15 +108,16 @@
                 Settings.Secure.LOCATION_CHANGER_QUICK_SETTINGS);
 
         assertThat(Settings.Secure.getInt(mContext.getContentResolver(),
-                Settings.Secure.LOCATION_CHANGER, Settings.Secure.LOCATION_CHANGER_UNKNOWN))
-                .isEqualTo(Settings.Secure.LOCATION_CHANGER_QUICK_SETTINGS);
+                Settings.Secure.LOCATION_CHANGER,
+                Settings.Secure.LOCATION_CHANGER_UNKNOWN)).isEqualTo(
+                Settings.Secure.LOCATION_CHANGER_QUICK_SETTINGS);
     }
 
     @Test
     public void testFormatPercentage_RoundTrue_RoundUpIfPossible() {
-        final String[] expectedPercentages = {PERCENTAGE_0, PERCENTAGE_0, PERCENTAGE_1,
-                PERCENTAGE_1, PERCENTAGE_49, PERCENTAGE_49, PERCENTAGE_50, PERCENTAGE_50,
-                PERCENTAGE_100};
+        final String[] expectedPercentages =
+                {PERCENTAGE_0, PERCENTAGE_0, PERCENTAGE_1, PERCENTAGE_1, PERCENTAGE_49,
+                        PERCENTAGE_49, PERCENTAGE_50, PERCENTAGE_50, PERCENTAGE_100};
 
         for (int i = 0, size = TEST_PERCENTAGES.length; i < size; i++) {
             final String percentage = Utils.formatPercentage(TEST_PERCENTAGES[i], true);
@@ -129,9 +127,9 @@
 
     @Test
     public void testFormatPercentage_RoundFalse_NoRound() {
-        final String[] expectedPercentages = {PERCENTAGE_0, PERCENTAGE_0, PERCENTAGE_0,
-                PERCENTAGE_0, PERCENTAGE_49, PERCENTAGE_49, PERCENTAGE_49, PERCENTAGE_50,
-                PERCENTAGE_100};
+        final String[] expectedPercentages =
+                {PERCENTAGE_0, PERCENTAGE_0, PERCENTAGE_0, PERCENTAGE_0, PERCENTAGE_49,
+                        PERCENTAGE_49, PERCENTAGE_49, PERCENTAGE_50, PERCENTAGE_100};
 
         for (int i = 0, size = TEST_PERCENTAGES.length; i < size; i++) {
             final String percentage = Utils.formatPercentage(TEST_PERCENTAGES[i], false);
@@ -143,12 +141,7 @@
     public void testGetDefaultStorageManagerDaysToRetain_storageManagerDaysToRetainUsesResources() {
         Resources resources = mock(Resources.class);
         when(resources.getInteger(
-                eq(
-                        com.android
-                                .internal
-                                .R
-                                .integer
-                                .config_storageManagerDaystoRetainDefault)))
+                eq(com.android.internal.R.integer.config_storageManagerDaystoRetainDefault)))
                 .thenReturn(60);
         assertThat(Utils.getDefaultStorageManagerDaysToRetain(resources)).isEqualTo(60);
     }
@@ -163,31 +156,6 @@
         return intent -> TextUtils.equals(expected, intent.getAction());
     }
 
-    @Implements(value = Settings.Secure.class)
-    public static class ShadowSecure extends ShadowSettings.ShadowSecure {
-        private static Map<String, Integer> map = new HashMap<>();
-
-        @Implementation
-        public static boolean putIntForUser(ContentResolver cr, String name, int value,
-                int userHandle) {
-            map.put(name, value);
-            return true;
-        }
-
-        @Implementation
-        public static int getIntForUser(ContentResolver cr, String name, int def, int userHandle) {
-            if (map.containsKey(name)) {
-                return map.get(name);
-            } else {
-                return def;
-            }
-        }
-
-        public static void reset() {
-            map.clear();
-        }
-    }
-
     @Implements(value = LocationManager.class)
     public static class ShadowLocationManager {
 
@@ -337,9 +305,8 @@
 
     @Test
     public void getBatteryStatus_statusIsFull_returnFullString() {
-        final Intent intent = new Intent()
-                .putExtra(BatteryManager.EXTRA_LEVEL, 100)
-                .putExtra(BatteryManager.EXTRA_SCALE, 100);
+        final Intent intent = new Intent().putExtra(BatteryManager.EXTRA_LEVEL, 100).putExtra(
+                BatteryManager.EXTRA_SCALE, 100);
         final Resources resources = mContext.getResources();
 
         assertThat(Utils.getBatteryStatus(mContext, intent, /* compactStatus= */ false)).isEqualTo(
@@ -348,9 +315,8 @@
 
     @Test
     public void getBatteryStatus_statusIsFullAndUseCompactStatus_returnFullyChargedString() {
-        final Intent intent = new Intent()
-                .putExtra(BatteryManager.EXTRA_LEVEL, 100)
-                .putExtra(BatteryManager.EXTRA_SCALE, 100);
+        final Intent intent = new Intent().putExtra(BatteryManager.EXTRA_LEVEL, 100).putExtra(
+                BatteryManager.EXTRA_SCALE, 100);
         final Resources resources = mContext.getResources();
 
         assertThat(Utils.getBatteryStatus(mContext, intent, /* compactStatus= */ true)).isEqualTo(
@@ -516,7 +482,6 @@
         when(mUsbPort.getStatus()).thenReturn(mUsbPortStatus);
         when(mUsbPort.supportsComplianceWarnings()).thenReturn(true);
         when(mUsbPortStatus.isConnected()).thenReturn(true);
-        when(mUsbPortStatus.getComplianceWarnings())
-                .thenReturn(new int[]{complianceWarningType});
+        when(mUsbPortStatus.getComplianceWarnings()).thenReturn(new int[]{complianceWarningType});
     }
 }
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/accessibility/AccessibilityUtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/accessibility/AccessibilityUtilsTest.java
index 44fdaec..3de8446 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/accessibility/AccessibilityUtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/accessibility/AccessibilityUtilsTest.java
@@ -23,13 +23,17 @@
 import android.os.UserHandle;
 import android.provider.Settings;
 
+import com.android.settingslib.testutils.shadow.ShadowSecure;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.robolectric.RobolectricTestRunner;
 import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
 
 @RunWith(RobolectricTestRunner.class)
+@Config(shadows = {ShadowSecure.class})
 public class AccessibilityUtilsTest {
 
     private Context mContext;
@@ -46,7 +50,7 @@
 
     @Test
     public void getEnabledServicesFromSettings_badFormat_emptyResult() {
-        Settings.Secure.putStringForUser(
+        ShadowSecure.putStringForUser(
                 mContext.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
                 ":",
                 UserHandle.myUserId());
@@ -57,7 +61,7 @@
     @Test
     public void getEnabledServicesFromSettings_1Service_1result() {
         final ComponentName cn = new ComponentName("pkg", "serv");
-        Settings.Secure.putStringForUser(
+        ShadowSecure.putStringForUser(
                 mContext.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
                 cn.flattenToString() + ":",
                 UserHandle.myUserId());
@@ -70,7 +74,7 @@
     public void getEnabledServicesFromSettings_2Services_2results() {
         final ComponentName cn1 = new ComponentName("pkg", "serv");
         final ComponentName cn2 = new ComponentName("pkg", "serv2");
-        Settings.Secure.putStringForUser(
+        ShadowSecure.putStringForUser(
                 mContext.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
                 cn1.flattenToString() + ":" + cn2.flattenToString(),
                 UserHandle.myUserId());
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/applications/RecentAppOpsAccessesTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/applications/RecentAppOpsAccessesTest.java
index cb62a73..f9505dd 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/applications/RecentAppOpsAccessesTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/applications/RecentAppOpsAccessesTest.java
@@ -37,6 +37,8 @@
 import android.os.UserManager;
 import android.util.LongSparseArray;
 
+import com.android.settingslib.testutils.shadow.ShadowPermissionChecker;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -45,7 +47,6 @@
 import org.robolectric.RobolectricTestRunner;
 import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Config;
-import org.robolectric.shadows.ShadowPermissionChecker;
 
 import java.time.Clock;
 import java.util.ArrayList;
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/MetricsFeatureProviderTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/MetricsFeatureProviderTest.java
index dd8d54a..a2e8c59 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/MetricsFeatureProviderTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/MetricsFeatureProviderTest.java
@@ -38,6 +38,7 @@
 import org.robolectric.Robolectric;
 import org.robolectric.RobolectricTestRunner;
 import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.LooperMode;
 import org.robolectric.util.ReflectionHelpers;
 
 import java.util.ArrayList;
@@ -167,6 +168,7 @@
     }
 
     @Test
+    @LooperMode(LooperMode.Mode.PAUSED)
     public void getAttribution_notSet_shouldReturnUnknown() {
         final Activity activity = Robolectric.setupActivity(Activity.class);
 
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/SettingsJankMonitorTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/SettingsJankMonitorTest.java
index d67d44b..25833b3 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/SettingsJankMonitorTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/SettingsJankMonitorTest.java
@@ -36,6 +36,7 @@
 
 import com.android.internal.jank.InteractionJankMonitor;
 import com.android.internal.jank.InteractionJankMonitor.CujType;
+import com.android.settingslib.testutils.OverpoweredReflectionHelper;
 import com.android.settingslib.testutils.shadow.ShadowInteractionJankMonitor;
 
 import org.junit.Before;
@@ -51,7 +52,6 @@
 import org.robolectric.annotation.Implementation;
 import org.robolectric.annotation.Implements;
 import org.robolectric.annotation.Resetter;
-import org.robolectric.util.ReflectionHelpers;
 
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
@@ -83,8 +83,10 @@
     public void setUp() {
         ShadowInteractionJankMonitor.reset();
         when(ShadowInteractionJankMonitor.MOCK_INSTANCE.begin(any())).thenReturn(true);
-        ReflectionHelpers.setStaticField(SettingsJankMonitor.class, "scheduledExecutorService",
-                mScheduledExecutorService);
+        OverpoweredReflectionHelper
+                .setStaticField(SettingsJankMonitor.class,
+                        "scheduledExecutorService",
+                        mScheduledExecutorService);
     }
 
     @Test
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/lifecycle/HideNonSystemOverlayMixinTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/lifecycle/HideNonSystemOverlayMixinTest.java
index cf702b53..471dac0 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/lifecycle/HideNonSystemOverlayMixinTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/lifecycle/HideNonSystemOverlayMixinTest.java
@@ -37,8 +37,10 @@
 import org.robolectric.Robolectric;
 import org.robolectric.RobolectricTestRunner;
 import org.robolectric.android.controller.ActivityController;
+import org.robolectric.annotation.LooperMode;
 
 @RunWith(RobolectricTestRunner.class)
+@LooperMode(LooperMode.Mode.PAUSED)
 public class HideNonSystemOverlayMixinTest {
 
     private ActivityController<TestActivity> mActivityController;
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/development/DevelopmentSettingsEnablerTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/development/DevelopmentSettingsEnablerTest.java
index 3475ff7..b009abd 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/development/DevelopmentSettingsEnablerTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/development/DevelopmentSettingsEnablerTest.java
@@ -22,13 +22,14 @@
 import android.os.UserManager;
 import android.provider.Settings;
 
+import com.android.settingslib.testutils.shadow.ShadowUserManager;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.robolectric.RobolectricTestRunner;
 import org.robolectric.RuntimeEnvironment;
 import org.robolectric.shadow.api.Shadow;
-import org.robolectric.shadows.ShadowUserManager;
 
 @RunWith(RobolectricTestRunner.class)
 public class DevelopmentSettingsEnablerTest {
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/license/LicenseHtmlGeneratorFromXmlTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/license/LicenseHtmlGeneratorFromXmlTest.java
index 8e33ca3..0cabab2 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/license/LicenseHtmlGeneratorFromXmlTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/license/LicenseHtmlGeneratorFromXmlTest.java
@@ -21,6 +21,7 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.LooperMode;
 import org.xmlpull.v1.XmlPullParserException;
 
 import java.io.ByteArrayInputStream;
@@ -269,6 +270,7 @@
     }
 
     @Test
+    @LooperMode(LooperMode.Mode.PAUSED)
     public void testGenerateHtmlWithCustomHeading() throws Exception {
         List<File> xmlFiles = new ArrayList<>();
         Map<String, Map<String, Set<String>>> fileNameToLibraryToContentIdMap = new HashMap<>();
@@ -292,6 +294,7 @@
     }
 
     @Test
+    @LooperMode(LooperMode.Mode.PAUSED)
     public void testGenerateNewHtmlWithCustomHeading() throws Exception {
         List<File> xmlFiles = new ArrayList<>();
         Map<String, Map<String, Set<String>>> fileNameToLibraryToContentIdMap = new HashMap<>();
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/package-info.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/package-info.java
new file mode 100644
index 0000000..9e9725f
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+@LooperMode(LooperMode.Mode.LEGACY)
+package com.android.settingslib;
+
+import org.robolectric.annotation.LooperMode;
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/AnimatedImageViewTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/AnimatedImageViewTest.java
index d41d511..faec02f7 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/AnimatedImageViewTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/AnimatedImageViewTest.java
@@ -27,6 +27,7 @@
 import org.junit.runner.RunWith;
 import org.robolectric.Robolectric;
 import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.LooperMode;
 
 @RunWith(RobolectricTestRunner.class)
 public class AnimatedImageViewTest {
@@ -40,6 +41,7 @@
     }
 
     @Test
+    @LooperMode(LooperMode.Mode.PAUSED)
     public void testAnimation_ViewVisible_AnimationRunning() {
         mAnimatedImageView.setVisibility(View.VISIBLE);
         mAnimatedImageView.setAnimating(true);
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BannerMessagePreferenceTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BannerMessagePreferenceTest.java
index 0a48f19..0d88913 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BannerMessagePreferenceTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BannerMessagePreferenceTest.java
@@ -41,6 +41,8 @@
 import androidx.preference.PreferenceViewHolder;
 import androidx.preference.R;
 
+import com.android.settingslib.testutils.OverpoweredReflectionHelper;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -502,14 +504,18 @@
     private void assumeAndroidR() {
         ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 30);
         ReflectionHelpers.setStaticField(Build.VERSION.class, "CODENAME", "R");
-        ReflectionHelpers.setStaticField(BannerMessagePreference.class, "IS_AT_LEAST_S", false);
+        OverpoweredReflectionHelper
+                .setStaticField(BannerMessagePreference.class, "IS_AT_LEAST_S", false);
         // Reset view holder to use correct layout.
     }
 
+
+
     private void assumeAndroidS() {
         ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 31);
         ReflectionHelpers.setStaticField(Build.VERSION.class, "CODENAME", "S");
-        ReflectionHelpers.setStaticField(BannerMessagePreference.class, "IS_AT_LEAST_S", true);
+        OverpoweredReflectionHelper
+                .setStaticField(BannerMessagePreference.class, "IS_AT_LEAST_S", true);
         // Re-inflate view to update layout.
         setUpViewHolder();
     }
diff --git a/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/OverpoweredReflectionHelper.java b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/OverpoweredReflectionHelper.java
new file mode 100644
index 0000000..4fcc5a1
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/OverpoweredReflectionHelper.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.testutils;
+
+import org.robolectric.util.ReflectionHelpers;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+public class OverpoweredReflectionHelper extends ReflectionHelpers {
+
+    /**
+     * Robolectric upstream does not rely on or encourage this behaviour.
+     *
+     * @param field
+     */
+    private static void makeFieldVeryAccessible(Field field) {
+        field.setAccessible(true);
+        // remove 'final' modifier if present
+        if ((field.getModifiers() & Modifier.FINAL) == Modifier.FINAL) {
+            Field modifiersField = getModifiersField();
+            modifiersField.setAccessible(true);
+            try {
+                modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
+            } catch (IllegalAccessException e) {
+
+                throw new AssertionError(e);
+            }
+        }
+    }
+
+    private static Field getModifiersField() {
+        try {
+            return Field.class.getDeclaredField("modifiers");
+        } catch (NoSuchFieldException e) {
+            try {
+                Method getFieldsMethod =
+                        Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class);
+                getFieldsMethod.setAccessible(true);
+                Field[] fields = (Field[]) getFieldsMethod.invoke(Field.class, false);
+                for (Field modifiersField : fields) {
+                    if ("modifiers".equals(modifiersField.getName())) {
+                        return modifiersField;
+                    }
+                }
+            } catch (ReflectiveOperationException innerE) {
+                throw new AssertionError(innerE);
+            }
+        }
+        throw new AssertionError();
+    }
+
+    /**
+     * Reflectively set the value of a static field.
+     *
+     * @param field Field object.
+     * @param fieldNewValue The new value.
+     */
+    public static void setStaticField(Field field, Object fieldNewValue) {
+        try {
+            makeFieldVeryAccessible(field);
+            field.setAccessible(true);
+            field.set(null, fieldNewValue);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * Reflectively set the value of a static field.
+     *
+     * @param clazz Target class.
+     * @param fieldName The field name.
+     * @param fieldNewValue The new value.
+     */
+    public static void setStaticField(Class<?> clazz, String fieldName, Object fieldNewValue) {
+        try {
+            setStaticField(clazz.getDeclaredField(fieldName), fieldNewValue);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+}
diff --git a/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowActivityManager.java b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowActivityManager.java
index 924eb04..0b9ba8d 100644
--- a/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowActivityManager.java
+++ b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowActivityManager.java
@@ -16,23 +16,27 @@
 
 package com.android.settingslib.testutils.shadow;
 
+import static android.os.Build.VERSION_CODES.O;
+
 import android.app.ActivityManager;
+import android.app.IActivityManager;
 
 import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Implementation;
 import org.robolectric.annotation.Implements;
 import org.robolectric.annotation.Resetter;
 import org.robolectric.shadow.api.Shadow;
+import org.robolectric.util.ReflectionHelpers;
 
 @Implements(ActivityManager.class)
 public class ShadowActivityManager {
     private static int sCurrentUserId = 0;
-    private int mUserSwitchedTo = -1;
+    private static int sUserSwitchedTo = -1;
 
     @Resetter
-    public void reset() {
+    public static void reset() {
         sCurrentUserId = 0;
-        mUserSwitchedTo = 0;
+        sUserSwitchedTo = 0;
     }
 
     @Implementation
@@ -42,16 +46,21 @@
 
     @Implementation
     protected boolean switchUser(int userId) {
-        mUserSwitchedTo = userId;
+        sUserSwitchedTo = userId;
         return true;
     }
 
+    @Implementation(minSdk = O)
+    protected static IActivityManager getService() {
+        return ReflectionHelpers.createNullProxy(IActivityManager.class);
+    }
+
     public boolean getSwitchUserCalled() {
-        return mUserSwitchedTo != -1;
+        return sUserSwitchedTo != -1;
     }
 
     public int getUserSwitchedTo() {
-        return mUserSwitchedTo;
+        return sUserSwitchedTo;
     }
 
     public static void setCurrentUser(int userId) {
diff --git a/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowDefaultDialerManager.java b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowDefaultDialerManager.java
index 2c0792f..bbfdb7f 100644
--- a/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowDefaultDialerManager.java
+++ b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowDefaultDialerManager.java
@@ -29,7 +29,7 @@
     private static String sDefaultDialer;
 
     @Resetter
-    public void reset() {
+    public static void reset() {
         sDefaultDialer = null;
     }
 
diff --git a/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowPermissionChecker.java b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowPermissionChecker.java
new file mode 100644
index 0000000..fae3aea
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowPermissionChecker.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.testutils.shadow;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.AttributionSource;
+import android.content.Context;
+import android.content.PermissionChecker;
+
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+
+import java.util.HashMap;
+import java.util.Map;
+/** Shadow class of {@link PermissionChecker}. */
+@Implements(PermissionChecker.class)
+public class ShadowPermissionChecker {
+    private static final Map<String, Map<String, Integer>> RESULTS = new HashMap<>();
+    /** Set the result of permission check for a specific permission. */
+    public static void setResult(String packageName, String permission, int result) {
+        if (!RESULTS.containsKey(packageName)) {
+            RESULTS.put(packageName, new HashMap<>());
+        }
+        RESULTS.get(packageName).put(permission, result);
+    }
+    /** Check the permission of calling package. */
+    @Implementation
+    public static int checkCallingPermissionForDataDelivery(
+            Context context,
+            String permission,
+            String packageName,
+            String attributionTag,
+            String message) {
+        return RESULTS.containsKey(packageName) && RESULTS.get(packageName).containsKey(permission)
+                ? RESULTS.get(packageName).get(permission)
+                : PermissionChecker.checkCallingPermissionForDataDelivery(
+                        context, permission, packageName, attributionTag, message);
+    }
+    /** Check general permission. */
+    @Implementation
+    public static int checkPermissionForDataDelivery(
+            Context context,
+            String permission,
+            int pid,
+            int uid,
+            String packageName,
+            String attributionTag,
+            String message) {
+        return RESULTS.containsKey(packageName) && RESULTS.get(packageName).containsKey(permission)
+                ? RESULTS.get(packageName).get(permission)
+                : PermissionChecker.checkPermissionForDataDelivery(
+                        context, permission, pid, uid, packageName, attributionTag, message);
+    }
+    /** Check general permission. */
+    @Implementation
+    public static int checkPermissionForPreflight(@NonNull Context context,
+            @NonNull String permission, int pid, int uid, @Nullable String packageName) {
+        return checkPermissionForPreflight(context, permission, new AttributionSource(
+                uid, packageName, null /*attributionTag*/));
+    }
+    /** Check general permission. */
+    @Implementation
+    public static int checkPermissionForPreflight(@NonNull Context context,
+            @NonNull String permission, @NonNull AttributionSource attributionSource) {
+        final String packageName = attributionSource.getPackageName();
+        return RESULTS.containsKey(packageName) && RESULTS.get(packageName).containsKey(permission)
+                ? RESULTS.get(packageName).get(permission)
+                : PermissionChecker.checkPermissionForPreflight(
+                        context, permission, attributionSource);
+    }
+}
diff --git a/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowSecure.java b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowSecure.java
new file mode 100644
index 0000000..70ebc67
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowSecure.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.testutils.shadow;
+
+import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
+
+import android.content.ContentResolver;
+import android.provider.Settings;
+
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+import org.robolectric.shadows.ShadowSettings;
+
+@Implements(value = Settings.Secure.class)
+public class ShadowSecure extends ShadowSettings.ShadowSecure {
+    @Implementation(minSdk = JELLY_BEAN_MR1)
+    public static boolean putStringForUser(ContentResolver cr, String name, String value,
+            int userHandle) {
+        return putString(cr, name, value);
+    }
+}
diff --git a/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowSmsApplication.java b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowSmsApplication.java
index 381d072..5ac0a87 100644
--- a/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowSmsApplication.java
+++ b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowSmsApplication.java
@@ -31,7 +31,7 @@
     private static ComponentName sDefaultSmsApplication;
 
     @Resetter
-    public void reset() {
+    public static void reset() {
         sDefaultSmsApplication = null;
     }
 
diff --git a/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowUserManager.java b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowUserManager.java
index ca1eefc..60d7721 100644
--- a/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowUserManager.java
+++ b/packages/SettingsLib/tests/robotests/testutils/com/android/settingslib/testutils/shadow/ShadowUserManager.java
@@ -16,20 +16,28 @@
 
 package com.android.settingslib.testutils.shadow;
 
+import static android.os.Build.VERSION_CODES.N_MR1;
+
 import android.annotation.UserIdInt;
 import android.content.Context;
 import android.content.pm.UserInfo;
+import android.content.pm.UserProperties;
+import android.os.UserHandle;
 import android.os.UserManager;
 
 import org.robolectric.annotation.Implementation;
 import org.robolectric.annotation.Implements;
+import org.robolectric.shadows.ShadowBuild;
 
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
 @Implements(value = UserManager.class)
 public class ShadowUserManager extends org.robolectric.shadows.ShadowUserManager {
     private List<UserInfo> mUserInfos = addProfile(0, "Owner");
+    private final Map<Integer, UserProperties> mUserPropertiesMap = new HashMap<>();
 
     @Implementation
     protected static UserManager get(Context context) {
@@ -62,4 +70,37 @@
     protected List<UserInfo> getProfiles(@UserIdInt int userHandle) {
         return getProfiles();
     }
+
+    /**
+     * @return {@code false} by default, or the value specified via {@link #setIsAdminUser(boolean)}
+     */
+    @Implementation(minSdk = N_MR1)
+    public boolean isAdminUser() {
+        return getUserInfo(UserHandle.myUserId()).isAdmin();
+    }
+
+    /**
+     * Sets that the current user is an admin user; controls the return value of
+     * {@link UserManager#isAdminUser}.
+     */
+    public void setIsAdminUser(boolean isAdminUser) {
+        UserInfo userInfo = getUserInfo(UserHandle.myUserId());
+        if (isAdminUser) {
+            userInfo.flags |= UserInfo.FLAG_ADMIN;
+        } else {
+            userInfo.flags &= ~UserInfo.FLAG_ADMIN;
+        }
+    }
+
+    public void setupUserProperty(int userId, int showInSettings) {
+        UserProperties userProperties = new UserProperties(new UserProperties.Builder()
+                .setShowInSettings(showInSettings).build());
+        mUserPropertiesMap.putIfAbsent(userId, userProperties);
+    }
+
+    @Implementation(minSdk = ShadowBuild.UPSIDE_DOWN_CAKE)
+    protected UserProperties getUserProperties(UserHandle user) {
+        return mUserPropertiesMap.getOrDefault(user.getIdentifier(),
+            new UserProperties(new UserProperties.Builder().build()));
+    }
 }
diff --git a/packages/SystemUI/res-keyguard/layout/shade_carrier_new.xml b/packages/SystemUI/res-keyguard/layout/shade_carrier_new.xml
new file mode 100644
index 0000000..952f056
--- /dev/null
+++ b/packages/SystemUI/res-keyguard/layout/shade_carrier_new.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+**
+** Copyright 2023, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+-->
+<com.android.systemui.statusbar.pipeline.mobile.ui.view.ModernShadeCarrierGroupMobileView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/carrier_combo"
+    android:layout_width="wrap_content"
+    android:layout_height="match_parent"
+    android:gravity="center_vertical"
+    android:orientation="horizontal" >
+
+    <com.android.systemui.util.AutoMarqueeTextView
+        android:id="@+id/mobile_carrier_text"
+        android:layout_width="0dp"
+        android:layout_height="wrap_content"
+        android:layout_weight="1"
+        android:layout_marginEnd="@dimen/qs_carrier_margin_width"
+        android:visibility="gone"
+        android:textDirection="locale"
+        android:marqueeRepeatLimit="marquee_forever"
+        android:singleLine="true"
+        android:maxEms="7"/>
+
+    <include layout="@layout/status_bar_mobile_signal_group_new" />
+
+</com.android.systemui.statusbar.pipeline.mobile.ui.view.ModernShadeCarrierGroupMobileView>
+
diff --git a/packages/SystemUI/res/drawable/auth_credential_emergency_button_background.xml b/packages/SystemUI/res/drawable/auth_credential_emergency_button_background.xml
new file mode 100644
index 0000000..85450b4
--- /dev/null
+++ b/packages/SystemUI/res/drawable/auth_credential_emergency_button_background.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2023 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+<inset xmlns:android="http://schemas.android.com/apk/res/android">
+    <shape android:shape="rectangle">
+        <corners android:radius="25dp"/>
+        <solid android:color="@android:color/system_accent3_100" />
+    </shape>
+</inset>
diff --git a/packages/SystemUI/res/drawable/stat_sys_ringer_silent.xml b/packages/SystemUI/res/drawable/stat_sys_ringer_silent.xml
index 4a9d41f..b83f15a 100644
--- a/packages/SystemUI/res/drawable/stat_sys_ringer_silent.xml
+++ b/packages/SystemUI/res/drawable/stat_sys_ringer_silent.xml
@@ -14,6 +14,4 @@
     limitations under the License.
 -->
 <inset xmlns:android="http://schemas.android.com/apk/res/android"
-    android:insetLeft="3dp"
-    android:insetRight="3dp"
     android:drawable="@drawable/ic_speaker_mute" />
diff --git a/packages/SystemUI/res/layout-land/auth_credential_password_view.xml b/packages/SystemUI/res/layout-land/auth_credential_password_view.xml
index e2ce34f..e439f77 100644
--- a/packages/SystemUI/res/layout-land/auth_credential_password_view.xml
+++ b/packages/SystemUI/res/layout-land/auth_credential_password_view.xml
@@ -61,29 +61,46 @@
 
     </RelativeLayout>
 
-    <LinearLayout
+    <FrameLayout
         android:id="@+id/auth_credential_input"
-        android:layout_width="wrap_content"
+        android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical">
 
-        <ImeAwareEditText
-            android:id="@+id/lockPassword"
-            style="?passwordTextAppearance"
-            android:layout_width="208dp"
-            android:layout_height="wrap_content"
-            android:layout_gravity="center"
-            android:imeOptions="actionNext|flagNoFullscreen|flagForceAscii"
-            android:inputType="textPassword"
-            android:minHeight="48dp" />
-
-        <TextView
-            android:id="@+id/error"
-            style="?errorTextAppearance"
-            android:layout_gravity="center"
+        <LinearLayout
             android:layout_width="wrap_content"
-            android:layout_height="wrap_content" />
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_horizontal|top"
+            android:orientation="vertical">
 
-    </LinearLayout>
+            <ImeAwareEditText
+                android:id="@+id/lockPassword"
+                style="?passwordTextAppearance"
+                android:layout_width="208dp"
+                android:layout_height="wrap_content"
+                android:layout_gravity="center_horizontal"
+                android:imeOptions="actionNext|flagNoFullscreen|flagForceAscii"
+                android:inputType="textPassword"
+                android:minHeight="48dp"/>
+
+            <TextView
+                android:id="@+id/error"
+                style="?errorTextAppearance"
+                android:layout_gravity="center_horizontal"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"/>
+        </LinearLayout>
+
+        <Button
+            android:id="@+id/emergencyCallButton"
+            style="@style/AuthCredentialEmergencyButtonStyle"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:visibility="gone"
+            android:layout_gravity="center_horizontal|bottom"
+            android:layout_marginTop="12dp"
+            android:layout_marginBottom="12dp"
+            android:text="@string/work_challenge_emergency_button_text"/>
+    </FrameLayout>
 
 </com.android.systemui.biometrics.ui.CredentialPasswordView>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout-land/auth_credential_pattern_view.xml b/packages/SystemUI/res/layout-land/auth_credential_pattern_view.xml
index 88f138f..d5af377 100644
--- a/packages/SystemUI/res/layout-land/auth_credential_pattern_view.xml
+++ b/packages/SystemUI/res/layout-land/auth_credential_pattern_view.xml
@@ -60,27 +60,44 @@
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"/>
 
+        <TextView
+            android:id="@+id/error"
+            style="?errorTextAppearanceLand"
+            android:layout_below="@id/description"
+            android:layout_alignParentLeft="true"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"/>
+
     </RelativeLayout>
 
-    <FrameLayout
+    <RelativeLayout
         android:layout_weight="1"
-        style="?containerStyle"
         android:layout_width="0dp"
         android:layout_height="match_parent">
 
-        <com.android.internal.widget.LockPatternView
-            android:id="@+id/lockPattern"
-            android:layout_gravity="center"
-            android:layout_width="@dimen/biometric_auth_pattern_view_size"
-            android:layout_height="@dimen/biometric_auth_pattern_view_size"/>
-
-        <TextView
-            android:id="@+id/error"
-            style="?errorTextAppearance"
+        <FrameLayout
+            style="?containerStyle"
+            android:layout_above="@id/emergencyCallButton"
             android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_gravity="center_horizontal|bottom"/>
+            android:layout_height="match_parent">
 
-    </FrameLayout>
+            <com.android.internal.widget.LockPatternView
+                android:id="@+id/lockPattern"
+                android:layout_gravity="center"
+                android:layout_width="@dimen/biometric_auth_pattern_view_size"
+                android:layout_height="@dimen/biometric_auth_pattern_view_size"/>
+        </FrameLayout>
+
+        <Button
+            android:id="@+id/emergencyCallButton"
+            style="@style/AuthCredentialEmergencyButtonStyle"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginBottom="35dp"
+            android:visibility="gone"
+            android:layout_alignParentBottom="true"
+            android:layout_centerHorizontal="true"
+            android:text="@string/work_challenge_emergency_button_text"/>
+    </RelativeLayout>
 
 </com.android.systemui.biometrics.ui.CredentialPatternView>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/auth_credential_password_view.xml b/packages/SystemUI/res/layout/auth_credential_password_view.xml
index 33f1b10..9336845 100644
--- a/packages/SystemUI/res/layout/auth_credential_password_view.xml
+++ b/packages/SystemUI/res/layout/auth_credential_password_view.xml
@@ -65,29 +65,46 @@
 
     </ScrollView>
 
-    <LinearLayout
+    <FrameLayout
         android:id="@+id/auth_credential_input"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical">
 
-        <ImeAwareEditText
-            android:id="@+id/lockPassword"
-            style="?passwordTextAppearance"
-            android:layout_width="208dp"
-            android:layout_height="wrap_content"
-            android:layout_gravity="center_horizontal"
-            android:imeOptions="actionNext|flagNoFullscreen|flagForceAscii"
-            android:inputType="textPassword"
-            android:minHeight="48dp" />
-
-        <TextView
-            android:id="@+id/error"
-            style="?errorTextAppearance"
-            android:layout_gravity="center_horizontal"
+        <LinearLayout
             android:layout_width="match_parent"
-            android:layout_height="wrap_content" />
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_horizontal|top"
+            android:orientation="vertical">
 
-    </LinearLayout>
+            <ImeAwareEditText
+                android:id="@+id/lockPassword"
+                style="?passwordTextAppearance"
+                android:layout_width="208dp"
+                android:layout_height="wrap_content"
+                android:layout_gravity="center_horizontal"
+                android:imeOptions="actionNext|flagNoFullscreen|flagForceAscii"
+                android:inputType="textPassword"
+                android:minHeight="48dp"/>
+
+            <TextView
+                android:id="@+id/error"
+                style="?errorTextAppearance"
+                android:layout_gravity="center_horizontal"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"/>
+        </LinearLayout>
+
+        <Button
+            android:id="@+id/emergencyCallButton"
+            style="@style/AuthCredentialEmergencyButtonStyle"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:visibility="gone"
+            android:layout_gravity="center_horizontal|bottom"
+            android:layout_marginTop="12dp"
+            android:layout_marginBottom="12dp"
+            android:text="@string/work_challenge_emergency_button_text"/>
+    </FrameLayout>
 
 </com.android.systemui.biometrics.ui.CredentialPasswordView>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/auth_credential_pattern_view.xml b/packages/SystemUI/res/layout/auth_credential_pattern_view.xml
index 81ca3718..59828fd 100644
--- a/packages/SystemUI/res/layout/auth_credential_pattern_view.xml
+++ b/packages/SystemUI/res/layout/auth_credential_pattern_view.xml
@@ -58,24 +58,42 @@
             android:layout_height="wrap_content"/>
     </RelativeLayout>
 
-    <FrameLayout
+    <RelativeLayout
         android:id="@+id/auth_credential_container"
-        style="?containerStyle"
         android:layout_width="match_parent"
         android:layout_height="match_parent">
 
-        <com.android.internal.widget.LockPatternView
-            android:id="@+id/lockPattern"
-            android:layout_gravity="center"
-            android:layout_width="@dimen/biometric_auth_pattern_view_size"
-            android:layout_height="@dimen/biometric_auth_pattern_view_size"/>
+        <FrameLayout
+            android:layout_centerInParent="true"
+            android:layout_above="@id/emergencyCallButton"
+            style="?containerStyle"
+            android:layout_width="wrap_content"
+            android:layout_height="match_parent">
 
-        <TextView
-            android:id="@+id/error"
-            style="?errorTextAppearance"
-            android:layout_width="match_parent"
+            <com.android.internal.widget.LockPatternView
+                android:id="@+id/lockPattern"
+                android:layout_gravity="center"
+                android:layout_width="@dimen/biometric_auth_pattern_view_size"
+                android:layout_height="@dimen/biometric_auth_pattern_view_size"/>
+
+            <TextView
+                android:id="@+id/error"
+                style="?errorTextAppearance"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:layout_gravity="center_horizontal|bottom"/>
+        </FrameLayout>
+
+        <Button
+            android:id="@+id/emergencyCallButton"
+            style="@style/AuthCredentialEmergencyButtonStyle"
+            android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:layout_gravity="center_horizontal|bottom"/>
-    </FrameLayout>
+            android:layout_alignParentBottom="true"
+            android:visibility="gone"
+            android:layout_marginBottom="35dp"
+            android:layout_centerHorizontal="true"
+            android:text="@string/work_challenge_emergency_button_text"/>
+    </RelativeLayout>
 
 </com.android.systemui.biometrics.ui.CredentialPatternView>
diff --git a/packages/SystemUI/res/layout/screenshot_work_profile_first_run.xml b/packages/SystemUI/res/layout/screenshot_work_profile_first_run.xml
index 78cd718..39ec09b 100644
--- a/packages/SystemUI/res/layout/screenshot_work_profile_first_run.xml
+++ b/packages/SystemUI/res/layout/screenshot_work_profile_first_run.xml
@@ -34,8 +34,8 @@
         android:layout_height="@dimen/overlay_dismiss_button_tappable_size"
         android:contentDescription="@string/screenshot_dismiss_work_profile">
         <ImageView
-            android:layout_width="16dp"
-            android:layout_height="16dp"
+            android:layout_width="24dp"
+            android:layout_height="24dp"
             android:layout_gravity="center"
             android:background="@drawable/circular_background"
             android:backgroundTint="?androidprv:attr/materialColorSurfaceContainerHigh"
diff --git a/packages/SystemUI/res/values/attrs.xml b/packages/SystemUI/res/values/attrs.xml
index d693631..8bc3eed 100644
--- a/packages/SystemUI/res/values/attrs.xml
+++ b/packages/SystemUI/res/values/attrs.xml
@@ -221,6 +221,7 @@
         <attr name="descriptionTextAppearance" format="reference" />
         <attr name="passwordTextAppearance" format="reference" />
         <attr name="errorTextAppearance" format="reference"/>
+        <attr name="errorTextAppearanceLand" format="reference"/>
     </declare-styleable>
 
     <declare-styleable name="LogAccessPermissionGrantDialog">
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index cddfda2..2003fa3 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -386,6 +386,8 @@
     <string name="biometric_dialog_wrong_password">Wrong password</string>
     <!-- Error string shown when the user enters too many incorrect attempts [CHAR LIMIT=120]-->
     <string name="biometric_dialog_credential_too_many_attempts">Too many incorrect attempts.\nTry again in <xliff:g id="number">%d</xliff:g> seconds.</string>
+    <!-- Button text shown on an authentication screen giving the user the option to make an emergency call without unlocking their device [CHAR LIMIT=20] -->
+    <string name="work_challenge_emergency_button_text">Emergency</string>
 
     <!-- Error string shown when the user enters an incorrect PIN/pattern/password and it counts towards the max attempts before the data on the device is wiped. [CHAR LIMIT=NONE]-->
     <string name="biometric_dialog_credential_attempts_before_wipe">Try again. Attempt <xliff:g id="attempts" example="1">%1$d</xliff:g> of <xliff:g id="max_attempts" example="3">%2$d</xliff:g>.</string>
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index 10340c6..6991b96 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -236,6 +236,13 @@
         <item name="android:gravity">center</item>
     </style>
 
+    <style name="TextAppearance.AuthNonBioCredential.ErrorLand">
+        <item name="android:layout_marginTop">20dp</item>
+        <item name="android:textSize">14sp</item>
+        <item name="android:textColor">?android:attr/colorError</item>
+        <item name="android:gravity">start</item>
+    </style>
+
     <style name="TextAppearance.AuthCredential.PasswordEntry" parent="@android:style/TextAppearance.DeviceDefault">
         <item name="android:gravity">center</item>
         <item name="android:paddingTop">28dp</item>
@@ -276,6 +283,17 @@
         <item name="android:minWidth">200dp</item>
     </style>
 
+    <style name="AuthCredentialEmergencyButtonStyle">
+        <item name="android:background">@drawable/auth_credential_emergency_button_background</item>
+        <item name="android:textColor">@android:color/system_accent3_900</item>
+        <item name="android:outlineProvider">none</item>
+        <item name="android:paddingTop">15dp</item>
+        <item name="android:paddingBottom">15dp</item>
+        <item name="android:paddingLeft">30dp</item>
+        <item name="android:paddingRight">30dp</item>
+        <item name="android:textSize">16sp</item>
+    </style>
+
     <style name="DeviceManagementDialogTitle">
         <item name="android:gravity">center</item>
         <item name="android:textAppearance">@style/TextAppearance.Dialog.Title</item>
@@ -353,6 +371,7 @@
         <item name="descriptionTextAppearance">@style/TextAppearance.AuthNonBioCredential.Description</item>
         <item name="passwordTextAppearance">@style/TextAppearance.AuthCredential.PasswordEntry</item>
         <item name="errorTextAppearance">@style/TextAppearance.AuthNonBioCredential.Error</item>
+        <item name="errorTextAppearanceLand">@style/TextAppearance.AuthNonBioCredential.ErrorLand</item>
     </style>
 
     <style name="LockPatternViewStyle" >
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
index dd39f1d..05ace74 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
@@ -222,8 +222,10 @@
         mSmallClockFrame = mView.findViewById(R.id.lockscreen_clock_view);
         mLargeClockFrame = mView.findViewById(R.id.lockscreen_clock_view_large);
 
-        mDumpManager.unregisterDumpable(getClass().getSimpleName()); // unregister previous clocks
-        mDumpManager.registerDumpable(getClass().getSimpleName(), this);
+        if (!mOnlyClock) {
+            mDumpManager.unregisterDumpable(getClass().getSimpleName()); // unregister previous
+            mDumpManager.registerDumpable(getClass().getSimpleName(), this);
+        }
 
         if (mFeatureFlags.isEnabled(LOCKSCREEN_WALLPAPER_DREAM_ENABLED)) {
             mStatusArea = mView.findViewById(R.id.keyguard_status_area);
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
index 04692c4..9f3908a 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
@@ -27,6 +27,7 @@
 import static com.android.keyguard.KeyguardSecurityContainer.USER_TYPE_SECONDARY_USER;
 import static com.android.keyguard.KeyguardSecurityContainer.USER_TYPE_WORK_PROFILE;
 import static com.android.systemui.DejankUtils.whitelistIpcs;
+import static com.android.systemui.flags.Flags.LOCKSCREEN_ENABLE_LANDSCAPE;
 import static com.android.systemui.flags.Flags.REVAMPED_BOUNCER_MESSAGES;
 
 import android.app.ActivityManager;
@@ -370,8 +371,12 @@
 
                 @Override
                 public void onOrientationChanged(int orientation) {
-                    KeyguardSecurityContainerController.this
+                    if (mFeatureFlags.isEnabled(LOCKSCREEN_ENABLE_LANDSCAPE)) {
+                        // TODO(b/295603468)
+                        // Fix reinflation of views when flag is enabled.
+                        KeyguardSecurityContainerController.this
                             .onDensityOrFontScaleOrOrientationChanged();
+                    }
                 }
             };
     private final KeyguardUpdateMonitorCallback mKeyguardUpdateMonitorCallback =
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt b/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt
index caebc30..a3ee220 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt
@@ -16,6 +16,7 @@
     val description: String,
     val userInfo: BiometricUserInfo,
     val operationInfo: BiometricOperationInfo,
+    val showEmergencyCallButton: Boolean,
 ) {
     /** Prompt using one or more biometrics. */
     class Biometric(
@@ -29,7 +30,8 @@
             subtitle = info.subtitle?.toString() ?: "",
             description = info.description?.toString() ?: "",
             userInfo = userInfo,
-            operationInfo = operationInfo
+            operationInfo = operationInfo,
+            showEmergencyCallButton = info.isShowEmergencyCallButton
         ) {
         val negativeButtonText: String = info.negativeButtonText?.toString() ?: ""
     }
@@ -46,6 +48,7 @@
             description = (info.deviceCredentialDescription ?: info.description)?.toString() ?: "",
             userInfo = userInfo,
             operationInfo = operationInfo,
+            showEmergencyCallButton = info.isShowEmergencyCallButton
         ) {
 
         /** PIN prompt. */
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/CredentialViewBinder.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/CredentialViewBinder.kt
index 9292bd7..4ac9f96 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/CredentialViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/CredentialViewBinder.kt
@@ -2,6 +2,7 @@
 
 import android.view.View
 import android.view.ViewGroup
+import android.widget.Button
 import android.widget.ImageView
 import android.widget.TextView
 import androidx.lifecycle.Lifecycle
@@ -46,6 +47,7 @@
         val descriptionView: TextView = view.requireViewById(R.id.description)
         val iconView: ImageView? = view.findViewById(R.id.icon)
         val errorView: TextView = view.requireViewById(R.id.error)
+        val emergencyButtonView: Button = view.requireViewById(R.id.emergencyCallButton)
 
         var errorTimer: Job? = null
 
@@ -75,6 +77,13 @@
 
                         iconView?.setImageDrawable(header.icon)
 
+                        if (header.showEmergencyCallButton) {
+                            emergencyButtonView.visibility = View.VISIBLE
+                            emergencyButtonView.setOnClickListener {
+                                viewModel.doEmergencyCall(view.context)
+                            }
+                        }
+
                         // Only animate this if we're transitioning from a biometric view.
                         if (viewModel.animateContents.value) {
                             view.animateCredentialViewIn()
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialHeaderViewModel.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialHeaderViewModel.kt
index 3257f20..c6d9085 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialHeaderViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialHeaderViewModel.kt
@@ -10,4 +10,5 @@
     val subtitle: String
     val description: String
     val icon: Drawable
+    val showEmergencyCallButton: Boolean
 }
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialViewModel.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialViewModel.kt
index a3b23ca..6212ef0 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/CredentialViewModel.kt
@@ -41,6 +41,7 @@
                 subtitle = request.subtitle,
                 description = request.description,
                 icon = applicationContext.asLockIcon(request.userInfo.deviceCredentialOwnerId),
+                showEmergencyCallButton = request.showEmergencyCallButton
             )
         }
 
@@ -136,6 +137,18 @@
             }
         }
     }
+
+    fun doEmergencyCall(context: Context) {
+        val intent =
+            context
+                .getSystemService(android.telecom.TelecomManager::class.java)!!
+                .createLaunchEmergencyDialerIntent(null)
+                .setFlags(
+                    android.content.Intent.FLAG_ACTIVITY_NEW_TASK or
+                            android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
+                )
+        context.startActivity(intent)
+    }
 }
 
 private fun Context.asBadCredentialErrorMessage(prompt: BiometricPromptRequest?): String =
@@ -174,6 +187,7 @@
     override val subtitle: String,
     override val description: String,
     override val icon: Drawable,
+    override val showEmergencyCallButton: Boolean,
 ) : CredentialHeaderViewModel
 
 private fun CredentialHeaderViewModel.asRequest(): BiometricPromptRequest.Credential =
diff --git a/packages/SystemUI/src/com/android/systemui/flags/Flags.kt b/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
index 2fc4574..f0a048b 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
+++ b/packages/SystemUI/src/com/android/systemui/flags/Flags.kt
@@ -254,7 +254,7 @@
     // TODO(b/290652751): Tracking bug.
     @JvmField
     val MIGRATE_SPLIT_KEYGUARD_BOTTOM_AREA =
-        unreleasedFlag("migrate_split_keyguard_bottom_area")
+        unreleasedFlag("migrate_split_keyguard_bottom_area", teamfood = true)
 
     /** Whether to listen for fingerprint authentication over keyguard occluding activities. */
     // TODO(b/283260512): Tracking bug.
@@ -269,7 +269,7 @@
 
     /** Migrate the lock icon view to the new keyguard root view. */
     // TODO(b/286552209): Tracking bug.
-    @JvmField val MIGRATE_LOCK_ICON = unreleasedFlag("migrate_lock_icon")
+    @JvmField val MIGRATE_LOCK_ICON = unreleasedFlag("migrate_lock_icon", teamfood = true)
 
     // TODO(b/288276738): Tracking bug.
     @JvmField val WIDGET_ON_KEYGUARD = unreleasedFlag("widget_on_keyguard")
@@ -355,7 +355,7 @@
 
     // TODO(b/278068252): Tracking Bug
     @JvmField
-    val QS_PIPELINE_AUTO_ADD = unreleasedFlag("qs_pipeline_auto_add", teamfood = false)
+    val QS_PIPELINE_AUTO_ADD = unreleasedFlag("qs_pipeline_auto_add", teamfood = true)
 
     // TODO(b/254512383): Tracking Bug
     @JvmField
@@ -368,10 +368,6 @@
     // TODO(b/244064524): Tracking Bug
     @JvmField val QS_SECONDARY_DATA_SUB_INFO = releasedFlag("qs_secondary_data_sub_info")
 
-    /** Enables Font Scaling Quick Settings tile */
-    // TODO(b/269341316): Tracking Bug
-    @JvmField val ENABLE_FONT_SCALING_TILE = releasedFlag("enable_font_scaling_tile")
-
     /** Enables new QS Edit Mode visual refresh */
     // TODO(b/269787742): Tracking Bug
     @JvmField
@@ -398,6 +394,10 @@
     // TODO(b/294588085): Tracking Bug
     val WIFI_SECONDARY_NETWORKS = releasedFlag("wifi_secondary_networks")
 
+    // TODO(b/290676905): Tracking Bug
+    val NEW_SHADE_CARRIER_GROUP_MOBILE_ICONS =
+        unreleasedFlag("new_shade_carrier_group_mobile_icons")
+
     // 700 - dialer/calls
     // TODO(b/254512734): Tracking Bug
     val ONGOING_CALL_STATUS_BAR_CHIP = releasedFlag("ongoing_call_status_bar_chip")
@@ -502,16 +502,6 @@
     val WM_CAPTION_ON_SHELL =
         sysPropBooleanFlag("persist.wm.debug.caption_on_shell", default = true)
 
-    @Keep
-    @JvmField
-    val ENABLE_FLING_TO_DISMISS_BUBBLE =
-        sysPropBooleanFlag("persist.wm.debug.fling_to_dismiss_bubble", default = true)
-
-    @Keep
-    @JvmField
-    val ENABLE_FLING_TO_DISMISS_PIP =
-        sysPropBooleanFlag("persist.wm.debug.fling_to_dismiss_pip", default = true)
-
     // TODO(b/256873975): Tracking Bug
     @JvmField
     @Keep
@@ -533,13 +523,6 @@
             teamfood = false
         )
 
-    // TODO(b/198643358): Tracking bug
-    @Keep
-    @JvmField
-    val ENABLE_PIP_SIZE_LARGE_SCREEN =
-        sysPropBooleanFlag("persist.wm.debug.enable_pip_size_large_screen", default = true)
-
-
     // TODO(b/293252410) : Tracking Bug
     @JvmField
     val LOCKSCREEN_ENABLE_LANDSCAPE =
@@ -623,6 +606,10 @@
     // TODO(b/251205791): Tracking Bug
     @JvmField val SCREENSHOT_APP_CLIPS = releasedFlag("screenshot_app_clips")
 
+    /** TODO(b/295143676): Tracking bug. When enable, captures a screenshot for each display. */
+    @JvmField
+    val MULTI_DISPLAY_SCREENSHOT = unreleasedFlag("multi_display_screenshot")
+
     // 1400 - columbus
     // TODO(b/254512756): Tracking Bug
     val QUICK_TAP_IN_PCC = releasedFlag("quick_tap_in_pcc")
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractor.kt
index 635961b..e501ece 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractor.kt
@@ -54,7 +54,11 @@
         if (event.handleAction()) {
             when (event.keyCode) {
                 KeyEvent.KEYCODE_MENU -> return dispatchMenuKeyEvent()
-                KeyEvent.KEYCODE_SPACE -> return dispatchSpaceEvent()
+                KeyEvent.KEYCODE_SPACE,
+                KeyEvent.KEYCODE_ENTER ->
+                    if (isDeviceInteractive()) {
+                        return collapseShadeLockedOrShowPrimaryBouncer()
+                    }
             }
         }
         return false
@@ -90,16 +94,22 @@
                 (statusBarStateController.state != StatusBarState.SHADE) &&
                 statusBarKeyguardViewManager.shouldDismissOnMenuPressed()
         if (shouldUnlockOnMenuPressed) {
-            shadeController.animateCollapseShadeForced()
-            return true
+            return collapseShadeLockedOrShowPrimaryBouncer()
         }
         return false
     }
 
-    private fun dispatchSpaceEvent(): Boolean {
-        if (isDeviceInteractive() && statusBarStateController.state != StatusBarState.SHADE) {
-            shadeController.animateCollapseShadeForced()
-            return true
+    private fun collapseShadeLockedOrShowPrimaryBouncer(): Boolean {
+        when (statusBarStateController.state) {
+            StatusBarState.SHADE -> return false
+            StatusBarState.SHADE_LOCKED -> {
+                shadeController.animateCollapseShadeForced()
+                return true
+            }
+            StatusBarState.KEYGUARD -> {
+                statusBarKeyguardViewManager.showPrimaryBouncer(true)
+                return true
+            }
         }
         return false
     }
diff --git a/packages/SystemUI/src/com/android/systemui/media/NotificationPlayer.java b/packages/SystemUI/src/com/android/systemui/media/NotificationPlayer.java
index f8f784f..3d4fca1 100644
--- a/packages/SystemUI/src/com/android/systemui/media/NotificationPlayer.java
+++ b/packages/SystemUI/src/com/android/systemui/media/NotificationPlayer.java
@@ -216,6 +216,58 @@
         }
     }
 
+    private void stopSound(Command cmd) {
+        final MediaPlayer mp;
+        synchronized (mPlayerLock) {
+            mp = mPlayer;
+            mPlayer = null;
+        }
+        if (mp == null) {
+            Log.w(mTag, "STOP command without a player");
+            return;
+        }
+
+        long delay = SystemClock.uptimeMillis() - cmd.requestTime;
+        if (delay > 1000) {
+            Log.w(mTag, "Notification stop delayed by " + delay + "msecs");
+        }
+        try {
+            mp.stop();
+        } catch (Exception e) {
+            Log.w(mTag, "Failed to stop MediaPlayer", e);
+        }
+        if (DEBUG) {
+            Log.i(mTag, "About to release MediaPlayer piid:"
+                    + mp.getPlayerIId() + " due to notif cancelled");
+        }
+        try {
+            mp.release();
+        } catch (Exception e) {
+            Log.w(mTag, "Failed to release MediaPlayer", e);
+        }
+        synchronized (mQueueAudioFocusLock) {
+            if (mAudioManagerWithAudioFocus != null) {
+                if (DEBUG) {
+                    Log.d(mTag, "in STOP: abandonning AudioFocus");
+                }
+                try {
+                    mAudioManagerWithAudioFocus.abandonAudioFocus(null);
+                } catch (Exception e) {
+                    Log.w(mTag, "Failed to abandon audio focus", e);
+                }
+                mAudioManagerWithAudioFocus = null;
+            }
+        }
+        synchronized (mCompletionHandlingLock) {
+            if ((mLooper != null) && (mLooper.getThread().getState() != Thread.State.TERMINATED)) {
+                if (DEBUG) {
+                    Log.d(mTag, "in STOP: quitting looper " + mLooper);
+                }
+                mLooper.quit();
+            }
+        }
+    }
+
     private final class CmdThread extends java.lang.Thread {
         CmdThread() {
             super("NotificationPlayer-" + mTag);
@@ -229,62 +281,28 @@
                     if (DEBUG) Log.d(mTag, "RemoveFirst");
                     cmd = mCmdQueue.removeFirst();
                 }
-
-                switch (cmd.code) {
-                case PLAY:
-                    if (DEBUG) Log.d(mTag, "PLAY");
-                    startSound(cmd);
-                    break;
-                case STOP:
-                    if (DEBUG) Log.d(mTag, "STOP");
-                    final MediaPlayer mp;
-                    synchronized (mPlayerLock) {
-                        mp = mPlayer;
-                        mPlayer = null;
+                try {
+                    switch (cmd.code) {
+                        case PLAY:
+                            if (DEBUG) Log.d(mTag, "PLAY");
+                            startSound(cmd);
+                            break;
+                        case STOP:
+                            if (DEBUG) Log.d(mTag, "STOP");
+                            stopSound(cmd);
+                            break;
                     }
-                    if (mp != null) {
-                        long delay = SystemClock.uptimeMillis() - cmd.requestTime;
-                        if (delay > 1000) {
-                            Log.w(mTag, "Notification stop delayed by " + delay + "msecs");
+                } finally {
+                    synchronized (mCmdQueue) {
+                        if (mCmdQueue.size() == 0) {
+                            // nothing left to do, quit
+                            // doing this check after we're done prevents the case where they
+                            // added it during the operation from spawning two threads and
+                            // trying to do them in parallel.
+                            mThread = null;
+                            releaseWakeLock();
+                            return;
                         }
-                        try {
-                            mp.stop();
-                        } catch (Exception e) { }
-                        if (DEBUG) {
-                            Log.i(mTag, "About to release MediaPlayer piid:"
-                                    + mp.getPlayerIId() + " due to notif cancelled");
-                        }
-                        mp.release();
-                        synchronized(mQueueAudioFocusLock) {
-                            if (mAudioManagerWithAudioFocus != null) {
-                                if (DEBUG) { Log.d(mTag, "in STOP: abandonning AudioFocus"); }
-                                mAudioManagerWithAudioFocus.abandonAudioFocus(null);
-                                mAudioManagerWithAudioFocus = null;
-                            }
-                        }
-                        synchronized (mCompletionHandlingLock) {
-                            if ((mLooper != null) &&
-                                    (mLooper.getThread().getState() != Thread.State.TERMINATED))
-                            {
-                                if (DEBUG) { Log.d(mTag, "in STOP: quitting looper "+ mLooper); }
-                                mLooper.quit();
-                            }
-                        }
-                    } else {
-                        Log.w(mTag, "STOP command without a player");
-                    }
-                    break;
-                }
-
-                synchronized (mCmdQueue) {
-                    if (mCmdQueue.size() == 0) {
-                        // nothing left to do, quit
-                        // doing this check after we're done prevents the case where they
-                        // added it during the operation from spawning two threads and
-                        // trying to do them in parallel.
-                        mThread = null;
-                        releaseWakeLock();
-                        return;
                     }
                 }
             }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSHostAdapter.kt b/packages/SystemUI/src/com/android/systemui/qs/QSHostAdapter.kt
index 67927a4..cb87e3c 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSHostAdapter.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSHostAdapter.kt
@@ -22,13 +22,12 @@
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
 import com.android.systemui.dump.DumpManager
-import com.android.systemui.flags.FeatureFlags
-import com.android.systemui.flags.Flags
 import com.android.systemui.plugins.qs.QSTile
 import com.android.systemui.plugins.qs.QSTileView
 import com.android.systemui.qs.external.TileServiceRequestController
 import com.android.systemui.qs.pipeline.data.repository.TileSpecRepository.Companion.POSITION_AT_END
 import com.android.systemui.qs.pipeline.domain.interactor.CurrentTilesInteractor
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository
 import com.android.systemui.qs.pipeline.shared.TileSpec
 import javax.inject.Inject
 import kotlinx.coroutines.CoroutineScope
@@ -37,10 +36,11 @@
 
 /**
  * Adapter to determine what real class to use for classes that depend on [QSHost].
- * * When [Flags.QS_PIPELINE_NEW_HOST] is off, all calls will be routed to [QSTileHost].
- * * When [Flags.QS_PIPELINE_NEW_HOST] is on, calls regarding the current set of tiles will be
- *   routed to [CurrentTilesInteractor]. Other calls (like [createTileView]) will still be routed to
+ * * When [QSPipelineFlagsRepository.pipelineHostEnabled] is false, all calls will be routed to
  *   [QSTileHost].
+ * * When [QSPipelineFlagsRepository.pipelineHostEnabled] is true, calls regarding the current set
+ *   of tiles will be routed to [CurrentTilesInteractor]. Other calls (like [createTileView]) will
+ *   still be routed to [QSTileHost].
  *
  * This routing also includes dumps.
  */
@@ -53,7 +53,7 @@
     private val context: Context,
     private val tileServiceRequestControllerBuilder: TileServiceRequestController.Builder,
     @Application private val scope: CoroutineScope,
-    private val featureFlags: FeatureFlags,
+    flags: QSPipelineFlagsRepository,
     dumpManager: DumpManager,
 ) : QSHost {
 
@@ -61,7 +61,7 @@
         private const val TAG = "QSTileHost"
     }
 
-    private val useNewHost = featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)
+    private val useNewHost = flags.pipelineHostEnabled
 
     @GuardedBy("callbacksMap") private val callbacksMap = mutableMapOf<QSHost.Callback, Job>()
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java b/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java
index 432147f..e57db56 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java
@@ -35,8 +35,6 @@
 import com.android.systemui.dagger.SysUISingleton;
 import com.android.systemui.dagger.qualifiers.Main;
 import com.android.systemui.dump.nano.SystemUIProtoDump;
-import com.android.systemui.flags.FeatureFlags;
-import com.android.systemui.flags.Flags;
 import com.android.systemui.plugins.PluginListener;
 import com.android.systemui.plugins.PluginManager;
 import com.android.systemui.plugins.qs.QSFactory;
@@ -50,6 +48,7 @@
 import com.android.systemui.qs.nano.QsTileState;
 import com.android.systemui.qs.pipeline.data.repository.CustomTileAddedRepository;
 import com.android.systemui.qs.pipeline.domain.interactor.PanelInteractor;
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository;
 import com.android.systemui.settings.UserFileManager;
 import com.android.systemui.settings.UserTracker;
 import com.android.systemui.shade.ShadeController;
@@ -119,7 +118,7 @@
 
     private TileLifecycleManager.Factory mTileLifeCycleManagerFactory;
 
-    private final FeatureFlags mFeatureFlags;
+    private final QSPipelineFlagsRepository mFeatureFlags;
 
     @Inject
     public QSTileHost(Context context,
@@ -135,7 +134,7 @@
             CustomTileStatePersister customTileStatePersister,
             TileLifecycleManager.Factory tileLifecycleManagerFactory,
             UserFileManager userFileManager,
-            FeatureFlags featureFlags
+            QSPipelineFlagsRepository featureFlags
     ) {
         mContext = context;
         mUserContext = context;
@@ -162,7 +161,7 @@
             // finishes before creating any tiles.
             tunerService.addTunable(this, TILES_SETTING);
             // AutoTileManager can modify mTiles so make sure mTiles has already been initialized.
-            if (!mFeatureFlags.isEnabled(Flags.QS_PIPELINE_AUTO_ADD)) {
+            if (!mFeatureFlags.getPipelineAutoAddEnabled()) {
                 mAutoTiles = autoTiles.get();
             }
         });
@@ -283,7 +282,7 @@
             }
         }
         // Do not process tiles if the flag is enabled.
-        if (mFeatureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)) {
+        if (mFeatureFlags.getPipelineHostEnabled()) {
             return;
         }
         if (newValue == null && UserManager.isDeviceInDemoMode(mContext)) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/dagger/QSHostModule.kt b/packages/SystemUI/src/com/android/systemui/qs/dagger/QSHostModule.kt
index 1f63f5d..b2111d7 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/dagger/QSHostModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/dagger/QSHostModule.kt
@@ -16,8 +16,6 @@
 
 package com.android.systemui.qs.dagger
 
-import com.android.systemui.flags.FeatureFlags
-import com.android.systemui.flags.Flags
 import com.android.systemui.qs.QSHost
 import com.android.systemui.qs.QSHostAdapter
 import com.android.systemui.qs.QSTileHost
@@ -27,6 +25,7 @@
 import com.android.systemui.qs.pipeline.data.repository.CustomTileAddedSharedPrefsRepository
 import com.android.systemui.qs.pipeline.domain.interactor.PanelInteractor
 import com.android.systemui.qs.pipeline.domain.interactor.PanelInteractorImpl
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository
 import dagger.Binds
 import dagger.Module
 import dagger.Provides
@@ -45,11 +44,11 @@
         @Provides
         @JvmStatic
         fun providePanelInteractor(
-            featureFlags: FeatureFlags,
+            featureFlags: QSPipelineFlagsRepository,
             qsHost: QSTileHost,
             panelInteractorImpl: PanelInteractorImpl
         ): PanelInteractor {
-            return if (featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)) {
+            return if (featureFlags.pipelineHostEnabled) {
                 panelInteractorImpl
             } else {
                 qsHost
@@ -59,11 +58,11 @@
         @Provides
         @JvmStatic
         fun provideCustomTileAddedRepository(
-            featureFlags: FeatureFlags,
+            featureFlags: QSPipelineFlagsRepository,
             qsHost: QSTileHost,
             customTileAddedRepository: CustomTileAddedSharedPrefsRepository
         ): CustomTileAddedRepository {
-            return if (featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)) {
+            return if (featureFlags.pipelineHostEnabled) {
                 customTileAddedRepository
             } else {
                 qsHost
diff --git a/packages/SystemUI/src/com/android/systemui/qs/external/CustomTile.java b/packages/SystemUI/src/com/android/systemui/qs/external/CustomTile.java
index 5d02830..34d6233 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/external/CustomTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/external/CustomTile.java
@@ -36,7 +36,6 @@
 import android.service.quicksettings.IQSTileService;
 import android.service.quicksettings.Tile;
 import android.service.quicksettings.TileService;
-import android.text.TextUtils;
 import android.text.format.DateUtils;
 import android.util.Log;
 import android.view.IWindowManager;
@@ -190,13 +189,8 @@
             if (updateIcon) {
                 mTile.setIcon(mDefaultIcon);
             }
-            // Update the label if there is no label or it is the default label.
-            boolean updateLabel = mTile.getLabel() == null
-                    || TextUtils.equals(mTile.getLabel(), mDefaultLabel);
             mDefaultLabel = info.loadLabel(pm);
-            if (updateLabel) {
-                mTile.setLabel(mDefaultLabel);
-            }
+            mTile.setDefaultLabel(mDefaultLabel);
         } catch (PackageManager.NameNotFoundException e) {
             mDefaultIcon = null;
             mDefaultLabel = null;
@@ -291,8 +285,8 @@
         if (tile.getIcon() != null || overwriteNulls) {
             mTile.setIcon(tile.getIcon());
         }
-        if (tile.getLabel() != null || overwriteNulls) {
-            mTile.setLabel(tile.getLabel());
+        if (tile.getCustomLabel() != null || overwriteNulls) {
+            mTile.setLabel(tile.getCustomLabel());
         }
         if (tile.getSubtitle() != null || overwriteNulls) {
             mTile.setSubtitle(tile.getSubtitle());
diff --git a/packages/SystemUI/src/com/android/systemui/qs/external/CustomTileStatePersister.kt b/packages/SystemUI/src/com/android/systemui/qs/external/CustomTileStatePersister.kt
index 021e632..a321eef 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/external/CustomTileStatePersister.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/external/CustomTileStatePersister.kt
@@ -113,7 +113,7 @@
     return with(tile) {
         JSONObject()
             .put(STATE, state)
-            .put(LABEL, label)
+            .put(LABEL, customLabel)
             .put(SUBTITLE, subtitle)
             .put(CONTENT_DESCRIPTION, contentDescription)
             .put(STATE_DESCRIPTION, stateDescription)
diff --git a/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractor.kt b/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractor.kt
index 966f370..5a5e47a 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractor.kt
@@ -27,8 +27,6 @@
 import com.android.systemui.dagger.qualifiers.Background
 import com.android.systemui.dagger.qualifiers.Main
 import com.android.systemui.dump.nano.SystemUIProtoDump
-import com.android.systemui.flags.FeatureFlags
-import com.android.systemui.flags.Flags
 import com.android.systemui.plugins.qs.QSFactory
 import com.android.systemui.plugins.qs.QSTile
 import com.android.systemui.qs.external.CustomTile
@@ -39,6 +37,7 @@
 import com.android.systemui.qs.pipeline.data.repository.InstalledTilesComponentRepository
 import com.android.systemui.qs.pipeline.data.repository.TileSpecRepository
 import com.android.systemui.qs.pipeline.domain.model.TileModel
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository
 import com.android.systemui.qs.pipeline.shared.TileSpec
 import com.android.systemui.qs.pipeline.shared.logging.QSPipelineLogger
 import com.android.systemui.qs.toProto
@@ -139,7 +138,7 @@
     @Background private val backgroundDispatcher: CoroutineDispatcher,
     @Application private val scope: CoroutineScope,
     private val logger: QSPipelineLogger,
-    featureFlags: FeatureFlags,
+    featureFlags: QSPipelineFlagsRepository,
 ) : CurrentTilesInteractor {
 
     private val _currentSpecsAndTiles: MutableStateFlow<List<TileModel>> =
@@ -171,7 +170,7 @@
         }
 
     init {
-        if (featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)) {
+        if (featureFlags.pipelineHostEnabled) {
             startTileCollection()
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/startable/QSPipelineCoreStartable.kt b/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/startable/QSPipelineCoreStartable.kt
index 224fc1a..0743ba0 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/startable/QSPipelineCoreStartable.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/pipeline/domain/startable/QSPipelineCoreStartable.kt
@@ -18,10 +18,9 @@
 
 import com.android.systemui.CoreStartable
 import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.flags.FeatureFlags
-import com.android.systemui.flags.Flags
 import com.android.systemui.qs.pipeline.domain.interactor.AutoAddInteractor
 import com.android.systemui.qs.pipeline.domain.interactor.CurrentTilesInteractor
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository
 import javax.inject.Inject
 
 @SysUISingleton
@@ -30,14 +29,11 @@
 constructor(
     private val currentTilesInteractor: CurrentTilesInteractor,
     private val autoAddInteractor: AutoAddInteractor,
-    private val featureFlags: FeatureFlags,
+    private val featureFlags: QSPipelineFlagsRepository,
 ) : CoreStartable {
 
     override fun start() {
-        if (
-            featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST) &&
-                featureFlags.isEnabled(Flags.QS_PIPELINE_AUTO_ADD)
-        ) {
+        if (featureFlags.pipelineAutoAddEnabled) {
             autoAddInteractor.init(currentTilesInteractor)
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepository.kt b/packages/SystemUI/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepository.kt
new file mode 100644
index 0000000..551b0f4
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepository.kt
@@ -0,0 +1,23 @@
+package com.android.systemui.qs.pipeline.shared
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
+import javax.inject.Inject
+
+/** Encapsulate the different QS pipeline flags and their dependencies */
+@SysUISingleton
+class QSPipelineFlagsRepository
+@Inject
+constructor(
+    private val featureFlags: FeatureFlags,
+) {
+
+    /** @see Flags.QS_PIPELINE_NEW_HOST */
+    val pipelineHostEnabled: Boolean
+        get() = featureFlags.isEnabled(Flags.QS_PIPELINE_NEW_HOST)
+
+    /** @see Flags.QS_PIPELINE_AUTO_ADD */
+    val pipelineAutoAddEnabled: Boolean
+        get() = pipelineHostEnabled && featureFlags.isEnabled(Flags.QS_PIPELINE_AUTO_ADD)
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/FontScalingTile.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/FontScalingTile.kt
index 423fa80..1f9979a 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/FontScalingTile.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/FontScalingTile.kt
@@ -28,8 +28,6 @@
 import com.android.systemui.animation.DialogLaunchAnimator
 import com.android.systemui.dagger.qualifiers.Background
 import com.android.systemui.dagger.qualifiers.Main
-import com.android.systemui.flags.FeatureFlags
-import com.android.systemui.flags.Flags
 import com.android.systemui.plugins.ActivityStarter
 import com.android.systemui.plugins.FalsingManager
 import com.android.systemui.plugins.qs.QSTile
@@ -64,7 +62,6 @@
     private val systemSettings: SystemSettings,
     private val secureSettings: SecureSettings,
     private val systemClock: SystemClock,
-    private val featureFlags: FeatureFlags,
     private val userTracker: UserTracker,
     @Background private val backgroundDelayableExecutor: DelayableExecutor
 ) :
@@ -81,10 +78,6 @@
     ) {
     private val icon = ResourceIcon.get(R.drawable.ic_qs_font_scaling)
 
-    override fun isAvailable(): Boolean {
-        return featureFlags.isEnabled(Flags.ENABLE_FONT_SCALING_TILE)
-    }
-
     override fun newTileState(): QSTile.State {
         return QSTile.State()
     }
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
index 7c4b042..014093d 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
@@ -985,6 +985,7 @@
         // Make sure the clock is in the correct position after the unlock animation
         // so that it's not in the wrong place when we show the keyguard again.
         positionClockAndNotifications(true /* forceClockUpdate */);
+        mScrimController.onUnlockAnimationFinished();
     }
 
     private void unlockAnimationStarted(
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowViewController.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowViewController.java
index 832a25b..798f2d5 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowViewController.java
@@ -21,8 +21,6 @@
 import static com.android.systemui.util.kotlin.JavaAdapterKt.collectFlow;
 
 import android.app.StatusBarManager;
-import android.media.AudioManager;
-import android.media.session.MediaSessionLegacyHelper;
 import android.os.PowerManager;
 import android.util.Log;
 import android.view.GestureDetector;
@@ -47,6 +45,7 @@
 import com.android.systemui.dock.DockManager;
 import com.android.systemui.flags.FeatureFlags;
 import com.android.systemui.flags.Flags;
+import com.android.systemui.keyevent.domain.interactor.KeyEventInteractor;
 import com.android.systemui.keyguard.KeyguardUnlockAnimationController;
 import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor;
 import com.android.systemui.keyguard.shared.model.TransitionState;
@@ -101,13 +100,21 @@
     private final NotificationInsetsController mNotificationInsetsController;
     private final boolean mIsTrackpadCommonEnabled;
     private final FeatureFlags mFeatureFlags;
+    private final KeyEventInteractor mKeyEventInteractor;
     private GestureDetector mPulsingWakeupGestureHandler;
     private GestureDetector mDreamingWakeupGestureHandler;
     private View mBrightnessMirror;
     private boolean mTouchActive;
     private boolean mTouchCancelled;
     private MotionEvent mDownEvent;
+    // TODO rename to mLaunchAnimationRunning
     private boolean mExpandAnimationRunning;
+    /**
+     *  When mExpandAnimationRunning is true and the touch dispatcher receives a down even after
+     *  uptime exceeds this, the dispatcher will stop blocking touches for the launch animation,
+     *  which has presumabely not completed due to an error.
+     */
+    private long mLaunchAnimationTimeout;
     private NotificationStackScrollLayout mStackScrollLayout;
     private PhoneStatusBarViewController mStatusBarViewController;
     private final CentralSurfaces mService;
@@ -164,7 +171,8 @@
             FeatureFlags featureFlags,
             SystemClock clock,
             BouncerMessageInteractor bouncerMessageInteractor,
-            BouncerLogger bouncerLogger) {
+            BouncerLogger bouncerLogger,
+            KeyEventInteractor keyEventInteractor) {
         mLockscreenShadeTransitionController = transitionController;
         mFalsingCollector = falsingCollector;
         mStatusBarStateController = statusBarStateController;
@@ -190,6 +198,7 @@
         mNotificationInsetsController = notificationInsetsController;
         mIsTrackpadCommonEnabled = featureFlags.isEnabled(TRACKPAD_GESTURE_COMMON);
         mFeatureFlags = featureFlags;
+        mKeyEventInteractor = keyEventInteractor;
 
         // This view is not part of the newly inflated expanded status bar.
         mBrightnessMirror = mView.findViewById(R.id.brightness_mirror_container);
@@ -278,7 +287,12 @@
                     return logDownDispatch(ev, "touch cancelled", false);
                 }
                 if (mExpandAnimationRunning) {
-                    return logDownDispatch(ev, "expand animation running", false);
+                    if (isDown && mClock.uptimeMillis() > mLaunchAnimationTimeout) {
+                        mShadeLogger.d("NSWVC: launch animation timed out");
+                        setExpandAnimationRunning(false);
+                    } else {
+                        return logDownDispatch(ev, "expand animation running", false);
+                    }
                 }
 
                 if (mKeyguardUnlockAnimationController.isPlayingCannedUnlockAnimation()) {
@@ -457,44 +471,17 @@
 
             @Override
             public boolean interceptMediaKey(KeyEvent event) {
-                return mService.interceptMediaKey(event);
+                return mKeyEventInteractor.interceptMediaKey(event);
             }
 
             @Override
             public boolean dispatchKeyEventPreIme(KeyEvent event) {
-                return mService.dispatchKeyEventPreIme(event);
+                return mKeyEventInteractor.dispatchKeyEventPreIme(event);
             }
 
             @Override
             public boolean dispatchKeyEvent(KeyEvent event) {
-                boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
-                switch (event.getKeyCode()) {
-                    case KeyEvent.KEYCODE_BACK:
-                        if (!down) {
-                            mBackActionInteractor.onBackRequested();
-                        }
-                        return true;
-                    case KeyEvent.KEYCODE_MENU:
-                        if (!down) {
-                            return mService.onMenuPressed();
-                        }
-                        break;
-                    case KeyEvent.KEYCODE_SPACE:
-                        if (!down) {
-                            return mService.onSpacePressed();
-                        }
-                        break;
-                    case KeyEvent.KEYCODE_VOLUME_DOWN:
-                    case KeyEvent.KEYCODE_VOLUME_UP:
-                        if (mStatusBarStateController.isDozing()) {
-                            MediaSessionLegacyHelper.getHelper(mView.getContext())
-                                    .sendVolumeKeyEvent(
-                                            event, AudioManager.USE_DEFAULT_STREAM_TYPE, true);
-                            return true;
-                        }
-                        break;
-                }
-                return false;
+                return mKeyEventInteractor.dispatchKeyEvent(event);
             }
         });
 
@@ -555,8 +542,12 @@
         pw.println(mTouchActive);
     }
 
-    private void setExpandAnimationRunning(boolean running) {
+    @VisibleForTesting
+    void setExpandAnimationRunning(boolean running) {
         if (mExpandAnimationRunning != running) {
+            if (running) {
+                mLaunchAnimationTimeout = mClock.uptimeMillis() + 5000;
+            }
             mExpandAnimationRunning = running;
             mNotificationShadeWindowController.setLaunchingActivity(mExpandAnimationRunning);
         }
diff --git a/packages/SystemUI/src/com/android/systemui/shade/carrier/ShadeCarrier.java b/packages/SystemUI/src/com/android/systemui/shade/carrier/ShadeCarrier.java
index 8586828..8612cdf 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/carrier/ShadeCarrier.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/carrier/ShadeCarrier.java
@@ -34,6 +34,7 @@
 import com.android.settingslib.graph.SignalDrawable;
 import com.android.systemui.FontSizeUtils;
 import com.android.systemui.R;
+import com.android.systemui.statusbar.pipeline.mobile.ui.view.ModernShadeCarrierGroupMobileView;
 import com.android.systemui.util.LargeScreenUtils;
 
 import java.util.Objects;
@@ -44,6 +45,7 @@
     private TextView mCarrierText;
     private ImageView mMobileSignal;
     private ImageView mMobileRoaming;
+    private ModernShadeCarrierGroupMobileView mModernMobileView;
     private View mSpacer;
     @Nullable
     private CellSignalState mLastSignalState;
@@ -77,6 +79,23 @@
         updateResources();
     }
 
+    /** Removes a ModernStatusBarMobileView from the ViewGroup. */
+    public void removeModernMobileView() {
+        if (mModernMobileView != null) {
+            removeView(mModernMobileView);
+            mModernMobileView = null;
+        }
+    }
+
+    /** Adds a ModernStatusBarMobileView to the ViewGroup. */
+    public void addModernMobileView(ModernShadeCarrierGroupMobileView mobileView) {
+        mModernMobileView = mobileView;
+        mMobileGroup.setVisibility(View.GONE);
+        mSpacer.setVisibility(View.GONE);
+        mCarrierText.setVisibility(View.GONE);
+        addView(mobileView);
+    }
+
     /**
      * Update the state of this view
      * @param state the current state of the signal for this view
diff --git a/packages/SystemUI/src/com/android/systemui/shade/carrier/ShadeCarrierGroupController.java b/packages/SystemUI/src/com/android/systemui/shade/carrier/ShadeCarrierGroupController.java
index ad49b26..98d8a53 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/carrier/ShadeCarrierGroupController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/carrier/ShadeCarrierGroupController.java
@@ -16,6 +16,7 @@
 
 package com.android.systemui.shade.carrier;
 
+import static android.telephony.SubscriptionManager.INVALID_SIM_SLOT_INDEX;
 import static android.view.View.IMPORTANT_FOR_ACCESSIBILITY_YES;
 
 import android.annotation.MainThread;
@@ -46,8 +47,17 @@
 import com.android.systemui.statusbar.connectivity.MobileDataIndicators;
 import com.android.systemui.statusbar.connectivity.NetworkController;
 import com.android.systemui.statusbar.connectivity.SignalCallback;
+import com.android.systemui.statusbar.connectivity.ui.MobileContextProvider;
+import com.android.systemui.statusbar.phone.StatusBarLocation;
+import com.android.systemui.statusbar.pipeline.StatusBarPipelineFlags;
+import com.android.systemui.statusbar.pipeline.mobile.ui.MobileUiAdapter;
+import com.android.systemui.statusbar.pipeline.mobile.ui.binder.MobileIconsBinder;
+import com.android.systemui.statusbar.pipeline.mobile.ui.view.ModernShadeCarrierGroupMobileView;
+import com.android.systemui.statusbar.pipeline.mobile.ui.viewmodel.MobileIconsViewModel;
+import com.android.systemui.statusbar.pipeline.mobile.ui.viewmodel.ShadeCarrierGroupMobileIconViewModel;
 import com.android.systemui.util.CarrierConfigTracker;
 
+import java.util.List;
 import java.util.function.Consumer;
 
 import javax.inject.Inject;
@@ -62,12 +72,16 @@
 
     private final ActivityStarter mActivityStarter;
     private final Handler mBgHandler;
+    private final Context mContext;
     private final NetworkController mNetworkController;
     private final CarrierTextManager mCarrierTextManager;
     private final TextView mNoSimTextView;
     // Non final for testing
     private H mMainHandler;
     private final Callback mCallback;
+    private final MobileIconsViewModel mMobileIconsViewModel;
+    private final MobileContextProvider mMobileContextProvider;
+    private final StatusBarPipelineFlags mStatusBarPipelineFlags;
     private boolean mListening;
     private final CellSignalState[] mInfos =
             new CellSignalState[SIM_SLOTS];
@@ -91,7 +105,7 @@
                         Log.w(TAG, "setMobileDataIndicators - slot: " + slotIndex);
                         return;
                     }
-                    if (slotIndex == SubscriptionManager.INVALID_SIM_SLOT_INDEX) {
+                    if (slotIndex == INVALID_SIM_SLOT_INDEX) {
                         Log.e(TAG, "Invalid SIM slot index for subscription: " + indicators.subId);
                         return;
                     }
@@ -129,15 +143,25 @@
         }
     }
 
-    private ShadeCarrierGroupController(ShadeCarrierGroup view, ActivityStarter activityStarter,
-            @Background Handler bgHandler, @Main Looper mainLooper,
+    private ShadeCarrierGroupController(
+            ShadeCarrierGroup view,
+            ActivityStarter activityStarter,
+            @Background Handler bgHandler,
+            @Main Looper mainLooper,
             NetworkController networkController,
-            CarrierTextManager.Builder carrierTextManagerBuilder, Context context,
-            CarrierConfigTracker carrierConfigTracker, SlotIndexResolver slotIndexResolver) {
-
+            CarrierTextManager.Builder carrierTextManagerBuilder,
+            Context context,
+            CarrierConfigTracker carrierConfigTracker,
+            SlotIndexResolver slotIndexResolver,
+            MobileUiAdapter mobileUiAdapter,
+            MobileContextProvider mobileContextProvider,
+            StatusBarPipelineFlags statusBarPipelineFlags
+    ) {
+        mContext = context;
         mActivityStarter = activityStarter;
         mBgHandler = bgHandler;
         mNetworkController = networkController;
+        mStatusBarPipelineFlags = statusBarPipelineFlags;
         mCarrierTextManager = carrierTextManagerBuilder
                 .setShowAirplaneMode(false)
                 .setShowMissingSim(false)
@@ -162,6 +186,14 @@
         mCarrierGroups[1] = view.getCarrier2View();
         mCarrierGroups[2] = view.getCarrier3View();
 
+        mMobileContextProvider = mobileContextProvider;
+        mMobileIconsViewModel = mobileUiAdapter.getMobileIconsViewModel();
+
+        if (mStatusBarPipelineFlags.useNewShadeCarrierGroupMobileIcons()) {
+            mobileUiAdapter.setShadeCarrierGroupController(this);
+            MobileIconsBinder.bind(view, mMobileIconsViewModel);
+        }
+
         mCarrierDividers[0] = view.getCarrierDivider1();
         mCarrierDividers[1] = view.getCarrierDivider2();
 
@@ -193,6 +225,50 @@
         });
     }
 
+    /** Updates the number of visible mobile icons using the new pipeline. */
+    public void updateModernMobileIcons(List<Integer> subIds) {
+        if (!mStatusBarPipelineFlags.useNewShadeCarrierGroupMobileIcons()) {
+            Log.d(TAG, "ignoring new pipeline callback because new mobile icon is disabled");
+            return;
+        }
+
+        for (ShadeCarrier carrier : mCarrierGroups) {
+            carrier.removeModernMobileView();
+        }
+
+        List<IconData> iconDataList = processSubIdList(subIds);
+
+        for (IconData iconData : iconDataList) {
+            ShadeCarrier carrier = mCarrierGroups[iconData.slotIndex];
+
+            Context mobileContext =
+                    mMobileContextProvider.getMobileContextForSub(iconData.subId, mContext);
+            ModernShadeCarrierGroupMobileView modernMobileView = ModernShadeCarrierGroupMobileView
+                    .constructAndBind(
+                        mobileContext,
+                        mMobileIconsViewModel.getLogger(),
+                        "mobile_carrier_shade_group",
+                        (ShadeCarrierGroupMobileIconViewModel) mMobileIconsViewModel
+                                .viewModelForSub(iconData.subId,
+                                    StatusBarLocation.SHADE_CARRIER_GROUP)
+                    );
+            carrier.addModernMobileView(modernMobileView);
+        }
+    }
+
+    @VisibleForTesting
+    List<IconData> processSubIdList(List<Integer> subIds) {
+        return subIds
+                .stream()
+                .limit(SIM_SLOTS)
+                .map(subId -> new IconData(subId, getSlotIndex(subId)))
+                .filter(iconData ->
+                        iconData.slotIndex < SIM_SLOTS
+                                && iconData.slotIndex != INVALID_SIM_SLOT_INDEX
+                )
+                .toList();
+    }
+
     @VisibleForTesting
     protected int getSlotIndex(int subscriptionId) {
         return mSlotIndexResolver.getSlotIndex(subscriptionId);
@@ -269,8 +345,12 @@
             }
         }
 
-        for (int i = 0; i < SIM_SLOTS; i++) {
-            mCarrierGroups[i].updateState(mInfos[i], singleCarrier);
+        if (mStatusBarPipelineFlags.useNewShadeCarrierGroupMobileIcons()) {
+            Log.d(TAG, "ignoring old pipeline callback because new mobile icon is enabled");
+        } else {
+            for (int i = 0; i < SIM_SLOTS; i++) {
+                mCarrierGroups[i].updateState(mInfos[i], singleCarrier);
+            }
         }
 
         mCarrierDividers[0].setVisibility(
@@ -306,7 +386,7 @@
                         Log.w(TAG, "updateInfoCarrier - slot: " + slot);
                         continue;
                     }
-                    if (slot == SubscriptionManager.INVALID_SIM_SLOT_INDEX) {
+                    if (slot == INVALID_SIM_SLOT_INDEX) {
                         Log.e(TAG,
                                 "Invalid SIM slot index for subscription: "
                                         + info.subscriptionIds[i]);
@@ -385,12 +465,24 @@
         private final Context mContext;
         private final CarrierConfigTracker mCarrierConfigTracker;
         private final SlotIndexResolver mSlotIndexResolver;
+        private final MobileUiAdapter mMobileUiAdapter;
+        private final MobileContextProvider mMobileContextProvider;
+        private final StatusBarPipelineFlags mStatusBarPipelineFlags;
 
         @Inject
-        public Builder(ActivityStarter activityStarter, @Background Handler handler,
-                @Main Looper looper, NetworkController networkController,
-                CarrierTextManager.Builder carrierTextControllerBuilder, Context context,
-                CarrierConfigTracker carrierConfigTracker, SlotIndexResolver slotIndexResolver) {
+        public Builder(
+                ActivityStarter activityStarter,
+                @Background Handler handler,
+                @Main Looper looper,
+                NetworkController networkController,
+                CarrierTextManager.Builder carrierTextControllerBuilder,
+                Context context,
+                CarrierConfigTracker carrierConfigTracker,
+                SlotIndexResolver slotIndexResolver,
+                MobileUiAdapter mobileUiAdapter,
+                MobileContextProvider mobileContextProvider,
+                StatusBarPipelineFlags statusBarPipelineFlags
+        ) {
             mActivityStarter = activityStarter;
             mHandler = handler;
             mLooper = looper;
@@ -399,6 +491,9 @@
             mContext = context;
             mCarrierConfigTracker = carrierConfigTracker;
             mSlotIndexResolver = slotIndexResolver;
+            mMobileUiAdapter = mobileUiAdapter;
+            mMobileContextProvider = mobileContextProvider;
+            mStatusBarPipelineFlags = statusBarPipelineFlags;
         }
 
         public Builder setShadeCarrierGroup(ShadeCarrierGroup view) {
@@ -407,9 +502,20 @@
         }
 
         public ShadeCarrierGroupController build() {
-            return new ShadeCarrierGroupController(mView, mActivityStarter, mHandler, mLooper,
-                    mNetworkController, mCarrierTextControllerBuilder, mContext,
-                    mCarrierConfigTracker, mSlotIndexResolver);
+            return new ShadeCarrierGroupController(
+                    mView,
+                    mActivityStarter,
+                    mHandler,
+                    mLooper,
+                    mNetworkController,
+                    mCarrierTextControllerBuilder,
+                    mContext,
+                    mCarrierConfigTracker,
+                    mSlotIndexResolver,
+                    mMobileUiAdapter,
+                    mMobileContextProvider,
+                    mStatusBarPipelineFlags
+            );
         }
     }
 
@@ -448,4 +554,15 @@
             return SubscriptionManager.getSlotIndex(subscriptionId);
         }
     }
+
+    @VisibleForTesting
+    static class IconData {
+        public final int subId;
+        public final int slotIndex;
+
+        IconData(int subId, int slotIndex) {
+            this.subId = subId;
+            this.slotIndex = slotIndex;
+        }
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/PrecomputedTextViewFactory.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/PrecomputedTextViewFactory.kt
index b002330..c276827 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/PrecomputedTextViewFactory.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/PrecomputedTextViewFactory.kt
@@ -20,7 +20,9 @@
 import android.util.AttributeSet
 import android.view.View
 import android.widget.TextView
+import com.android.internal.widget.ConversationLayout
 import com.android.internal.widget.ImageFloatingTextView
+import com.android.internal.widget.MessagingLayout
 import javax.inject.Inject
 
 class PrecomputedTextViewFactory @Inject constructor() : NotifRemoteViewsFactory {
@@ -35,6 +37,10 @@
             TextView::class.java.simpleName -> PrecomputedTextView(context, attrs)
             ImageFloatingTextView::class.java.name ->
                 PrecomputedImageFloatingTextView(context, attrs)
+            MessagingLayout::class.java.name ->
+                MessagingLayout(context, attrs).apply { setPrecomputedTextEnabled(true) }
+            ConversationLayout::class.java.name ->
+                ConversationLayout(context, attrs).apply { setPrecomputedTextEnabled(true) }
             else -> null
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfaces.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfaces.java
index 5c28be3..af09bf2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfaces.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfaces.java
@@ -25,7 +25,6 @@
 import android.content.pm.PackageManager;
 import android.os.Bundle;
 import android.os.UserHandle;
-import android.view.KeyEvent;
 import android.view.MotionEvent;
 import android.view.RemoteAnimationAdapter;
 import android.view.View;
@@ -276,19 +275,11 @@
 
     void userActivity();
 
-    boolean interceptMediaKey(KeyEvent event);
-
-    boolean dispatchKeyEventPreIme(KeyEvent event);
-
-    boolean onMenuPressed();
-
     void endAffordanceLaunch();
 
     /** Should the keyguard be hidden immediately in response to a back press/gesture. */
     boolean shouldKeyguardHideImmediately();
 
-    boolean onSpacePressed();
-
     void showBouncerWithDimissAndCancelIfKeyguard(OnDismissAction performAction,
             Runnable cancelAction);
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
index 8ffd43a..ccb87bf 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
@@ -89,7 +89,6 @@
 import android.view.Display;
 import android.view.IRemoteAnimationRunner;
 import android.view.IWindowManager;
-import android.view.KeyEvent;
 import android.view.MotionEvent;
 import android.view.ThreadedRenderer;
 import android.view.View;
@@ -2636,44 +2635,6 @@
     }
 
     @Override
-    public boolean interceptMediaKey(KeyEvent event) {
-        return mState == StatusBarState.KEYGUARD
-                && mStatusBarKeyguardViewManager.interceptMediaKey(event);
-    }
-
-    /**
-     * While IME is active and a BACK event is detected, check with
-     * {@link StatusBarKeyguardViewManager#dispatchBackKeyEventPreIme()} to see if the event
-     * should be handled before routing to IME, in order to prevent the user having to hit back
-     * twice to exit bouncer.
-     */
-    @Override
-    public boolean dispatchKeyEventPreIme(KeyEvent event) {
-        switch (event.getKeyCode()) {
-            case KeyEvent.KEYCODE_BACK:
-                if (mState == StatusBarState.KEYGUARD
-                        && mStatusBarKeyguardViewManager.dispatchBackKeyEventPreIme()) {
-                    return mBackActionInteractor.onBackRequested();
-                }
-        }
-        return false;
-    }
-
-    protected boolean shouldUnlockOnMenuPressed() {
-        return mDeviceInteractive && mState != StatusBarState.SHADE
-            && mStatusBarKeyguardViewManager.shouldDismissOnMenuPressed();
-    }
-
-    @Override
-    public boolean onMenuPressed() {
-        if (shouldUnlockOnMenuPressed()) {
-            mShadeController.animateCollapseShadeForced();
-            return true;
-        }
-        return false;
-    }
-
-    @Override
     public void endAffordanceLaunch() {
         releaseGestureWakeLock();
         mCameraLauncherLazy.get().setLaunchingAffordance(false);
@@ -2692,15 +2653,6 @@
         return (isScrimmedBouncer || isBouncerOverDream);
     }
 
-    @Override
-    public boolean onSpacePressed() {
-        if (mDeviceInteractive && mState != StatusBarState.SHADE) {
-            mShadeController.animateCollapseShadeForced();
-            return true;
-        }
-        return false;
-    }
-
     private void showBouncerOrLockScreenIfKeyguard() {
         // If the keyguard is animating away, we aren't really the keyguard anymore and should not
         // show the bouncer/lockscreen.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
index fc66138..62a8cfd 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
@@ -709,6 +709,11 @@
         }
     }
 
+    public void onUnlockAnimationFinished() {
+        mAnimatingPanelExpansionOnUnlock = false;
+        applyAndDispatchState();
+    }
+
     /**
      * Set the amount of progress we are currently in if we're transitioning to the full shade.
      * 0.0f means we're not transitioning yet, while 1 means we're all the way in the full
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarLocation.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarLocation.kt
index 5ace226..32e5c35 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarLocation.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarLocation.kt
@@ -24,4 +24,6 @@
     KEYGUARD,
     /** Quick settings (inside the shade). */
     QS,
+    /** ShadeCarrierGroup (above QS status bar in expanded mode). */
+    SHADE_CARRIER_GROUP,
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/StatusBarPipelineFlags.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/StatusBarPipelineFlags.kt
index 6e51ed0..c695773 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/StatusBarPipelineFlags.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/StatusBarPipelineFlags.kt
@@ -18,6 +18,9 @@
 
 import android.content.Context
 import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.flags.Flags
+import com.android.systemui.shade.carrier.ShadeCarrierGroup
 import javax.inject.Inject
 
 /** All flagging methods related to the new status bar pipeline (see b/238425913). */
@@ -26,11 +29,19 @@
 @Inject
 constructor(
     context: Context,
+    private val featureFlags: FeatureFlags,
 ) {
     private val mobileSlot = context.getString(com.android.internal.R.string.status_bar_mobile)
     private val wifiSlot = context.getString(com.android.internal.R.string.status_bar_wifi)
 
     /**
+     * True if we should display the mobile icons in the [ShadeCarrierGroup] using the new status
+     * bar Data pipeline.
+     */
+    fun useNewShadeCarrierGroupMobileIcons(): Boolean =
+        featureFlags.isEnabled(Flags.NEW_SHADE_CARRIER_GROUP_MOBILE_ICONS)
+
+    /**
      * For convenience in the StatusBarIconController, we want to gate some actions based on slot
      * name and the flag together.
      *
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/NetworkNameModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/NetworkNameModel.kt
index 78231e2..99ed2d9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/NetworkNameModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/NetworkNameModel.kt
@@ -60,6 +60,19 @@
         }
     }
 
+    /** This name has been derived from SubscriptionModel. see [SubscriptionModel] */
+    data class SubscriptionDerived(override val name: String) : NetworkNameModel {
+        override fun logDiffs(prevVal: NetworkNameModel, row: TableRowLogger) {
+            if (prevVal !is SubscriptionDerived || prevVal.name != name) {
+                row.logChange(COL_NETWORK_NAME, "SubscriptionDerived($name)")
+            }
+        }
+
+        override fun logFull(row: TableRowLogger) {
+            row.logChange(COL_NETWORK_NAME, "SubscriptionDerived($name)")
+        }
+    }
+
     /**
      * This name has been derived from the sim via
      * [android.telephony.TelephonyManager.getSimOperatorName].
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/SubscriptionModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/SubscriptionModel.kt
index 16c4027..27f6df4 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/SubscriptionModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/SubscriptionModel.kt
@@ -34,4 +34,7 @@
 
     /** Subscriptions in the same group may be filtered or treated as a single subscription */
     val groupUuid: ParcelUuid? = null,
+
+    /** Text representing the name for this connection */
+    val carrierName: String,
 )
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
index c1af6df..a89b1b2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
@@ -115,10 +115,18 @@
      */
     val cdmaRoaming: StateFlow<Boolean>
 
-    /** The service provider name for this network connection, or the default name */
+    /** The service provider name for this network connection, or the default name. */
     val networkName: StateFlow<NetworkNameModel>
 
     /**
+     * The service provider name for this network connection, or the default name.
+     *
+     * TODO(b/296600321): De-duplicate this field with [networkName] after determining the data
+     *   provided is identical
+     */
+    val carrierName: StateFlow<NetworkNameModel>
+
+    /**
      * True if this type of connection is allowed while airplane mode is on, and false otherwise.
      */
     val isAllowedDuringAirplaneMode: StateFlow<Boolean>
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
index 17d20c2..c576b82 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
@@ -184,7 +184,10 @@
 
     override val cdmaRoaming = MutableStateFlow(false)
 
-    override val networkName = MutableStateFlow(NetworkNameModel.IntentDerived("demo network"))
+    override val networkName = MutableStateFlow(NetworkNameModel.IntentDerived(DEMO_CARRIER_NAME))
+
+    override val carrierName =
+        MutableStateFlow(NetworkNameModel.SubscriptionDerived(DEMO_CARRIER_NAME))
 
     override val isAllowedDuringAirplaneMode = MutableStateFlow(false)
 
@@ -200,6 +203,7 @@
         // This is always true here, because we split out disabled states at the data-source level
         dataEnabled.value = true
         networkName.value = NetworkNameModel.IntentDerived(event.name)
+        carrierName.value = NetworkNameModel.SubscriptionDerived("${event.name} ${event.subId}")
 
         _carrierId.value = event.carrierId ?: INVALID_SUBSCRIPTION_ID
 
@@ -227,6 +231,7 @@
         // This is always true here, because we split out disabled states at the data-source level
         dataEnabled.value = true
         networkName.value = NetworkNameModel.IntentDerived(CARRIER_MERGED_NAME)
+        carrierName.value = NetworkNameModel.SubscriptionDerived(CARRIER_MERGED_NAME)
         // TODO(b/276943904): is carrierId a thing with carrier merged networks?
         _carrierId.value = INVALID_SUBSCRIPTION_ID
         numberOfLevels.value = event.numberOfLevels
@@ -248,6 +253,7 @@
     }
 
     companion object {
+        private const val DEMO_CARRIER_NAME = "Demo Carrier"
         private const val CARRIER_MERGED_NAME = "Carrier Merged Network"
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepository.kt
index 0e4ceeb..ee13d93 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepository.kt
@@ -92,9 +92,12 @@
 
     private fun maybeCreateSubscription(subId: Int) {
         if (!subscriptionInfoCache.containsKey(subId)) {
-            SubscriptionModel(subscriptionId = subId, isOpportunistic = false).also {
-                subscriptionInfoCache[subId] = it
-            }
+            SubscriptionModel(
+                    subscriptionId = subId,
+                    isOpportunistic = false,
+                    carrierName = DEFAULT_CARRIER_NAME,
+                )
+                .also { subscriptionInfoCache[subId] = it }
 
             _subscriptions.value = subscriptionInfoCache.values.toList()
         }
@@ -327,6 +330,7 @@
         private const val TAG = "DemoMobileConnectionsRepo"
 
         private const val DEFAULT_SUB_ID = 1
+        private const val DEFAULT_CARRIER_NAME = "demo carrier"
     }
 }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt
index 65f4866..28be3be 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt
@@ -108,6 +108,8 @@
                 NetworkNameModel.SimDerived(telephonyManager.simOperatorName),
             )
 
+    override val carrierName: StateFlow<NetworkNameModel> = networkName
+
     override val numberOfLevels: StateFlow<Int> =
         wifiRepository.wifiNetwork
             .map {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt
index 8ba7d21..ee11c06 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt
@@ -22,6 +22,7 @@
 import com.android.systemui.log.table.TableLogBufferFactory
 import com.android.systemui.log.table.logDiffsForTable
 import com.android.systemui.statusbar.pipeline.mobile.data.model.NetworkNameModel
+import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel
 import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionRepository
 import javax.inject.Inject
 import kotlinx.coroutines.CoroutineScope
@@ -47,6 +48,7 @@
     override val subId: Int,
     startingIsCarrierMerged: Boolean,
     override val tableLogBuffer: TableLogBuffer,
+    subscriptionModel: StateFlow<SubscriptionModel?>,
     private val defaultNetworkName: NetworkNameModel,
     private val networkNameSeparator: String,
     @Application scope: CoroutineScope,
@@ -80,6 +82,7 @@
         mobileRepoFactory.build(
             subId,
             tableLogBuffer,
+            subscriptionModel,
             defaultNetworkName,
             networkNameSeparator,
         )
@@ -287,6 +290,16 @@
             )
             .stateIn(scope, SharingStarted.WhileSubscribed(), activeRepo.value.networkName.value)
 
+    override val carrierName =
+        activeRepo
+            .flatMapLatest { it.carrierName }
+            .logDiffsForTable(
+                tableLogBuffer,
+                columnPrefix = "",
+                initialValue = activeRepo.value.carrierName.value,
+            )
+            .stateIn(scope, SharingStarted.WhileSubscribed(), activeRepo.value.carrierName.value)
+
     override val isAllowedDuringAirplaneMode =
         activeRepo
             .flatMapLatest { it.isAllowedDuringAirplaneMode }
@@ -307,6 +320,7 @@
         fun build(
             subId: Int,
             startingIsCarrierMerged: Boolean,
+            subscriptionModel: StateFlow<SubscriptionModel?>,
             defaultNetworkName: NetworkNameModel,
             networkNameSeparator: String,
         ): FullMobileConnectionRepository {
@@ -317,6 +331,7 @@
                 subId,
                 startingIsCarrierMerged,
                 mobileLogger,
+                subscriptionModel,
                 defaultNetworkName,
                 networkNameSeparator,
                 scope,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt
index aadc975..1f1ac92 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt
@@ -43,6 +43,7 @@
 import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.DefaultNetworkType
 import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.OverrideNetworkType
 import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.UnknownNetworkType
+import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel
 import com.android.systemui.statusbar.pipeline.mobile.data.model.SystemUiCarrierConfig
 import com.android.systemui.statusbar.pipeline.mobile.data.model.toDataConnectionType
 import com.android.systemui.statusbar.pipeline.mobile.data.model.toNetworkNameModel
@@ -80,6 +81,7 @@
 @OptIn(ExperimentalCoroutinesApi::class)
 class MobileConnectionRepositoryImpl(
     override val subId: Int,
+    subscriptionModel: StateFlow<SubscriptionModel?>,
     defaultNetworkName: NetworkNameModel,
     networkNameSeparator: String,
     private val telephonyManager: TelephonyManager,
@@ -281,6 +283,14 @@
             }
             .stateIn(scope, SharingStarted.WhileSubscribed(), DEFAULT_NUM_LEVELS)
 
+    override val carrierName =
+        subscriptionModel
+            .map {
+                it?.let { model -> NetworkNameModel.SubscriptionDerived(model.carrierName) }
+                    ?: defaultNetworkName
+            }
+            .stateIn(scope, SharingStarted.WhileSubscribed(), defaultNetworkName)
+
     /**
      * There are a few cases where we will need to poll [TelephonyManager] so we can update some
      * internal state where callbacks aren't provided. Any of those events should be merged into
@@ -350,11 +360,13 @@
         fun build(
             subId: Int,
             mobileLogger: TableLogBuffer,
+            subscriptionModel: StateFlow<SubscriptionModel?>,
             defaultNetworkName: NetworkNameModel,
             networkNameSeparator: String,
         ): MobileConnectionRepository {
             return MobileConnectionRepositoryImpl(
                 subId,
+                subscriptionModel,
                 defaultNetworkName,
                 networkNameSeparator,
                 telephonyManager.createForSubscriptionId(subId),
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryImpl.kt
index 54948a4..67b04db 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryImpl.kt
@@ -319,10 +319,17 @@
 
     @VisibleForTesting fun getSubIdRepoCache() = subIdRepositoryCache
 
+    private fun subscriptionModelForSubId(subId: Int): StateFlow<SubscriptionModel?> {
+        return subscriptions
+            .map { list -> list.firstOrNull { model -> model.subscriptionId == subId } }
+            .stateIn(scope, SharingStarted.WhileSubscribed(), null)
+    }
+
     private fun createRepositoryForSubId(subId: Int): FullMobileConnectionRepository {
         return fullMobileRepoFactory.build(
             subId,
             isCarrierMerged(subId),
+            subscriptionModelForSubId(subId),
             defaultNetworkName,
             networkNameSeparator,
         )
@@ -373,6 +380,7 @@
             subscriptionId = subscriptionId,
             isOpportunistic = isOpportunistic,
             groupUuid = groupUuid,
+            carrierName = carrierName.toString(),
         )
 
     companion object {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
index 1a13827..4cfde5b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
@@ -92,6 +92,22 @@
      */
     val networkName: StateFlow<NetworkNameModel>
 
+    /**
+     * Provider name for this network connection. The name can be one of 3 values:
+     * 1. The default network name, if one is configured
+     * 2. A name provided by the [SubscriptionModel] of this network connection
+     * 3. Or, in the case where the repository sends us the default network name, we check for an
+     *    override in [connectionInfo.operatorAlphaShort], a value that is derived from
+     *    [ServiceState]
+     *
+     * TODO(b/296600321): De-duplicate this field with [networkName] after determining the data
+     *   provided is identical
+     */
+    val carrierName: StateFlow<String>
+
+    /** True if there is only one active subscription. */
+    val isSingleCarrier: StateFlow<Boolean>
+
     /** True if this line of service is emergency-only */
     val isEmergencyOnly: StateFlow<Boolean>
 
@@ -126,6 +142,7 @@
     defaultSubscriptionHasDataEnabled: StateFlow<Boolean>,
     override val alwaysShowDataRatIcon: StateFlow<Boolean>,
     override val alwaysUseCdmaLevel: StateFlow<Boolean>,
+    override val isSingleCarrier: StateFlow<Boolean>,
     override val mobileIsDefault: StateFlow<Boolean>,
     defaultMobileIconMapping: StateFlow<Map<String, MobileIconGroup>>,
     defaultMobileIconGroup: StateFlow<MobileIconGroup>,
@@ -171,6 +188,22 @@
                 connectionRepository.networkName.value
             )
 
+    override val carrierName =
+        combine(connectionRepository.operatorAlphaShort, connectionRepository.carrierName) {
+                operatorAlphaShort,
+                networkName ->
+                if (networkName is NetworkNameModel.Default && operatorAlphaShort != null) {
+                    operatorAlphaShort
+                } else {
+                    networkName.name
+                }
+            }
+            .stateIn(
+                scope,
+                SharingStarted.WhileSubscribed(),
+                connectionRepository.carrierName.value.name
+            )
+
     /** What the mobile icon would be before carrierId overrides */
     private val defaultNetworkType: StateFlow<MobileIconGroup> =
         combine(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt
index e90f40c7..d08808b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt
@@ -76,6 +76,9 @@
     /** True if the CDMA level should be preferred over the primary level. */
     val alwaysUseCdmaLevel: StateFlow<Boolean>
 
+    /** True if there is only one active subscription. */
+    val isSingleCarrier: StateFlow<Boolean>
+
     /** The icon mapping from network type to [MobileIconGroup] for the default subscription */
     val defaultMobileIconMapping: StateFlow<Map<String, MobileIconGroup>>
 
@@ -252,6 +255,17 @@
             .mapLatest { it.alwaysShowCdmaRssi }
             .stateIn(scope, SharingStarted.WhileSubscribed(), false)
 
+    override val isSingleCarrier: StateFlow<Boolean> =
+        mobileConnectionsRepo.subscriptions
+            .map { it.size == 1 }
+            .logDiffsForTable(
+                tableLogger,
+                columnPrefix = LOGGING_PREFIX,
+                columnName = "isSingleCarrier",
+                initialValue = false,
+            )
+            .stateIn(scope, SharingStarted.WhileSubscribed(), false)
+
     /** If there is no mapping in [defaultMobileIconMapping], then use this default icon group */
     override val defaultMobileIconGroup: StateFlow<MobileIconGroup> =
         mobileConnectionsRepo.defaultMobileIconGroup.stateIn(
@@ -298,6 +312,7 @@
             activeDataConnectionHasDataEnabled,
             alwaysShowDataRatIcon,
             alwaysUseCdmaLevel,
+            isSingleCarrier,
             mobileIsDefault,
             defaultMobileIconMapping,
             defaultMobileIconGroup,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileUiAdapter.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileUiAdapter.kt
index d7fcf48..02e50a0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileUiAdapter.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileUiAdapter.kt
@@ -19,6 +19,7 @@
 import com.android.systemui.CoreStartable
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.dagger.qualifiers.Application
+import com.android.systemui.shade.carrier.ShadeCarrierGroupController
 import com.android.systemui.statusbar.phone.StatusBarIconController
 import com.android.systemui.statusbar.pipeline.mobile.domain.interactor.MobileIconsInteractor
 import com.android.systemui.statusbar.pipeline.mobile.ui.viewmodel.MobileIconsViewModel
@@ -49,6 +50,8 @@
     private var isCollecting: Boolean = false
     private var lastValue: List<Int>? = null
 
+    private var shadeCarrierGroupController: ShadeCarrierGroupController? = null
+
     override fun start() {
         // Start notifying the icon controller of subscriptions
         scope.launch {
@@ -57,10 +60,16 @@
                 logger.logUiAdapterSubIdsSentToIconController(it)
                 lastValue = it
                 iconController.setNewMobileIconSubIds(it)
+                shadeCarrierGroupController?.updateModernMobileIcons(it)
             }
         }
     }
 
+    /** Set the [ShadeCarrierGroupController] to notify of subscription updates */
+    fun setShadeCarrierGroupController(controller: ShadeCarrierGroupController) {
+        shadeCarrierGroupController = controller
+    }
+
     override fun dump(pw: PrintWriter, args: Array<out String>) {
         pw.println("isCollecting=$isCollecting")
         pw.println("Last values sent to icon controller: $lastValue")
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileViewLogger.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileViewLogger.kt
index cea6654..2af6795b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileViewLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileViewLogger.kt
@@ -57,7 +57,7 @@
             {
                 str1 = view.getIdForLogging()
                 str2 = viewModel.getIdForLogging()
-                str3 = viewModel.locationName
+                str3 = viewModel.location.name
             },
             { "New view binding. viewId=$str1, viewModelId=$str2, viewModelLocation=$str3" },
         )
@@ -71,7 +71,7 @@
             {
                 str1 = view.getIdForLogging()
                 str2 = viewModel.getIdForLogging()
-                str3 = viewModel.locationName
+                str3 = viewModel.location.name
             },
             { "Collection started. viewId=$str1, viewModelId=$str2, viewModelLocation=$str3" },
         )
@@ -85,7 +85,7 @@
             {
                 str1 = view.getIdForLogging()
                 str2 = viewModel.getIdForLogging()
-                str3 = viewModel.locationName
+                str3 = viewModel.location.name
             },
             { "Collection stopped. viewId=$str1, viewModelId=$str2, viewModelLocation=$str3" },
         )
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/MobileIconBinder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/MobileIconBinder.kt
index 55bc8d5..4b2fb43 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/MobileIconBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/MobileIconBinder.kt
@@ -50,6 +50,7 @@
     fun bind(
         view: ViewGroup,
         viewModel: LocationBasedMobileViewModel,
+        @StatusBarIconView.VisibleState initialVisibilityState: Int = STATE_HIDDEN,
         logger: MobileViewLogger,
     ): ModernStatusBarViewBinding {
         val mobileGroupView = view.requireViewById<ViewGroup>(R.id.mobile_group)
@@ -68,12 +69,12 @@
 
         // TODO(b/238425913): We should log this visibility state.
         @StatusBarIconView.VisibleState
-        val visibilityState: MutableStateFlow<Int> = MutableStateFlow(STATE_HIDDEN)
+        val visibilityState: MutableStateFlow<Int> = MutableStateFlow(initialVisibilityState)
 
         val iconTint: MutableStateFlow<Int> = MutableStateFlow(viewModel.defaultColor)
         val decorTint: MutableStateFlow<Int> = MutableStateFlow(viewModel.defaultColor)
 
-        var isCollecting: Boolean = false
+        var isCollecting = false
 
         view.repeatWhenAttached {
             repeatOnLifecycle(Lifecycle.State.STARTED) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/ShadeCarrierBinder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/ShadeCarrierBinder.kt
new file mode 100644
index 0000000..081e101
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/ShadeCarrierBinder.kt
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.pipeline.mobile.ui.binder
+
+import androidx.core.view.isVisible
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.repeatOnLifecycle
+import com.android.systemui.lifecycle.repeatWhenAttached
+import com.android.systemui.statusbar.pipeline.mobile.ui.viewmodel.ShadeCarrierGroupMobileIconViewModel
+import com.android.systemui.util.AutoMarqueeTextView
+import kotlinx.coroutines.launch
+
+object ShadeCarrierBinder {
+    /** Binds the view to the view-model, continuing to update the former based on the latter */
+    @JvmStatic
+    fun bind(
+        carrierTextView: AutoMarqueeTextView,
+        viewModel: ShadeCarrierGroupMobileIconViewModel,
+    ) {
+        carrierTextView.isVisible = true
+
+        carrierTextView.repeatWhenAttached {
+            repeatOnLifecycle(Lifecycle.State.STARTED) {
+                launch { viewModel.carrierName.collect { carrierTextView.text = it } }
+            }
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernShadeCarrierGroupMobileView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernShadeCarrierGroupMobileView.kt
new file mode 100644
index 0000000..f407127
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernShadeCarrierGroupMobileView.kt
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.pipeline.mobile.ui.view
+
+import android.content.Context
+import android.util.AttributeSet
+import android.view.LayoutInflater
+import android.widget.LinearLayout
+import com.android.systemui.R
+import com.android.systemui.statusbar.StatusBarIconView.STATE_ICON
+import com.android.systemui.statusbar.pipeline.mobile.ui.MobileViewLogger
+import com.android.systemui.statusbar.pipeline.mobile.ui.binder.MobileIconBinder
+import com.android.systemui.statusbar.pipeline.mobile.ui.binder.ShadeCarrierBinder
+import com.android.systemui.statusbar.pipeline.mobile.ui.viewmodel.ShadeCarrierGroupMobileIconViewModel
+import com.android.systemui.util.AutoMarqueeTextView
+
+/**
+ * ViewGroup containing a mobile carrier name and icon in the Shade Header. Can be multiple
+ * instances as children under [ShadeCarrierGroup]
+ */
+class ModernShadeCarrierGroupMobileView(
+    context: Context,
+    attrs: AttributeSet?,
+) : LinearLayout(context, attrs) {
+
+    var subId: Int = -1
+
+    override fun toString(): String {
+        return "ModernShadeCarrierGroupMobileView(" +
+            "subId=$subId, " +
+            "viewString=${super.toString()}"
+    }
+
+    companion object {
+
+        /**
+         * Inflates a new instance of [ModernShadeCarrierGroupMobileView], binds it to [viewModel],
+         * and returns it.
+         */
+        @JvmStatic
+        fun constructAndBind(
+            context: Context,
+            logger: MobileViewLogger,
+            slot: String,
+            viewModel: ShadeCarrierGroupMobileIconViewModel,
+        ): ModernShadeCarrierGroupMobileView {
+            return (LayoutInflater.from(context).inflate(R.layout.shade_carrier_new, null)
+                    as ModernShadeCarrierGroupMobileView)
+                .also {
+                    it.subId = viewModel.subscriptionId
+
+                    val iconView = it.requireViewById<ModernStatusBarMobileView>(R.id.mobile_combo)
+                    iconView.initView(slot) {
+                        MobileIconBinder.bind(iconView, viewModel, STATE_ICON, logger)
+                    }
+                    logger.logNewViewBinding(it, viewModel)
+
+                    val textView = it.requireViewById<AutoMarqueeTextView>(R.id.mobile_carrier_text)
+                    ShadeCarrierBinder.bind(textView, viewModel)
+                }
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt
index 4144293d..68d02de 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt
@@ -60,7 +60,9 @@
                     as ModernStatusBarMobileView)
                 .also {
                     it.subId = viewModel.subscriptionId
-                    it.initView(slot) { MobileIconBinder.bind(it, viewModel, logger) }
+                    it.initView(slot) {
+                        MobileIconBinder.bind(view = it, viewModel = viewModel, logger = logger)
+                    }
                     logger.logNewViewBinding(it, viewModel)
                 }
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/LocationBasedMobileViewModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/LocationBasedMobileViewModel.kt
index a51982c..e7c311d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/LocationBasedMobileViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/LocationBasedMobileViewModel.kt
@@ -18,7 +18,13 @@
 
 import android.graphics.Color
 import com.android.systemui.statusbar.phone.StatusBarLocation
+import com.android.systemui.statusbar.pipeline.mobile.domain.interactor.MobileIconInteractor
 import com.android.systemui.statusbar.pipeline.mobile.ui.VerboseMobileViewLogger
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.stateIn
 
 /**
  * A view model for an individual mobile icon that embeds the notion of a [StatusBarLocation]. This
@@ -26,12 +32,12 @@
  *
  * @param commonImpl for convenience, this class wraps a base interface that can provides all of the
  *   common implementations between locations. See [MobileIconViewModel]
- * @property locationName the name of the location of this VM, used for logging.
+ * @property location the [StatusBarLocation] of this VM.
  * @property verboseLogger an optional logger to log extremely verbose view updates.
  */
 abstract class LocationBasedMobileViewModel(
     val commonImpl: MobileIconViewModelCommon,
-    val locationName: String,
+    val location: StatusBarLocation,
     val verboseLogger: VerboseMobileViewLogger?,
 ) : MobileIconViewModelCommon by commonImpl {
     val defaultColor: Int = Color.WHITE
@@ -39,10 +45,12 @@
     companion object {
         fun viewModelForLocation(
             commonImpl: MobileIconViewModelCommon,
+            interactor: MobileIconInteractor,
             verboseMobileViewLogger: VerboseMobileViewLogger,
-            loc: StatusBarLocation,
+            location: StatusBarLocation,
+            scope: CoroutineScope,
         ): LocationBasedMobileViewModel =
-            when (loc) {
+            when (location) {
                 StatusBarLocation.HOME ->
                     HomeMobileIconViewModel(
                         commonImpl,
@@ -50,6 +58,12 @@
                     )
                 StatusBarLocation.KEYGUARD -> KeyguardMobileIconViewModel(commonImpl)
                 StatusBarLocation.QS -> QsMobileIconViewModel(commonImpl)
+                StatusBarLocation.SHADE_CARRIER_GROUP ->
+                    ShadeCarrierGroupMobileIconViewModel(
+                        commonImpl,
+                        interactor,
+                        scope,
+                    )
             }
     }
 }
@@ -61,7 +75,7 @@
     MobileIconViewModelCommon,
     LocationBasedMobileViewModel(
         commonImpl,
-        locationName = "Home",
+        location = StatusBarLocation.HOME,
         verboseMobileViewLogger,
     )
 
@@ -71,18 +85,40 @@
     MobileIconViewModelCommon,
     LocationBasedMobileViewModel(
         commonImpl,
-        locationName = "QS",
+        location = StatusBarLocation.QS,
         // Only do verbose logging for the Home location.
         verboseLogger = null,
     )
 
+class ShadeCarrierGroupMobileIconViewModel(
+    commonImpl: MobileIconViewModelCommon,
+    interactor: MobileIconInteractor,
+    scope: CoroutineScope,
+) :
+    MobileIconViewModelCommon,
+    LocationBasedMobileViewModel(
+        commonImpl,
+        location = StatusBarLocation.SHADE_CARRIER_GROUP,
+        // Only do verbose logging for the Home location.
+        verboseLogger = null,
+    ) {
+    private val isSingleCarrier = interactor.isSingleCarrier
+    val carrierName = interactor.carrierName
+
+    override val isVisible: StateFlow<Boolean> =
+        combine(super.isVisible, isSingleCarrier) { isVisible, isSingleCarrier ->
+                if (isSingleCarrier) false else isVisible
+            }
+            .stateIn(scope, SharingStarted.WhileSubscribed(), super.isVisible.value)
+}
+
 class KeyguardMobileIconViewModel(
     commonImpl: MobileIconViewModelCommon,
 ) :
     MobileIconViewModelCommon,
     LocationBasedMobileViewModel(
         commonImpl,
-        locationName = "Keyguard",
+        location = StatusBarLocation.KEYGUARD,
         // Only do verbose logging for the Home location.
         verboseLogger = null,
     )
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt
index 5cf887e..216afb9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt
@@ -22,6 +22,7 @@
 import com.android.systemui.statusbar.phone.StatusBarLocation
 import com.android.systemui.statusbar.pipeline.StatusBarPipelineFlags
 import com.android.systemui.statusbar.pipeline.airplane.domain.interactor.AirplaneModeInteractor
+import com.android.systemui.statusbar.pipeline.mobile.domain.interactor.MobileIconInteractor
 import com.android.systemui.statusbar.pipeline.mobile.domain.interactor.MobileIconsInteractor
 import com.android.systemui.statusbar.pipeline.mobile.ui.MobileViewLogger
 import com.android.systemui.statusbar.pipeline.mobile.ui.VerboseMobileViewLogger
@@ -58,6 +59,8 @@
     private val statusBarPipelineFlags: StatusBarPipelineFlags,
 ) {
     @VisibleForTesting val mobileIconSubIdCache = mutableMapOf<Int, MobileIconViewModel>()
+    @VisibleForTesting
+    val mobileIconInteractorSubIdCache = mutableMapOf<Int, MobileIconInteractor>()
 
     val subscriptionIdsFlow: StateFlow<List<Int>> =
         interactor.filteredSubscriptions
@@ -91,15 +94,17 @@
             .stateIn(scope, SharingStarted.WhileSubscribed(), false)
 
     init {
-        scope.launch { subscriptionIdsFlow.collect { removeInvalidModelsFromCache(it) } }
+        scope.launch { subscriptionIdsFlow.collect { invalidateCaches(it) } }
     }
 
     fun viewModelForSub(subId: Int, location: StatusBarLocation): LocationBasedMobileViewModel {
         val common = commonViewModelForSub(subId)
         return LocationBasedMobileViewModel.viewModelForLocation(
             common,
+            mobileIconInteractorForSub(subId),
             verboseLogger,
             location,
+            scope,
         )
     }
 
@@ -107,7 +112,7 @@
         return mobileIconSubIdCache[subId]
             ?: MobileIconViewModel(
                     subId,
-                    interactor.createMobileConnectionInteractorForSubId(subId),
+                    mobileIconInteractorForSub(subId),
                     airplaneModeInteractor,
                     constants,
                     scope,
@@ -115,8 +120,20 @@
                 .also { mobileIconSubIdCache[subId] = it }
     }
 
-    private fun removeInvalidModelsFromCache(subIds: List<Int>) {
+    @VisibleForTesting
+    fun mobileIconInteractorForSub(subId: Int): MobileIconInteractor {
+        return mobileIconInteractorSubIdCache[subId]
+            ?: interactor.createMobileConnectionInteractorForSubId(subId).also {
+                mobileIconInteractorSubIdCache[subId] = it
+            }
+    }
+
+    private fun invalidateCaches(subIds: List<Int>) {
         val subIdsToRemove = mobileIconSubIdCache.keys.filter { !subIds.contains(it) }
         subIdsToRemove.forEach { mobileIconSubIdCache.remove(it) }
+
+        mobileIconInteractorSubIdCache.keys
+            .filter { !subIds.contains(it) }
+            .forEach { subId -> mobileIconInteractorSubIdCache.remove(subId) }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/LocationBasedWifiViewModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/LocationBasedWifiViewModel.kt
index cd5b92c..00bd616 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/LocationBasedWifiViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/LocationBasedWifiViewModel.kt
@@ -18,6 +18,7 @@
 
 import android.graphics.Color
 import com.android.systemui.statusbar.phone.StatusBarLocation
+import java.lang.IllegalArgumentException
 
 /**
  * A view model for a wifi icon in a specific location. This allows us to control parameters that
@@ -43,6 +44,8 @@
                 StatusBarLocation.HOME -> HomeWifiViewModel(commonImpl)
                 StatusBarLocation.KEYGUARD -> KeyguardWifiViewModel(commonImpl)
                 StatusBarLocation.QS -> QsWifiViewModel(commonImpl)
+                StatusBarLocation.SHADE_CARRIER_GROUP ->
+                    throw IllegalArgumentException("invalid location for WifiViewModel: $location")
             }
     }
 }
@@ -64,3 +67,11 @@
 class QsWifiViewModel(
     commonImpl: WifiViewModelCommon,
 ) : WifiViewModelCommon, LocationBasedWifiViewModel(commonImpl)
+
+/**
+ * A view model for the wifi icon in the shade carrier group (visible when quick settings is fully
+ * expanded, and in large screen shade). Currently unused.
+ */
+class ShadeCarrierGroupWifiViewModel(
+    commonImpl: WifiViewModelCommon,
+) : WifiViewModelCommon, LocationBasedWifiViewModel(commonImpl)
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.kt
index ad4bd58..dff058c 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.kt
@@ -621,6 +621,51 @@
         configurationListenerArgumentCaptor.value.onUiModeChanged()
         verify(view).reloadColors()
     }
+    @Test
+    fun onOrientationChanged_landscapeKeyguardFlagDisabled_blockReinflate() {
+        featureFlags.set(Flags.LOCKSCREEN_ENABLE_LANDSCAPE, false)
+
+        // Run onOrientationChanged
+        val configurationListenerArgumentCaptor =
+            ArgumentCaptor.forClass(ConfigurationController.ConfigurationListener::class.java)
+        underTest.onViewAttached()
+        verify(configurationController).addCallback(configurationListenerArgumentCaptor.capture())
+        clearInvocations(viewFlipperController)
+        configurationListenerArgumentCaptor.value.onOrientationChanged(
+            Configuration.ORIENTATION_LANDSCAPE
+        )
+        // Verify view is reinflated when flag is on
+        verify(viewFlipperController, never()).clearViews()
+        verify(viewFlipperController, never())
+            .asynchronouslyInflateView(
+                eq(SecurityMode.PIN),
+                any(),
+                onViewInflatedCallbackArgumentCaptor.capture()
+            )
+    }
+
+    @Test
+    fun onOrientationChanged_landscapeKeyguardFlagEnabled_doesReinflate() {
+        featureFlags.set(Flags.LOCKSCREEN_ENABLE_LANDSCAPE, true)
+
+        // Run onOrientationChanged
+        val configurationListenerArgumentCaptor =
+            ArgumentCaptor.forClass(ConfigurationController.ConfigurationListener::class.java)
+        underTest.onViewAttached()
+        verify(configurationController).addCallback(configurationListenerArgumentCaptor.capture())
+        clearInvocations(viewFlipperController)
+        configurationListenerArgumentCaptor.value.onOrientationChanged(
+            Configuration.ORIENTATION_LANDSCAPE
+        )
+        // Verify view is reinflated when flag is on
+        verify(viewFlipperController).clearViews()
+        verify(viewFlipperController)
+            .asynchronouslyInflateView(
+                eq(SecurityMode.PIN),
+                any(),
+                onViewInflatedCallbackArgumentCaptor.capture()
+            )
+    }
 
     @Test
     fun hasDismissActions() {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractorTest.kt
index a3f7fc5..e0ae0c3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/domain/interactor/KeyguardKeyEventInteractorTest.kt
@@ -131,14 +131,12 @@
     }
 
     @Test
-    fun dispatchKeyEvent_menuActionUp_interactiveKeyguard_collapsesShade() {
+    fun dispatchKeyEvent_menuActionUp_interactiveKeyguard_showsPrimaryBouncer() {
         keyguardInteractorWithDependencies.repository.setWakefulnessModel(awakeWakefulnessMode)
         whenever(statusBarStateController.state).thenReturn(StatusBarState.KEYGUARD)
         whenever(statusBarKeyguardViewManager.shouldDismissOnMenuPressed()).thenReturn(true)
 
-        val actionUpMenuKeyEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU)
-        assertThat(underTest.dispatchKeyEvent(actionUpMenuKeyEvent)).isTrue()
-        verify(shadeController).animateCollapseShadeForced()
+        verifyActionUpShowsPrimaryBouncer(KeyEvent.KEYCODE_MENU)
     }
 
     @Test
@@ -147,42 +145,48 @@
         whenever(statusBarStateController.state).thenReturn(StatusBarState.SHADE_LOCKED)
         whenever(statusBarKeyguardViewManager.shouldDismissOnMenuPressed()).thenReturn(true)
 
-        // action down: does NOT collapse the shade
-        val actionDownMenuKeyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU)
-        assertThat(underTest.dispatchKeyEvent(actionDownMenuKeyEvent)).isFalse()
-        verify(shadeController, never()).animateCollapseShadeForced()
-
-        // action up: collapses the shade
-        val actionUpMenuKeyEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU)
-        assertThat(underTest.dispatchKeyEvent(actionUpMenuKeyEvent)).isTrue()
-        verify(shadeController).animateCollapseShadeForced()
+        verifyActionUpCollapsesTheShade(KeyEvent.KEYCODE_MENU)
     }
 
     @Test
-    fun dispatchKeyEvent_menuActionUp_nonInteractiveKeyguard_neverCollapsesShade() {
+    fun dispatchKeyEvent_menuActionUp_nonInteractiveKeyguard_doNothing() {
         keyguardInteractorWithDependencies.repository.setWakefulnessModel(asleepWakefulnessMode)
         whenever(statusBarStateController.state).thenReturn(StatusBarState.KEYGUARD)
         whenever(statusBarKeyguardViewManager.shouldDismissOnMenuPressed()).thenReturn(true)
 
-        val actionUpMenuKeyEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU)
-        assertThat(underTest.dispatchKeyEvent(actionUpMenuKeyEvent)).isFalse()
-        verify(shadeController, never()).animateCollapseShadeForced()
+        verifyActionsDoNothing(KeyEvent.KEYCODE_MENU)
     }
 
     @Test
-    fun dispatchKeyEvent_spaceActionUp_interactiveKeyguard_collapsesShade() {
+    fun dispatchKeyEvent_spaceActionUp_interactiveKeyguard_showsPrimaryBouncer() {
         keyguardInteractorWithDependencies.repository.setWakefulnessModel(awakeWakefulnessMode)
         whenever(statusBarStateController.state).thenReturn(StatusBarState.KEYGUARD)
 
-        // action down: does NOT collapse the shade
-        val actionDownMenuKeyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SPACE)
-        assertThat(underTest.dispatchKeyEvent(actionDownMenuKeyEvent)).isFalse()
-        verify(shadeController, never()).animateCollapseShadeForced()
+        verifyActionUpShowsPrimaryBouncer(KeyEvent.KEYCODE_SPACE)
+    }
 
-        // action up: collapses the shade
-        val actionUpMenuKeyEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SPACE)
-        assertThat(underTest.dispatchKeyEvent(actionUpMenuKeyEvent)).isTrue()
-        verify(shadeController).animateCollapseShadeForced()
+    @Test
+    fun dispatchKeyEvent_spaceActionUp_shadeLocked_collapsesShade() {
+        keyguardInteractorWithDependencies.repository.setWakefulnessModel(awakeWakefulnessMode)
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.SHADE_LOCKED)
+
+        verifyActionUpCollapsesTheShade(KeyEvent.KEYCODE_SPACE)
+    }
+
+    @Test
+    fun dispatchKeyEvent_enterActionUp_interactiveKeyguard_showsPrimaryBouncer() {
+        keyguardInteractorWithDependencies.repository.setWakefulnessModel(awakeWakefulnessMode)
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.KEYGUARD)
+
+        verifyActionUpShowsPrimaryBouncer(KeyEvent.KEYCODE_ENTER)
+    }
+
+    @Test
+    fun dispatchKeyEvent_enterActionUp_shadeLocked_collapsesShade() {
+        keyguardInteractorWithDependencies.repository.setWakefulnessModel(awakeWakefulnessMode)
+        whenever(statusBarStateController.state).thenReturn(StatusBarState.SHADE_LOCKED)
+
+        verifyActionUpCollapsesTheShade(KeyEvent.KEYCODE_ENTER)
     }
 
     @Test
@@ -252,4 +256,42 @@
             .isFalse()
         verify(statusBarKeyguardViewManager, never()).interceptMediaKey(any())
     }
+
+    private fun verifyActionUpCollapsesTheShade(keycode: Int) {
+        // action down: does NOT collapse the shade
+        val actionDownMenuKeyEvent = KeyEvent(KeyEvent.ACTION_DOWN, keycode)
+        assertThat(underTest.dispatchKeyEvent(actionDownMenuKeyEvent)).isFalse()
+        verify(shadeController, never()).animateCollapseShadeForced()
+
+        // action up: collapses the shade
+        val actionUpMenuKeyEvent = KeyEvent(KeyEvent.ACTION_UP, keycode)
+        assertThat(underTest.dispatchKeyEvent(actionUpMenuKeyEvent)).isTrue()
+        verify(shadeController).animateCollapseShadeForced()
+    }
+
+    private fun verifyActionUpShowsPrimaryBouncer(keycode: Int) {
+        // action down: does NOT collapse the shade
+        val actionDownMenuKeyEvent = KeyEvent(KeyEvent.ACTION_DOWN, keycode)
+        assertThat(underTest.dispatchKeyEvent(actionDownMenuKeyEvent)).isFalse()
+        verify(statusBarKeyguardViewManager, never()).showPrimaryBouncer(any())
+
+        // action up: collapses the shade
+        val actionUpMenuKeyEvent = KeyEvent(KeyEvent.ACTION_UP, keycode)
+        assertThat(underTest.dispatchKeyEvent(actionUpMenuKeyEvent)).isTrue()
+        verify(statusBarKeyguardViewManager).showPrimaryBouncer(eq(true))
+    }
+
+    private fun verifyActionsDoNothing(keycode: Int) {
+        // action down: does nothing
+        val actionDownMenuKeyEvent = KeyEvent(KeyEvent.ACTION_DOWN, keycode)
+        assertThat(underTest.dispatchKeyEvent(actionDownMenuKeyEvent)).isFalse()
+        verify(shadeController, never()).animateCollapseShadeForced()
+        verify(statusBarKeyguardViewManager, never()).showPrimaryBouncer(any())
+
+        // action up: doesNothing
+        val actionUpMenuKeyEvent = KeyEvent(KeyEvent.ACTION_UP, keycode)
+        assertThat(underTest.dispatchKeyEvent(actionUpMenuKeyEvent)).isFalse()
+        verify(shadeController, never()).animateCollapseShadeForced()
+        verify(statusBarKeyguardViewManager, never()).showPrimaryBouncer(any())
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
index 9781baa..64d3b82 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
@@ -53,7 +53,6 @@
 import com.android.systemui.classifier.FalsingManagerFake;
 import com.android.systemui.dump.nano.SystemUIProtoDump;
 import com.android.systemui.flags.FakeFeatureFlags;
-import com.android.systemui.flags.FeatureFlags;
 import com.android.systemui.flags.Flags;
 import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.plugins.PluginManager;
@@ -65,6 +64,7 @@
 import com.android.systemui.qs.external.TileLifecycleManager;
 import com.android.systemui.qs.external.TileServiceKey;
 import com.android.systemui.qs.logging.QSLogger;
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository;
 import com.android.systemui.qs.tileimpl.QSTileImpl;
 import com.android.systemui.settings.UserFileManager;
 import com.android.systemui.settings.UserTracker;
@@ -131,6 +131,8 @@
 
     private FakeFeatureFlags mFeatureFlags;
 
+    private QSPipelineFlagsRepository mQSPipelineFlagsRepository;
+
     private FakeExecutor mMainExecutor;
 
     private QSTileHost mQSTileHost;
@@ -142,6 +144,7 @@
 
         mFeatureFlags.set(Flags.QS_PIPELINE_NEW_HOST, false);
         mFeatureFlags.set(Flags.QS_PIPELINE_AUTO_ADD, false);
+        mQSPipelineFlagsRepository = new QSPipelineFlagsRepository(mFeatureFlags);
 
         mMainExecutor = new FakeExecutor(new FakeSystemClock());
 
@@ -164,7 +167,7 @@
         mQSTileHost = new TestQSTileHost(mContext, mDefaultFactory, mMainExecutor,
                 mPluginManager, mTunerService, () -> mAutoTiles, mShadeController,
                 mQSLogger, mUserTracker, mSecureSettings, mCustomTileStatePersister,
-                mTileLifecycleManagerFactory, mUserFileManager, mFeatureFlags);
+                mTileLifecycleManagerFactory, mUserFileManager, mQSPipelineFlagsRepository);
         mMainExecutor.runAllReady();
 
         mSecureSettings.registerContentObserverForUser(SETTING, new ContentObserver(null) {
@@ -708,7 +711,7 @@
                 UserTracker userTracker, SecureSettings secureSettings,
                 CustomTileStatePersister customTileStatePersister,
                 TileLifecycleManager.Factory tileLifecycleManagerFactory,
-                UserFileManager userFileManager, FeatureFlags featureFlags) {
+                UserFileManager userFileManager, QSPipelineFlagsRepository featureFlags) {
             super(context, defaultFactory, mainExecutor, pluginManager,
                     tunerService, autoTiles,  shadeController, qsLogger,
                     userTracker, secureSettings, customTileStatePersister,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/external/CustomTileStatePersisterTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/external/CustomTileStatePersisterTest.kt
index 6c96576..a9f8ea0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/external/CustomTileStatePersisterTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/external/CustomTileStatePersisterTest.kt
@@ -36,8 +36,8 @@
 import org.mockito.ArgumentMatchers.anyString
 import org.mockito.Captor
 import org.mockito.Mock
-import org.mockito.Mockito.`when`
 import org.mockito.Mockito.verify
+import org.mockito.Mockito.`when`
 import org.mockito.MockitoAnnotations
 
 @SmallTest
@@ -54,6 +54,7 @@
         private const val TEST_SUBTITLE = "test_subtitle"
         private const val TEST_CONTENT_DESCRIPTION = "test_content_description"
         private const val TEST_STATE_DESCRIPTION = "test_state_description"
+        private const val TEST_DEFAULT_LABEL = "default_label"
 
         private fun Tile.isEqualTo(other: Tile): Boolean {
             return state == other.state &&
@@ -156,4 +157,14 @@
 
         verify(editor).remove(KEY.toString())
     }
+
+    @Test
+    fun testWithDefaultLabel_notStored() {
+        tile.setDefaultLabel(TEST_DEFAULT_LABEL)
+
+        `when`(sharedPreferences.getString(eq(KEY.toString()), any()))
+                .thenReturn(writeToString(tile))
+
+        assertThat(customTileStatePersister.readState(KEY)!!.label).isNull()
+    }
 }
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/external/CustomTileTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/external/CustomTileTest.kt
index 41240e5..244f627 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/external/CustomTileTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/external/CustomTileTest.kt
@@ -25,6 +25,7 @@
 import android.graphics.drawable.Drawable
 import android.graphics.drawable.Icon
 import android.os.Handler
+import android.os.Parcel
 import android.service.quicksettings.IQSTileService
 import android.service.quicksettings.Tile
 import android.test.suitebuilder.annotation.SmallTest
@@ -33,6 +34,7 @@
 import android.view.IWindowManager
 import android.view.View
 import com.android.internal.logging.MetricsLogger
+import com.android.systemui.R
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.animation.ActivityLaunchAnimator
 import com.android.systemui.animation.view.LaunchableFrameLayout
@@ -47,6 +49,7 @@
 import com.android.systemui.util.mockito.any
 import com.android.systemui.util.mockito.eq
 import com.android.systemui.util.mockito.nullable
+import com.google.common.truth.Truth.assertThat
 import org.junit.Assert.assertEquals
 import org.junit.Assert.assertFalse
 import org.junit.Assert.assertThrows
@@ -395,4 +398,45 @@
         verify(tileServiceManager, never()).setBindRequested(true)
         verify(tileService, never()).onStartListening()
     }
+
+    @Test
+    fun testAlwaysUseDefaultLabelIfNoLabelIsSet() {
+        // Give it an icon to prevent issues
+        serviceInfo.icon = R.drawable.android
+
+        val label1 = "Label 1"
+        val label2 = "Label 2"
+
+        `when`(serviceInfo.loadLabel(any())).thenReturn(label1)
+        customTile.handleSetListening(true)
+        testableLooper.processAllMessages()
+        customTile.handleSetListening(false)
+        testableLooper.processAllMessages()
+
+        assertThat(customTile.state.label).isEqualTo(label1)
+
+        // Retrieve the tile as if bound (a separate copy)
+        val tile = copyTileUsingParcel(customTile.qsTile)
+
+        // Change the language
+        `when`(serviceInfo.loadLabel(any())).thenReturn(label2)
+
+        // Set the tile to listening and apply the tile (unmodified)
+        customTile.handleSetListening(true)
+        testableLooper.processAllMessages()
+        customTile.updateTileState(tile)
+        customTile.refreshState()
+        testableLooper.processAllMessages()
+
+        assertThat(customTile.state.label).isEqualTo(label2)
+    }
+
+    private fun copyTileUsingParcel(t: Tile): Tile {
+        val parcel = Parcel.obtain()
+        parcel.setDataPosition(0)
+        t.writeToParcel(parcel, 0)
+        parcel.setDataPosition(0)
+
+        return Tile.CREATOR.createFromParcel(parcel)
+    }
 }
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractorImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractorImplTest.kt
index 6689514..54a9360 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractorImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/domain/interactor/CurrentTilesInteractorImplTest.kt
@@ -42,6 +42,7 @@
 import com.android.systemui.qs.pipeline.data.repository.FakeTileSpecRepository
 import com.android.systemui.qs.pipeline.data.repository.TileSpecRepository
 import com.android.systemui.qs.pipeline.domain.model.TileModel
+import com.android.systemui.qs.pipeline.shared.QSPipelineFlagsRepository
 import com.android.systemui.qs.pipeline.shared.TileSpec
 import com.android.systemui.qs.pipeline.shared.logging.QSPipelineLogger
 import com.android.systemui.qs.toProto
@@ -79,6 +80,7 @@
     private val customTileAddedRepository: CustomTileAddedRepository =
         FakeCustomTileAddedRepository()
     private val featureFlags = FakeFeatureFlags()
+    private val pipelineFlags = QSPipelineFlagsRepository(featureFlags)
     private val tileLifecycleManagerFactory = TLMFactory()
 
     @Mock private lateinit var customTileStatePersister: CustomTileStatePersister
@@ -120,7 +122,7 @@
                 backgroundDispatcher = testDispatcher,
                 scope = testScope.backgroundScope,
                 logger = logger,
-                featureFlags = featureFlags,
+                featureFlags = pipelineFlags,
             )
     }
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepositoryTest.kt
new file mode 100644
index 0000000..489221e
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/pipeline/shared/QSPipelineFlagsRepositoryTest.kt
@@ -0,0 +1,61 @@
+package com.android.systemui.qs.pipeline.shared
+
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.flags.FakeFeatureFlags
+import com.android.systemui.flags.Flags
+import com.google.common.truth.Truth.assertThat
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+import org.junit.runners.Parameterized.Parameter
+import org.junit.runners.Parameterized.Parameters
+
+@SmallTest
+@RunWith(Parameterized::class)
+class QSPipelineFlagsRepositoryTest : SysuiTestCase() {
+    companion object {
+        @Parameters(
+            name =
+                """
+WHEN: qs_pipeline_new_host = {0}, qs_pipeline_auto_add = {1}
+THEN: pipelineNewHost = {2}, pipelineAutoAdd = {3}
+                """
+        )
+        @JvmStatic
+        fun data(): List<Array<Boolean>> =
+            (0 until 4).map { combination ->
+                val qs_pipeline_new_host = combination and 0b10 != 0
+                val qs_pipeline_auto_add = combination and 0b01 != 0
+                arrayOf(
+                    qs_pipeline_new_host,
+                    qs_pipeline_auto_add,
+                    /* pipelineNewHost = */ qs_pipeline_new_host,
+                    /* pipelineAutoAdd = */ qs_pipeline_new_host && qs_pipeline_auto_add,
+                )
+            }
+    }
+
+    @JvmField @Parameter(0) var qsPipelineNewHostFlag: Boolean = false
+    @JvmField @Parameter(1) var qsPipelineAutoAddFlag: Boolean = false
+    @JvmField @Parameter(2) var pipelineNewHostExpected: Boolean = false
+    @JvmField @Parameter(3) var pipelineAutoAddExpected: Boolean = false
+
+    private val featureFlags = FakeFeatureFlags()
+    private val pipelineFlags = QSPipelineFlagsRepository(featureFlags)
+
+    @Before
+    fun setUp() {
+        featureFlags.apply {
+            set(Flags.QS_PIPELINE_NEW_HOST, qsPipelineNewHostFlag)
+            set(Flags.QS_PIPELINE_AUTO_ADD, qsPipelineAutoAddFlag)
+        }
+    }
+
+    @Test
+    fun flagLogic() {
+        assertThat(pipelineFlags.pipelineHostEnabled).isEqualTo(pipelineNewHostExpected)
+        assertThat(pipelineFlags.pipelineAutoAddEnabled).isEqualTo(pipelineAutoAddExpected)
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/FontScalingTileTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/FontScalingTileTest.kt
index cbc3553..d1d3c17 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/FontScalingTileTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/FontScalingTileTest.kt
@@ -26,8 +26,6 @@
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.animation.DialogLaunchAnimator
 import com.android.systemui.classifier.FalsingManagerFake
-import com.android.systemui.flags.FakeFeatureFlags
-import com.android.systemui.flags.Flags
 import com.android.systemui.plugins.ActivityStarter
 import com.android.systemui.plugins.statusbar.StatusBarStateController
 import com.android.systemui.qs.QSHost
@@ -74,8 +72,6 @@
     private lateinit var backgroundDelayableExecutor: FakeExecutor
     private lateinit var fontScalingTile: FontScalingTile
 
-    val featureFlags = FakeFeatureFlags()
-
     @Captor private lateinit var argumentCaptor: ArgumentCaptor<Runnable>
 
     @Before
@@ -102,7 +98,6 @@
                 FakeSettings(),
                 FakeSettings(),
                 FakeSystemClock(),
-                featureFlags,
                 userTracker,
                 backgroundDelayableExecutor,
             )
@@ -117,18 +112,7 @@
     }
 
     @Test
-    fun isAvailable_whenFlagIsFalse_returnsFalse() {
-        featureFlags.set(Flags.ENABLE_FONT_SCALING_TILE, false)
-
-        val isAvailable = fontScalingTile.isAvailable()
-
-        assertThat(isAvailable).isFalse()
-    }
-
-    @Test
-    fun isAvailable_whenFlagIsTrue_returnsTrue() {
-        featureFlags.set(Flags.ENABLE_FONT_SCALING_TILE, true)
-
+    fun isAvailable_alwaysReturnsTrue() {
         val isAvailable = fontScalingTile.isAvailable()
 
         assertThat(isAvailable).isTrue()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewControllerTest.kt
index 1edeeff..3cce423 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewControllerTest.kt
@@ -18,6 +18,7 @@
 
 import android.testing.AndroidTestingRunner
 import android.testing.TestableLooper.RunWithLooper
+import android.view.KeyEvent
 import android.view.MotionEvent
 import android.view.ViewGroup
 import androidx.test.filters.SmallTest
@@ -38,6 +39,7 @@
 import com.android.systemui.dump.logcatLogBuffer
 import com.android.systemui.flags.FakeFeatureFlags
 import com.android.systemui.flags.Flags
+import com.android.systemui.keyevent.domain.interactor.KeyEventInteractor
 import com.android.systemui.keyguard.KeyguardUnlockAnimationController
 import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
 import com.android.systemui.keyguard.shared.model.TransitionStep
@@ -118,8 +120,10 @@
     @Mock lateinit var keyguardTransitionInteractor: KeyguardTransitionInteractor
     @Mock
     lateinit var primaryBouncerToGoneTransitionViewModel: PrimaryBouncerToGoneTransitionViewModel
+    @Mock lateinit var keyEventInteractor: KeyEventInteractor
     private val notificationExpansionRepository = NotificationExpansionRepository()
 
+    private lateinit var fakeClock: FakeSystemClock
     private lateinit var interactionEventHandlerCaptor: ArgumentCaptor<InteractionEventHandler>
     private lateinit var interactionEventHandler: InteractionEventHandler
 
@@ -148,6 +152,7 @@
         featureFlags.set(Flags.LOCKSCREEN_WALLPAPER_DREAM_ENABLED, false)
 
         testScope = TestScope()
+        fakeClock = FakeSystemClock()
         underTest =
             NotificationShadeWindowViewController(
                     lockscreenShadeTransitionController,
@@ -180,7 +185,7 @@
                     primaryBouncerToGoneTransitionViewModel,
                     notificationExpansionRepository,
                     featureFlags,
-                    FakeSystemClock(),
+                    fakeClock,
                     BouncerMessageInteractor(
                         FakeBouncerMessageRepository(),
                         mock(BouncerMessageFactory::class.java),
@@ -188,7 +193,8 @@
                         CountDownTimerUtil(),
                         featureFlags
                     ),
-                    BouncerLogger(logcatLogBuffer("BouncerLog"))
+                    BouncerLogger(logcatLogBuffer("BouncerLog")),
+                    keyEventInteractor,
             )
         underTest.setupExpandedStatusBar()
 
@@ -328,6 +334,33 @@
         }
 
     @Test
+    fun handleDispatchTouchEvent_launchAnimationRunningTimesOut() =
+        testScope.runTest {
+            // GIVEN touch dispatcher in a state that returns true
+            underTest.setStatusBarViewController(phoneStatusBarViewController)
+            whenever(keyguardUnlockAnimationController.isPlayingCannedUnlockAnimation()).thenReturn(
+                true
+            )
+            assertThat(interactionEventHandler.handleDispatchTouchEvent(DOWN_EVENT)).isTrue()
+
+            // WHEN launch animation is running for 2 seconds
+            fakeClock.setUptimeMillis(10000)
+            underTest.setExpandAnimationRunning(true)
+            fakeClock.advanceTime(2000)
+
+            // THEN touch is ignored
+            assertThat(interactionEventHandler.handleDispatchTouchEvent(DOWN_EVENT)).isFalse()
+
+            // WHEN Launch animation is running for 6 seconds
+            fakeClock.advanceTime(4000)
+
+            // THEN move is ignored, down is handled, and window is notified
+            assertThat(interactionEventHandler.handleDispatchTouchEvent(MOVE_EVENT)).isFalse()
+            assertThat(interactionEventHandler.handleDispatchTouchEvent(DOWN_EVENT)).isTrue()
+            verify(notificationShadeWindowController).setLaunchingActivity(false)
+        }
+
+    @Test
     fun shouldInterceptTouchEvent_statusBarKeyguardViewManagerShouldIntercept() {
         // down event should be intercepted by keyguardViewManager
         whenever(statusBarKeyguardViewManager.shouldInterceptTouchEvent(DOWN_EVENT))
@@ -345,8 +378,30 @@
             verify(view).findViewById<ViewGroup>(R.id.keyguard_message_area)
         }
 
+    @Test
+    fun forwardsDispatchKeyEvent() {
+        val keyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_B)
+        interactionEventHandler.dispatchKeyEvent(keyEvent)
+        verify(keyEventInteractor).dispatchKeyEvent(keyEvent)
+    }
+
+    @Test
+    fun forwardsDispatchKeyEventPreIme() {
+        val keyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_B)
+        interactionEventHandler.dispatchKeyEventPreIme(keyEvent)
+        verify(keyEventInteractor).dispatchKeyEventPreIme(keyEvent)
+    }
+
+    @Test
+    fun forwardsInterceptMediaKey() {
+        val keyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_VOLUME_UP)
+        interactionEventHandler.interceptMediaKey(keyEvent)
+        verify(keyEventInteractor).interceptMediaKey(keyEvent)
+    }
+
     companion object {
         private val DOWN_EVENT = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_DOWN, 0f, 0f, 0)
+        private val MOVE_EVENT = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 0f, 0f, 0)
         private const val VIEW_BOTTOM = 100
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt
index 829184c..66d48d6 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt
@@ -38,6 +38,7 @@
 import com.android.systemui.dump.logcatLogBuffer
 import com.android.systemui.flags.FakeFeatureFlags
 import com.android.systemui.flags.Flags
+import com.android.systemui.keyevent.domain.interactor.KeyEventInteractor
 import com.android.systemui.keyguard.KeyguardUnlockAnimationController
 import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
 import com.android.systemui.keyguard.ui.viewmodel.PrimaryBouncerToGoneTransitionViewModel
@@ -198,7 +199,8 @@
                     CountDownTimerUtil(),
                     featureFlags
                 ),
-                BouncerLogger(logcatLogBuffer("BouncerLog"))
+                BouncerLogger(logcatLogBuffer("BouncerLog")),
+                Mockito.mock(KeyEventInteractor::class.java),
             )
 
         controller.setupExpandedStatusBar()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/carrier/ShadeCarrierGroupControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/shade/carrier/ShadeCarrierGroupControllerTest.java
index 31bfa3fd..5fa6b3a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/carrier/ShadeCarrierGroupControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/carrier/ShadeCarrierGroupControllerTest.java
@@ -29,6 +29,7 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyZeroInteractions;
 import static org.mockito.Mockito.when;
@@ -50,6 +51,12 @@
 import com.android.systemui.statusbar.connectivity.MobileDataIndicators;
 import com.android.systemui.statusbar.connectivity.NetworkController;
 import com.android.systemui.statusbar.connectivity.SignalCallback;
+import com.android.systemui.statusbar.connectivity.ui.MobileContextProvider;
+import com.android.systemui.statusbar.pipeline.StatusBarPipelineFlags;
+import com.android.systemui.statusbar.pipeline.mobile.ui.MobileUiAdapter;
+import com.android.systemui.statusbar.pipeline.mobile.ui.MobileViewLogger;
+import com.android.systemui.statusbar.pipeline.mobile.ui.viewmodel.MobileIconsViewModel;
+import com.android.systemui.statusbar.pipeline.mobile.ui.viewmodel.ShadeCarrierGroupMobileIconViewModel;
 import com.android.systemui.util.CarrierConfigTracker;
 import com.android.systemui.utils.leaks.LeakCheckedTest;
 import com.android.systemui.utils.os.FakeHandler;
@@ -61,6 +68,10 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
 @RunWith(AndroidTestingRunner.class)
 @TestableLooper.RunWithLooper
 @SmallTest
@@ -95,6 +106,18 @@
     private TestableLooper mTestableLooper;
     @Mock
     private ShadeCarrierGroupController.OnSingleCarrierChangedListener mOnSingleCarrierChangedListener;
+    @Mock
+    private MobileUiAdapter mMobileUiAdapter;
+    @Mock
+    private MobileIconsViewModel mMobileIconsViewModel;
+    @Mock
+    private ShadeCarrierGroupMobileIconViewModel mShadeCarrierGroupMobileIconViewModel;
+    @Mock
+    private MobileViewLogger mMobileViewLogger;
+    @Mock
+    private MobileContextProvider mMobileContextProvider;
+    @Mock
+    private StatusBarPipelineFlags mStatusBarPipelineFlags;
 
     private FakeSlotIndexResolver mSlotIndexResolver;
     private ClickListenerTextView mNoCarrierTextView;
@@ -133,16 +156,35 @@
 
         mSlotIndexResolver = new FakeSlotIndexResolver();
 
+        when(mMobileUiAdapter.getMobileIconsViewModel()).thenReturn(mMobileIconsViewModel);
+
         mShadeCarrierGroupController = new ShadeCarrierGroupController.Builder(
-                mActivityStarter, handler, TestableLooper.get(this).getLooper(),
-                mNetworkController, mCarrierTextControllerBuilder, mContext, mCarrierConfigTracker,
-                mSlotIndexResolver)
+                mActivityStarter,
+                handler,
+                TestableLooper.get(this).getLooper(),
+                mNetworkController,
+                mCarrierTextControllerBuilder,
+                mContext,
+                mCarrierConfigTracker,
+                mSlotIndexResolver,
+                mMobileUiAdapter,
+                mMobileContextProvider,
+                mStatusBarPipelineFlags
+            )
                 .setShadeCarrierGroup(mShadeCarrierGroup)
                 .build();
 
         mShadeCarrierGroupController.setListening(true);
     }
 
+    private void setupWithNewPipeline() {
+        when(mStatusBarPipelineFlags.useNewShadeCarrierGroupMobileIcons()).thenReturn(true);
+        when(mMobileContextProvider.getMobileContextForSub(anyInt(), any())).thenReturn(mContext);
+        when(mMobileIconsViewModel.getLogger()).thenReturn(mMobileViewLogger);
+        when(mMobileIconsViewModel.viewModelForSub(anyInt(), any()))
+                .thenReturn(mShadeCarrierGroupMobileIconViewModel);
+    }
+
     @Test
     public void testInitiallyMultiCarrier() {
         assertFalse(mShadeCarrierGroupController.isSingleCarrier());
@@ -406,6 +448,129 @@
         verify(mOnSingleCarrierChangedListener, never()).onSingleCarrierChanged(anyBoolean());
     }
 
+    @TestableLooper.RunWithLooper(setAsMainLooper = true)
+    @Test
+    public void testUpdateModernMobileIcons_addSubscription() {
+        setupWithNewPipeline();
+
+        mShadeCarrier1.setVisibility(View.GONE);
+        mShadeCarrier2.setVisibility(View.GONE);
+        mShadeCarrier3.setVisibility(View.GONE);
+
+        List<Integer> subIds = new ArrayList<>();
+        subIds.add(0);
+        mShadeCarrierGroupController.updateModernMobileIcons(subIds);
+
+        verify(mShadeCarrier1).addModernMobileView(any());
+        verify(mShadeCarrier2, never()).addModernMobileView(any());
+        verify(mShadeCarrier3, never()).addModernMobileView(any());
+
+        resetShadeCarriers();
+
+        subIds.add(1);
+        mShadeCarrierGroupController.updateModernMobileIcons(subIds);
+
+        verify(mShadeCarrier1, times(1)).removeModernMobileView();
+
+        verify(mShadeCarrier1).addModernMobileView(any());
+        verify(mShadeCarrier2).addModernMobileView(any());
+        verify(mShadeCarrier3, never()).addModernMobileView(any());
+    }
+
+    @TestableLooper.RunWithLooper(setAsMainLooper = true)
+    @Test
+    public void testUpdateModernMobileIcons_removeSubscription() {
+        setupWithNewPipeline();
+
+        List<Integer> subIds = new ArrayList<>();
+        subIds.add(0);
+        subIds.add(1);
+        mShadeCarrierGroupController.updateModernMobileIcons(subIds);
+
+        verify(mShadeCarrier1).addModernMobileView(any());
+        verify(mShadeCarrier2).addModernMobileView(any());
+        verify(mShadeCarrier3, never()).addModernMobileView(any());
+
+        resetShadeCarriers();
+
+        subIds.remove(1);
+        mShadeCarrierGroupController.updateModernMobileIcons(subIds);
+
+        verify(mShadeCarrier1, times(1)).removeModernMobileView();
+        verify(mShadeCarrier2, times(1)).removeModernMobileView();
+
+        verify(mShadeCarrier1).addModernMobileView(any());
+        verify(mShadeCarrier2, never()).addModernMobileView(any());
+        verify(mShadeCarrier3, never()).addModernMobileView(any());
+    }
+
+    @TestableLooper.RunWithLooper(setAsMainLooper = true)
+    @Test
+    public void testUpdateModernMobileIcons_removeSubscriptionOutOfOrder() {
+        setupWithNewPipeline();
+
+        List<Integer> subIds = new ArrayList<>();
+        subIds.add(0);
+        subIds.add(1);
+        subIds.add(2);
+        mShadeCarrierGroupController.updateModernMobileIcons(subIds);
+
+        verify(mShadeCarrier1).addModernMobileView(any());
+        verify(mShadeCarrier2).addModernMobileView(any());
+        verify(mShadeCarrier3).addModernMobileView(any());
+
+        resetShadeCarriers();
+
+        subIds.remove(1);
+        mShadeCarrierGroupController.updateModernMobileIcons(subIds);
+
+        verify(mShadeCarrier1).removeModernMobileView();
+        verify(mShadeCarrier2).removeModernMobileView();
+        verify(mShadeCarrier3).removeModernMobileView();
+
+        verify(mShadeCarrier1).addModernMobileView(any());
+        verify(mShadeCarrier2, never()).addModernMobileView(any());
+        verify(mShadeCarrier3).addModernMobileView(any());
+    }
+
+    @TestableLooper.RunWithLooper(setAsMainLooper = true)
+    @Test
+    public void testProcessSubIdList_moreSubsThanSimSlots_listLimitedToMax() {
+        setupWithNewPipeline();
+
+        List<Integer> subIds = Arrays.asList(0, 1, 2, 2);
+
+        assertThat(mShadeCarrierGroupController.processSubIdList(subIds).size()).isEqualTo(3);
+    }
+
+    @TestableLooper.RunWithLooper(setAsMainLooper = true)
+    @Test
+    public void testProcessSubIdList_invalidSimSlotIndexFilteredOut() {
+        setupWithNewPipeline();
+
+        List<Integer> subIds = Arrays.asList(0, 1, -1);
+
+        List<ShadeCarrierGroupController.IconData> processedSubs =
+                mShadeCarrierGroupController.processSubIdList(subIds);
+        assertThat(processedSubs).hasSize(2);
+        assertThat(processedSubs.get(0).subId).isNotEqualTo(-1);
+        assertThat(processedSubs.get(1).subId).isNotEqualTo(-1);
+    }
+
+    @TestableLooper.RunWithLooper(setAsMainLooper = true)
+    @Test
+    public void testProcessSubIdList_indexGreaterThanSimSlotsFilteredOut() {
+        setupWithNewPipeline();
+
+        List<Integer> subIds = Arrays.asList(0, 4);
+
+        List<ShadeCarrierGroupController.IconData> processedSubs =
+                mShadeCarrierGroupController.processSubIdList(subIds);
+        assertThat(processedSubs).hasSize(1);
+        assertThat(processedSubs.get(0).subId).isNotEqualTo(4);
+    }
+
+
     @Test
     public void testOnlyInternalViewsHaveClickableListener() {
         ArgumentCaptor<View.OnClickListener> captor =
@@ -447,6 +612,12 @@
                 .isEqualTo(Settings.ACTION_WIRELESS_SETTINGS);
     }
 
+    private void resetShadeCarriers() {
+        reset(mShadeCarrier1);
+        reset(mShadeCarrier2);
+        reset(mShadeCarrier3);
+    }
+
     private class FakeSlotIndexResolver implements ShadeCarrierGroupController.SlotIndexResolver {
         public boolean overrideInvalid;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
index 0dc1d9a..6b3bd22 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
@@ -1802,6 +1802,15 @@
         assertFalse(ScrimState.UNLOCKED.mAnimateChange);
     }
 
+    @Test
+    public void testNotifScrimAlpha_1f_afterUnlockFinishedAndExpanded() {
+        mScrimController.transitionTo(ScrimState.KEYGUARD);
+        when(mKeyguardUnlockAnimationController.isPlayingCannedUnlockAnimation()).thenReturn(true);
+        mScrimController.transitionTo(ScrimState.UNLOCKED);
+        mScrimController.onUnlockAnimationFinished();
+        assertAlphaAfterExpansion(mNotificationsScrim, 1f, 1f);
+    }
+
     private void assertAlphaAfterExpansion(ScrimView scrim, float expectedAlpha, float expansion) {
         mScrimController.setRawPanelExpansionFraction(expansion);
         finishAnimationsImmediately();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt
index 50ee6a3..ff28753 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt
@@ -52,12 +52,19 @@
 
     override val cdmaRoaming = MutableStateFlow(false)
 
-    override val networkName =
-        MutableStateFlow<NetworkNameModel>(NetworkNameModel.Default("default"))
+    override val networkName: MutableStateFlow<NetworkNameModel> =
+        MutableStateFlow(NetworkNameModel.Default(DEFAULT_NETWORK_NAME))
+
+    override val carrierName: MutableStateFlow<NetworkNameModel> =
+        MutableStateFlow(NetworkNameModel.Default(DEFAULT_NETWORK_NAME))
 
     override val isAllowedDuringAirplaneMode = MutableStateFlow(false)
 
     fun setDataEnabled(enabled: Boolean) {
         _dataEnabled.value = enabled
     }
+
+    companion object {
+        const val DEFAULT_NETWORK_NAME = "default name"
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionsRepository.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionsRepository.kt
index 3591c17..99e4030 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionsRepository.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionsRepository.kt
@@ -75,7 +75,11 @@
 
     override fun getRepoForSubId(subId: Int): MobileConnectionRepository {
         return subIdRepos[subId]
-            ?: FakeMobileConnectionRepository(subId, tableLogBuffer).also { subIdRepos[subId] = it }
+            ?: FakeMobileConnectionRepository(
+                    subId,
+                    tableLogBuffer,
+                )
+                .also { subIdRepos[subId] = it }
     }
 
     override val defaultDataSubRatConfig = MutableStateFlow(MobileMappings.Config())
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcherTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcherTest.kt
index 5a887eb..d005972 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcherTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcherTest.kt
@@ -243,13 +243,29 @@
         private val IMMEDIATE = Dispatchers.Main.immediate
 
         private const val SUB_1_ID = 1
+        private const val SUB_1_NAME = "Carrier $SUB_1_ID"
         private val SUB_1 =
-            mock<SubscriptionInfo>().also { whenever(it.subscriptionId).thenReturn(SUB_1_ID) }
-        private val MODEL_1 = SubscriptionModel(subscriptionId = SUB_1_ID)
+            mock<SubscriptionInfo>().also {
+                whenever(it.subscriptionId).thenReturn(SUB_1_ID)
+                whenever(it.carrierName).thenReturn(SUB_1_NAME)
+            }
+        private val MODEL_1 =
+            SubscriptionModel(
+                subscriptionId = SUB_1_ID,
+                carrierName = SUB_1_NAME,
+            )
 
         private const val SUB_2_ID = 2
+        private const val SUB_2_NAME = "Carrier $SUB_2_ID"
         private val SUB_2 =
-            mock<SubscriptionInfo>().also { whenever(it.subscriptionId).thenReturn(SUB_2_ID) }
-        private val MODEL_2 = SubscriptionModel(subscriptionId = SUB_2_ID)
+            mock<SubscriptionInfo>().also {
+                whenever(it.subscriptionId).thenReturn(SUB_2_ID)
+                whenever(it.carrierName).thenReturn(SUB_2_NAME)
+            }
+        private val MODEL_2 =
+            SubscriptionModel(
+                subscriptionId = SUB_2_ID,
+                carrierName = SUB_2_NAME,
+            )
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionParameterizedTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionParameterizedTest.kt
index 7573b28..57f97ec 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionParameterizedTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionParameterizedTest.kt
@@ -38,7 +38,6 @@
 import kotlinx.coroutines.Job
 import kotlinx.coroutines.cancel
 import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.collect
 import kotlinx.coroutines.launch
 import kotlinx.coroutines.test.TestScope
 import kotlinx.coroutines.test.UnconfinedTestDispatcher
@@ -140,6 +139,7 @@
             launch { conn.carrierNetworkChangeActive.collect {} }
             launch { conn.isRoaming.collect {} }
             launch { conn.networkName.collect {} }
+            launch { conn.carrierName.collect {} }
             launch { conn.isEmergencyOnly.collect {} }
             launch { conn.dataConnectionState.collect {} }
         }
@@ -163,6 +163,8 @@
                 assertThat(conn.isRoaming.value).isEqualTo(model.roaming)
                 assertThat(conn.networkName.value)
                     .isEqualTo(NetworkNameModel.IntentDerived(model.name))
+                assertThat(conn.carrierName.value)
+                    .isEqualTo(NetworkNameModel.SubscriptionDerived("${model.name} ${model.subId}"))
 
                 // TODO(b/261029387): check these once we start handling them
                 assertThat(conn.isEmergencyOnly.value).isFalse()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt
index efaf152..2712b70 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt
@@ -546,6 +546,7 @@
             launch { conn.carrierNetworkChangeActive.collect {} }
             launch { conn.isRoaming.collect {} }
             launch { conn.networkName.collect {} }
+            launch { conn.carrierName.collect {} }
             launch { conn.isEmergencyOnly.collect {} }
             launch { conn.dataConnectionState.collect {} }
         }
@@ -571,6 +572,8 @@
                 assertThat(conn.isRoaming.value).isEqualTo(model.roaming)
                 assertThat(conn.networkName.value)
                     .isEqualTo(NetworkNameModel.IntentDerived(model.name))
+                assertThat(conn.carrierName.value)
+                    .isEqualTo(NetworkNameModel.SubscriptionDerived("${model.name} ${model.subId}"))
 
                 // TODO(b/261029387) check these once we start handling them
                 assertThat(conn.isEmergencyOnly.value).isFalse()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepositoryTest.kt
index 3dd2eaf..9c0cb17 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepositoryTest.kt
@@ -26,6 +26,7 @@
 import com.android.systemui.log.table.TableLogBuffer
 import com.android.systemui.log.table.TableLogBufferFactory
 import com.android.systemui.statusbar.pipeline.mobile.data.model.NetworkNameModel
+import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel
 import com.android.systemui.statusbar.pipeline.mobile.data.repository.FakeMobileConnectionRepository
 import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionRepository
 import com.android.systemui.statusbar.pipeline.mobile.data.repository.prod.FullMobileConnectionRepository.Companion.COL_EMERGENCY
@@ -43,6 +44,7 @@
 import java.io.PrintWriter
 import java.io.StringWriter
 import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.launchIn
 import kotlinx.coroutines.flow.onEach
 import kotlinx.coroutines.test.TestScope
@@ -79,28 +81,51 @@
     private val mobileFactory = mock<MobileConnectionRepositoryImpl.Factory>()
     private val carrierMergedFactory = mock<CarrierMergedConnectionRepository.Factory>()
 
+    private val subscriptionModel =
+        MutableStateFlow(
+            SubscriptionModel(
+                subscriptionId = SUB_ID,
+                carrierName = DEFAULT_NAME,
+            )
+        )
+
     private lateinit var mobileRepo: FakeMobileConnectionRepository
     private lateinit var carrierMergedRepo: FakeMobileConnectionRepository
 
     @Before
     fun setUp() {
-        mobileRepo = FakeMobileConnectionRepository(SUB_ID, tableLogBuffer)
+        mobileRepo =
+            FakeMobileConnectionRepository(
+                SUB_ID,
+                tableLogBuffer,
+            )
         carrierMergedRepo =
-            FakeMobileConnectionRepository(SUB_ID, tableLogBuffer).apply {
-                // Mimicks the real carrier merged repository
-                this.isAllowedDuringAirplaneMode.value = true
-            }
+            FakeMobileConnectionRepository(
+                    SUB_ID,
+                    tableLogBuffer,
+                )
+                .apply {
+                    // Mimicks the real carrier merged repository
+                    this.isAllowedDuringAirplaneMode.value = true
+                }
 
         whenever(
                 mobileFactory.build(
                     eq(SUB_ID),
                     any(),
-                    eq(DEFAULT_NAME),
+                    any(),
+                    eq(DEFAULT_NAME_MODEL),
                     eq(SEP),
                 )
             )
             .thenReturn(mobileRepo)
-        whenever(carrierMergedFactory.build(eq(SUB_ID), any())).thenReturn(carrierMergedRepo)
+        whenever(
+                carrierMergedFactory.build(
+                    eq(SUB_ID),
+                    any(),
+                )
+            )
+            .thenReturn(carrierMergedRepo)
     }
 
     @Test
@@ -120,7 +145,8 @@
                 .build(
                     SUB_ID,
                     tableLogBuffer,
-                    DEFAULT_NAME,
+                    subscriptionModel,
+                    DEFAULT_NAME_MODEL,
                     SEP,
                 )
         }
@@ -138,7 +164,11 @@
 
             assertThat(underTest.activeRepo.value).isEqualTo(mobileRepo)
             assertThat(underTest.operatorAlphaShort.value).isEqualTo(nonCarrierMergedName)
-            verify(carrierMergedFactory, never()).build(SUB_ID, tableLogBuffer)
+            verify(carrierMergedFactory, never())
+                .build(
+                    SUB_ID,
+                    tableLogBuffer,
+                )
         }
 
     @Test
@@ -348,7 +378,8 @@
                 factory.build(
                     SUB_ID,
                     startingIsCarrierMerged = false,
-                    DEFAULT_NAME,
+                    subscriptionModel,
+                    DEFAULT_NAME_MODEL,
                     SEP,
                 )
 
@@ -356,7 +387,8 @@
                 factory.build(
                     SUB_ID,
                     startingIsCarrierMerged = false,
-                    DEFAULT_NAME,
+                    subscriptionModel,
+                    DEFAULT_NAME_MODEL,
                     SEP,
                 )
 
@@ -388,7 +420,8 @@
                 factory.build(
                     SUB_ID,
                     startingIsCarrierMerged = false,
-                    DEFAULT_NAME,
+                    subscriptionModel,
+                    DEFAULT_NAME_MODEL,
                     SEP,
                 )
 
@@ -397,7 +430,8 @@
                 factory.build(
                     SUB_ID,
                     startingIsCarrierMerged = true,
-                    DEFAULT_NAME,
+                    subscriptionModel,
+                    DEFAULT_NAME_MODEL,
                     SEP,
                 )
 
@@ -623,7 +657,8 @@
                 SUB_ID,
                 startingIsCarrierMerged,
                 tableLogBuffer,
-                DEFAULT_NAME,
+                subscriptionModel,
+                DEFAULT_NAME_MODEL,
                 SEP,
                 testScope.backgroundScope,
                 mobileFactory,
@@ -639,8 +674,9 @@
         val realRepo =
             MobileConnectionRepositoryImpl(
                 SUB_ID,
-                defaultNetworkName = NetworkNameModel.Default("default"),
-                networkNameSeparator = SEP,
+                subscriptionModel,
+                DEFAULT_NAME_MODEL,
+                SEP,
                 telephonyManager,
                 systemUiCarrierConfig = mock(),
                 fakeBroadcastDispatcher,
@@ -654,7 +690,8 @@
                 mobileFactory.build(
                     eq(SUB_ID),
                     any(),
-                    eq(DEFAULT_NAME),
+                    any(),
+                    eq(DEFAULT_NAME_MODEL),
                     eq(SEP),
                 )
             )
@@ -677,7 +714,13 @@
                 testScope.backgroundScope,
                 wifiRepository,
             )
-        whenever(carrierMergedFactory.build(eq(SUB_ID), any())).thenReturn(realRepo)
+        whenever(
+                carrierMergedFactory.build(
+                    eq(SUB_ID),
+                    any(),
+                )
+            )
+            .thenReturn(realRepo)
 
         return realRepo
     }
@@ -690,7 +733,8 @@
 
     private companion object {
         const val SUB_ID = 42
-        private val DEFAULT_NAME = NetworkNameModel.Default("default name")
+        private val DEFAULT_NAME = "default name"
+        private val DEFAULT_NAME_MODEL = NetworkNameModel.Default(DEFAULT_NAME)
         private const val SEP = "-"
         private const val BUFFER_SEPARATOR = "|"
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt
index 1ff737b..e50e5e3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt
@@ -62,6 +62,7 @@
 import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.DefaultNetworkType
 import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.OverrideNetworkType
 import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.UnknownNetworkType
+import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel
 import com.android.systemui.statusbar.pipeline.mobile.data.model.SystemUiCarrierConfig
 import com.android.systemui.statusbar.pipeline.mobile.data.model.SystemUiCarrierConfigTest.Companion.configWithOverride
 import com.android.systemui.statusbar.pipeline.mobile.data.model.SystemUiCarrierConfigTest.Companion.createTestConfig
@@ -78,6 +79,7 @@
 import com.android.systemui.util.mockito.whenever
 import com.google.common.truth.Truth.assertThat
 import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.launchIn
 import kotlinx.coroutines.flow.onEach
 import kotlinx.coroutines.test.TestScope
@@ -109,6 +111,14 @@
     private val testDispatcher = UnconfinedTestDispatcher()
     private val testScope = TestScope(testDispatcher)
 
+    private val subscriptionModel: MutableStateFlow<SubscriptionModel?> =
+        MutableStateFlow(
+            SubscriptionModel(
+                subscriptionId = SUB_1_ID,
+                carrierName = DEFAULT_NAME,
+            )
+        )
+
     @Before
     fun setUp() {
         MockitoAnnotations.initMocks(this)
@@ -119,7 +129,8 @@
         underTest =
             MobileConnectionRepositoryImpl(
                 SUB_1_ID,
-                DEFAULT_NAME,
+                subscriptionModel,
+                DEFAULT_NAME_MODEL,
                 SEP,
                 telephonyManager,
                 systemUiCarrierConfig,
@@ -179,6 +190,7 @@
 
             // gsmLevel updates, no change to cdmaLevel
             strength = signalStrength(gsmLevel = 3, cdmaLevel = 2, isGsm = true)
+            callback.onSignalStrengthsChanged(strength)
 
             assertThat(latest).isEqualTo(2)
 
@@ -638,12 +650,51 @@
         }
 
     @Test
+    fun networkNameForSubId_updates() =
+        testScope.runTest {
+            var latest: NetworkNameModel? = null
+            val job = underTest.carrierName.onEach { latest = it }.launchIn(this)
+
+            subscriptionModel.value =
+                SubscriptionModel(
+                    subscriptionId = SUB_1_ID,
+                    carrierName = DEFAULT_NAME,
+                )
+
+            assertThat(latest?.name).isEqualTo(DEFAULT_NAME)
+
+            val updatedName = "Derived Carrier"
+            subscriptionModel.value =
+                SubscriptionModel(
+                    subscriptionId = SUB_1_ID,
+                    carrierName = updatedName,
+                )
+
+            assertThat(latest?.name).isEqualTo(updatedName)
+
+            job.cancel()
+        }
+
+    @Test
+    fun networkNameForSubId_defaultWhenSubscriptionModelNull() =
+        testScope.runTest {
+            var latest: NetworkNameModel? = null
+            val job = underTest.carrierName.onEach { latest = it }.launchIn(this)
+
+            subscriptionModel.value = null
+
+            assertThat(latest?.name).isEqualTo(DEFAULT_NAME)
+
+            job.cancel()
+        }
+
+    @Test
     fun networkName_default() =
         testScope.runTest {
             var latest: NetworkNameModel? = null
             val job = underTest.networkName.onEach { latest = it }.launchIn(this)
 
-            assertThat(latest).isEqualTo(DEFAULT_NAME)
+            assertThat(latest).isEqualTo(DEFAULT_NAME_MODEL)
 
             job.cancel()
         }
@@ -701,7 +752,7 @@
 
             fakeBroadcastDispatcher.sendIntentToMatchingReceiversOnly(context, intentWithoutInfo)
 
-            assertThat(latest).isEqualTo(DEFAULT_NAME)
+            assertThat(latest).isEqualTo(DEFAULT_NAME_MODEL)
 
             job.cancel()
         }
@@ -852,8 +903,9 @@
     companion object {
         private const val SUB_1_ID = 1
 
-        private val DEFAULT_NAME = NetworkNameModel.Default("default name")
-        private const val SEP = "-"
+        private val DEFAULT_NAME = "Fake Mobile Network"
+        private val DEFAULT_NAME_MODEL = NetworkNameModel.Default(DEFAULT_NAME)
+        private val SEP = "-"
 
         private const val SPN = "testSpn"
         private const val PLMN = "testPlmn"
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionTelephonySmokeTests.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionTelephonySmokeTests.kt
index 4f15aed..ea60aa7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionTelephonySmokeTests.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionTelephonySmokeTests.kt
@@ -36,6 +36,7 @@
 import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState
 import com.android.systemui.statusbar.pipeline.mobile.data.model.NetworkNameModel
 import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType
+import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel
 import com.android.systemui.statusbar.pipeline.mobile.data.model.SystemUiCarrierConfig
 import com.android.systemui.statusbar.pipeline.mobile.data.model.SystemUiCarrierConfigTest
 import com.android.systemui.statusbar.pipeline.mobile.data.repository.FakeMobileConnectionsRepository
@@ -47,6 +48,7 @@
 import com.android.systemui.util.mockito.whenever
 import com.google.common.truth.Truth.assertThat
 import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.flow.launchIn
 import kotlinx.coroutines.flow.onEach
 import kotlinx.coroutines.test.TestScope
@@ -97,6 +99,7 @@
     @Mock private lateinit var telephonyManager: TelephonyManager
     @Mock private lateinit var logger: MobileInputLogger
     @Mock private lateinit var tableLogger: TableLogBuffer
+    @Mock private lateinit var subscriptionModel: StateFlow<SubscriptionModel?>
 
     private val mobileMappings = FakeMobileMappingsProxy()
     private val systemUiCarrierConfig =
@@ -113,11 +116,16 @@
         MockitoAnnotations.initMocks(this)
         whenever(telephonyManager.subscriptionId).thenReturn(SUB_1_ID)
 
-        connectionsRepo = FakeMobileConnectionsRepository(mobileMappings, tableLogger)
+        connectionsRepo =
+            FakeMobileConnectionsRepository(
+                mobileMappings,
+                tableLogger,
+            )
 
         underTest =
             MobileConnectionRepositoryImpl(
                 SUB_1_ID,
+                subscriptionModel,
                 DEFAULT_NAME,
                 SEP,
                 telephonyManager,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt
index c8b6f13d..fd05cc4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt
@@ -1190,30 +1190,36 @@
     companion object {
         // Subscription 1
         private const val SUB_1_ID = 1
+        private const val SUB_1_NAME = "Carrier $SUB_1_ID"
         private val GROUP_1 = ParcelUuid(UUID.randomUUID())
         private val SUB_1 =
             mock<SubscriptionInfo>().also {
                 whenever(it.subscriptionId).thenReturn(SUB_1_ID)
                 whenever(it.groupUuid).thenReturn(GROUP_1)
+                whenever(it.carrierName).thenReturn(SUB_1_NAME)
             }
         private val MODEL_1 =
             SubscriptionModel(
                 subscriptionId = SUB_1_ID,
                 groupUuid = GROUP_1,
+                carrierName = SUB_1_NAME,
             )
 
         // Subscription 2
         private const val SUB_2_ID = 2
+        private const val SUB_2_NAME = "Carrier $SUB_2_ID"
         private val GROUP_2 = ParcelUuid(UUID.randomUUID())
         private val SUB_2 =
             mock<SubscriptionInfo>().also {
                 whenever(it.subscriptionId).thenReturn(SUB_2_ID)
                 whenever(it.groupUuid).thenReturn(GROUP_2)
+                whenever(it.carrierName).thenReturn(SUB_2_NAME)
             }
         private val MODEL_2 =
             SubscriptionModel(
                 subscriptionId = SUB_2_ID,
                 groupUuid = GROUP_2,
+                carrierName = SUB_2_NAME,
             )
 
         // Subs 3 and 4 are considered to be in the same group ------------------------------------
@@ -1242,9 +1248,14 @@
 
         // Carrier merged subscription
         private const val SUB_CM_ID = 5
+        private const val SUB_CM_NAME = "Carrier $SUB_CM_ID"
         private val SUB_CM =
-            mock<SubscriptionInfo>().also { whenever(it.subscriptionId).thenReturn(SUB_CM_ID) }
-        private val MODEL_CM = SubscriptionModel(subscriptionId = SUB_CM_ID)
+            mock<SubscriptionInfo>().also {
+                whenever(it.subscriptionId).thenReturn(SUB_CM_ID)
+                whenever(it.carrierName).thenReturn(SUB_CM_NAME)
+            }
+        private val MODEL_CM =
+            SubscriptionModel(subscriptionId = SUB_CM_ID, carrierName = SUB_CM_NAME)
 
         private val WIFI_INFO_CM =
             mock<WifiInfo>().apply {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconInteractor.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconInteractor.kt
index 8d1da69..a3df785 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconInteractor.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconInteractor.kt
@@ -44,6 +44,8 @@
 
     override val mobileIsDefault = MutableStateFlow(true)
 
+    override val isSingleCarrier = MutableStateFlow(true)
+
     override val networkTypeIconGroup =
         MutableStateFlow<NetworkTypeIconModel>(
             NetworkTypeIconModel.DefaultIcon(TelephonyIcons.THREE_G)
@@ -51,6 +53,8 @@
 
     override val networkName = MutableStateFlow(NetworkNameModel.IntentDerived("demo mode"))
 
+    override val carrierName = MutableStateFlow("demo mode")
+
     private val _isEmergencyOnly = MutableStateFlow(false)
     override val isEmergencyOnly = _isEmergencyOnly
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt
index b2bbcfd..82b7ec4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt
@@ -64,6 +64,8 @@
 
     override val mobileIsDefault = MutableStateFlow(false)
 
+    override val isSingleCarrier = MutableStateFlow(true)
+
     private val _defaultMobileIconMapping = MutableStateFlow(TEST_MAPPING)
     override val defaultMobileIconMapping = _defaultMobileIconMapping
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt
index 58d3804..e3c59ad 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt
@@ -29,6 +29,7 @@
 import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.CarrierMergedNetworkType
 import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.DefaultNetworkType
 import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.OverrideNetworkType
+import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel
 import com.android.systemui.statusbar.pipeline.mobile.data.repository.FakeMobileConnectionRepository
 import com.android.systemui.statusbar.pipeline.mobile.domain.interactor.FakeMobileIconsInteractor.Companion.FIVE_G_OVERRIDE
 import com.android.systemui.statusbar.pipeline.mobile.domain.interactor.FakeMobileIconsInteractor.Companion.FOUR_G
@@ -40,6 +41,7 @@
 import com.android.systemui.util.mockito.whenever
 import com.google.common.truth.Truth.assertThat
 import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.launchIn
 import kotlinx.coroutines.flow.onEach
 import kotlinx.coroutines.test.TestScope
@@ -56,6 +58,15 @@
     private lateinit var underTest: MobileIconInteractor
     private val mobileMappingsProxy = FakeMobileMappingsProxy()
     private val mobileIconsInteractor = FakeMobileIconsInteractor(mobileMappingsProxy, mock())
+
+    private val subscriptionModel =
+        MutableStateFlow(
+            SubscriptionModel(
+                subscriptionId = SUB_1_ID,
+                carrierName = DEFAULT_NAME,
+            )
+        )
+
     private val connectionRepository = FakeMobileConnectionRepository(SUB_1_ID, mock())
 
     private val testDispatcher = UnconfinedTestDispatcher()
@@ -432,7 +443,7 @@
         }
 
     @Test
-    fun networkName_usesOperatorAlphaShotWhenNonNullAndRepoIsDefault() =
+    fun networkName_usesOperatorAlphaShortWhenNonNullAndRepoIsDefault() =
         testScope.runTest {
             var latest: NetworkNameModel? = null
             val job = underTest.networkName.onEach { latest = it }.launchIn(this)
@@ -440,7 +451,7 @@
             val testOperatorName = "operatorAlphaShort"
 
             // Default network name, operator name is non-null, uses the operator name
-            connectionRepository.networkName.value = DEFAULT_NAME
+            connectionRepository.networkName.value = DEFAULT_NAME_MODEL
             connectionRepository.operatorAlphaShort.value = testOperatorName
 
             assertThat(latest).isEqualTo(NetworkNameModel.IntentDerived(testOperatorName))
@@ -448,10 +459,39 @@
             // Default network name, operator name is null, uses the default
             connectionRepository.operatorAlphaShort.value = null
 
+            assertThat(latest).isEqualTo(DEFAULT_NAME_MODEL)
+
+            // Derived network name, operator name non-null, uses the derived name
+            connectionRepository.networkName.value = DERIVED_NAME_MODEL
+            connectionRepository.operatorAlphaShort.value = testOperatorName
+
+            assertThat(latest).isEqualTo(DERIVED_NAME_MODEL)
+
+            job.cancel()
+        }
+
+    @Test
+    fun networkNameForSubId_usesOperatorAlphaShortWhenNonNullAndRepoIsDefault() =
+        testScope.runTest {
+            var latest: String? = null
+            val job = underTest.carrierName.onEach { latest = it }.launchIn(this)
+
+            val testOperatorName = "operatorAlphaShort"
+
+            // Default network name, operator name is non-null, uses the operator name
+            connectionRepository.carrierName.value = DEFAULT_NAME_MODEL
+            connectionRepository.operatorAlphaShort.value = testOperatorName
+
+            assertThat(latest).isEqualTo(testOperatorName)
+
+            // Default network name, operator name is null, uses the default
+            connectionRepository.operatorAlphaShort.value = null
+
             assertThat(latest).isEqualTo(DEFAULT_NAME)
 
             // Derived network name, operator name non-null, uses the derived name
-            connectionRepository.networkName.value = DERIVED_NAME
+            connectionRepository.carrierName.value =
+                NetworkNameModel.SubscriptionDerived(DERIVED_NAME)
             connectionRepository.operatorAlphaShort.value = testOperatorName
 
             assertThat(latest).isEqualTo(DERIVED_NAME)
@@ -460,6 +500,21 @@
         }
 
     @Test
+    fun isSingleCarrier_matchesParent() =
+        testScope.runTest {
+            var latest: Boolean? = null
+            val job = underTest.isSingleCarrier.onEach { latest = it }.launchIn(this)
+
+            mobileIconsInteractor.isSingleCarrier.value = true
+            assertThat(latest).isTrue()
+
+            mobileIconsInteractor.isSingleCarrier.value = false
+            assertThat(latest).isFalse()
+
+            job.cancel()
+        }
+
+    @Test
     fun isForceHidden_matchesParent() =
         testScope.runTest {
             var latest: Boolean? = null
@@ -494,6 +549,7 @@
             mobileIconsInteractor.activeDataConnectionHasDataEnabled,
             mobileIconsInteractor.alwaysShowDataRatIcon,
             mobileIconsInteractor.alwaysUseCdmaLevel,
+            mobileIconsInteractor.isSingleCarrier,
             mobileIconsInteractor.mobileIsDefault,
             mobileIconsInteractor.defaultMobileIconMapping,
             mobileIconsInteractor.defaultMobileIconGroup,
@@ -510,7 +566,9 @@
 
         private const val SUB_1_ID = 1
 
-        private val DEFAULT_NAME = NetworkNameModel.Default("test default name")
-        private val DERIVED_NAME = NetworkNameModel.IntentDerived("test derived name")
+        private val DEFAULT_NAME = "test default name"
+        private val DEFAULT_NAME_MODEL = NetworkNameModel.Default(DEFAULT_NAME)
+        private val DERIVED_NAME = "test derived name"
+        private val DERIVED_NAME_MODEL = NetworkNameModel.IntentDerived(DERIVED_NAME)
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractorTest.kt
index 1fb76b0..3e6f909 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractorTest.kt
@@ -527,6 +527,57 @@
         }
 
     @Test
+    fun isSingleCarrier_zeroSubscriptions_false() =
+        testScope.runTest {
+            var latest: Boolean? = true
+            val job = underTest.isSingleCarrier.onEach { latest = it }.launchIn(this)
+
+            connectionsRepository.setSubscriptions(emptyList())
+            assertThat(latest).isFalse()
+
+            job.cancel()
+        }
+
+    @Test
+    fun isSingleCarrier_oneSubscription_true() =
+        testScope.runTest {
+            var latest: Boolean? = false
+            val job = underTest.isSingleCarrier.onEach { latest = it }.launchIn(this)
+
+            connectionsRepository.setSubscriptions(listOf(SUB_1))
+            assertThat(latest).isTrue()
+
+            job.cancel()
+        }
+
+    @Test
+    fun isSingleCarrier_twoSubscriptions_false() =
+        testScope.runTest {
+            var latest: Boolean? = true
+            val job = underTest.isSingleCarrier.onEach { latest = it }.launchIn(this)
+
+            connectionsRepository.setSubscriptions(listOf(SUB_1, SUB_2))
+            assertThat(latest).isFalse()
+
+            job.cancel()
+        }
+
+    @Test
+    fun isSingleCarrier_updates() =
+        testScope.runTest {
+            var latest: Boolean? = false
+            val job = underTest.isSingleCarrier.onEach { latest = it }.launchIn(this)
+
+            connectionsRepository.setSubscriptions(listOf(SUB_1))
+            assertThat(latest).isTrue()
+
+            connectionsRepository.setSubscriptions(listOf(SUB_1, SUB_2))
+            assertThat(latest).isFalse()
+
+            job.cancel()
+        }
+
+    @Test
     fun mobileIsDefault_mobileFalseAndCarrierMergedFalse_false() =
         testScope.runTest {
             var latest: Boolean? = null
@@ -745,6 +796,7 @@
                 subscriptionId = subscriptionIds.first,
                 isOpportunistic = opportunistic.first,
                 groupUuid = groupUuid,
+                carrierName = "Carrier ${subscriptionIds.first}"
             )
 
         val sub2 =
@@ -752,6 +804,7 @@
                 subscriptionId = subscriptionIds.second,
                 isOpportunistic = opportunistic.second,
                 groupUuid = groupUuid,
+                carrierName = "Carrier ${opportunistic.second}"
             )
 
         return Pair(sub1, sub2)
@@ -760,11 +813,13 @@
     companion object {
 
         private const val SUB_1_ID = 1
-        private val SUB_1 = SubscriptionModel(subscriptionId = SUB_1_ID)
+        private val SUB_1 =
+            SubscriptionModel(subscriptionId = SUB_1_ID, carrierName = "Carrier $SUB_1_ID")
         private val CONNECTION_1 = FakeMobileConnectionRepository(SUB_1_ID, mock())
 
         private const val SUB_2_ID = 2
-        private val SUB_2 = SubscriptionModel(subscriptionId = SUB_2_ID)
+        private val SUB_2 =
+            SubscriptionModel(subscriptionId = SUB_2_ID, carrierName = "Carrier $SUB_2_ID")
         private val CONNECTION_2 = FakeMobileConnectionRepository(SUB_2_ID, mock())
 
         private const val SUB_3_ID = 3
@@ -773,6 +828,7 @@
                 subscriptionId = SUB_3_ID,
                 isOpportunistic = true,
                 groupUuid = ParcelUuid(UUID.randomUUID()),
+                carrierName = "Carrier $SUB_3_ID"
             )
         private val CONNECTION_3 = FakeMobileConnectionRepository(SUB_3_ID, mock())
 
@@ -782,6 +838,7 @@
                 subscriptionId = SUB_4_ID,
                 isOpportunistic = true,
                 groupUuid = ParcelUuid(UUID.randomUUID()),
+                carrierName = "Carrier $SUB_4_ID"
             )
         private val CONNECTION_4 = FakeMobileConnectionRepository(SUB_4_ID, mock())
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModelTest.kt
index f0458fa..065dfba 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModelTest.kt
@@ -92,15 +92,31 @@
 
             interactor.filteredSubscriptions.value =
                 listOf(
-                    SubscriptionModel(subscriptionId = 1, isOpportunistic = false),
+                    SubscriptionModel(
+                        subscriptionId = 1,
+                        isOpportunistic = false,
+                        carrierName = "Carrier 1",
+                    ),
                 )
             assertThat(latest).isEqualTo(listOf(1))
 
             interactor.filteredSubscriptions.value =
                 listOf(
-                    SubscriptionModel(subscriptionId = 2, isOpportunistic = false),
-                    SubscriptionModel(subscriptionId = 5, isOpportunistic = true),
-                    SubscriptionModel(subscriptionId = 7, isOpportunistic = true),
+                    SubscriptionModel(
+                        subscriptionId = 2,
+                        isOpportunistic = false,
+                        carrierName = "Carrier 2",
+                    ),
+                    SubscriptionModel(
+                        subscriptionId = 5,
+                        isOpportunistic = true,
+                        carrierName = "Carrier 5",
+                    ),
+                    SubscriptionModel(
+                        subscriptionId = 7,
+                        isOpportunistic = true,
+                        carrierName = "Carrier 7",
+                    ),
                 )
             assertThat(latest).isEqualTo(listOf(2, 5, 7))
 
@@ -138,6 +154,33 @@
         }
 
     @Test
+    fun caching_mobileIconInteractorIsReusedForSameSubId() =
+        testScope.runTest {
+            val interactor1 = underTest.mobileIconInteractorForSub(1)
+            val interactor2 = underTest.mobileIconInteractorForSub(1)
+
+            assertThat(interactor1).isSameInstanceAs(interactor2)
+        }
+
+    @Test
+    fun caching_invalidInteractorssAreRemovedFromCacheWhenSubDisappears() =
+        testScope.runTest {
+            // Retrieve interactors to trigger caching
+            val interactor1 = underTest.mobileIconInteractorForSub(1)
+            val interactor2 = underTest.mobileIconInteractorForSub(2)
+
+            // Both impls are cached
+            assertThat(underTest.mobileIconInteractorSubIdCache)
+                .containsExactly(1, interactor1, 2, interactor2)
+
+            // SUB_1 is removed from the list...
+            interactor.filteredSubscriptions.value = listOf(SUB_2)
+
+            // ... and dropped from the cache
+            assertThat(underTest.mobileIconInteractorSubIdCache).containsExactly(2, interactor2)
+        }
+
+    @Test
     fun firstMobileSubShowingNetworkTypeIcon_noSubs_false() =
         testScope.runTest {
             var latest: Boolean? = null
@@ -308,8 +351,23 @@
         }
 
     companion object {
-        private val SUB_1 = SubscriptionModel(subscriptionId = 1, isOpportunistic = false)
-        private val SUB_2 = SubscriptionModel(subscriptionId = 2, isOpportunistic = false)
-        private val SUB_3 = SubscriptionModel(subscriptionId = 3, isOpportunistic = false)
+        private val SUB_1 =
+            SubscriptionModel(
+                subscriptionId = 1,
+                isOpportunistic = false,
+                carrierName = "Carrier 1",
+            )
+        private val SUB_2 =
+            SubscriptionModel(
+                subscriptionId = 2,
+                isOpportunistic = false,
+                carrierName = "Carrier 2",
+            )
+        private val SUB_3 =
+            SubscriptionModel(
+                subscriptionId = 3,
+                isOpportunistic = false,
+                carrierName = "Carrier 3",
+            )
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
index 5f0011b..fdc4f37 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
@@ -32,7 +32,6 @@
 import static org.junit.Assume.assumeNotNull;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.times;
@@ -500,123 +499,45 @@
 
     @Test
     public void ifPortraitHalfOpen_drawVerticallyTop() {
-        DevicePostureController devicePostureController = mock(DevicePostureController.class);
-        when(devicePostureController.getDevicePosture())
-                .thenReturn(DevicePostureController.DEVICE_POSTURE_CLOSED);
-
-        VolumeDialogImpl dialog = new VolumeDialogImpl(
-                getContext(),
-                mVolumeDialogController,
-                mAccessibilityMgr,
-                mDeviceProvisionedController,
-                mConfigurationController,
-                mMediaOutputDialogFactory,
-                mVolumePanelFactory,
-                mActivityStarter,
-                mInteractionJankMonitor,
-                false,
-                mCsdWarningDialogFactory,
-                devicePostureController,
-                mTestableLooper.getLooper(),
-                mDumpManager,
-                mFeatureFlags
-        );
-        dialog.init(0 , null);
-
-        verify(devicePostureController).addCallback(any());
-        dialog.onPostureChanged(DevicePostureController.DEVICE_POSTURE_HALF_OPENED);
+        mDialog.onPostureChanged(DevicePostureController.DEVICE_POSTURE_HALF_OPENED);
         mTestableLooper.processAllMessages(); // let dismiss() finish
 
         setOrientation(Configuration.ORIENTATION_PORTRAIT);
 
         // Call show() to trigger layout updates before verifying position
-        dialog.show(SHOW_REASON_UNKNOWN);
+        mDialog.show(SHOW_REASON_UNKNOWN);
         mTestableLooper.processAllMessages(); // let show() finish before assessing its side-effect
 
-        int gravity = dialog.getWindowGravity();
+        int gravity = mDialog.getWindowGravity();
         assertEquals(Gravity.TOP, gravity & Gravity.VERTICAL_GRAVITY_MASK);
-
-        cleanUp(dialog);
     }
 
     @Test
     public void ifPortraitAndOpen_drawCenterVertically() {
-        DevicePostureController devicePostureController = mock(DevicePostureController.class);
-        when(devicePostureController.getDevicePosture())
-                .thenReturn(DevicePostureController.DEVICE_POSTURE_CLOSED);
-
-        VolumeDialogImpl dialog = new VolumeDialogImpl(
-                getContext(),
-                mVolumeDialogController,
-                mAccessibilityMgr,
-                mDeviceProvisionedController,
-                mConfigurationController,
-                mMediaOutputDialogFactory,
-                mVolumePanelFactory,
-                mActivityStarter,
-                mInteractionJankMonitor,
-                false,
-                mCsdWarningDialogFactory,
-                devicePostureController,
-                mTestableLooper.getLooper(),
-                mDumpManager,
-                mFeatureFlags
-        );
-        dialog.init(0, null);
-
-        verify(devicePostureController).addCallback(any());
-        dialog.onPostureChanged(DevicePostureController.DEVICE_POSTURE_OPENED);
+        mDialog.onPostureChanged(DevicePostureController.DEVICE_POSTURE_OPENED);
         mTestableLooper.processAllMessages(); // let dismiss() finish
 
         setOrientation(Configuration.ORIENTATION_PORTRAIT);
 
-        dialog.show(SHOW_REASON_UNKNOWN);
+        mDialog.show(SHOW_REASON_UNKNOWN);
         mTestableLooper.processAllMessages(); // let show() finish before assessing its side-effect
 
-        int gravity = dialog.getWindowGravity();
+        int gravity = mDialog.getWindowGravity();
         assertEquals(Gravity.CENTER_VERTICAL, gravity & Gravity.VERTICAL_GRAVITY_MASK);
-
-        cleanUp(dialog);
     }
 
     @Test
     public void ifLandscapeAndHalfOpen_drawCenterVertically() {
-        DevicePostureController devicePostureController = mock(DevicePostureController.class);
-        when(devicePostureController.getDevicePosture())
-                .thenReturn(DevicePostureController.DEVICE_POSTURE_CLOSED);
-
-        VolumeDialogImpl dialog = new VolumeDialogImpl(
-                getContext(),
-                mVolumeDialogController,
-                mAccessibilityMgr,
-                mDeviceProvisionedController,
-                mConfigurationController,
-                mMediaOutputDialogFactory,
-                mVolumePanelFactory,
-                mActivityStarter,
-                mInteractionJankMonitor,
-                false,
-                mCsdWarningDialogFactory,
-                devicePostureController,
-                mTestableLooper.getLooper(),
-                mDumpManager,
-                mFeatureFlags
-        );
-        dialog.init(0, null);
-
-        verify(devicePostureController).addCallback(any());
-        dialog.onPostureChanged(DevicePostureController.DEVICE_POSTURE_HALF_OPENED);
+        mDialog.onPostureChanged(DevicePostureController.DEVICE_POSTURE_HALF_OPENED);
         mTestableLooper.processAllMessages(); // let dismiss() finish
 
         setOrientation(Configuration.ORIENTATION_LANDSCAPE);
 
-        dialog.show(SHOW_REASON_UNKNOWN);
+        mDialog.show(SHOW_REASON_UNKNOWN);
         mTestableLooper.processAllMessages(); // let show() finish before assessing its side-effect
 
-        int gravity = dialog.getWindowGravity();
+        int gravity = mDialog.getWindowGravity();
         assertEquals(Gravity.CENTER_VERTICAL, gravity & Gravity.VERTICAL_GRAVITY_MASK);
-
-        cleanUp(dialog);
     }
 
     @Test
@@ -627,31 +548,9 @@
 
     @Test
     public void dialogDestroy_removesPostureControllerCallback() {
-        VolumeDialogImpl dialog = new VolumeDialogImpl(
-                getContext(),
-                mVolumeDialogController,
-                mAccessibilityMgr,
-                mDeviceProvisionedController,
-                mConfigurationController,
-                mMediaOutputDialogFactory,
-                mVolumePanelFactory,
-                mActivityStarter,
-                mInteractionJankMonitor,
-                false,
-                mCsdWarningDialogFactory,
-                mPostureController,
-                mTestableLooper.getLooper(),
-                mDumpManager,
-                mFeatureFlags
-        );
-        dialog.init(0, null);
-
         verify(mPostureController, never()).removeCallback(any());
-        dialog.destroy();
-
+        mDialog.destroy();
         verify(mPostureController).removeCallback(any());
-
-        cleanUp(dialog);
     }
 
     private void setOrientation(int orientation) {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/wmshell/BubbleEducationControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/wmshell/BubbleEducationControllerTest.kt
new file mode 100644
index 0000000..94ed608
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/wmshell/BubbleEducationControllerTest.kt
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.systemui.wmshell
+
+import android.content.ContentResolver
+import android.content.Context
+import android.content.SharedPreferences
+import android.testing.AndroidTestingRunner
+import android.testing.TestableLooper
+import androidx.test.filters.SmallTest
+import com.android.systemui.model.SysUiStateTest
+import com.android.wm.shell.bubbles.Bubble
+import com.android.wm.shell.bubbles.BubbleEducationController
+import com.android.wm.shell.bubbles.PREF_MANAGED_EDUCATION
+import com.android.wm.shell.bubbles.PREF_STACK_EDUCATION
+import org.junit.Assert.assertEquals
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.anyBoolean
+import org.mockito.ArgumentMatchers.anyInt
+import org.mockito.ArgumentMatchers.anyString
+import org.mockito.Mockito
+
+@SmallTest
+@RunWith(AndroidTestingRunner::class)
+@TestableLooper.RunWithLooper(setAsMainLooper = true)
+class BubbleEducationControllerTest : SysUiStateTest() {
+    private val sharedPrefsEditor = Mockito.mock(SharedPreferences.Editor::class.java)
+    private val sharedPrefs = Mockito.mock(SharedPreferences::class.java)
+    private val context = Mockito.mock(Context::class.java)
+    private lateinit var sut: BubbleEducationController
+
+    @Before
+    fun setUp() {
+        Mockito.`when`(context.packageName).thenReturn("packageName")
+        Mockito.`when`(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPrefs)
+        Mockito.`when`(context.contentResolver)
+            .thenReturn(Mockito.mock(ContentResolver::class.java))
+        Mockito.`when`(sharedPrefs.edit()).thenReturn(sharedPrefsEditor)
+        sut = BubbleEducationController(context)
+    }
+
+    @Test
+    fun testSeenStackEducation_read() {
+        Mockito.`when`(sharedPrefs.getBoolean(anyString(), anyBoolean())).thenReturn(true)
+        assertEquals(sut.hasSeenStackEducation, true)
+        Mockito.verify(sharedPrefs).getBoolean(PREF_STACK_EDUCATION, false)
+    }
+
+    @Test
+    fun testSeenStackEducation_write() {
+        sut.hasSeenStackEducation = true
+        Mockito.verify(sharedPrefsEditor).putBoolean(PREF_STACK_EDUCATION, true)
+    }
+
+    @Test
+    fun testSeenManageEducation_read() {
+        Mockito.`when`(sharedPrefs.getBoolean(anyString(), anyBoolean())).thenReturn(true)
+        assertEquals(sut.hasSeenManageEducation, true)
+        Mockito.verify(sharedPrefs).getBoolean(PREF_MANAGED_EDUCATION, false)
+    }
+
+    @Test
+    fun testSeenManageEducation_write() {
+        sut.hasSeenManageEducation = true
+        Mockito.verify(sharedPrefsEditor).putBoolean(PREF_MANAGED_EDUCATION, true)
+    }
+
+    @Test
+    fun testShouldShowStackEducation() {
+        val bubble = Mockito.mock(Bubble::class.java)
+        // When bubble is null
+        assertEquals(sut.shouldShowStackEducation(null), false)
+        // When bubble is not conversation
+        Mockito.`when`(bubble.isConversation).thenReturn(false)
+        assertEquals(sut.shouldShowStackEducation(bubble), false)
+        // When bubble is conversation and has seen stack edu
+        Mockito.`when`(bubble.isConversation).thenReturn(true)
+        Mockito.`when`(sharedPrefs.getBoolean(anyString(), anyBoolean())).thenReturn(true)
+        assertEquals(sut.shouldShowStackEducation(bubble), false)
+        // When bubble is conversation and has not seen stack edu
+        Mockito.`when`(bubble.isConversation).thenReturn(true)
+        Mockito.`when`(sharedPrefs.getBoolean(anyString(), anyBoolean())).thenReturn(false)
+        assertEquals(sut.shouldShowStackEducation(bubble), true)
+    }
+
+    @Test
+    fun testShouldShowManageEducation() {
+        val bubble = Mockito.mock(Bubble::class.java)
+        // When bubble is null
+        assertEquals(sut.shouldShowManageEducation(null), false)
+        // When bubble is not conversation
+        Mockito.`when`(bubble.isConversation).thenReturn(false)
+        assertEquals(sut.shouldShowManageEducation(bubble), false)
+        // When bubble is conversation and has seen stack edu
+        Mockito.`when`(bubble.isConversation).thenReturn(true)
+        Mockito.`when`(sharedPrefs.getBoolean(anyString(), anyBoolean())).thenReturn(true)
+        assertEquals(sut.shouldShowManageEducation(bubble), false)
+        // When bubble is conversation and has not seen stack edu
+        Mockito.`when`(bubble.isConversation).thenReturn(true)
+        Mockito.`when`(sharedPrefs.getBoolean(anyString(), anyBoolean())).thenReturn(false)
+        assertEquals(sut.shouldShowManageEducation(bubble), true)
+    }
+}
diff --git a/services/autofill/java/com/android/server/autofill/InlineSuggestionRendorInfoCallbackOnResultListener.java b/services/autofill/java/com/android/server/autofill/InlineSuggestionRendorInfoCallbackOnResultListener.java
new file mode 100644
index 0000000..7351ef5
--- /dev/null
+++ b/services/autofill/java/com/android/server/autofill/InlineSuggestionRendorInfoCallbackOnResultListener.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.autofill;
+
+import android.annotation.Nullable;
+import android.os.Bundle;
+import android.os.RemoteCallback;
+import android.util.Slog;
+import android.view.autofill.AutofillId;
+import android.view.inputmethod.InlineSuggestionsRequest;
+
+import java.lang.ref.WeakReference;
+import java.util.function.Consumer;
+
+final class InlineSuggestionRendorInfoCallbackOnResultListener implements
+        RemoteCallback.OnResultListener{
+    private static final String TAG = "InlineSuggestionRendorInfoCallbackOnResultListener";
+
+    private final int mRequestIdCopy;
+    private final AutofillId mFocusedId;
+    private final WeakReference<Session> mSessionWeakReference;
+    private final Consumer<InlineSuggestionsRequest> mInlineSuggestionsRequestConsumer;
+
+    InlineSuggestionRendorInfoCallbackOnResultListener(WeakReference<Session> sessionWeakReference,
+            int requestIdCopy,
+            Consumer<InlineSuggestionsRequest> inlineSuggestionsRequestConsumer,
+            AutofillId focusedId) {
+        this.mRequestIdCopy = requestIdCopy;
+        this.mInlineSuggestionsRequestConsumer = inlineSuggestionsRequestConsumer;
+        this.mSessionWeakReference = sessionWeakReference;
+        this.mFocusedId = focusedId;
+    }
+    public void onResult(@Nullable Bundle result) {
+        Session session = this.mSessionWeakReference.get();
+        if (session == null) {
+            Slog.wtf(TAG, "Session is null before trying to call onResult");
+            return;
+        }
+        synchronized (session.mLock) {
+            if (session.mDestroyed) {
+                Slog.wtf(TAG, "Session is destroyed before trying to call onResult");
+                return;
+            }
+            session.mInlineSessionController.onCreateInlineSuggestionsRequestLocked(
+                    this.mFocusedId,
+                    session.inlineSuggestionsRequestCacheDecorator(
+                        this.mInlineSuggestionsRequestConsumer, this.mRequestIdCopy),
+                    result);
+        }
+    }
+}
diff --git a/services/autofill/java/com/android/server/autofill/Session.java b/services/autofill/java/com/android/server/autofill/Session.java
index 1827a5b..0c4f877 100644
--- a/services/autofill/java/com/android/server/autofill/Session.java
+++ b/services/autofill/java/com/android/server/autofill/Session.java
@@ -326,7 +326,7 @@
      * Id of the View currently being displayed.
      */
     @GuardedBy("mLock")
-    @Nullable private AutofillId mCurrentViewId;
+    @Nullable AutofillId mCurrentViewId;
 
     @GuardedBy("mLock")
     private IAutoFillManagerClient mClient;
@@ -374,7 +374,7 @@
     private Bundle mClientState;
 
     @GuardedBy("mLock")
-    private boolean mDestroyed;
+    boolean mDestroyed;
 
     /**
      * Helper used to handle state of Save UI when it must be hiding to show a custom description
@@ -453,7 +453,7 @@
     private ArrayList<AutofillId> mAugmentedAutofillableIds;
 
     @NonNull
-    private final AutofillInlineSessionController mInlineSessionController;
+    final AutofillInlineSessionController mInlineSessionController;
 
     /**
      * Receiver of assist data from the app's {@link Activity}.
@@ -1276,18 +1276,22 @@
                         viewState, /* isInlineRequest= */ true);
             }
             if (inlineSuggestionsRequestConsumer != null) {
-                final AutofillId focusedId = mCurrentViewId;
                 final int requestIdCopy = requestId;
+                final AutofillId focusedId = mCurrentViewId;
+
+                WeakReference sessionWeakReference = new WeakReference<Session>(this);
+                InlineSuggestionRendorInfoCallbackOnResultListener
+                        inlineSuggestionRendorInfoCallbackOnResultListener =
+                                new InlineSuggestionRendorInfoCallbackOnResultListener(
+                                        sessionWeakReference,
+                                        requestIdCopy,
+                                        inlineSuggestionsRequestConsumer,
+                                        focusedId);
+                RemoteCallback inlineSuggestionRendorInfoCallback = new RemoteCallback(
+                        inlineSuggestionRendorInfoCallbackOnResultListener, mHandler);
+
                 remoteRenderService.getInlineSuggestionsRendererInfo(
-                        new RemoteCallback((extras) -> {
-                            synchronized (mLock) {
-                                mInlineSessionController.onCreateInlineSuggestionsRequestLocked(
-                                        focusedId, inlineSuggestionsRequestCacheDecorator(
-                                                inlineSuggestionsRequestConsumer, requestIdCopy),
-                                        extras);
-                            }
-                        }, mHandler)
-                );
+                        inlineSuggestionRendorInfoCallback);
                 viewState.setState(ViewState.STATE_PENDING_CREATE_INLINE_REQUEST);
             }
         } else if (mSessionFlags.mClientSuggestionsEnabled) {
@@ -5554,7 +5558,7 @@
     }
 
     @NonNull
-    private Consumer<InlineSuggestionsRequest> inlineSuggestionsRequestCacheDecorator(
+    Consumer<InlineSuggestionsRequest> inlineSuggestionsRequestCacheDecorator(
             @NonNull Consumer<InlineSuggestionsRequest> consumer, int requestId) {
         return inlineSuggestionsRequest -> {
             consumer.accept(inlineSuggestionsRequest);
diff --git a/services/core/java/com/android/server/am/BatteryStatsService.java b/services/core/java/com/android/server/am/BatteryStatsService.java
index 04ebb2b..b0f30d6 100644
--- a/services/core/java/com/android/server/am/BatteryStatsService.java
+++ b/services/core/java/com/android/server/am/BatteryStatsService.java
@@ -156,6 +156,7 @@
 
     private final PowerProfile mPowerProfile;
     private final CpuScalingPolicies mCpuScalingPolicies;
+    private final BatteryStatsImpl.BatteryStatsConfig mBatteryStatsConfig;
     final BatteryStatsImpl mStats;
     final CpuWakeupStats mCpuWakeupStats;
     private final BatteryUsageStatsStore mBatteryUsageStatsStore;
@@ -374,22 +375,24 @@
         mPowerProfile = new PowerProfile(context);
         mCpuScalingPolicies = new CpuScalingPolicyReader().read();
 
-        mStats = new BatteryStatsImpl(systemDir, handler, this,
+        final boolean resetOnUnplugHighBatteryLevel = context.getResources().getBoolean(
+                com.android.internal.R.bool.config_batteryStatsResetOnUnplugHighBatteryLevel);
+        final boolean resetOnUnplugAfterSignificantCharge = context.getResources().getBoolean(
+                com.android.internal.R.bool.config_batteryStatsResetOnUnplugAfterSignificantCharge);
+        final long powerStatsThrottlePeriodCpu = context.getResources().getInteger(
+                com.android.internal.R.integer.config_defaultPowerStatsThrottlePeriodCpu);
+        mBatteryStatsConfig =
+                new BatteryStatsImpl.BatteryStatsConfig.Builder()
+                        .setResetOnUnplugHighBatteryLevel(resetOnUnplugHighBatteryLevel)
+                        .setResetOnUnplugAfterSignificantCharge(resetOnUnplugAfterSignificantCharge)
+                        .setPowerStatsThrottlePeriodCpu(powerStatsThrottlePeriodCpu)
+                        .build();
+        mStats = new BatteryStatsImpl(mBatteryStatsConfig, systemDir, handler, this,
                 this, mUserManagerUserInfoProvider, mPowerProfile, mCpuScalingPolicies);
         mWorker = new BatteryExternalStatsWorker(context, mStats);
         mStats.setExternalStatsSyncLocked(mWorker);
         mStats.setRadioScanningTimeoutLocked(mContext.getResources().getInteger(
                 com.android.internal.R.integer.config_radioScanningTimeout) * 1000L);
-
-        final boolean resetOnUnplugHighBatteryLevel = context.getResources().getBoolean(
-                com.android.internal.R.bool.config_batteryStatsResetOnUnplugHighBatteryLevel);
-        final boolean resetOnUnplugAfterSignificantCharge = context.getResources().getBoolean(
-                com.android.internal.R.bool.config_batteryStatsResetOnUnplugAfterSignificantCharge);
-        mStats.setBatteryStatsConfig(
-                new BatteryStatsImpl.BatteryStatsConfig.Builder()
-                        .setResetOnUnplugHighBatteryLevel(resetOnUnplugHighBatteryLevel)
-                        .setResetOnUnplugAfterSignificantCharge(resetOnUnplugAfterSignificantCharge)
-                        .build());
         mStats.startTrackingSystemServerCpuTime();
 
         if (BATTERY_USAGE_STORE_ENABLED) {
@@ -2591,6 +2594,7 @@
         pw.println("     --proto: output as a binary protobuffer");
         pw.println("     --model power-profile: use the power profile model"
                 + " even if measured energy is available");
+        pw.println("  --sample: collect and dump a sample of stats for debugging purpose");
         pw.println("  <package.name>: optional name of package to filter output by.");
         pw.println("  -h: print this help text.");
         pw.println("Battery stats (batterystats) commands:");
@@ -2623,6 +2627,10 @@
         }
     }
 
+    private void dumpStatsSample(PrintWriter pw) {
+        mStats.dumpStatsSample(pw);
+    }
+
     private void dumpMeasuredEnergyStats(PrintWriter pw) {
         // Wait for the completion of pending works if there is any
         awaitCompletion();
@@ -2864,6 +2872,9 @@
                     mCpuWakeupStats.dump(new IndentingPrintWriter(pw, "  "),
                             SystemClock.elapsedRealtime());
                     return;
+                } else if ("--sample".equals(arg)) {
+                    dumpStatsSample(pw);
+                    return;
                 } else if ("-a".equals(arg)) {
                     flags |= BatteryStats.DUMP_VERBOSE;
                 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
@@ -2924,6 +2935,7 @@
                                 in.unmarshall(raw, 0, raw.length);
                                 in.setDataPosition(0);
                                 BatteryStatsImpl checkinStats = new BatteryStatsImpl(
+                                        mBatteryStatsConfig,
                                         null, mStats.mHandler, null, null,
                                         mUserManagerUserInfoProvider, mPowerProfile,
                                         mCpuScalingPolicies);
@@ -2965,6 +2977,7 @@
                                 in.unmarshall(raw, 0, raw.length);
                                 in.setDataPosition(0);
                                 BatteryStatsImpl checkinStats = new BatteryStatsImpl(
+                                        mBatteryStatsConfig,
                                         null, mStats.mHandler, null, null,
                                         mUserManagerUserInfoProvider, mPowerProfile,
                                         mCpuScalingPolicies);
diff --git a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
index 0e4465d..1d09dce 100644
--- a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
+++ b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
@@ -87,7 +87,6 @@
         DeviceConfig.NAMESPACE_CAMERA_NATIVE,
         DeviceConfig.NAMESPACE_CONFIGURATION,
         DeviceConfig.NAMESPACE_CONNECTIVITY,
-        DeviceConfig.NAMESPACE_CORE_EXPERIMENTS_TEAM_INTERNAL,
         DeviceConfig.NAMESPACE_EDGETPU_NATIVE,
         DeviceConfig.NAMESPACE_INPUT_NATIVE_BOOT,
         DeviceConfig.NAMESPACE_INTELLIGENCE_CONTENT_SUGGESTIONS,
@@ -115,19 +114,29 @@
         NAMESPACE_TETHERING_U_OR_LATER_NATIVE
     };
 
+    // All the aconfig flags under the listed DeviceConfig scopes will be synced to native level.
+    @VisibleForTesting
+    static final String[] sDeviceConfigAconfigScopes = new String[] {
+        DeviceConfig.NAMESPACE_CORE_EXPERIMENTS_TEAM_INTERNAL,
+    };
+
     private final String[] mGlobalSettings;
 
     private final String[] mDeviceConfigScopes;
 
+    private final String[] mDeviceConfigAconfigScopes;
+
     private final ContentResolver mContentResolver;
 
     @VisibleForTesting
     protected SettingsToPropertiesMapper(ContentResolver contentResolver,
             String[] globalSettings,
-            String[] deviceConfigScopes) {
+            String[] deviceConfigScopes,
+            String[] deviceConfigAconfigScopes) {
         mContentResolver = contentResolver;
         mGlobalSettings = globalSettings;
         mDeviceConfigScopes = deviceConfigScopes;
+        mDeviceConfigAconfigScopes = deviceConfigAconfigScopes;
     }
 
     @VisibleForTesting
@@ -173,6 +182,36 @@
                                 return;
                             }
                             setProperty(propertyName, properties.getString(key, null));
+
+                            // for legacy namespaces, they can also be used for trunk stable
+                            // purposes. so push flag also into trunk stable slot in sys prop,
+                            // later all legacy usage will be refactored and the sync to old
+                            // sys prop slot can be removed.
+                            String aconfigPropertyName = makeAconfigFlagPropertyName(scope, key);
+                            if (aconfigPropertyName == null) {
+                                log("unable to construct system property for " + scope + "/"
+                                        + key);
+                                return;
+                            }
+                            setProperty(aconfigPropertyName, properties.getString(key, null));
+                        }
+                    });
+        }
+
+        for (String deviceConfigAconfigScope : mDeviceConfigAconfigScopes) {
+            DeviceConfig.addOnPropertiesChangedListener(
+                    deviceConfigAconfigScope,
+                    AsyncTask.THREAD_POOL_EXECUTOR,
+                    (DeviceConfig.Properties properties) -> {
+                        String scope = properties.getNamespace();
+                        for (String key : properties.getKeyset()) {
+                            String aconfigPropertyName = makeAconfigFlagPropertyName(scope, key);
+                            if (aconfigPropertyName == null) {
+                                log("unable to construct system property for " + scope + "/"
+                                        + key);
+                                return;
+                            }
+                            setProperty(aconfigPropertyName, properties.getString(key, null));
                         }
                     });
         }
@@ -180,7 +219,10 @@
 
     public static SettingsToPropertiesMapper start(ContentResolver contentResolver) {
         SettingsToPropertiesMapper mapper =  new SettingsToPropertiesMapper(
-                contentResolver, sGlobalSettings, sDeviceConfigScopes);
+                contentResolver,
+                sGlobalSettings,
+                sDeviceConfigScopes,
+                sDeviceConfigAconfigScopes);
         mapper.updatePropertiesFromSettings();
         return mapper;
     }
@@ -243,6 +285,28 @@
         return propertyName;
     }
 
+    /**
+     * system property name constructing rule for aconfig flags:
+     * "persist.device_config.aconfig_flags.[category_name].[flag_name]".
+     * If the name contains invalid characters or substrings for system property name,
+     * will return null.
+     * @param categoryName
+     * @param flagName
+     * @return
+     */
+    @VisibleForTesting
+    static String makeAconfigFlagPropertyName(String categoryName, String flagName) {
+        String propertyName = SYSTEM_PROPERTY_PREFIX + "aconfig_flags." +
+                              categoryName + "." + flagName;
+
+        if (!propertyName.matches(SYSTEM_PROPERTY_VALID_CHARACTERS_REGEX)
+                || propertyName.contains(SYSTEM_PROPERTY_INVALID_SUBSTRING)) {
+            return null;
+        }
+
+        return propertyName;
+    }
+
     private void setProperty(String key, String value) {
         // Check if need to clear the property
         if (value == null) {
diff --git a/services/core/java/com/android/server/audio/AudioDeviceBroker.java b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
index d89171d..4a523af 100644
--- a/services/core/java/com/android/server/audio/AudioDeviceBroker.java
+++ b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
@@ -391,7 +391,6 @@
         final boolean wasBtScoRequested = isBluetoothScoRequested();
         CommunicationRouteClient client;
 
-
         // Save previous client route in case of failure to start BT SCO audio
         AudioDeviceAttributes prevClientDevice = null;
         boolean prevPrivileged = false;
@@ -1043,7 +1042,7 @@
         synchronized (mBluetoothAudioStateLock) {
             mBluetoothScoOn = on;
             updateAudioHalBluetoothState();
-            postUpdateCommunicationRouteClient(eventSource);
+            postUpdateCommunicationRouteClient(isBluetoothScoRequested(), eventSource);
         }
     }
 
@@ -1395,8 +1394,10 @@
                 MSG_I_SAVE_CLEAR_PREF_DEVICES_FOR_CAPTURE_PRESET, SENDMSG_QUEUE, capturePreset);
     }
 
-    /*package*/ void postUpdateCommunicationRouteClient(String eventSource) {
-        sendLMsgNoDelay(MSG_L_UPDATE_COMMUNICATION_ROUTE_CLIENT, SENDMSG_QUEUE, eventSource);
+    /*package*/ void postUpdateCommunicationRouteClient(
+            boolean wasBtScoRequested, String eventSource) {
+        sendILMsgNoDelay(MSG_IL_UPDATE_COMMUNICATION_ROUTE_CLIENT, SENDMSG_QUEUE,
+                wasBtScoRequested ? 1 : 0, eventSource);
     }
 
     /*package*/ void postSetCommunicationDeviceForClient(CommunicationDeviceInfo info) {
@@ -1708,7 +1709,8 @@
                                             : AudioSystem.STREAM_DEFAULT);
                             if (btInfo.mProfile == BluetoothProfile.LE_AUDIO
                                     || btInfo.mProfile == BluetoothProfile.HEARING_AID) {
-                                onUpdateCommunicationRouteClient("setBluetoothActiveDevice");
+                                onUpdateCommunicationRouteClient(isBluetoothScoRequested(),
+                                        "setBluetoothActiveDevice");
                             }
                         }
                     }
@@ -1762,9 +1764,11 @@
                 case MSG_I_SET_MODE_OWNER:
                     synchronized (mSetModeLock) {
                         synchronized (mDeviceStateLock) {
+                            boolean wasBtScoRequested = isBluetoothScoRequested();
                             mAudioModeOwner = (AudioModeInfo) msg.obj;
                             if (mAudioModeOwner.mMode != AudioSystem.MODE_RINGTONE) {
-                                onUpdateCommunicationRouteClient("setNewModeOwner");
+                                onUpdateCommunicationRouteClient(
+                                        wasBtScoRequested, "setNewModeOwner");
                             }
                         }
                     }
@@ -1787,10 +1791,10 @@
                     }
                     break;
 
-                case MSG_L_UPDATE_COMMUNICATION_ROUTE_CLIENT:
+                case MSG_IL_UPDATE_COMMUNICATION_ROUTE_CLIENT:
                     synchronized (mSetModeLock) {
                         synchronized (mDeviceStateLock) {
-                            onUpdateCommunicationRouteClient((String) msg.obj);
+                            onUpdateCommunicationRouteClient(msg.arg1 == 1, (String) msg.obj);
                         }
                     }
                     break;
@@ -1971,7 +1975,7 @@
     private static final int MSG_I_SAVE_CLEAR_PREF_DEVICES_FOR_CAPTURE_PRESET = 38;
 
     private static final int MSG_L_SET_COMMUNICATION_DEVICE_FOR_CLIENT = 42;
-    private static final int MSG_L_UPDATE_COMMUNICATION_ROUTE_CLIENT = 43;
+    private static final int MSG_IL_UPDATE_COMMUNICATION_ROUTE_CLIENT = 43;
     private static final int MSG_I_SCO_AUDIO_STATE_CHANGED = 44;
 
     private static final int MSG_L_BT_ACTIVE_DEVICE_CHANGE_EXT = 45;
@@ -2328,16 +2332,20 @@
      */
     // @GuardedBy("mSetModeLock")
     @GuardedBy("mDeviceStateLock")
-    private void onUpdateCommunicationRouteClient(String eventSource) {
-        updateCommunicationRoute(eventSource);
+    private void onUpdateCommunicationRouteClient(boolean wasBtScoRequested, String eventSource) {
         CommunicationRouteClient crc = topCommunicationRouteClient();
         if (AudioService.DEBUG_COMM_RTE) {
-            Log.v(TAG, "onUpdateCommunicationRouteClient, crc: "
-                    + crc + " eventSource: " + eventSource);
+            Log.v(TAG, "onUpdateCommunicationRouteClient, crc: " + crc
+                    + " wasBtScoRequested: " + wasBtScoRequested + " eventSource: " + eventSource);
         }
         if (crc != null) {
             setCommunicationRouteForClient(crc.getBinder(), crc.getUid(), crc.getDevice(),
                     BtHelper.SCO_MODE_UNDEFINED, crc.isPrivileged(), eventSource);
+        } else {
+            if (!isBluetoothScoRequested() && wasBtScoRequested) {
+                mBtHelper.stopBluetoothSco(eventSource);
+            }
+            updateCommunicationRoute(eventSource);
         }
     }
 
@@ -2401,7 +2409,11 @@
     }
 
     @GuardedBy("mDeviceStateLock")
-    private boolean communnicationDeviceCompatOn() {
+    // LE Audio: For system server (Telecom) and APKs targeting S and above, we let the audio
+    // policy routing rules select the default communication device.
+    // For older APKs, we force LE Audio headset when connected as those APKs cannot select a LE
+    // Audiodevice explicitly.
+    private boolean communnicationDeviceLeAudioCompatOn() {
         return mAudioModeOwner.mMode == AudioSystem.MODE_IN_COMMUNICATION
                 && !(CompatChanges.isChangeEnabled(
                         USE_SET_COMMUNICATION_DEVICE, mAudioModeOwner.mUid)
@@ -2409,19 +2421,25 @@
     }
 
     @GuardedBy("mDeviceStateLock")
+    // Hearing Aid: For system server (Telecom) and IN_CALL mode we let the audio
+    // policy routing rules select the default communication device.
+    // For 3p apps and IN_COMMUNICATION mode we force Hearing aid when connected to maintain
+    // backwards compatibility
+    private boolean communnicationDeviceHaCompatOn() {
+        return mAudioModeOwner.mMode == AudioSystem.MODE_IN_COMMUNICATION
+                && !(mAudioModeOwner.mUid == android.os.Process.SYSTEM_UID);
+    }
+
+    @GuardedBy("mDeviceStateLock")
     AudioDeviceAttributes getDefaultCommunicationDevice() {
-        // For system server (Telecom) and APKs targeting S and above, we let the audio
-        // policy routing rules select the default communication device.
-        // For older APKs, we force Hearing Aid or LE Audio headset when connected as
-        // those APKs cannot select a LE Audio or Hearing Aid device explicitly.
         AudioDeviceAttributes device = null;
-        if (communnicationDeviceCompatOn()) {
-            // If both LE and Hearing Aid are active (thie should not happen),
-            // priority to Hearing Aid.
+        // If both LE and Hearing Aid are active (thie should not happen),
+        // priority to Hearing Aid.
+        if (communnicationDeviceHaCompatOn()) {
             device = mDeviceInventory.getDeviceOfType(AudioSystem.DEVICE_OUT_HEARING_AID);
-            if (device == null) {
-                device = mDeviceInventory.getDeviceOfType(AudioSystem.DEVICE_OUT_BLE_HEADSET);
-            }
+        }
+        if (device == null && communnicationDeviceLeAudioCompatOn()) {
+            device = mDeviceInventory.getDeviceOfType(AudioSystem.DEVICE_OUT_BLE_HEADSET);
         }
         return device;
     }
@@ -2431,6 +2449,7 @@
             List<AudioRecordingConfiguration> recordConfigs) {
         synchronized (mSetModeLock) {
             synchronized (mDeviceStateLock) {
+                final boolean wasBtScoRequested = isBluetoothScoRequested();
                 boolean updateCommunicationRoute = false;
                 for (CommunicationRouteClient crc : mCommunicationRouteClients) {
                     boolean wasActive = crc.isActive();
@@ -2459,7 +2478,8 @@
                     }
                 }
                 if (updateCommunicationRoute) {
-                    postUpdateCommunicationRouteClient("updateCommunicationRouteClientsActivity");
+                    postUpdateCommunicationRouteClient(
+                            wasBtScoRequested, "updateCommunicationRouteClientsActivity");
                 }
             }
         }
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index 3f50dfd3..0bc0472 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -7636,6 +7636,10 @@
             throw new IllegalArgumentException("Illegal BluetoothProfile profile for device "
                     + previousDevice + " -> " + newDevice + ". Got: " + profile);
         }
+
+        sDeviceLogger.enqueue(new EventLogger.StringEvent("BlutoothActiveDeviceChanged for "
+                + BluetoothProfile.getProfileName(profile) + ", device update " + previousDevice
+                + " -> " + newDevice));
         AudioDeviceBroker.BtDeviceChangedData data =
                 new AudioDeviceBroker.BtDeviceChangedData(newDevice, previousDevice, info,
                         "AudioService");
@@ -9685,6 +9689,9 @@
                 }
             } else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                 state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
+                sDeviceLogger.enqueue(new EventLogger.StringEvent(
+                        "BluetoothAdapter ACTION_STATE_CHANGED with state " + state));
+
                 if (state == BluetoothAdapter.STATE_OFF ||
                         state == BluetoothAdapter.STATE_TURNING_OFF) {
                     mDeviceBroker.disconnectAllBluetoothProfiles();
diff --git a/services/core/java/com/android/server/audio/BtHelper.java b/services/core/java/com/android/server/audio/BtHelper.java
index 3560797..b350363 100644
--- a/services/core/java/com/android/server/audio/BtHelper.java
+++ b/services/core/java/com/android/server/audio/BtHelper.java
@@ -329,7 +329,7 @@
             default:
                 break;
         }
-        if(broadcast) {
+        if (broadcast) {
             broadcastScoConnectionState(scoAudioState);
             //FIXME: this is to maintain compatibility with deprecated intent
             // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
@@ -459,6 +459,8 @@
 
     //@GuardedBy("AudioDeviceBroker.mDeviceStateLock")
     /*package*/ synchronized void onBtProfileDisconnected(int profile) {
+        AudioService.sDeviceLogger.enqueue(new EventLogger.StringEvent(
+                "BT profile " + BluetoothProfile.getProfileName(profile) + " disconnected"));
         switch (profile) {
             case BluetoothProfile.A2DP:
                 mA2dp = null;
@@ -487,6 +489,9 @@
 
     @GuardedBy("AudioDeviceBroker.mDeviceStateLock")
     /*package*/ synchronized void onBtProfileConnected(int profile, BluetoothProfile proxy) {
+        AudioService.sDeviceLogger.enqueue(new EventLogger.StringEvent(
+                "BT profile " + BluetoothProfile.getProfileName(profile) + " connected to proxy "
+                + proxy));
         if (profile == BluetoothProfile.HEADSET) {
             onHeadsetProfileConnected((BluetoothHeadset) proxy);
             return;
@@ -718,8 +723,10 @@
         checkScoAudioState();
         if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
             // Make sure that the state transitions to CONNECTING even if we cannot initiate
-            // the connection.
-            broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTING);
+            // the connection except if already connected internally
+            if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL) {
+                broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTING);
+            }
             switch (mScoAudioState) {
                 case SCO_STATE_INACTIVE:
                     mScoAudioMode = scoAudioMode;
@@ -775,7 +782,7 @@
                     broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTED);
                     break;
                 case SCO_STATE_ACTIVE_INTERNAL:
-                    Log.w(TAG, "requestScoState: already in ACTIVE mode, simply return");
+                    // Already in ACTIVE mode, simply return
                     break;
                 case SCO_STATE_ACTIVE_EXTERNAL:
                     /* Confirm SCO Audio connection to requesting app as it is already connected
diff --git a/services/core/java/com/android/server/display/DisplayDevice.java b/services/core/java/com/android/server/display/DisplayDevice.java
index d57dc47..8642fb8 100644
--- a/services/core/java/com/android/server/display/DisplayDevice.java
+++ b/services/core/java/com/android/server/display/DisplayDevice.java
@@ -16,6 +16,9 @@
 
 package com.android.server.display;
 
+import static android.view.Surface.ROTATION_270;
+import static android.view.Surface.ROTATION_90;
+
 import android.annotation.Nullable;
 import android.content.Context;
 import android.graphics.Point;
@@ -132,12 +135,15 @@
     /**
      * Returns the default size of the surface associated with the display, or null if the surface
      * is not provided for layer mirroring by SurfaceFlinger. For non virtual displays, this will
-     * be the actual display device's size.
+     * be the actual display device's size, reflecting the current rotation.
      */
     @Nullable
     public Point getDisplaySurfaceDefaultSizeLocked() {
         DisplayDeviceInfo displayDeviceInfo = getDisplayDeviceInfoLocked();
-        return new Point(displayDeviceInfo.width, displayDeviceInfo.height);
+        final boolean isRotated = mCurrentOrientation == ROTATION_90
+                || mCurrentOrientation == ROTATION_270;
+        return isRotated ? new Point(displayDeviceInfo.height, displayDeviceInfo.width)
+                : new Point(displayDeviceInfo.width, displayDeviceInfo.height);
     }
 
     /**
@@ -358,7 +364,7 @@
         }
 
         boolean isRotated = (mCurrentOrientation == Surface.ROTATION_90
-                || mCurrentOrientation == Surface.ROTATION_270);
+                || mCurrentOrientation == ROTATION_270);
         DisplayDeviceInfo info = getDisplayDeviceInfoLocked();
         viewport.deviceWidth = isRotated ? info.height : info.width;
         viewport.deviceHeight = isRotated ? info.width : info.height;
diff --git a/services/core/java/com/android/server/display/DisplayDeviceConfig.java b/services/core/java/com/android/server/display/DisplayDeviceConfig.java
index c131226..01eceda 100644
--- a/services/core/java/com/android/server/display/DisplayDeviceConfig.java
+++ b/services/core/java/com/android/server/display/DisplayDeviceConfig.java
@@ -2093,7 +2093,7 @@
 
     /** Loads the refresh rate profiles. */
     private void loadRefreshRateZoneProfiles(RefreshRateConfigs refreshRateConfigs) {
-        if (refreshRateConfigs == null) {
+        if (refreshRateConfigs == null || refreshRateConfigs.getRefreshRateZoneProfiles() == null) {
             return;
         }
         for (RefreshRateZone zone :
diff --git a/services/core/java/com/android/server/input/FocusEventDebugView.java b/services/core/java/com/android/server/input/FocusEventDebugView.java
deleted file mode 100644
index 4b8fabde..0000000
--- a/services/core/java/com/android/server/input/FocusEventDebugView.java
+++ /dev/null
@@ -1,848 +0,0 @@
-/*
- * Copyright 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.input;
-
-import static android.util.TypedValue.COMPLEX_UNIT_DIP;
-import static android.util.TypedValue.COMPLEX_UNIT_SP;
-import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
-
-import android.animation.LayoutTransition;
-import android.annotation.AnyThread;
-import android.annotation.Nullable;
-import android.content.Context;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.ColorFilter;
-import android.graphics.ColorMatrixColorFilter;
-import android.graphics.Paint;
-import android.graphics.Typeface;
-import android.util.DisplayMetrics;
-import android.util.Pair;
-import android.util.Slog;
-import android.util.TypedValue;
-import android.view.Gravity;
-import android.view.InputDevice;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-import android.view.RoundedCorner;
-import android.view.View;
-import android.view.ViewConfiguration;
-import android.view.WindowInsets;
-import android.view.animation.AccelerateInterpolator;
-import android.widget.HorizontalScrollView;
-import android.widget.LinearLayout;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-
-import com.android.internal.R;
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-import java.util.function.Supplier;
-
-/**
- *  Displays focus events, such as physical keyboard KeyEvents and non-pointer MotionEvents on
- *  the screen.
- */
-class FocusEventDebugView extends RelativeLayout {
-
-    private static final String TAG = FocusEventDebugView.class.getSimpleName();
-
-    private static final int KEY_FADEOUT_DURATION_MILLIS = 1000;
-    private static final int KEY_TRANSITION_DURATION_MILLIS = 100;
-
-    private static final int OUTER_PADDING_DP = 16;
-    private static final int KEY_SEPARATION_MARGIN_DP = 16;
-    private static final int KEY_VIEW_SIDE_PADDING_DP = 16;
-    private static final int KEY_VIEW_VERTICAL_PADDING_DP = 8;
-    private static final int KEY_VIEW_MIN_WIDTH_DP = 32;
-    private static final int KEY_VIEW_TEXT_SIZE_SP = 12;
-    private static final double ROTATY_GRAPH_HEIGHT_FRACTION = 0.5;
-
-    private final InputManagerService mService;
-    private final int mOuterPadding;
-    private final DisplayMetrics mDm;
-
-    // Tracks all keys that are currently pressed/down.
-    private final Map<Pair<Integer /*deviceId*/, Integer /*scanCode*/>, PressedKeyView>
-            mPressedKeys = new HashMap<>();
-
-    @Nullable
-    private FocusEventDebugGlobalMonitor mFocusEventDebugGlobalMonitor;
-    @Nullable
-    private PressedKeyContainer mPressedKeyContainer;
-    @Nullable
-    private PressedKeyContainer mPressedModifierContainer;
-    private final Supplier<RotaryInputValueView> mRotaryInputValueViewFactory;
-    @Nullable
-    private RotaryInputValueView mRotaryInputValueView;
-    private final Supplier<RotaryInputGraphView> mRotaryInputGraphViewFactory;
-    @Nullable
-    private RotaryInputGraphView mRotaryInputGraphView;
-
-    @VisibleForTesting
-    FocusEventDebugView(Context c, InputManagerService service,
-            Supplier<RotaryInputValueView> rotaryInputValueViewFactory,
-            Supplier<RotaryInputGraphView> rotaryInputGraphViewFactory) {
-        super(c);
-        setFocusableInTouchMode(true);
-
-        mService = service;
-        mRotaryInputValueViewFactory = rotaryInputValueViewFactory;
-        mRotaryInputGraphViewFactory = rotaryInputGraphViewFactory;
-        mDm = mContext.getResources().getDisplayMetrics();
-        mOuterPadding = (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, OUTER_PADDING_DP, mDm);
-    }
-
-    FocusEventDebugView(Context c, InputManagerService service) {
-        this(c, service, () -> new RotaryInputValueView(c), () -> new RotaryInputGraphView(c));
-    }
-
-    @Override
-    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
-        int paddingBottom = 0;
-
-        final RoundedCorner bottomLeft =
-                insets.getRoundedCorner(RoundedCorner.POSITION_BOTTOM_LEFT);
-        if (bottomLeft != null && !insets.isRound()) {
-            paddingBottom = bottomLeft.getRadius();
-        }
-
-        final RoundedCorner bottomRight =
-                insets.getRoundedCorner(RoundedCorner.POSITION_BOTTOM_RIGHT);
-        if (bottomRight != null && !insets.isRound()) {
-            paddingBottom = Math.max(paddingBottom, bottomRight.getRadius());
-        }
-
-        if (insets.getDisplayCutout() != null) {
-            paddingBottom =
-                    Math.max(paddingBottom, insets.getDisplayCutout().getSafeInsetBottom());
-        }
-
-        setPadding(mOuterPadding, mOuterPadding, mOuterPadding, mOuterPadding + paddingBottom);
-        setClipToPadding(false);
-        invalidate();
-        return super.onApplyWindowInsets(insets);
-    }
-
-    @Override
-    public boolean dispatchKeyEvent(KeyEvent event) {
-        handleKeyEvent(event);
-        return super.dispatchKeyEvent(event);
-    }
-
-    @AnyThread
-    public void updateShowKeyPresses(boolean enabled) {
-        post(() -> handleUpdateShowKeyPresses(enabled));
-    }
-
-    @AnyThread
-    public void updateShowRotaryInput(boolean enabled) {
-        post(() -> handleUpdateShowRotaryInput(enabled));
-    }
-
-    private void handleUpdateShowKeyPresses(boolean enabled) {
-        if (enabled == showKeyPresses()) {
-            return;
-        }
-
-        if (!enabled) {
-            removeView(mPressedKeyContainer);
-            mPressedKeyContainer = null;
-            removeView(mPressedModifierContainer);
-            mPressedModifierContainer = null;
-            return;
-        }
-
-        mPressedKeyContainer = new PressedKeyContainer(mContext);
-        mPressedKeyContainer.setOrientation(LinearLayout.HORIZONTAL);
-        mPressedKeyContainer.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
-        mPressedKeyContainer.setLayoutDirection(LAYOUT_DIRECTION_LTR);
-        final var scroller = new HorizontalScrollView(mContext);
-        scroller.addView(mPressedKeyContainer);
-        scroller.setHorizontalScrollBarEnabled(false);
-        scroller.addOnLayoutChangeListener(
-                (view, l, t, r, b, ol, ot, or, ob) -> scroller.fullScroll(View.FOCUS_RIGHT));
-        scroller.setHorizontalFadingEdgeEnabled(true);
-        LayoutParams scrollerLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
-        scrollerLayoutParams.addRule(ALIGN_PARENT_BOTTOM);
-        scrollerLayoutParams.addRule(ALIGN_PARENT_RIGHT);
-        addView(scroller, scrollerLayoutParams);
-
-        mPressedModifierContainer = new PressedKeyContainer(mContext);
-        mPressedModifierContainer.setOrientation(LinearLayout.VERTICAL);
-        mPressedModifierContainer.setGravity(Gravity.LEFT | Gravity.BOTTOM);
-        LayoutParams modifierLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
-        modifierLayoutParams.addRule(ALIGN_PARENT_BOTTOM);
-        modifierLayoutParams.addRule(ALIGN_PARENT_LEFT);
-        modifierLayoutParams.addRule(LEFT_OF, scroller.getId());
-        addView(mPressedModifierContainer, modifierLayoutParams);
-    }
-
-    @VisibleForTesting
-    void handleUpdateShowRotaryInput(boolean enabled) {
-        if (enabled == showRotaryInput()) {
-            return;
-        }
-
-        if (!enabled) {
-            mFocusEventDebugGlobalMonitor.dispose();
-            mFocusEventDebugGlobalMonitor = null;
-            removeView(mRotaryInputValueView);
-            mRotaryInputValueView = null;
-            removeView(mRotaryInputGraphView);
-            mRotaryInputGraphView = null;
-            return;
-        }
-
-        mFocusEventDebugGlobalMonitor = new FocusEventDebugGlobalMonitor(this, mService);
-
-        mRotaryInputValueView = mRotaryInputValueViewFactory.get();
-        LayoutParams valueLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
-        valueLayoutParams.addRule(CENTER_HORIZONTAL);
-        valueLayoutParams.addRule(ALIGN_PARENT_BOTTOM);
-        addView(mRotaryInputValueView, valueLayoutParams);
-
-        mRotaryInputGraphView = mRotaryInputGraphViewFactory.get();
-        LayoutParams graphLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
-                (int) (ROTATY_GRAPH_HEIGHT_FRACTION * mDm.heightPixels));
-        graphLayoutParams.addRule(CENTER_IN_PARENT);
-        addView(mRotaryInputGraphView, graphLayoutParams);
-    }
-
-    /** Report a key event to the debug view. */
-    @AnyThread
-    public void reportKeyEvent(KeyEvent event) {
-        post(() -> handleKeyEvent(KeyEvent.obtain((KeyEvent) event)));
-    }
-
-    /** Report a motion event to the debug view. */
-    @AnyThread
-    public void reportMotionEvent(MotionEvent event) {
-        if (event.getSource() != InputDevice.SOURCE_ROTARY_ENCODER) {
-            return;
-        }
-
-        post(() -> handleRotaryInput(MotionEvent.obtain((MotionEvent) event)));
-    }
-
-    private void handleKeyEvent(KeyEvent keyEvent) {
-        if (!showKeyPresses()) {
-            return;
-        }
-
-        final var identifier = new Pair<>(keyEvent.getDeviceId(), keyEvent.getScanCode());
-        final var container = KeyEvent.isModifierKey(keyEvent.getKeyCode())
-                ? mPressedModifierContainer
-                : mPressedKeyContainer;
-        PressedKeyView pressedKeyView = mPressedKeys.get(identifier);
-        switch (keyEvent.getAction()) {
-            case KeyEvent.ACTION_DOWN: {
-                if (pressedKeyView != null) {
-                    if (keyEvent.getRepeatCount() == 0) {
-                        Slog.w(TAG, "Got key down for "
-                                + KeyEvent.keyCodeToString(keyEvent.getKeyCode())
-                                + " that was already tracked as being down.");
-                        break;
-                    }
-                    container.handleKeyRepeat(pressedKeyView);
-                    break;
-                }
-
-                pressedKeyView = new PressedKeyView(mContext, getLabel(keyEvent));
-                mPressedKeys.put(identifier, pressedKeyView);
-                container.handleKeyPressed(pressedKeyView);
-                break;
-            }
-            case KeyEvent.ACTION_UP: {
-                if (pressedKeyView == null) {
-                    Slog.w(TAG, "Got key up for " + KeyEvent.keyCodeToString(keyEvent.getKeyCode())
-                            + " that was not tracked as being down.");
-                    break;
-                }
-                mPressedKeys.remove(identifier);
-                container.handleKeyRelease(pressedKeyView);
-                break;
-            }
-            default:
-                break;
-        }
-        keyEvent.recycle();
-    }
-
-    @VisibleForTesting
-    void handleRotaryInput(MotionEvent motionEvent) {
-        if (!showRotaryInput()) {
-            return;
-        }
-
-        float scrollAxisValue = motionEvent.getAxisValue(MotionEvent.AXIS_SCROLL);
-        mRotaryInputValueView.updateValue(scrollAxisValue);
-        mRotaryInputGraphView.addValue(scrollAxisValue, motionEvent.getEventTime());
-
-        motionEvent.recycle();
-    }
-
-    private static String getLabel(KeyEvent event) {
-        switch (event.getKeyCode()) {
-            case KeyEvent.KEYCODE_SPACE:
-                return "\u2423";
-            case KeyEvent.KEYCODE_TAB:
-                return "\u21e5";
-            case KeyEvent.KEYCODE_ENTER:
-            case KeyEvent.KEYCODE_NUMPAD_ENTER:
-                return "\u23CE";
-            case KeyEvent.KEYCODE_DEL:
-                return "\u232B";
-            case KeyEvent.KEYCODE_FORWARD_DEL:
-                return "\u2326";
-            case KeyEvent.KEYCODE_ESCAPE:
-                return "ESC";
-            case KeyEvent.KEYCODE_DPAD_UP:
-                return "\u2191";
-            case KeyEvent.KEYCODE_DPAD_DOWN:
-                return "\u2193";
-            case KeyEvent.KEYCODE_DPAD_LEFT:
-                return "\u2190";
-            case KeyEvent.KEYCODE_DPAD_RIGHT:
-                return "\u2192";
-            case KeyEvent.KEYCODE_DPAD_UP_RIGHT:
-                return "\u2197";
-            case KeyEvent.KEYCODE_DPAD_UP_LEFT:
-                return "\u2196";
-            case KeyEvent.KEYCODE_DPAD_DOWN_RIGHT:
-                return "\u2198";
-            case KeyEvent.KEYCODE_DPAD_DOWN_LEFT:
-                return "\u2199";
-            default:
-                break;
-        }
-
-        final int unicodeChar = event.getUnicodeChar();
-        if (unicodeChar != 0) {
-            return new String(Character.toChars(unicodeChar));
-        }
-
-        final var label = KeyEvent.keyCodeToString(event.getKeyCode());
-        if (label.startsWith("KEYCODE_")) {
-            return label.substring(8);
-        }
-        return label;
-    }
-
-    /** Determine whether to show key presses by checking one of the key-related objects. */
-    private boolean showKeyPresses() {
-        return mPressedKeyContainer != null;
-    }
-
-    /** Determine whether to show rotary input by checking one of the rotary-related objects. */
-    private boolean showRotaryInput() {
-        return mRotaryInputValueView != null;
-    }
-
-    /**
-     * Converts a dimension in scaled pixel units to integer display pixels.
-     */
-    private static int applyDimensionSp(int dimensionSp, DisplayMetrics dm) {
-        return (int) TypedValue.applyDimension(COMPLEX_UNIT_SP, dimensionSp, dm);
-    }
-
-    private static class PressedKeyView extends TextView {
-
-        private static final ColorFilter sInvertColors = new ColorMatrixColorFilter(new float[]{
-                -1.0f,     0,     0,    0, 255, // red
-                0, -1.0f,     0,    0, 255, // green
-                0,     0, -1.0f,    0, 255, // blue
-                0,     0,     0, 1.0f, 0    // alpha
-        });
-
-        PressedKeyView(Context c, String label) {
-            super(c);
-
-            final var dm = c.getResources().getDisplayMetrics();
-            final int keyViewSidePadding =
-                    (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, KEY_VIEW_SIDE_PADDING_DP, dm);
-            final int keyViewVerticalPadding =
-                    (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, KEY_VIEW_VERTICAL_PADDING_DP,
-                            dm);
-            final int keyViewMinWidth =
-                    (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, KEY_VIEW_MIN_WIDTH_DP, dm);
-            final int textSize =
-                    (int) TypedValue.applyDimension(COMPLEX_UNIT_SP, KEY_VIEW_TEXT_SIZE_SP, dm);
-
-            setText(label);
-            setGravity(Gravity.CENTER);
-            setMinimumWidth(keyViewMinWidth);
-            setTextSize(textSize);
-            setTypeface(Typeface.SANS_SERIF);
-            setBackgroundResource(R.drawable.focus_event_pressed_key_background);
-            setPaddingRelative(keyViewSidePadding, keyViewVerticalPadding, keyViewSidePadding,
-                    keyViewVerticalPadding);
-
-            setHighlighted(true);
-        }
-
-        void setHighlighted(boolean isHighlighted) {
-            if (isHighlighted) {
-                setTextColor(Color.BLACK);
-                getBackground().setColorFilter(sInvertColors);
-            } else {
-                setTextColor(Color.WHITE);
-                getBackground().clearColorFilter();
-            }
-            invalidate();
-        }
-    }
-
-    private static class PressedKeyContainer extends LinearLayout {
-
-        private final MarginLayoutParams mPressedKeyLayoutParams;
-
-        PressedKeyContainer(Context c) {
-            super(c);
-
-            final var dm = c.getResources().getDisplayMetrics();
-            final int keySeparationMargin =
-                    (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, KEY_SEPARATION_MARGIN_DP, dm);
-
-            final var transition = new LayoutTransition();
-            transition.disableTransitionType(LayoutTransition.APPEARING);
-            transition.disableTransitionType(LayoutTransition.DISAPPEARING);
-            transition.disableTransitionType(LayoutTransition.CHANGE_DISAPPEARING);
-            transition.setDuration(KEY_TRANSITION_DURATION_MILLIS);
-            setLayoutTransition(transition);
-
-            mPressedKeyLayoutParams = new MarginLayoutParams(WRAP_CONTENT, WRAP_CONTENT);
-            if (getOrientation() == VERTICAL) {
-                mPressedKeyLayoutParams.setMargins(0, keySeparationMargin, 0, 0);
-            } else {
-                mPressedKeyLayoutParams.setMargins(keySeparationMargin, 0, 0, 0);
-            }
-        }
-
-        public void handleKeyPressed(PressedKeyView pressedKeyView) {
-            addView(pressedKeyView, getChildCount(), mPressedKeyLayoutParams);
-            invalidate();
-        }
-
-        public void handleKeyRepeat(PressedKeyView repeatedKeyView) {
-            // Do nothing for now.
-        }
-
-        public void handleKeyRelease(PressedKeyView releasedKeyView) {
-            releasedKeyView.setHighlighted(false);
-            releasedKeyView.clearAnimation();
-            releasedKeyView.animate()
-                    .alpha(0)
-                    .setDuration(KEY_FADEOUT_DURATION_MILLIS)
-                    .setInterpolator(new AccelerateInterpolator())
-                    .withEndAction(this::cleanUpPressedKeyViews)
-                    .start();
-        }
-
-        private void cleanUpPressedKeyViews() {
-            int numChildrenToRemove = 0;
-            for (int i = 0; i < getChildCount(); i++) {
-                final View child = getChildAt(i);
-                if (child.getAlpha() != 0) {
-                    break;
-                }
-                child.setVisibility(View.GONE);
-                child.clearAnimation();
-                numChildrenToRemove++;
-            }
-            removeViews(0, numChildrenToRemove);
-            invalidate();
-        }
-    }
-
-    // TODO(b/286086154): move RotaryInputGraphView and RotaryInputValueView to a subpackage.
-
-    /** Draws the most recent rotary input value and indicates whether the source is active. */
-    @VisibleForTesting
-    static class RotaryInputValueView extends TextView {
-
-        private static final int INACTIVE_TEXT_COLOR = 0xffff00ff;
-        private static final int ACTIVE_TEXT_COLOR = 0xff420f28;
-        private static final int TEXT_SIZE_SP = 8;
-        private static final int SIDE_PADDING_SP = 4;
-        /** Determines how long the active status lasts. */
-        private static final int ACTIVE_STATUS_DURATION = 250 /* milliseconds */;
-        private static final ColorFilter ACTIVE_BACKGROUND_FILTER =
-                new ColorMatrixColorFilter(new float[]{
-                        0, 0, 0, 0, 255, // red
-                        0, 0, 0, 0,   0, // green
-                        0, 0, 0, 0, 255, // blue
-                        0, 0, 0, 0, 200  // alpha
-                });
-
-        private final Runnable mUpdateActivityStatusCallback = () -> updateActivityStatus(false);
-        private final float mScaledVerticalScrollFactor;
-
-        @VisibleForTesting
-        RotaryInputValueView(Context c) {
-            super(c);
-
-            DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
-            mScaledVerticalScrollFactor = ViewConfiguration.get(c).getScaledVerticalScrollFactor();
-
-            setText(getFormattedValue(0));
-            setTextColor(INACTIVE_TEXT_COLOR);
-            setTextSize(applyDimensionSp(TEXT_SIZE_SP, dm));
-            setPaddingRelative(applyDimensionSp(SIDE_PADDING_SP, dm), 0,
-                    applyDimensionSp(SIDE_PADDING_SP, dm), 0);
-            setTypeface(null, Typeface.BOLD);
-            setBackgroundResource(R.drawable.focus_event_rotary_input_background);
-        }
-
-        void updateValue(float value) {
-            removeCallbacks(mUpdateActivityStatusCallback);
-
-            setText(getFormattedValue(value * mScaledVerticalScrollFactor));
-
-            updateActivityStatus(true);
-            postDelayed(mUpdateActivityStatusCallback, ACTIVE_STATUS_DURATION);
-        }
-
-        @VisibleForTesting
-        void updateActivityStatus(boolean active) {
-            if (active) {
-                setTextColor(ACTIVE_TEXT_COLOR);
-                getBackground().setColorFilter(ACTIVE_BACKGROUND_FILTER);
-            } else {
-                setTextColor(INACTIVE_TEXT_COLOR);
-                getBackground().clearColorFilter();
-            }
-        }
-
-        private static String getFormattedValue(float value) {
-            return String.format("%s%.1f", value < 0 ? "-" : "+", Math.abs(value));
-        }
-    }
-
-    /**
-     * Shows a graph with the rotary input values as a function of time.
-     * The graph gets reset if no action is received for a certain amount of time.
-     */
-    @VisibleForTesting
-    static class RotaryInputGraphView extends View {
-
-        private static final int FRAME_COLOR = 0xbf741b47;
-        private static final int FRAME_WIDTH_SP = 2;
-        private static final int FRAME_BORDER_GAP_SP = 10;
-        private static final int FRAME_TEXT_SIZE_SP = 10;
-        private static final int FRAME_TEXT_OFFSET_SP = 2;
-        private static final int GRAPH_COLOR = 0xffff00ff;
-        private static final int GRAPH_LINE_WIDTH_SP = 1;
-        private static final int GRAPH_POINT_RADIUS_SP = 4;
-        private static final long MAX_SHOWN_TIME_INTERVAL = TimeUnit.SECONDS.toMillis(5);
-        private static final float DEFAULT_FRAME_CENTER_POSITION = 0;
-        private static final int MAX_GRAPH_VALUES_SIZE = 400;
-        /** Maximum time between values so that they are considered part of the same gesture. */
-        private static final long MAX_GESTURE_TIME = TimeUnit.SECONDS.toMillis(1);
-
-        private final DisplayMetrics mDm;
-        /**
-         * Distance in position units (amount scrolled in display pixels) from the center to the
-         * top/bottom frame lines.
-         */
-        private final float mFrameCenterToBorderDistance;
-        private final float mScaledVerticalScrollFactor;
-        private final Locale mDefaultLocale;
-        private final Paint mFramePaint = new Paint();
-        private final Paint mFrameTextPaint = new Paint();
-        private final Paint mGraphLinePaint = new Paint();
-        private final Paint mGraphPointPaint = new Paint();
-
-        private final CyclicBuffer mGraphValues = new CyclicBuffer(MAX_GRAPH_VALUES_SIZE);
-        /** Position at which graph values are placed at the center of the graph. */
-        private float mFrameCenterPosition = DEFAULT_FRAME_CENTER_POSITION;
-
-        @VisibleForTesting
-        RotaryInputGraphView(Context c) {
-            super(c);
-
-            mDm = mContext.getResources().getDisplayMetrics();
-            // This makes the center-to-border distance equivalent to the display height, meaning
-            // that the total height of the graph is equivalent to 2x the display height.
-            mFrameCenterToBorderDistance = mDm.heightPixels;
-            mScaledVerticalScrollFactor = ViewConfiguration.get(c).getScaledVerticalScrollFactor();
-            mDefaultLocale = Locale.getDefault();
-
-            mFramePaint.setColor(FRAME_COLOR);
-            mFramePaint.setStrokeWidth(applyDimensionSp(FRAME_WIDTH_SP, mDm));
-
-            mFrameTextPaint.setColor(GRAPH_COLOR);
-            mFrameTextPaint.setTextSize(applyDimensionSp(FRAME_TEXT_SIZE_SP, mDm));
-
-            mGraphLinePaint.setColor(GRAPH_COLOR);
-            mGraphLinePaint.setStrokeWidth(applyDimensionSp(GRAPH_LINE_WIDTH_SP, mDm));
-            mGraphLinePaint.setStrokeCap(Paint.Cap.ROUND);
-            mGraphLinePaint.setStrokeJoin(Paint.Join.ROUND);
-
-            mGraphPointPaint.setColor(GRAPH_COLOR);
-            mGraphPointPaint.setStrokeWidth(applyDimensionSp(GRAPH_POINT_RADIUS_SP, mDm));
-            mGraphPointPaint.setStrokeCap(Paint.Cap.ROUND);
-            mGraphPointPaint.setStrokeJoin(Paint.Join.ROUND);
-        }
-
-        /**
-         * Reads new scroll axis value and updates the list accordingly. Old positions are
-         * kept at the front (what you would get with getFirst), while the recent positions are
-         * kept at the back (what you would get with getLast). Also updates the frame center
-         * position to handle out-of-bounds cases.
-         */
-        void addValue(float scrollAxisValue, long eventTime) {
-            // Remove values that are too old.
-            while (mGraphValues.getSize() > 0
-                    && (eventTime - mGraphValues.getFirst().mTime) > MAX_SHOWN_TIME_INTERVAL) {
-                mGraphValues.removeFirst();
-            }
-
-            // If there are no recent values, reset the frame center.
-            if (mGraphValues.getSize() == 0) {
-                mFrameCenterPosition = DEFAULT_FRAME_CENTER_POSITION;
-            }
-
-            // Handle new value. We multiply the scroll axis value by the scaled scroll factor to
-            // get the amount of pixels to be scrolled. We also compute the accumulated position
-            // by adding the current value to the last one (if not empty).
-            final float displacement = scrollAxisValue * mScaledVerticalScrollFactor;
-            final float prevPos = (mGraphValues.getSize() == 0 ? 0 : mGraphValues.getLast().mPos);
-            final float pos = prevPos + displacement;
-
-            mGraphValues.add(pos, eventTime);
-
-            // The difference between the distance of the most recent position from the center
-            // frame (pos - mFrameCenterPosition) and the maximum allowed distance from the center
-            // frame (mFrameCenterToBorderDistance).
-            final float verticalDiff = Math.abs(pos - mFrameCenterPosition)
-                    - mFrameCenterToBorderDistance;
-            // If needed, translate frame.
-            if (verticalDiff > 0) {
-                final int sign = pos - mFrameCenterPosition < 0 ? -1 : 1;
-                // Here, we update the center frame position by the exact amount needed for us to
-                // stay within the maximum allowed distance from the center frame.
-                mFrameCenterPosition += sign * verticalDiff;
-            }
-
-            // Redraw canvas.
-            invalidate();
-        }
-
-        @Override
-        protected void onDraw(Canvas canvas) {
-            super.onDraw(canvas);
-
-            // Note: vertical coordinates in Canvas go from top to bottom,
-            // that is bottomY > middleY > topY.
-            final int verticalMargin = applyDimensionSp(FRAME_BORDER_GAP_SP, mDm);
-            final int topY = verticalMargin;
-            final int bottomY = getHeight() - verticalMargin;
-            final int middleY = (topY + bottomY) / 2;
-
-            // Note: horizontal coordinates in Canvas go from left to right,
-            // that is rightX > leftX.
-            final int leftX = 0;
-            final int rightX = getWidth();
-
-            // Draw the frame, which includes 3 lines that show the maximum,
-            // minimum and middle positions of the graph.
-            canvas.drawLine(leftX, topY, rightX, topY, mFramePaint);
-            canvas.drawLine(leftX, middleY, rightX, middleY, mFramePaint);
-            canvas.drawLine(leftX, bottomY, rightX, bottomY, mFramePaint);
-
-            // Draw the position that each frame line corresponds to.
-            final int frameTextOffset = applyDimensionSp(FRAME_TEXT_OFFSET_SP, mDm);
-            canvas.drawText(
-                    String.format(mDefaultLocale, "%.1f",
-                            mFrameCenterPosition + mFrameCenterToBorderDistance),
-                    leftX,
-                    topY - frameTextOffset, mFrameTextPaint
-            );
-            canvas.drawText(
-                    String.format(mDefaultLocale, "%.1f", mFrameCenterPosition),
-                    leftX,
-                    middleY - frameTextOffset, mFrameTextPaint
-            );
-            canvas.drawText(
-                    String.format(mDefaultLocale, "%.1f",
-                            mFrameCenterPosition - mFrameCenterToBorderDistance),
-                    leftX,
-                    bottomY - frameTextOffset, mFrameTextPaint
-            );
-
-            // If there are no graph values to be drawn, stop here.
-            if (mGraphValues.getSize() == 0) {
-                return;
-            }
-
-            // Draw the graph using the times and positions.
-            // We start at the most recent value (which should be drawn at the right) and move
-            // to the older values (which should be drawn to the left of more recent ones). Negative
-            // indices are handled by circuling back to the end of the buffer.
-            final long mostRecentTime = mGraphValues.getLast().mTime;
-            float prevCoordX = 0;
-            float prevCoordY = 0;
-            float prevAge = 0;
-            for (Iterator<GraphValue> iter = mGraphValues.reverseIterator(); iter.hasNext();) {
-                final GraphValue value = iter.next();
-
-                final int age = (int) (mostRecentTime - value.mTime);
-                final float pos = value.mPos;
-
-                // We get the horizontal coordinate in time units from left to right with
-                // (MAX_SHOWN_TIME_INTERVAL - age). Then, we rescale it to match the canvas
-                // units by dividing it by the time-domain length (MAX_SHOWN_TIME_INTERVAL)
-                // and by multiplying it by the canvas length (rightX - leftX). Finally, we
-                // offset the coordinate by adding it to leftX.
-                final float coordX = leftX + ((float) (MAX_SHOWN_TIME_INTERVAL - age)
-                        / MAX_SHOWN_TIME_INTERVAL) * (rightX - leftX);
-
-                // We get the vertical coordinate in position units from middle to top with
-                // (pos - mFrameCenterPosition). Then, we rescale it to match the canvas
-                // units by dividing it by half of the position-domain length
-                // (mFrameCenterToBorderDistance) and by multiplying it by half of the canvas
-                // length (middleY - topY). Finally, we offset the coordinate by subtracting
-                // it from middleY (we can't "add" here because the coordinate grows from top
-                // to bottom).
-                final float coordY = middleY - ((pos - mFrameCenterPosition)
-                        / mFrameCenterToBorderDistance) * (middleY - topY);
-
-                // Draw a point for this value.
-                canvas.drawPoint(coordX, coordY, mGraphPointPaint);
-
-                // If this value is part of the same gesture as the previous one, draw a line
-                // between them. We ignore the first value (with age = 0).
-                if (age != 0 && (age - prevAge) <= MAX_GESTURE_TIME) {
-                    canvas.drawLine(prevCoordX, prevCoordY, coordX, coordY, mGraphLinePaint);
-                }
-
-                prevCoordX = coordX;
-                prevCoordY = coordY;
-                prevAge = age;
-            }
-        }
-
-        @VisibleForTesting
-        float getFrameCenterPosition() {
-            return mFrameCenterPosition;
-        }
-
-        /**
-         * Holds data needed to draw each entry in the graph.
-         */
-        private static class GraphValue {
-            /** Position. */
-            float mPos;
-            /** Time when this value was added. */
-            long mTime;
-
-            GraphValue(float pos, long time) {
-                this.mPos = pos;
-                this.mTime = time;
-            }
-        }
-
-        /**
-         * Holds the graph values as a cyclic buffer. It has a fixed capacity, and it replaces the
-         * old values with new ones to avoid creating new objects.
-         */
-        private static class CyclicBuffer {
-            private final GraphValue[] mValues;
-            private final int mCapacity;
-            private int mSize = 0;
-            private int mLastIndex = 0;
-
-            // The iteration index and counter are here to make it easier to reset them.
-            /** Determines the value currently pointed by the iterator. */
-            private int mIteratorIndex;
-            /** Counts how many values have been iterated through. */
-            private int mIteratorCount;
-
-            /** Used traverse the values in reverse order. */
-            private final Iterator<GraphValue> mReverseIterator = new Iterator<GraphValue>() {
-                @Override
-                public boolean hasNext() {
-                    return mIteratorCount <= mSize;
-                }
-
-                @Override
-                public GraphValue next() {
-                    // Returns the value currently pointed by the iterator and moves the iterator to
-                    // the previous one.
-                    mIteratorCount++;
-                    return mValues[(mIteratorIndex-- + mCapacity) % mCapacity];
-                }
-            };
-
-            CyclicBuffer(int capacity) {
-                mCapacity = capacity;
-                mValues = new GraphValue[capacity];
-            }
-
-            /**
-             * Add new graph value. If there is an existing object, we replace its data with the
-             * new one. With this, we re-use old objects instead of creating new ones.
-             */
-            void add(float pos, long time) {
-                mLastIndex = (mLastIndex + 1) % mCapacity;
-                if (mValues[mLastIndex] == null) {
-                    mValues[mLastIndex] = new GraphValue(pos, time);
-                } else {
-                    final GraphValue oldValue = mValues[mLastIndex];
-                    oldValue.mPos = pos;
-                    oldValue.mTime = time;
-                }
-
-                // If needed, account for new value in the buffer size.
-                if (mSize != mCapacity) {
-                    mSize++;
-                }
-            }
-
-            int getSize() {
-                return mSize;
-            }
-
-            GraphValue getFirst() {
-                final int distanceBetweenLastAndFirst = (mCapacity - mSize) + 1;
-                final int firstIndex = (mLastIndex + distanceBetweenLastAndFirst) % mCapacity;
-                return mValues[firstIndex];
-            }
-
-            GraphValue getLast() {
-                return mValues[mLastIndex];
-            }
-
-            void removeFirst() {
-                mSize--;
-            }
-
-            /** Returns an iterator pointing at the last value. */
-            Iterator<GraphValue> reverseIterator() {
-                mIteratorIndex = mLastIndex;
-                mIteratorCount = 1;
-                return mReverseIterator;
-            }
-        }
-    }
-}
diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java
index b8e9d5d..cc972c2 100644
--- a/services/core/java/com/android/server/input/InputManagerService.java
+++ b/services/core/java/com/android/server/input/InputManagerService.java
@@ -116,6 +116,7 @@
 import com.android.server.LocalServices;
 import com.android.server.Watchdog;
 import com.android.server.input.InputManagerInternal.LidSwitchCallback;
+import com.android.server.input.debug.FocusEventDebugView;
 import com.android.server.inputmethod.InputMethodManagerInternal;
 import com.android.server.policy.WindowManagerPolicy;
 
diff --git a/services/core/java/com/android/server/input/FocusEventDebugGlobalMonitor.java b/services/core/java/com/android/server/input/debug/FocusEventDebugGlobalMonitor.java
similarity index 94%
rename from services/core/java/com/android/server/input/FocusEventDebugGlobalMonitor.java
rename to services/core/java/com/android/server/input/debug/FocusEventDebugGlobalMonitor.java
index 67c221f..2b21e49 100644
--- a/services/core/java/com/android/server/input/FocusEventDebugGlobalMonitor.java
+++ b/services/core/java/com/android/server/input/debug/FocusEventDebugGlobalMonitor.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.input;
+package com.android.server.input.debug;
 
 import android.view.Display;
 import android.view.InputEvent;
@@ -22,6 +22,7 @@
 import android.view.MotionEvent;
 
 import com.android.server.UiThread;
+import com.android.server.input.InputManagerService;
 
 /**
  * Receives input events before they are dispatched and reports them to FocusEventDebugView.
diff --git a/services/core/java/com/android/server/input/debug/FocusEventDebugView.java b/services/core/java/com/android/server/input/debug/FocusEventDebugView.java
new file mode 100644
index 0000000..6eec0de
--- /dev/null
+++ b/services/core/java/com/android/server/input/debug/FocusEventDebugView.java
@@ -0,0 +1,466 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.input.debug;
+
+import static android.util.TypedValue.COMPLEX_UNIT_DIP;
+import static android.util.TypedValue.COMPLEX_UNIT_SP;
+import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
+
+import android.animation.LayoutTransition;
+import android.annotation.AnyThread;
+import android.annotation.Nullable;
+import android.content.Context;
+import android.graphics.Color;
+import android.graphics.ColorFilter;
+import android.graphics.ColorMatrixColorFilter;
+import android.graphics.Typeface;
+import android.util.DisplayMetrics;
+import android.util.Pair;
+import android.util.Slog;
+import android.util.TypedValue;
+import android.view.Gravity;
+import android.view.InputDevice;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+import android.view.RoundedCorner;
+import android.view.View;
+import android.view.WindowInsets;
+import android.view.animation.AccelerateInterpolator;
+import android.widget.HorizontalScrollView;
+import android.widget.LinearLayout;
+import android.widget.RelativeLayout;
+import android.widget.TextView;
+
+import com.android.internal.R;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.input.InputManagerService;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.Supplier;
+
+/**
+ *  Displays focus events, such as physical keyboard KeyEvents and non-pointer MotionEvents on
+ *  the screen.
+ */
+public class FocusEventDebugView extends RelativeLayout {
+
+    private static final String TAG = FocusEventDebugView.class.getSimpleName();
+
+    private static final int KEY_FADEOUT_DURATION_MILLIS = 1000;
+    private static final int KEY_TRANSITION_DURATION_MILLIS = 100;
+
+    private static final int OUTER_PADDING_DP = 16;
+    private static final int KEY_SEPARATION_MARGIN_DP = 16;
+    private static final int KEY_VIEW_SIDE_PADDING_DP = 16;
+    private static final int KEY_VIEW_VERTICAL_PADDING_DP = 8;
+    private static final int KEY_VIEW_MIN_WIDTH_DP = 32;
+    private static final int KEY_VIEW_TEXT_SIZE_SP = 12;
+    private static final double ROTATY_GRAPH_HEIGHT_FRACTION = 0.5;
+
+    private final InputManagerService mService;
+    private final int mOuterPadding;
+    private final DisplayMetrics mDm;
+
+    // Tracks all keys that are currently pressed/down.
+    private final Map<Pair<Integer /*deviceId*/, Integer /*scanCode*/>, PressedKeyView>
+            mPressedKeys = new HashMap<>();
+
+    @Nullable
+    private FocusEventDebugGlobalMonitor mFocusEventDebugGlobalMonitor;
+    @Nullable
+    private PressedKeyContainer mPressedKeyContainer;
+    @Nullable
+    private PressedKeyContainer mPressedModifierContainer;
+    private final Supplier<RotaryInputValueView> mRotaryInputValueViewFactory;
+    @Nullable
+    private RotaryInputValueView mRotaryInputValueView;
+    private final Supplier<RotaryInputGraphView> mRotaryInputGraphViewFactory;
+    @Nullable
+    private RotaryInputGraphView mRotaryInputGraphView;
+
+    @VisibleForTesting
+    FocusEventDebugView(Context c, InputManagerService service,
+            Supplier<RotaryInputValueView> rotaryInputValueViewFactory,
+            Supplier<RotaryInputGraphView> rotaryInputGraphViewFactory) {
+        super(c);
+        setFocusableInTouchMode(true);
+
+        mService = service;
+        mRotaryInputValueViewFactory = rotaryInputValueViewFactory;
+        mRotaryInputGraphViewFactory = rotaryInputGraphViewFactory;
+        mDm = mContext.getResources().getDisplayMetrics();
+        mOuterPadding = (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, OUTER_PADDING_DP, mDm);
+    }
+
+    public FocusEventDebugView(Context c, InputManagerService service) {
+        this(c, service, () -> new RotaryInputValueView(c), () -> new RotaryInputGraphView(c));
+    }
+
+    @Override
+    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
+        int paddingBottom = 0;
+
+        final RoundedCorner bottomLeft =
+                insets.getRoundedCorner(RoundedCorner.POSITION_BOTTOM_LEFT);
+        if (bottomLeft != null && !insets.isRound()) {
+            paddingBottom = bottomLeft.getRadius();
+        }
+
+        final RoundedCorner bottomRight =
+                insets.getRoundedCorner(RoundedCorner.POSITION_BOTTOM_RIGHT);
+        if (bottomRight != null && !insets.isRound()) {
+            paddingBottom = Math.max(paddingBottom, bottomRight.getRadius());
+        }
+
+        if (insets.getDisplayCutout() != null) {
+            paddingBottom =
+                    Math.max(paddingBottom, insets.getDisplayCutout().getSafeInsetBottom());
+        }
+
+        setPadding(mOuterPadding, mOuterPadding, mOuterPadding, mOuterPadding + paddingBottom);
+        setClipToPadding(false);
+        invalidate();
+        return super.onApplyWindowInsets(insets);
+    }
+
+    @Override
+    public boolean dispatchKeyEvent(KeyEvent event) {
+        handleKeyEvent(event);
+        return super.dispatchKeyEvent(event);
+    }
+
+    /** Determines whether to show the key presses visualization. */
+    @AnyThread
+    public void updateShowKeyPresses(boolean enabled) {
+        post(() -> handleUpdateShowKeyPresses(enabled));
+    }
+
+    /** Determines whether to show the rotary input visualization. */
+    @AnyThread
+    public void updateShowRotaryInput(boolean enabled) {
+        post(() -> handleUpdateShowRotaryInput(enabled));
+    }
+
+    private void handleUpdateShowKeyPresses(boolean enabled) {
+        if (enabled == showKeyPresses()) {
+            return;
+        }
+
+        if (!enabled) {
+            removeView(mPressedKeyContainer);
+            mPressedKeyContainer = null;
+            removeView(mPressedModifierContainer);
+            mPressedModifierContainer = null;
+            return;
+        }
+
+        mPressedKeyContainer = new PressedKeyContainer(mContext);
+        mPressedKeyContainer.setOrientation(LinearLayout.HORIZONTAL);
+        mPressedKeyContainer.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
+        mPressedKeyContainer.setLayoutDirection(LAYOUT_DIRECTION_LTR);
+        final var scroller = new HorizontalScrollView(mContext);
+        scroller.addView(mPressedKeyContainer);
+        scroller.setHorizontalScrollBarEnabled(false);
+        scroller.addOnLayoutChangeListener(
+                (view, l, t, r, b, ol, ot, or, ob) -> scroller.fullScroll(View.FOCUS_RIGHT));
+        scroller.setHorizontalFadingEdgeEnabled(true);
+        LayoutParams scrollerLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
+        scrollerLayoutParams.addRule(ALIGN_PARENT_BOTTOM);
+        scrollerLayoutParams.addRule(ALIGN_PARENT_RIGHT);
+        addView(scroller, scrollerLayoutParams);
+
+        mPressedModifierContainer = new PressedKeyContainer(mContext);
+        mPressedModifierContainer.setOrientation(LinearLayout.VERTICAL);
+        mPressedModifierContainer.setGravity(Gravity.LEFT | Gravity.BOTTOM);
+        LayoutParams modifierLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
+        modifierLayoutParams.addRule(ALIGN_PARENT_BOTTOM);
+        modifierLayoutParams.addRule(ALIGN_PARENT_LEFT);
+        modifierLayoutParams.addRule(LEFT_OF, scroller.getId());
+        addView(mPressedModifierContainer, modifierLayoutParams);
+    }
+
+    @VisibleForTesting
+    void handleUpdateShowRotaryInput(boolean enabled) {
+        if (enabled == showRotaryInput()) {
+            return;
+        }
+
+        if (!enabled) {
+            mFocusEventDebugGlobalMonitor.dispose();
+            mFocusEventDebugGlobalMonitor = null;
+            removeView(mRotaryInputValueView);
+            mRotaryInputValueView = null;
+            removeView(mRotaryInputGraphView);
+            mRotaryInputGraphView = null;
+            return;
+        }
+
+        mFocusEventDebugGlobalMonitor = new FocusEventDebugGlobalMonitor(this, mService);
+
+        mRotaryInputValueView = mRotaryInputValueViewFactory.get();
+        LayoutParams valueLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
+        valueLayoutParams.addRule(CENTER_HORIZONTAL);
+        valueLayoutParams.addRule(ALIGN_PARENT_BOTTOM);
+        addView(mRotaryInputValueView, valueLayoutParams);
+
+        mRotaryInputGraphView = mRotaryInputGraphViewFactory.get();
+        LayoutParams graphLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
+                (int) (ROTATY_GRAPH_HEIGHT_FRACTION * mDm.heightPixels));
+        graphLayoutParams.addRule(CENTER_IN_PARENT);
+        addView(mRotaryInputGraphView, graphLayoutParams);
+    }
+
+    /** Report a key event to the debug view. */
+    @AnyThread
+    public void reportKeyEvent(KeyEvent event) {
+        post(() -> handleKeyEvent(KeyEvent.obtain((KeyEvent) event)));
+    }
+
+    /** Report a motion event to the debug view. */
+    @AnyThread
+    public void reportMotionEvent(MotionEvent event) {
+        if (event.getSource() != InputDevice.SOURCE_ROTARY_ENCODER) {
+            return;
+        }
+
+        post(() -> handleRotaryInput(MotionEvent.obtain((MotionEvent) event)));
+    }
+
+    private void handleKeyEvent(KeyEvent keyEvent) {
+        if (!showKeyPresses()) {
+            return;
+        }
+
+        final var identifier = new Pair<>(keyEvent.getDeviceId(), keyEvent.getScanCode());
+        final var container = KeyEvent.isModifierKey(keyEvent.getKeyCode())
+                ? mPressedModifierContainer
+                : mPressedKeyContainer;
+        PressedKeyView pressedKeyView = mPressedKeys.get(identifier);
+        switch (keyEvent.getAction()) {
+            case KeyEvent.ACTION_DOWN: {
+                if (pressedKeyView != null) {
+                    if (keyEvent.getRepeatCount() == 0) {
+                        Slog.w(TAG, "Got key down for "
+                                + KeyEvent.keyCodeToString(keyEvent.getKeyCode())
+                                + " that was already tracked as being down.");
+                        break;
+                    }
+                    container.handleKeyRepeat(pressedKeyView);
+                    break;
+                }
+
+                pressedKeyView = new PressedKeyView(mContext, getLabel(keyEvent));
+                mPressedKeys.put(identifier, pressedKeyView);
+                container.handleKeyPressed(pressedKeyView);
+                break;
+            }
+            case KeyEvent.ACTION_UP: {
+                if (pressedKeyView == null) {
+                    Slog.w(TAG, "Got key up for " + KeyEvent.keyCodeToString(keyEvent.getKeyCode())
+                            + " that was not tracked as being down.");
+                    break;
+                }
+                mPressedKeys.remove(identifier);
+                container.handleKeyRelease(pressedKeyView);
+                break;
+            }
+            default:
+                break;
+        }
+        keyEvent.recycle();
+    }
+
+    @VisibleForTesting
+    void handleRotaryInput(MotionEvent motionEvent) {
+        if (!showRotaryInput()) {
+            return;
+        }
+
+        float scrollAxisValue = motionEvent.getAxisValue(MotionEvent.AXIS_SCROLL);
+        mRotaryInputValueView.updateValue(scrollAxisValue);
+        mRotaryInputGraphView.addValue(scrollAxisValue, motionEvent.getEventTime());
+
+        motionEvent.recycle();
+    }
+
+    private static String getLabel(KeyEvent event) {
+        switch (event.getKeyCode()) {
+            case KeyEvent.KEYCODE_SPACE:
+                return "\u2423";
+            case KeyEvent.KEYCODE_TAB:
+                return "\u21e5";
+            case KeyEvent.KEYCODE_ENTER:
+            case KeyEvent.KEYCODE_NUMPAD_ENTER:
+                return "\u23CE";
+            case KeyEvent.KEYCODE_DEL:
+                return "\u232B";
+            case KeyEvent.KEYCODE_FORWARD_DEL:
+                return "\u2326";
+            case KeyEvent.KEYCODE_ESCAPE:
+                return "ESC";
+            case KeyEvent.KEYCODE_DPAD_UP:
+                return "\u2191";
+            case KeyEvent.KEYCODE_DPAD_DOWN:
+                return "\u2193";
+            case KeyEvent.KEYCODE_DPAD_LEFT:
+                return "\u2190";
+            case KeyEvent.KEYCODE_DPAD_RIGHT:
+                return "\u2192";
+            case KeyEvent.KEYCODE_DPAD_UP_RIGHT:
+                return "\u2197";
+            case KeyEvent.KEYCODE_DPAD_UP_LEFT:
+                return "\u2196";
+            case KeyEvent.KEYCODE_DPAD_DOWN_RIGHT:
+                return "\u2198";
+            case KeyEvent.KEYCODE_DPAD_DOWN_LEFT:
+                return "\u2199";
+            default:
+                break;
+        }
+
+        final int unicodeChar = event.getUnicodeChar();
+        if (unicodeChar != 0) {
+            return new String(Character.toChars(unicodeChar));
+        }
+
+        final var label = KeyEvent.keyCodeToString(event.getKeyCode());
+        if (label.startsWith("KEYCODE_")) {
+            return label.substring(8);
+        }
+        return label;
+    }
+
+    /** Determine whether to show key presses by checking one of the key-related objects. */
+    private boolean showKeyPresses() {
+        return mPressedKeyContainer != null;
+    }
+
+    /** Determine whether to show rotary input by checking one of the rotary-related objects. */
+    private boolean showRotaryInput() {
+        return mRotaryInputValueView != null;
+    }
+
+    private static class PressedKeyView extends TextView {
+
+        private static final ColorFilter sInvertColors = new ColorMatrixColorFilter(new float[]{
+                -1.0f,     0,     0,    0, 255, // red
+                0, -1.0f,     0,    0, 255, // green
+                0,     0, -1.0f,    0, 255, // blue
+                0,     0,     0, 1.0f, 0    // alpha
+        });
+
+        PressedKeyView(Context c, String label) {
+            super(c);
+
+            final var dm = c.getResources().getDisplayMetrics();
+            final int keyViewSidePadding =
+                    (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, KEY_VIEW_SIDE_PADDING_DP, dm);
+            final int keyViewVerticalPadding =
+                    (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, KEY_VIEW_VERTICAL_PADDING_DP,
+                            dm);
+            final int keyViewMinWidth =
+                    (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, KEY_VIEW_MIN_WIDTH_DP, dm);
+            final int textSize =
+                    (int) TypedValue.applyDimension(COMPLEX_UNIT_SP, KEY_VIEW_TEXT_SIZE_SP, dm);
+
+            setText(label);
+            setGravity(Gravity.CENTER);
+            setMinimumWidth(keyViewMinWidth);
+            setTextSize(textSize);
+            setTypeface(Typeface.SANS_SERIF);
+            setBackgroundResource(R.drawable.focus_event_pressed_key_background);
+            setPaddingRelative(keyViewSidePadding, keyViewVerticalPadding, keyViewSidePadding,
+                    keyViewVerticalPadding);
+
+            setHighlighted(true);
+        }
+
+        void setHighlighted(boolean isHighlighted) {
+            if (isHighlighted) {
+                setTextColor(Color.BLACK);
+                getBackground().setColorFilter(sInvertColors);
+            } else {
+                setTextColor(Color.WHITE);
+                getBackground().clearColorFilter();
+            }
+            invalidate();
+        }
+    }
+
+    private static class PressedKeyContainer extends LinearLayout {
+
+        private final MarginLayoutParams mPressedKeyLayoutParams;
+
+        PressedKeyContainer(Context c) {
+            super(c);
+
+            final var dm = c.getResources().getDisplayMetrics();
+            final int keySeparationMargin =
+                    (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, KEY_SEPARATION_MARGIN_DP, dm);
+
+            final var transition = new LayoutTransition();
+            transition.disableTransitionType(LayoutTransition.APPEARING);
+            transition.disableTransitionType(LayoutTransition.DISAPPEARING);
+            transition.disableTransitionType(LayoutTransition.CHANGE_DISAPPEARING);
+            transition.setDuration(KEY_TRANSITION_DURATION_MILLIS);
+            setLayoutTransition(transition);
+
+            mPressedKeyLayoutParams = new MarginLayoutParams(WRAP_CONTENT, WRAP_CONTENT);
+            if (getOrientation() == VERTICAL) {
+                mPressedKeyLayoutParams.setMargins(0, keySeparationMargin, 0, 0);
+            } else {
+                mPressedKeyLayoutParams.setMargins(keySeparationMargin, 0, 0, 0);
+            }
+        }
+
+        public void handleKeyPressed(PressedKeyView pressedKeyView) {
+            addView(pressedKeyView, getChildCount(), mPressedKeyLayoutParams);
+            invalidate();
+        }
+
+        public void handleKeyRepeat(PressedKeyView repeatedKeyView) {
+            // Do nothing for now.
+        }
+
+        public void handleKeyRelease(PressedKeyView releasedKeyView) {
+            releasedKeyView.setHighlighted(false);
+            releasedKeyView.clearAnimation();
+            releasedKeyView.animate()
+                    .alpha(0)
+                    .setDuration(KEY_FADEOUT_DURATION_MILLIS)
+                    .setInterpolator(new AccelerateInterpolator())
+                    .withEndAction(this::cleanUpPressedKeyViews)
+                    .start();
+        }
+
+        private void cleanUpPressedKeyViews() {
+            int numChildrenToRemove = 0;
+            for (int i = 0; i < getChildCount(); i++) {
+                final View child = getChildAt(i);
+                if (child.getAlpha() != 0) {
+                    break;
+                }
+                child.setVisibility(View.GONE);
+                child.clearAnimation();
+                numChildrenToRemove++;
+            }
+            removeViews(0, numChildrenToRemove);
+            invalidate();
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/input/debug/RotaryInputGraphView.java b/services/core/java/com/android/server/input/debug/RotaryInputGraphView.java
new file mode 100644
index 0000000..6a9fe2f
--- /dev/null
+++ b/services/core/java/com/android/server/input/debug/RotaryInputGraphView.java
@@ -0,0 +1,345 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.input.debug;
+
+import static android.util.TypedValue.COMPLEX_UNIT_SP;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.util.DisplayMetrics;
+import android.util.TypedValue;
+import android.view.View;
+import android.view.ViewConfiguration;
+
+import com.android.internal.annotations.VisibleForTesting;
+
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Shows a graph with the rotary input values as a function of time.
+ * The graph gets reset if no action is received for a certain amount of time.
+ */
+class RotaryInputGraphView extends View {
+
+    private static final int FRAME_COLOR = 0xbf741b47;
+    private static final int FRAME_WIDTH_SP = 2;
+    private static final int FRAME_BORDER_GAP_SP = 10;
+    private static final int FRAME_TEXT_SIZE_SP = 10;
+    private static final int FRAME_TEXT_OFFSET_SP = 2;
+    private static final int GRAPH_COLOR = 0xffff00ff;
+    private static final int GRAPH_LINE_WIDTH_SP = 1;
+    private static final int GRAPH_POINT_RADIUS_SP = 4;
+    private static final long MAX_SHOWN_TIME_INTERVAL = TimeUnit.SECONDS.toMillis(5);
+    private static final float DEFAULT_FRAME_CENTER_POSITION = 0;
+    private static final int MAX_GRAPH_VALUES_SIZE = 400;
+    /** Maximum time between values so that they are considered part of the same gesture. */
+    private static final long MAX_GESTURE_TIME = TimeUnit.SECONDS.toMillis(1);
+
+    private final DisplayMetrics mDm;
+    /**
+     * Distance in position units (amount scrolled in display pixels) from the center to the
+     * top/bottom frame lines.
+     */
+    private final float mFrameCenterToBorderDistance;
+    private final float mScaledVerticalScrollFactor;
+    private final Locale mDefaultLocale = Locale.getDefault();
+    private final Paint mFramePaint = new Paint();
+    private final Paint mFrameTextPaint = new Paint();
+    private final Paint mGraphLinePaint = new Paint();
+    private final Paint mGraphPointPaint = new Paint();
+
+    private final CyclicBuffer mGraphValues = new CyclicBuffer(MAX_GRAPH_VALUES_SIZE);
+    /** Position at which graph values are placed at the center of the graph. */
+    private float mFrameCenterPosition = DEFAULT_FRAME_CENTER_POSITION;
+
+    RotaryInputGraphView(Context c) {
+        super(c);
+
+        mDm = mContext.getResources().getDisplayMetrics();
+        // This makes the center-to-border distance equivalent to the display height, meaning
+        // that the total height of the graph is equivalent to 2x the display height.
+        mFrameCenterToBorderDistance = mDm.heightPixels;
+        mScaledVerticalScrollFactor = ViewConfiguration.get(c).getScaledVerticalScrollFactor();
+
+        mFramePaint.setColor(FRAME_COLOR);
+        mFramePaint.setStrokeWidth(applyDimensionSp(FRAME_WIDTH_SP, mDm));
+
+        mFrameTextPaint.setColor(GRAPH_COLOR);
+        mFrameTextPaint.setTextSize(applyDimensionSp(FRAME_TEXT_SIZE_SP, mDm));
+
+        mGraphLinePaint.setColor(GRAPH_COLOR);
+        mGraphLinePaint.setStrokeWidth(applyDimensionSp(GRAPH_LINE_WIDTH_SP, mDm));
+        mGraphLinePaint.setStrokeCap(Paint.Cap.ROUND);
+        mGraphLinePaint.setStrokeJoin(Paint.Join.ROUND);
+
+        mGraphPointPaint.setColor(GRAPH_COLOR);
+        mGraphPointPaint.setStrokeWidth(applyDimensionSp(GRAPH_POINT_RADIUS_SP, mDm));
+        mGraphPointPaint.setStrokeCap(Paint.Cap.ROUND);
+        mGraphPointPaint.setStrokeJoin(Paint.Join.ROUND);
+    }
+
+    /**
+     * Reads new scroll axis value and updates the list accordingly. Old positions are
+     * kept at the front (what you would get with getFirst), while the recent positions are
+     * kept at the back (what you would get with getLast). Also updates the frame center
+     * position to handle out-of-bounds cases.
+     */
+    void addValue(float scrollAxisValue, long eventTime) {
+        // Remove values that are too old.
+        while (mGraphValues.getSize() > 0
+                && (eventTime - mGraphValues.getFirst().mTime) > MAX_SHOWN_TIME_INTERVAL) {
+            mGraphValues.removeFirst();
+        }
+
+        // If there are no recent values, reset the frame center.
+        if (mGraphValues.getSize() == 0) {
+            mFrameCenterPosition = DEFAULT_FRAME_CENTER_POSITION;
+        }
+
+        // Handle new value. We multiply the scroll axis value by the scaled scroll factor to
+        // get the amount of pixels to be scrolled. We also compute the accumulated position
+        // by adding the current value to the last one (if not empty).
+        final float displacement = scrollAxisValue * mScaledVerticalScrollFactor;
+        final float prevPos = (mGraphValues.getSize() == 0 ? 0 : mGraphValues.getLast().mPos);
+        final float pos = prevPos + displacement;
+
+        mGraphValues.add(pos, eventTime);
+
+        // The difference between the distance of the most recent position from the center
+        // frame (pos - mFrameCenterPosition) and the maximum allowed distance from the center
+        // frame (mFrameCenterToBorderDistance).
+        final float verticalDiff = Math.abs(pos - mFrameCenterPosition)
+                - mFrameCenterToBorderDistance;
+        // If needed, translate frame.
+        if (verticalDiff > 0) {
+            final int sign = pos - mFrameCenterPosition < 0 ? -1 : 1;
+            // Here, we update the center frame position by the exact amount needed for us to
+            // stay within the maximum allowed distance from the center frame.
+            mFrameCenterPosition += sign * verticalDiff;
+        }
+
+        // Redraw canvas.
+        invalidate();
+    }
+
+    @Override
+    protected void onDraw(Canvas canvas) {
+        super.onDraw(canvas);
+
+        // Note: vertical coordinates in Canvas go from top to bottom,
+        // that is bottomY > middleY > topY.
+        final int verticalMargin = applyDimensionSp(FRAME_BORDER_GAP_SP, mDm);
+        final int topY = verticalMargin;
+        final int bottomY = getHeight() - verticalMargin;
+        final int middleY = (topY + bottomY) / 2;
+
+        // Note: horizontal coordinates in Canvas go from left to right,
+        // that is rightX > leftX.
+        final int leftX = 0;
+        final int rightX = getWidth();
+
+        // Draw the frame, which includes 3 lines that show the maximum,
+        // minimum and middle positions of the graph.
+        canvas.drawLine(leftX, topY, rightX, topY, mFramePaint);
+        canvas.drawLine(leftX, middleY, rightX, middleY, mFramePaint);
+        canvas.drawLine(leftX, bottomY, rightX, bottomY, mFramePaint);
+
+        // Draw the position that each frame line corresponds to.
+        final int frameTextOffset = applyDimensionSp(FRAME_TEXT_OFFSET_SP, mDm);
+        canvas.drawText(
+                String.format(mDefaultLocale, "%.1f",
+                        mFrameCenterPosition + mFrameCenterToBorderDistance),
+                leftX,
+                topY - frameTextOffset, mFrameTextPaint
+        );
+        canvas.drawText(
+                String.format(mDefaultLocale, "%.1f", mFrameCenterPosition),
+                leftX,
+                middleY - frameTextOffset, mFrameTextPaint
+        );
+        canvas.drawText(
+                String.format(mDefaultLocale, "%.1f",
+                        mFrameCenterPosition - mFrameCenterToBorderDistance),
+                leftX,
+                bottomY - frameTextOffset, mFrameTextPaint
+        );
+
+        // If there are no graph values to be drawn, stop here.
+        if (mGraphValues.getSize() == 0) {
+            return;
+        }
+
+        // Draw the graph using the times and positions.
+        // We start at the most recent value (which should be drawn at the right) and move
+        // to the older values (which should be drawn to the left of more recent ones). Negative
+        // indices are handled by circuling back to the end of the buffer.
+        final long mostRecentTime = mGraphValues.getLast().mTime;
+        float prevCoordX = 0;
+        float prevCoordY = 0;
+        float prevAge = 0;
+        for (Iterator<GraphValue> iter = mGraphValues.reverseIterator(); iter.hasNext();) {
+            final GraphValue value = iter.next();
+
+            final int age = (int) (mostRecentTime - value.mTime);
+            final float pos = value.mPos;
+
+            // We get the horizontal coordinate in time units from left to right with
+            // (MAX_SHOWN_TIME_INTERVAL - age). Then, we rescale it to match the canvas
+            // units by dividing it by the time-domain length (MAX_SHOWN_TIME_INTERVAL)
+            // and by multiplying it by the canvas length (rightX - leftX). Finally, we
+            // offset the coordinate by adding it to leftX.
+            final float coordX = leftX + ((float) (MAX_SHOWN_TIME_INTERVAL - age)
+                    / MAX_SHOWN_TIME_INTERVAL) * (rightX - leftX);
+
+            // We get the vertical coordinate in position units from middle to top with
+            // (pos - mFrameCenterPosition). Then, we rescale it to match the canvas
+            // units by dividing it by half of the position-domain length
+            // (mFrameCenterToBorderDistance) and by multiplying it by half of the canvas
+            // length (middleY - topY). Finally, we offset the coordinate by subtracting
+            // it from middleY (we can't "add" here because the coordinate grows from top
+            // to bottom).
+            final float coordY = middleY - ((pos - mFrameCenterPosition)
+                    / mFrameCenterToBorderDistance) * (middleY - topY);
+
+            // Draw a point for this value.
+            canvas.drawPoint(coordX, coordY, mGraphPointPaint);
+
+            // If this value is part of the same gesture as the previous one, draw a line
+            // between them. We ignore the first value (with age = 0).
+            if (age != 0 && (age - prevAge) <= MAX_GESTURE_TIME) {
+                canvas.drawLine(prevCoordX, prevCoordY, coordX, coordY, mGraphLinePaint);
+            }
+
+            prevCoordX = coordX;
+            prevCoordY = coordY;
+            prevAge = age;
+        }
+    }
+
+    @VisibleForTesting
+    float getFrameCenterPosition() {
+        return mFrameCenterPosition;
+    }
+
+    /**
+     * Converts a dimension in scaled pixel units to integer display pixels.
+     */
+    private static int applyDimensionSp(int dimensionSp, DisplayMetrics dm) {
+        return (int) TypedValue.applyDimension(COMPLEX_UNIT_SP, dimensionSp, dm);
+    }
+
+    /**
+     * Holds data needed to draw each entry in the graph.
+     */
+    private static class GraphValue {
+        /** Position. */
+        float mPos;
+        /** Time when this value was added. */
+        long mTime;
+
+        GraphValue(float pos, long time) {
+            this.mPos = pos;
+            this.mTime = time;
+        }
+    }
+
+    /**
+     * Holds the graph values as a cyclic buffer. It has a fixed capacity, and it replaces the
+     * old values with new ones to avoid creating new objects.
+     */
+    private static class CyclicBuffer {
+        private final GraphValue[] mValues;
+        private final int mCapacity;
+        private int mSize = 0;
+        private int mLastIndex = 0;
+
+        // The iteration index and counter are here to make it easier to reset them.
+        /** Determines the value currently pointed by the iterator. */
+        private int mIteratorIndex;
+        /** Counts how many values have been iterated through. */
+        private int mIteratorCount;
+
+        /** Used traverse the values in reverse order. */
+        private final Iterator<GraphValue> mReverseIterator = new Iterator<GraphValue>() {
+            @Override
+            public boolean hasNext() {
+                return mIteratorCount <= mSize;
+            }
+
+            @Override
+            public GraphValue next() {
+                // Returns the value currently pointed by the iterator and moves the iterator to
+                // the previous one.
+                mIteratorCount++;
+                return mValues[(mIteratorIndex-- + mCapacity) % mCapacity];
+            }
+        };
+
+        CyclicBuffer(int capacity) {
+            mCapacity = capacity;
+            mValues = new GraphValue[capacity];
+        }
+
+        /**
+         * Add new graph value. If there is an existing object, we replace its data with the
+         * new one. With this, we re-use old objects instead of creating new ones.
+         */
+        void add(float pos, long time) {
+            mLastIndex = (mLastIndex + 1) % mCapacity;
+            if (mValues[mLastIndex] == null) {
+                mValues[mLastIndex] = new GraphValue(pos, time);
+            } else {
+                final GraphValue oldValue = mValues[mLastIndex];
+                oldValue.mPos = pos;
+                oldValue.mTime = time;
+            }
+
+            // If needed, account for new value in the buffer size.
+            if (mSize != mCapacity) {
+                mSize++;
+            }
+        }
+
+        int getSize() {
+            return mSize;
+        }
+
+        GraphValue getFirst() {
+            final int distanceBetweenLastAndFirst = (mCapacity - mSize) + 1;
+            final int firstIndex = (mLastIndex + distanceBetweenLastAndFirst) % mCapacity;
+            return mValues[firstIndex];
+        }
+
+        GraphValue getLast() {
+            return mValues[mLastIndex];
+        }
+
+        void removeFirst() {
+            mSize--;
+        }
+
+        /** Returns an iterator pointing at the last value. */
+        Iterator<GraphValue> reverseIterator() {
+            mIteratorIndex = mLastIndex;
+            mIteratorCount = 1;
+            return mReverseIterator;
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/input/debug/RotaryInputValueView.java b/services/core/java/com/android/server/input/debug/RotaryInputValueView.java
new file mode 100644
index 0000000..38613eb
--- /dev/null
+++ b/services/core/java/com/android/server/input/debug/RotaryInputValueView.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.input.debug;
+
+import static android.util.TypedValue.COMPLEX_UNIT_SP;
+
+import android.content.Context;
+import android.graphics.ColorFilter;
+import android.graphics.ColorMatrixColorFilter;
+import android.graphics.Typeface;
+import android.util.DisplayMetrics;
+import android.util.TypedValue;
+import android.view.ViewConfiguration;
+import android.widget.TextView;
+
+import com.android.internal.R;
+import com.android.internal.annotations.VisibleForTesting;
+
+import java.util.Locale;
+
+/** Draws the most recent rotary input value and indicates whether the source is active. */
+class RotaryInputValueView extends TextView {
+
+    private static final int INACTIVE_TEXT_COLOR = 0xffff00ff;
+    private static final int ACTIVE_TEXT_COLOR = 0xff420f28;
+    private static final int TEXT_SIZE_SP = 8;
+    private static final int SIDE_PADDING_SP = 4;
+    /** Determines how long the active status lasts. */
+    private static final int ACTIVE_STATUS_DURATION = 250 /* milliseconds */;
+    private static final ColorFilter ACTIVE_BACKGROUND_FILTER =
+            new ColorMatrixColorFilter(new float[]{
+                    0, 0, 0, 0, 255, // red
+                    0, 0, 0, 0,   0, // green
+                    0, 0, 0, 0, 255, // blue
+                    0, 0, 0, 0, 200  // alpha
+            });
+
+    private final Runnable mUpdateActivityStatusCallback = () -> updateActivityStatus(false);
+    private final float mScaledVerticalScrollFactor;
+    private final Locale mDefaultLocale = Locale.getDefault();
+
+    RotaryInputValueView(Context c) {
+        super(c);
+
+        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
+        mScaledVerticalScrollFactor = ViewConfiguration.get(c).getScaledVerticalScrollFactor();
+
+        setText(getFormattedValue(0));
+        setTextColor(INACTIVE_TEXT_COLOR);
+        setTextSize(applyDimensionSp(TEXT_SIZE_SP, dm));
+        setPaddingRelative(applyDimensionSp(SIDE_PADDING_SP, dm), 0,
+                applyDimensionSp(SIDE_PADDING_SP, dm), 0);
+        setTypeface(null, Typeface.BOLD);
+        setBackgroundResource(R.drawable.focus_event_rotary_input_background);
+    }
+
+    /** Updates the shown text with the formatted value. */
+    void updateValue(float value) {
+        removeCallbacks(mUpdateActivityStatusCallback);
+
+        setText(getFormattedValue(value * mScaledVerticalScrollFactor));
+
+        updateActivityStatus(true);
+        postDelayed(mUpdateActivityStatusCallback, ACTIVE_STATUS_DURATION);
+    }
+
+    @VisibleForTesting
+    void updateActivityStatus(boolean active) {
+        if (active) {
+            setTextColor(ACTIVE_TEXT_COLOR);
+            getBackground().setColorFilter(ACTIVE_BACKGROUND_FILTER);
+        } else {
+            setTextColor(INACTIVE_TEXT_COLOR);
+            getBackground().clearColorFilter();
+        }
+    }
+
+    private String getFormattedValue(float value) {
+        return String.format(mDefaultLocale, "%s%.1f", value < 0 ? "-" : "+", Math.abs(value));
+    }
+
+    /**
+     * Converts a dimension in scaled pixel units to integer display pixels.
+     */
+    private static int applyDimensionSp(int dimensionSp, DisplayMetrics dm) {
+        return (int) TypedValue.applyDimension(COMPLEX_UNIT_SP, dimensionSp, dm);
+    }
+}
diff --git a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
index e7bd68e..515c7fb 100644
--- a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
+++ b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
@@ -735,12 +735,9 @@
         }
 
         @Override //Binder call
+        @EnforcePermission(MANAGE_MEDIA_PROJECTION)
         public void addCallback(final IMediaProjectionWatcherCallback callback) {
-            if (mContext.checkCallingPermission(MANAGE_MEDIA_PROJECTION)
-                        != PackageManager.PERMISSION_GRANTED) {
-                throw new SecurityException("Requires MANAGE_MEDIA_PROJECTION in order to add "
-                        + "projection callbacks");
-            }
+            addCallback_enforcePermission();
             final long token = Binder.clearCallingIdentity();
             try {
                 MediaProjectionManagerService.this.addCallback(callback);
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index faf132e..2f68021 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -208,7 +208,6 @@
 import com.android.internal.policy.PhoneWindow;
 import com.android.internal.policy.TransitionAnimation;
 import com.android.internal.statusbar.IStatusBarService;
-import com.android.internal.util.FrameworkStatsLog;
 import com.android.internal.widget.LockPatternUtils;
 import com.android.server.AccessibilityManagerInternal;
 import com.android.server.ExtconStateObserver;
@@ -622,9 +621,16 @@
     private boolean mAllowTheaterModeWakeFromLidSwitch;
     private boolean mAllowTheaterModeWakeFromWakeGesture;
 
-    // Whether to support long press from power button in non-interactive mode
+    // If true, the power button long press behavior will be invoked even if the default display is
+    // non-interactive. If false, the power button long press behavior will be skipped if the
+    // default display is non-interactive.
     private boolean mSupportLongPressPowerWhenNonInteractive;
 
+    // If true, the power button short press behavior will be always invoked as long as the default
+    // display is on, even if the display is not interactive. If false, the power button short press
+    // behavior will be skipped if the default display is non-interactive.
+    private boolean mSupportShortPressPowerWhenDefaultDisplayOn;
+
     // Whether to go to sleep entering theater mode from power button
     private boolean mGoToSleepOnButtonPressTheaterMode;
 
@@ -1041,7 +1047,7 @@
         }
     }
 
-    private void powerPress(long eventTime, int count, boolean beganFromNonInteractive) {
+    private void powerPress(long eventTime, int count) {
         // SideFPS still needs to know about suppressed power buttons, in case it needs to block
         // an auth attempt.
         if (count == 1) {
@@ -1055,9 +1061,16 @@
 
         final boolean interactive = mDefaultDisplayPolicy.isAwake();
 
-        Slog.d(TAG, "powerPress: eventTime=" + eventTime + " interactive=" + interactive
-                + " count=" + count + " beganFromNonInteractive=" + beganFromNonInteractive
-                + " mShortPressOnPowerBehavior=" + mShortPressOnPowerBehavior);
+        Slog.d(
+                TAG,
+                "powerPress: eventTime="
+                        + eventTime
+                        + " interactive="
+                        + interactive
+                        + " count="
+                        + count
+                        + " mShortPressOnPowerBehavior="
+                        + mShortPressOnPowerBehavior);
 
         if (count == 2) {
             powerMultiPressAction(eventTime, interactive, mDoublePressOnPowerBehavior);
@@ -1065,12 +1078,7 @@
             powerMultiPressAction(eventTime, interactive, mTriplePressOnPowerBehavior);
         } else if (count > 3 && count <= getMaxMultiPressPowerCount()) {
             Slog.d(TAG, "No behavior defined for power press count " + count);
-        } else if (count == 1 && interactive && !beganFromNonInteractive) {
-            if (mSideFpsEventHandler.shouldConsumeSinglePress(eventTime)) {
-                Slog.i(TAG, "Suppressing power key because the user is interacting with the "
-                        + "fingerprint sensor");
-                return;
-            }
+        } else if (count == 1 && shouldHandleShortPressPowerAction(interactive, eventTime)) {
             switch (mShortPressOnPowerBehavior) {
                 case SHORT_PRESS_POWER_NOTHING:
                     break;
@@ -1118,6 +1126,44 @@
         }
     }
 
+    private boolean shouldHandleShortPressPowerAction(boolean interactive, long eventTime) {
+        if (mSupportShortPressPowerWhenDefaultDisplayOn) {
+            final boolean defaultDisplayOn = Display.isOnState(mDefaultDisplay.getState());
+            final boolean beganFromDefaultDisplayOn =
+                    mSingleKeyGestureDetector.beganFromDefaultDisplayOn();
+            if (!defaultDisplayOn || !beganFromDefaultDisplayOn) {
+                Slog.v(
+                        TAG,
+                        "Ignoring short press of power button because the default display is not"
+                                + " on. defaultDisplayOn="
+                                + defaultDisplayOn
+                                + ", beganFromDefaultDisplayOn="
+                                + beganFromDefaultDisplayOn);
+                return false;
+            }
+            return true;
+        }
+        final boolean beganFromNonInteractive = mSingleKeyGestureDetector.beganFromNonInteractive();
+        if (!interactive || beganFromNonInteractive) {
+            Slog.v(
+                    TAG,
+                    "Ignoring short press of power button because the device is not interactive."
+                            + " interactive="
+                            + interactive
+                            + ", beganFromNonInteractive="
+                            + beganFromNonInteractive);
+            return false;
+        }
+        if (mSideFpsEventHandler.shouldConsumeSinglePress(eventTime)) {
+            Slog.i(
+                    TAG,
+                    "Suppressing power key because the user is interacting with the "
+                            + "fingerprint sensor");
+            return false;
+        }
+        return true;
+    }
+
     /**
      * Attempt to dream from a power button press.
      *
@@ -2231,6 +2277,11 @@
 
         mSupportLongPressPowerWhenNonInteractive = mContext.getResources().getBoolean(
                 com.android.internal.R.bool.config_supportLongPressPowerWhenNonInteractive);
+        mSupportShortPressPowerWhenDefaultDisplayOn =
+                mContext.getResources()
+                        .getBoolean(
+                                com.android.internal.R.bool
+                                        .config_supportShortPressPowerWhenDefaultDisplayOn);
 
         mLongPressOnBackBehavior = mContext.getResources().getInteger(
                 com.android.internal.R.integer.config_longPressOnBackBehavior);
@@ -2518,8 +2569,7 @@
 
         @Override
         void onPress(long downTime) {
-            powerPress(downTime, 1 /*count*/,
-                    mSingleKeyGestureDetector.beganFromNonInteractive());
+            powerPress(downTime, 1 /*count*/);
         }
 
         @Override
@@ -2550,7 +2600,7 @@
 
         @Override
         void onMultiPress(long downTime, int count) {
-            powerPress(downTime, count, mSingleKeyGestureDetector.beganFromNonInteractive());
+            powerPress(downTime, count);
         }
     }
 
@@ -4323,10 +4373,11 @@
 
         // This could prevent some wrong state in multi-displays environment,
         // the default display may turned off but interactive is true.
-        final boolean isDefaultDisplayOn = mDefaultDisplayPolicy.isAwake();
-        final boolean interactiveAndOn = interactive && isDefaultDisplayOn;
+        final boolean isDefaultDisplayOn = Display.isOnState(mDefaultDisplay.getState());
+        final boolean isDefaultDisplayAwake = mDefaultDisplayPolicy.isAwake();
+        final boolean interactiveAndAwake = interactive && isDefaultDisplayAwake;
         if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
-            handleKeyGesture(event, interactiveAndOn);
+            handleKeyGesture(event, interactiveAndAwake, isDefaultDisplayOn);
         }
 
         // Enable haptics if down and virtual key without multiple repetitions. If this is a hard
@@ -4479,7 +4530,7 @@
                 result &= ~ACTION_PASS_TO_USER;
                 isWakeKey = false; // wake-up will be handled separately
                 if (down) {
-                    interceptPowerKeyDown(event, interactiveAndOn);
+                    interceptPowerKeyDown(event, interactiveAndAwake);
                 } else {
                     interceptPowerKeyUp(event, canceled);
                 }
@@ -4695,7 +4746,7 @@
         return result;
     }
 
-    private void handleKeyGesture(KeyEvent event, boolean interactive) {
+    private void handleKeyGesture(KeyEvent event, boolean interactive, boolean defaultDisplayOn) {
         if (mKeyCombinationManager.interceptKey(event, interactive)) {
             // handled by combo keys manager.
             mSingleKeyGestureDetector.reset();
@@ -4711,7 +4762,7 @@
             }
         }
 
-        mSingleKeyGestureDetector.interceptKey(event, interactive);
+        mSingleKeyGestureDetector.interceptKey(event, interactive, defaultDisplayOn);
     }
 
     // The camera gesture will be detected by GestureLauncherService.
@@ -6167,6 +6218,9 @@
                 pw.print("mTriplePressOnPowerBehavior=");
                 pw.println(multiPressOnPowerBehaviorToString(mTriplePressOnPowerBehavior));
         pw.print(prefix);
+                pw.print("mSupportShortPressPowerWhenDefaultDisplayOn=");
+                pw.println(mSupportShortPressPowerWhenDefaultDisplayOn);
+        pw.print(prefix);
         pw.print("mPowerVolUpBehavior=");
         pw.println(powerVolumeUpBehaviorToString(mPowerVolUpBehavior));
         pw.print(prefix);
diff --git a/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java b/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java
index b999bbb3..5fc0637 100644
--- a/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java
+++ b/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java
@@ -43,6 +43,7 @@
 
     private int mKeyPressCounter;
     private boolean mBeganFromNonInteractive = false;
+    private boolean mBeganFromDefaultDisplayOn = false;
 
     private final ArrayList<SingleKeyRule> mRules = new ArrayList();
     private SingleKeyRule mActiveRule = null;
@@ -194,11 +195,12 @@
         mRules.remove(rule);
     }
 
-    void interceptKey(KeyEvent event, boolean interactive) {
+    void interceptKey(KeyEvent event, boolean interactive, boolean defaultDisplayOn) {
         if (event.getAction() == KeyEvent.ACTION_DOWN) {
-            // Store the non interactive state when first down.
+            // Store the non interactive state and display on state when first down.
             if (mDownKeyCode == KeyEvent.KEYCODE_UNKNOWN || mDownKeyCode != event.getKeyCode()) {
                 mBeganFromNonInteractive = !interactive;
+                mBeganFromDefaultDisplayOn = defaultDisplayOn;
             }
             interceptKeyDown(event);
         } else {
@@ -388,6 +390,10 @@
         return mBeganFromNonInteractive;
     }
 
+    boolean beganFromDefaultDisplayOn() {
+        return mBeganFromDefaultDisplayOn;
+    }
+
     void dump(String prefix, PrintWriter pw) {
         pw.println(prefix + "SingleKey rules:");
         for (SingleKeyRule rule : mRules) {
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 cf4e845..5b10afa 100644
--- a/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java
+++ b/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java
@@ -281,6 +281,7 @@
     private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
     private int[] mCpuPowerBracketMap;
     private final CpuUsageDetails mCpuUsageDetails = new CpuUsageDetails();
+    private final CpuPowerStatsCollector mCpuPowerStatsCollector;
 
     public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
         return mKernelMemoryStats;
@@ -439,6 +440,7 @@
         static final int RESET_ON_UNPLUG_AFTER_SIGNIFICANT_CHARGE_FLAG = 1 << 1;
 
         private final int mFlags;
+        private final long mPowerStatsThrottlePeriodCpu;
 
         private BatteryStatsConfig(Builder builder) {
             int flags = 0;
@@ -449,6 +451,7 @@
                 flags |= RESET_ON_UNPLUG_AFTER_SIGNIFICANT_CHARGE_FLAG;
             }
             mFlags = flags;
+            mPowerStatsThrottlePeriodCpu = builder.mPowerStatsThrottlePeriodCpu;
         }
 
         /**
@@ -469,15 +472,22 @@
                     == RESET_ON_UNPLUG_AFTER_SIGNIFICANT_CHARGE_FLAG;
         }
 
+        long getPowerStatsThrottlePeriodCpu() {
+            return mPowerStatsThrottlePeriodCpu;
+        }
+
         /**
          * Builder for BatteryStatsConfig
          */
         public static class Builder {
             private boolean mResetOnUnplugHighBatteryLevel;
             private boolean mResetOnUnplugAfterSignificantCharge;
+            private long mPowerStatsThrottlePeriodCpu;
+
             public Builder() {
                 mResetOnUnplugHighBatteryLevel = true;
                 mResetOnUnplugAfterSignificantCharge = true;
+                mPowerStatsThrottlePeriodCpu = 60000;
             }
 
             /**
@@ -504,8 +514,16 @@
                 mResetOnUnplugAfterSignificantCharge = reset;
                 return this;
             }
-        }
 
+            /**
+             * Sets the minimum amount of time (in millis) to wait between passes
+             * of CPU power stats collection.
+             */
+            public Builder setPowerStatsThrottlePeriodCpu(long periodMs) {
+                mPowerStatsThrottlePeriodCpu = periodMs;
+                return this;
+            }
+        }
     }
 
     private final PlatformIdleStateCallback mPlatformIdleStateCallback;
@@ -1556,7 +1574,7 @@
 
     @VisibleForTesting
     @GuardedBy("this")
-    protected BatteryStatsConfig mBatteryStatsConfig = new BatteryStatsConfig.Builder().build();
+    protected BatteryStatsConfig mBatteryStatsConfig;
 
     @GuardedBy("this")
     private AlarmManager mAlarmManager = null;
@@ -1733,6 +1751,7 @@
 
     public BatteryStatsImpl(Clock clock, File historyDirectory) {
         init(clock);
+        mBatteryStatsConfig = new BatteryStatsConfig.Builder().build();
         mHandler = null;
         mConstants = new Constants(mHandler);
         mStartClockTimeMs = clock.currentTimeMillis();
@@ -1751,6 +1770,7 @@
         mPlatformIdleStateCallback = null;
         mEnergyConsumerRetriever = null;
         mUserInfoProvider = null;
+        mCpuPowerStatsCollector = null;
     }
 
     private void init(Clock clock) {
@@ -10911,21 +10931,23 @@
         return mTmpCpuTimeInFreq;
     }
 
-    public BatteryStatsImpl(@Nullable File systemDir, @NonNull Handler handler,
-            @Nullable PlatformIdleStateCallback cb, @Nullable EnergyStatsRetriever energyStatsCb,
-            @NonNull UserInfoProvider userInfoProvider, @NonNull PowerProfile powerProfile,
-            @NonNull CpuScalingPolicies cpuScalingPolicies) {
-        this(Clock.SYSTEM_CLOCK, systemDir, handler, cb, energyStatsCb, userInfoProvider,
-                powerProfile, cpuScalingPolicies);
-    }
-
-    private BatteryStatsImpl(@NonNull Clock clock, @Nullable File systemDir,
+    public BatteryStatsImpl(@NonNull BatteryStatsConfig config, @Nullable File systemDir,
             @NonNull Handler handler, @Nullable PlatformIdleStateCallback cb,
             @Nullable EnergyStatsRetriever energyStatsCb,
             @NonNull UserInfoProvider userInfoProvider, @NonNull PowerProfile powerProfile,
             @NonNull CpuScalingPolicies cpuScalingPolicies) {
+        this(config, Clock.SYSTEM_CLOCK, systemDir, handler, cb, energyStatsCb, userInfoProvider,
+                powerProfile, cpuScalingPolicies);
+    }
+
+    private BatteryStatsImpl(@NonNull BatteryStatsConfig config, @NonNull Clock clock,
+            @Nullable File systemDir, @NonNull Handler handler,
+            @Nullable PlatformIdleStateCallback cb, @Nullable EnergyStatsRetriever energyStatsCb,
+            @NonNull UserInfoProvider userInfoProvider, @NonNull PowerProfile powerProfile,
+            @NonNull CpuScalingPolicies cpuScalingPolicies) {
         init(clock);
 
+        mBatteryStatsConfig = config;
         mHandler = new MyHandler(handler.getLooper());
         mConstants = new Constants(mHandler);
 
@@ -10947,6 +10969,10 @@
             mHistory = new BatteryStatsHistory(systemDir, mConstants.MAX_HISTORY_FILES,
                     mConstants.MAX_HISTORY_BUFFER, mStepDetailsCalculator, mClock);
         }
+
+        mCpuPowerStatsCollector = new CpuPowerStatsCollector(mCpuScalingPolicies, mPowerProfile,
+                mHandler, mBatteryStatsConfig.getPowerStatsThrottlePeriodCpu());
+
         mStartCount++;
         initTimersAndCounters();
         mOnBattery = mOnBatteryInternal = false;
@@ -11095,15 +11121,6 @@
     }
 
     /**
-     * Injects BatteryStatsConfig
-     */
-    public void setBatteryStatsConfig(BatteryStatsConfig config) {
-        synchronized (this) {
-            mBatteryStatsConfig = config;
-        }
-    }
-
-    /**
      * Starts tracking CPU time-in-state for threads of the system server process,
      * keeping a separate account of threads receiving incoming binder calls.
      */
@@ -14197,6 +14214,9 @@
         if (mCpuUidFreqTimeReader != null) {
             mCpuUidFreqTimeReader.onSystemReady();
         }
+        if (mCpuPowerStatsCollector != null) {
+            mCpuPowerStatsCollector.onSystemReady();
+        }
         mSystemReady = true;
     }
 
@@ -15705,6 +15725,13 @@
         iPw.decreaseIndent();
     }
 
+    /**
+     * Grabs one sample of PowerStats and prints it.
+     */
+    public void dumpStatsSample(PrintWriter pw) {
+        mCpuPowerStatsCollector.collectAndDump(pw);
+    }
+
     private final Runnable mWriteAsyncRunnable = () -> {
         synchronized (BatteryStatsImpl.this) {
             writeSyncLocked();
diff --git a/services/core/java/com/android/server/power/stats/CpuPowerStatsCollector.java b/services/core/java/com/android/server/power/stats/CpuPowerStatsCollector.java
new file mode 100644
index 0000000..1401746
--- /dev/null
+++ b/services/core/java/com/android/server/power/stats/CpuPowerStatsCollector.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.power.stats;
+
+import android.os.Handler;
+import android.util.SparseArray;
+
+import com.android.internal.annotations.Keep;
+import com.android.internal.annotations.VisibleForNative;
+import com.android.internal.os.Clock;
+import com.android.internal.os.CpuScalingPolicies;
+import com.android.internal.os.PowerProfile;
+import com.android.internal.os.PowerStats;
+import com.android.server.power.optimization.Flags;
+
+/**
+ * Collects snapshots of power-related system statistics.
+ * <p>
+ * The class is intended to be used in a serialized fashion using the handler supplied in the
+ * constructor. Thus the object is not thread-safe except where noted.
+ */
+public class CpuPowerStatsCollector extends PowerStatsCollector {
+    private static final long NANOS_PER_MILLIS = 1000000;
+
+    private final KernelCpuStatsReader mKernelCpuStatsReader;
+    private final int[] mScalingStepToPowerBracketMap;
+    private final long[] mTempUidStats;
+    private final SparseArray<UidStats> mUidStats = new SparseArray<>();
+    private final int mUidStatsSize;
+    // Reusable instance
+    private final PowerStats mCpuPowerStats = new PowerStats();
+    private long mLastUpdateTimestampNanos;
+
+    public CpuPowerStatsCollector(CpuScalingPolicies cpuScalingPolicies, PowerProfile powerProfile,
+                                  Handler handler, long throttlePeriodMs) {
+        this(cpuScalingPolicies, powerProfile, handler, new KernelCpuStatsReader(),
+                throttlePeriodMs, Clock.SYSTEM_CLOCK);
+    }
+
+    public CpuPowerStatsCollector(CpuScalingPolicies cpuScalingPolicies, PowerProfile powerProfile,
+                                  Handler handler, KernelCpuStatsReader kernelCpuStatsReader,
+                                  long throttlePeriodMs, Clock clock) {
+        super(handler, throttlePeriodMs, clock);
+        mKernelCpuStatsReader = kernelCpuStatsReader;
+
+        int scalingStepCount = cpuScalingPolicies.getScalingStepCount();
+        mScalingStepToPowerBracketMap = new int[scalingStepCount];
+        int index = 0;
+        for (int policy : cpuScalingPolicies.getPolicies()) {
+            int[] frequencies = cpuScalingPolicies.getFrequencies(policy);
+            for (int step = 0; step < frequencies.length; step++) {
+                int bracket = powerProfile.getCpuPowerBracketForScalingStep(policy, step);
+                mScalingStepToPowerBracketMap[index++] = bracket;
+            }
+        }
+        mUidStatsSize = powerProfile.getCpuPowerBracketCount();
+        mTempUidStats = new long[mUidStatsSize];
+    }
+
+    /**
+     * Initializes the collector during the boot sequence.
+     */
+    public void onSystemReady() {
+        setEnabled(Flags.streamlinedBatteryStats());
+    }
+
+    @Override
+    protected PowerStats collectStats() {
+        mCpuPowerStats.uidStats.clear();
+        long newTimestampNanos = mKernelCpuStatsReader.nativeReadCpuStats(
+                this::processUidStats, mScalingStepToPowerBracketMap, mLastUpdateTimestampNanos,
+                mTempUidStats);
+        mCpuPowerStats.durationMs =
+                (newTimestampNanos - mLastUpdateTimestampNanos) / NANOS_PER_MILLIS;
+        mLastUpdateTimestampNanos = newTimestampNanos;
+        return mCpuPowerStats;
+    }
+
+    @VisibleForNative
+    interface KernelCpuStatsCallback {
+        @Keep // Called from native
+        void processUidStats(int uid, long[] stats);
+    }
+
+    private void processUidStats(int uid, long[] stats) {
+        UidStats uidStats = mUidStats.get(uid);
+        if (uidStats == null) {
+            uidStats = new UidStats();
+            uidStats.stats = new long[mUidStatsSize];
+            uidStats.delta = new long[mUidStatsSize];
+            mUidStats.put(uid, uidStats);
+        }
+
+        boolean nonzero = false;
+        for (int i = mUidStatsSize - 1; i >= 0; i--) {
+            long delta = uidStats.delta[i] = stats[i] - uidStats.stats[i];
+            if (delta != 0) {
+                nonzero = true;
+            }
+            uidStats.stats[i] = stats[i];
+        }
+        if (nonzero) {
+            mCpuPowerStats.uidStats.put(uid, uidStats.delta);
+        }
+    }
+
+    /**
+     * Native class that retrieves CPU stats from the kernel.
+     */
+    public static class KernelCpuStatsReader {
+        protected native long nativeReadCpuStats(KernelCpuStatsCallback callback,
+                int[] scalingStepToPowerBracketMap, long lastUpdateTimestampNanos,
+                long[] tempForUidStats);
+    }
+
+    private static class UidStats {
+        public long[] stats;
+        public long[] delta;
+    }
+}
diff --git a/services/core/java/com/android/server/power/stats/PowerStatsCollector.java b/services/core/java/com/android/server/power/stats/PowerStatsCollector.java
new file mode 100644
index 0000000..b49c89f
--- /dev/null
+++ b/services/core/java/com/android/server/power/stats/PowerStatsCollector.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.power.stats;
+
+import android.os.ConditionVariable;
+import android.os.Handler;
+import android.util.FastImmutableArraySet;
+import android.util.IndentingPrintWriter;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.os.Clock;
+import com.android.internal.os.PowerStats;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+
+/**
+ * Collects snapshots of power-related system statistics.
+ * <p>
+ * Instances of this class are intended to be used in a serialized fashion using
+ * the handler supplied in the constructor. Thus these objects are not thread-safe
+ * except where noted.
+ */
+public abstract class PowerStatsCollector {
+    private final Handler mHandler;
+    private final Clock mClock;
+    private final long mThrottlePeriodMs;
+    private final Runnable mCollectAndDeliverStats = this::collectAndDeliverStats;
+    private boolean mEnabled;
+    private long mLastScheduledUpdateMs = -1;
+
+    @GuardedBy("this")
+    @SuppressWarnings("unchecked")
+    private volatile FastImmutableArraySet<Consumer<PowerStats>> mConsumerList =
+            new FastImmutableArraySet<Consumer<PowerStats>>(new Consumer[0]);
+
+    public PowerStatsCollector(Handler handler, long throttlePeriodMs, Clock clock) {
+        mHandler = handler;
+        mThrottlePeriodMs = throttlePeriodMs;
+        mClock = clock;
+    }
+
+    /**
+     * Adds a consumer that will receive a callback every time a snapshot of stats is collected.
+     * The method is thread safe.
+     */
+    @SuppressWarnings("unchecked")
+    public void addConsumer(Consumer<PowerStats> consumer) {
+        synchronized (this) {
+            mConsumerList = new FastImmutableArraySet<Consumer<PowerStats>>(
+                    Stream.concat(mConsumerList.stream(), Stream.of(consumer))
+                            .toArray(Consumer[]::new));
+        }
+    }
+
+    /**
+     * Removes a consumer.
+     * The method is thread safe.
+     */
+    @SuppressWarnings("unchecked")
+    public void removeConsumer(Consumer<PowerStats> consumer) {
+        synchronized (this) {
+            mConsumerList = new FastImmutableArraySet<Consumer<PowerStats>>(
+                    mConsumerList.stream().filter(c -> c != consumer)
+                            .toArray(Consumer[]::new));
+        }
+    }
+
+    /**
+     * Should be called at most once, before the first invocation of {@link #schedule} or
+     * {@link #forceSchedule}
+     */
+    public void setEnabled(boolean enabled) {
+        mEnabled = enabled;
+    }
+
+    /**
+     * Returns true if the collector is enabled.
+     */
+    public boolean isEnabled() {
+        return mEnabled;
+    }
+
+    @SuppressWarnings("GuardedBy")  // Field is volatile
+    private void collectAndDeliverStats() {
+        PowerStats stats = collectStats();
+        for (Consumer<PowerStats> consumer : mConsumerList) {
+            consumer.accept(stats);
+        }
+    }
+
+    /**
+     * Schedules a stats snapshot collection, throttled in accordance with the
+     * {@link #mThrottlePeriodMs} parameter.
+     */
+    public boolean schedule() {
+        if (!mEnabled) {
+            return false;
+        }
+
+        long uptimeMillis = mClock.uptimeMillis();
+        if (uptimeMillis - mLastScheduledUpdateMs < mThrottlePeriodMs
+                && mLastScheduledUpdateMs >= 0) {
+            return false;
+        }
+        mLastScheduledUpdateMs = uptimeMillis;
+        mHandler.post(mCollectAndDeliverStats);
+        return true;
+    }
+
+    /**
+     * Schedules an immediate snapshot collection, foregoing throttling.
+     */
+    public boolean forceSchedule() {
+        if (!mEnabled) {
+            return false;
+        }
+
+        mHandler.removeCallbacks(mCollectAndDeliverStats);
+        mHandler.postAtFrontOfQueue(mCollectAndDeliverStats);
+        return true;
+    }
+
+    protected abstract PowerStats collectStats();
+
+    /**
+     * Collects a fresh stats snapshot and prints it to the supplied printer.
+     */
+    public void collectAndDump(PrintWriter pw) {
+        if (Thread.currentThread() == mHandler.getLooper().getThread()) {
+            throw new RuntimeException(
+                    "Calling this method from the handler thread would cause a deadlock");
+        }
+
+        IndentingPrintWriter out = new IndentingPrintWriter(pw);
+        out.print(getClass().getSimpleName());
+        if (!isEnabled()) {
+            out.println(": disabled");
+            return;
+        }
+        out.println();
+
+        ArrayList<PowerStats> collected = new ArrayList<>();
+        Consumer<PowerStats> consumer = collected::add;
+        addConsumer(consumer);
+
+        try {
+            if (forceSchedule()) {
+                awaitCompletion();
+            }
+        } finally {
+            removeConsumer(consumer);
+        }
+
+        out.increaseIndent();
+        for (PowerStats stats : collected) {
+            stats.dump(out);
+        }
+        out.decreaseIndent();
+    }
+
+    private void awaitCompletion() {
+        ConditionVariable done = new ConditionVariable();
+        mHandler.post(done::open);
+        done.block();
+    }
+}
diff --git a/services/core/java/com/android/server/tv/TvInputManagerService.java b/services/core/java/com/android/server/tv/TvInputManagerService.java
index cb09aef..5b36cd6 100644
--- a/services/core/java/com/android/server/tv/TvInputManagerService.java
+++ b/services/core/java/com/android/server/tv/TvInputManagerService.java
@@ -3055,10 +3055,10 @@
         TvInputInfo tvInputInfo = tvInputState.info;
         int inputState = tvInputState.state;
         int inputType = tvInputInfo.getType();
-        // For non-CEC input, the value of vendorId is 0.
-        int vendorId = 0;
-        // For non-HDMI input, the value of hdmiPort is 0.
-        int hdmiPort = 0;
+        // For non-CEC input, the value of vendorId is 0xFFFFFF (16777215 in decimal).
+        int vendorId = 16777215;
+        // For non-HDMI input, the value of hdmiPort is -1.
+        int hdmiPort = -1;
         String tifSessionId = sessionState.sessionId;
 
         if (tvInputInfo.getType() == TvInputInfo.TYPE_HDMI) {
diff --git a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
index ddc0519..aaf48fb 100644
--- a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
+++ b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
@@ -2000,12 +2000,7 @@
             WallpaperData wallpaper, IRemoteCallback reply, ServiceInfo serviceInfo) {
 
         if (serviceInfo == null) {
-            if (wallpaper.mWhich == (FLAG_LOCK | FLAG_SYSTEM)) {
-                clearWallpaperLocked(FLAG_SYSTEM, wallpaper.userId, null);
-                clearWallpaperLocked(FLAG_LOCK, wallpaper.userId, reply);
-            } else {
-                clearWallpaperLocked(wallpaper.mWhich, wallpaper.userId, reply);
-            }
+            clearWallpaperLocked(wallpaper.mWhich, wallpaper.userId, reply);
             return;
         }
         Slog.w(TAG, "Wallpaper isn't direct boot aware; using fallback until unlocked");
@@ -2037,7 +2032,7 @@
         WallpaperData data = null;
         synchronized (mLock) {
             if (mIsLockscreenLiveWallpaperEnabled) {
-                clearWallpaperLocked(callingPackage, which, userId);
+                clearWallpaperLocked(callingPackage, which, userId, null);
             } else {
                 clearWallpaperLocked(which, userId, null);
             }
@@ -2057,7 +2052,8 @@
         }
     }
 
-    private void clearWallpaperLocked(String callingPackage, int which, int userId) {
+    private void clearWallpaperLocked(String callingPackage, int which, int userId,
+            IRemoteCallback reply) {
 
         // Might need to bring it in the first time to establish our rewrite
         if (!mWallpaperMap.contains(userId)) {
@@ -2111,8 +2107,14 @@
         withCleanCallingIdentity(() -> clearWallpaperComponentLocked(wallpaper));
     }
 
-    // TODO(b/266818039) remove this version of the method
     private void clearWallpaperLocked(int which, int userId, IRemoteCallback reply) {
+
+        if (mIsLockscreenLiveWallpaperEnabled) {
+            String callingPackage = mPackageManagerInternal.getNameForUid(getCallingUid());
+            clearWallpaperLocked(callingPackage, which, userId, reply);
+            return;
+        }
+
         if (which != FLAG_SYSTEM && which != FLAG_LOCK) {
             throw new IllegalArgumentException("Must specify exactly one kind of wallpaper to clear");
         }
@@ -3284,15 +3286,21 @@
     boolean setWallpaperComponent(ComponentName name, String callingPackage,
             @SetWallpaperFlags int which, int userId) {
         if (mIsLockscreenLiveWallpaperEnabled) {
-            return setWallpaperComponentInternal(name, callingPackage, which, userId);
+            return setWallpaperComponentInternal(name, callingPackage, which, userId, null);
         } else {
             setWallpaperComponentInternalLegacy(name, callingPackage, which, userId);
             return true;
         }
     }
 
+    private boolean setWallpaperComponent(ComponentName name, @SetWallpaperFlags int which,
+            int userId) {
+        String callingPackage = mPackageManagerInternal.getNameForUid(getCallingUid());
+        return setWallpaperComponentInternal(name, callingPackage, which, userId, null);
+    }
+
     private boolean setWallpaperComponentInternal(ComponentName name, String callingPackage,
-            @SetWallpaperFlags int which, int userIdIn) {
+            @SetWallpaperFlags int which, int userIdIn, IRemoteCallback reply) {
         if (DEBUG) {
             Slog.v(TAG, "Setting new live wallpaper: which=" + which + ", component: " + name);
         }
@@ -3341,6 +3349,7 @@
                             Slog.d(TAG, "publish system wallpaper changed!");
                         }
                         liveSync.complete();
+                        if (reply != null) reply.sendResult(null);
                     }
                 };
 
diff --git a/services/core/java/com/android/server/wm/AsyncRotationController.java b/services/core/java/com/android/server/wm/AsyncRotationController.java
index 2eceecc..0250475 100644
--- a/services/core/java/com/android/server/wm/AsyncRotationController.java
+++ b/services/core/java/com/android/server/wm/AsyncRotationController.java
@@ -172,10 +172,9 @@
                 if (recents != null && recents.isNavigationBarAttachedToApp()) {
                     return;
                 }
-            } else if (navigationBarCanMove || mTransitionOp == OP_CHANGE_MAY_SEAMLESS) {
+            } else if (navigationBarCanMove || mTransitionOp == OP_CHANGE_MAY_SEAMLESS
+                    || mDisplayContent.mTransitionController.mNavigationBarAttachedToApp) {
                 action = Operation.ACTION_SEAMLESS;
-            } else if (mDisplayContent.mTransitionController.mNavigationBarAttachedToApp) {
-                return;
             }
             mTargetWindowTokens.put(w.mToken, new Operation(action));
             return;
@@ -294,6 +293,11 @@
             finishOp(mTargetWindowTokens.keyAt(i));
         }
         mTargetWindowTokens.clear();
+        onAllCompleted();
+    }
+
+    private void onAllCompleted() {
+        if (DEBUG) Slog.d(TAG, "onAllCompleted");
         if (mTimeoutRunnable != null) {
             mService.mH.removeCallbacks(mTimeoutRunnable);
         }
@@ -333,7 +337,7 @@
             if (DEBUG) Slog.d(TAG, "Complete directly " + token.getTopChild());
             finishOp(token);
             if (mTargetWindowTokens.isEmpty()) {
-                if (mTimeoutRunnable != null) mService.mH.removeCallbacks(mTimeoutRunnable);
+                onAllCompleted();
                 return true;
             }
         }
@@ -411,14 +415,18 @@
         if (mDisplayContent.mInputMethodWindow == null) return;
         final WindowToken imeWindowToken = mDisplayContent.mInputMethodWindow.mToken;
         if (isTargetToken(imeWindowToken)) return;
+        hideImmediately(imeWindowToken, Operation.ACTION_TOGGLE_IME);
+        if (DEBUG) Slog.d(TAG, "hideImeImmediately " + imeWindowToken.getTopChild());
+    }
+
+    private void hideImmediately(WindowToken token, @Operation.Action int action) {
         final boolean original = mHideImmediately;
         mHideImmediately = true;
-        final Operation op = new Operation(Operation.ACTION_TOGGLE_IME);
-        mTargetWindowTokens.put(imeWindowToken, op);
-        fadeWindowToken(false /* show */, imeWindowToken, ANIMATION_TYPE_TOKEN_TRANSFORM);
-        op.mLeash = imeWindowToken.getAnimationLeash();
+        final Operation op = new Operation(action);
+        mTargetWindowTokens.put(token, op);
+        fadeWindowToken(false /* show */, token, ANIMATION_TYPE_TOKEN_TRANSFORM);
+        op.mLeash = token.getAnimationLeash();
         mHideImmediately = original;
-        if (DEBUG) Slog.d(TAG, "hideImeImmediately " + imeWindowToken.getTopChild());
     }
 
     /** Returns {@code true} if the window will rotate independently. */
@@ -428,11 +436,20 @@
                 || isTargetToken(w.mToken);
     }
 
-    /** Returns {@code true} if the controller will run fade animations on the window. */
+    /**
+     * Returns {@code true} if the rotation transition appearance of the window is currently
+     * managed by this controller.
+     */
     boolean isTargetToken(WindowToken token) {
         return mTargetWindowTokens.containsKey(token);
     }
 
+    /** Returns {@code true} if the controller will run fade animations on the window. */
+    boolean hasFadeOperation(WindowToken token) {
+        final Operation op = mTargetWindowTokens.get(token);
+        return op != null && op.mAction == Operation.ACTION_FADE;
+    }
+
     /**
      * Whether the insets animation leash should use previous position when running fade animation
      * or seamless transformation in a rotated display.
@@ -564,7 +581,18 @@
             return false;
         }
         final Operation op = mTargetWindowTokens.get(w.mToken);
-        if (op == null) return false;
+        if (op == null) {
+            // If a window becomes visible after the rotation transition is requested but before
+            // the transition is ready, hide it by an animation leash so it won't be flickering
+            // by drawing the rotated content before applying projection transaction of display.
+            // And it will fade in after the display transition is finished.
+            if (mTransitionOp == OP_APP_SWITCH && !mIsStartTransactionCommitted
+                    && canBeAsync(w.mToken)) {
+                hideImmediately(w.mToken, Operation.ACTION_FADE);
+                if (DEBUG) Slog.d(TAG, "Hide on finishDrawing " + w.mToken.getTopChild());
+            }
+            return false;
+        }
         if (DEBUG) Slog.d(TAG, "handleFinishDrawing " + w);
         if (postDrawTransaction == null || !mIsSyncDrawRequested
                 || canDrawBeforeStartTransaction(op)) {
diff --git a/services/core/java/com/android/server/wm/NavBarFadeAnimationController.java b/services/core/java/com/android/server/wm/NavBarFadeAnimationController.java
index 2e5474e..79b26d2 100644
--- a/services/core/java/com/android/server/wm/NavBarFadeAnimationController.java
+++ b/services/core/java/com/android/server/wm/NavBarFadeAnimationController.java
@@ -86,7 +86,7 @@
                 ANIMATION_TYPE_TOKEN_TRANSFORM);
         if (controller == null) {
             fadeAnim.run();
-        } else if (!controller.isTargetToken(mNavigationBar.mToken)) {
+        } else if (!controller.hasFadeOperation(mNavigationBar.mToken)) {
             // If fade rotation animation is running and the nav bar is not controlled by it:
             // - For fade-in animation, defer the animation until fade rotation animation finishes.
             // - For fade-out animation, just play the animation.
diff --git a/services/core/java/com/android/server/wm/Transition.java b/services/core/java/com/android/server/wm/Transition.java
index 1566bb2c..e9af42b 100644
--- a/services/core/java/com/android/server/wm/Transition.java
+++ b/services/core/java/com/android/server/wm/Transition.java
@@ -1930,11 +1930,6 @@
             break;
         }
 
-        final AsyncRotationController asyncRotationController = dc.getAsyncRotationController();
-        if (asyncRotationController != null) {
-            asyncRotationController.accept(navWindow);
-        }
-
         if (animate) {
             final NavBarFadeAnimationController controller =
                     new NavBarFadeAnimationController(dc);
diff --git a/services/core/java/com/android/server/wm/TransitionController.java b/services/core/java/com/android/server/wm/TransitionController.java
index 6432ff0..6ede345 100644
--- a/services/core/java/com/android/server/wm/TransitionController.java
+++ b/services/core/java/com/android/server/wm/TransitionController.java
@@ -1124,14 +1124,15 @@
                         + "track #%d", transition.getSyncId(), track);
             }
         }
-        if (sync) {
+        transition.mAnimationTrack = track;
+        info.setTrack(track);
+        mTrackCount = Math.max(mTrackCount, track + 1);
+        if (sync && mTrackCount > 1) {
+            // If there are >1 tracks, mark as sync so that all tracks finish.
             info.setFlags(info.getFlags() | TransitionInfo.FLAG_SYNC);
             ProtoLog.v(ProtoLogGroup.WM_DEBUG_WINDOW_TRANSITIONS, "Marking #%d animation as SYNC.",
                     transition.getSyncId());
         }
-        transition.mAnimationTrack = track;
-        info.setTrack(track);
-        mTrackCount = Math.max(mTrackCount, track + 1);
     }
 
     void updateAnimatingState(SurfaceControl.Transaction t) {
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index 5a45fe1..a172d99 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -30,7 +30,6 @@
 import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
 import static android.view.SurfaceControl.Transaction;
 import static android.view.SurfaceControl.getGlobalTransaction;
-import static android.view.ViewRootImpl.LOCAL_LAYOUT;
 import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT;
 import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
 import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION;
@@ -1446,9 +1445,7 @@
         }
 
         final boolean dragResizingChanged = !mDragResizingChangeReported && isDragResizeChanged();
-
-        final boolean attachedFrameChanged = LOCAL_LAYOUT
-                && mLayoutAttached && getParentWindow().frameChanged();
+        final boolean attachedFrameChanged = mLayoutAttached && getParentWindow().frameChanged();
 
         if (DEBUG) {
             Slog.v(TAG_WM, "Resizing " + this + ": configChanged=" + configChanged
diff --git a/services/core/jni/Android.bp b/services/core/jni/Android.bp
index 405b133..2f150a1 100644
--- a/services/core/jni/Android.bp
+++ b/services/core/jni/Android.bp
@@ -50,6 +50,7 @@
         "com_android_server_locksettings_SyntheticPasswordManager.cpp",
         "com_android_server_power_PowerManagerService.cpp",
         "com_android_server_powerstats_PowerStatsService.cpp",
+        "com_android_server_power_stats_CpuPowerStatsCollector.cpp",
         "com_android_server_hint_HintManagerService.cpp",
         "com_android_server_SerialService.cpp",
         "com_android_server_soundtrigger_middleware_AudioSessionProviderImpl.cpp",
@@ -144,6 +145,7 @@
         "libsensorservicehidl",
         "libsensorserviceaidl",
         "libgui",
+        "libtimeinstate",
         "libtimestats_atoms_proto",
         "libusbhost",
         "libtinyalsa",
diff --git a/services/core/jni/OWNERS b/services/core/jni/OWNERS
index d9acf41..7e8ce60 100644
--- a/services/core/jni/OWNERS
+++ b/services/core/jni/OWNERS
@@ -23,6 +23,7 @@
 per-file com_android_server_pm_* = file:/services/core/java/com/android/server/pm/OWNERS
 per-file com_android_server_power_* = file:/services/core/java/com/android/server/power/OWNERS
 per-file com_android_server_powerstats_* = file:/services/core/java/com/android/server/powerstats/OWNERS
+per-file com_android_server_power_stats_* = file:/BATTERY_STATS_OWNERS
 per-file com_android_server_security_* = file:/core/java/android/security/OWNERS
 per-file com_android_server_tv_* = file:/media/java/android/media/tv/OWNERS
 per-file com_android_server_vibrator_* = file:/services/core/java/com/android/server/vibrator/OWNERS
diff --git a/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp b/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
index cfc63f0..7b08413 100644
--- a/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
+++ b/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
@@ -54,6 +54,9 @@
 using android::meminfo::ProcMemInfo;
 using namespace android::meminfo;
 
+static const size_t kPageSize = getpagesize();
+static const size_t kPageMask = ~(kPageSize - 1);
+
 #define COMPACT_ACTION_FILE_FLAG 1
 #define COMPACT_ACTION_ANON_FLAG 2
 
@@ -64,7 +67,7 @@
 #define ASYNC_RECEIVED_WHILE_FROZEN (2)
 #define TXNS_PENDING_WHILE_FROZEN (4)
 
-#define MAX_RW_COUNT (INT_MAX & PAGE_MASK)
+#define MAX_RW_COUNT (INT_MAX & kPageMask)
 
 // Defines the maximum amount of VMAs we can send per process_madvise syscall.
 // Currently this is set to UIO_MAXIOV which is the maximum segments allowed by
@@ -233,7 +236,6 @@
 // process_madvise on failure
 int madviseVmasFromBatch(unique_fd& pidfd, VmaBatch& batch, int madviseType,
                          uint64_t* outBytesProcessed) {
-    static const size_t kPageSize = getpagesize();
     if (batch.totalVmas == 0 || batch.totalBytes == 0) {
         // No VMAs in Batch, skip.
         *outBytesProcessed = 0;
diff --git a/services/core/jni/com_android_server_input_InputManagerService.cpp b/services/core/jni/com_android_server_input_InputManagerService.cpp
index 7c8c558..5ab8d36 100644
--- a/services/core/jni/com_android_server_input_InputManagerService.cpp
+++ b/services/core/jni/com_android_server_input_InputManagerService.cpp
@@ -400,7 +400,7 @@
         PointerCaptureRequest pointerCaptureRequest{};
 
         // Sprite controller singleton, created on first use.
-        sp<SpriteController> spriteController{};
+        std::shared_ptr<SpriteController> spriteController{};
 
         // Pointer controller singleton, created and destroyed as needed.
         std::weak_ptr<PointerController> pointerController{};
@@ -709,7 +709,7 @@
     if (controller == nullptr) {
         ensureSpriteControllerLocked();
 
-        controller = PointerController::create(this, mLooper, mLocked.spriteController);
+        controller = PointerController::create(this, mLooper, *mLocked.spriteController);
         mLocked.pointerController = controller;
         updateInactivityTimeoutLocked();
     }
@@ -738,16 +738,21 @@
 }
 
 void NativeInputManager::ensureSpriteControllerLocked() REQUIRES(mLock) {
-    if (mLocked.spriteController == nullptr) {
-        JNIEnv* env = jniEnv();
-        jint layer = env->CallIntMethod(mServiceObj, gServiceClassInfo.getPointerLayer);
-        if (checkAndClearExceptionFromCallback(env, "getPointerLayer")) {
-            layer = -1;
-        }
-        mLocked.spriteController = new SpriteController(mLooper, layer, [this](int displayId) {
-            return getParentSurfaceForPointers(displayId);
-        });
+    if (mLocked.spriteController) {
+        return;
     }
+    JNIEnv* env = jniEnv();
+    jint layer = env->CallIntMethod(mServiceObj, gServiceClassInfo.getPointerLayer);
+    if (checkAndClearExceptionFromCallback(env, "getPointerLayer")) {
+        layer = -1;
+    }
+    mLocked.spriteController =
+            std::make_shared<SpriteController>(mLooper, layer, [this](int displayId) {
+                return getParentSurfaceForPointers(displayId);
+            });
+    // The SpriteController needs to be shared pointer because the handler callback needs to hold
+    // a weak reference so that we can avoid racy conditions when the controller is being destroyed.
+    mLocked.spriteController->setHandlerController(mLocked.spriteController);
 }
 
 void NativeInputManager::notifyInputDevicesChanged(const std::vector<InputDeviceInfo>& inputDevices) {
diff --git a/services/core/jni/com_android_server_power_stats_CpuPowerStatsCollector.cpp b/services/core/jni/com_android_server_power_stats_CpuPowerStatsCollector.cpp
new file mode 100644
index 0000000..a6084ea
--- /dev/null
+++ b/services/core/jni/com_android_server_power_stats_CpuPowerStatsCollector.cpp
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "CpuPowerStatsCollector"
+
+#include <cputimeinstate.h>
+#include <log/log.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
+
+#include "core_jni_helpers.h"
+
+#define EXCEPTION (-1)
+
+namespace android {
+
+#define JAVA_CLASS_CPU_POWER_STATS_COLLECTOR "com/android/server/power/stats/CpuPowerStatsCollector"
+#define JAVA_CLASS_KERNEL_CPU_STATS_READER \
+    JAVA_CLASS_CPU_POWER_STATS_COLLECTOR "$KernelCpuStatsReader"
+#define JAVA_CLASS_KERNEL_CPU_STATS_CALLBACK \
+    JAVA_CLASS_CPU_POWER_STATS_COLLECTOR "$KernelCpuStatsCallback"
+
+static constexpr uint64_t NSEC_PER_MSEC = 1000000;
+
+static int extractUidStats(JNIEnv *env, std::vector<std::vector<uint64_t>> &times,
+                           ScopedIntArrayRO &scopedScalingStepToPowerBracketMap,
+                           jlongArray tempForUidStats);
+
+static bool initialized = false;
+static jclass class_KernelCpuStatsCallback;
+static jmethodID method_KernelCpuStatsCallback_processUidStats;
+
+static int init(JNIEnv *env) {
+    jclass temp = env->FindClass(JAVA_CLASS_KERNEL_CPU_STATS_CALLBACK);
+    class_KernelCpuStatsCallback = (jclass)env->NewGlobalRef(temp);
+    if (!class_KernelCpuStatsCallback) {
+        jniThrowExceptionFmt(env, "java/lang/ClassNotFoundException",
+                             "Class not found: " JAVA_CLASS_KERNEL_CPU_STATS_CALLBACK);
+        return EXCEPTION;
+    }
+    method_KernelCpuStatsCallback_processUidStats =
+            env->GetMethodID(class_KernelCpuStatsCallback, "processUidStats", "(I[J)V");
+    if (!method_KernelCpuStatsCallback_processUidStats) {
+        jniThrowExceptionFmt(env, "java/lang/NoSuchMethodException",
+                             "Method not found: " JAVA_CLASS_KERNEL_CPU_STATS_CALLBACK
+                             ".processUidStats");
+        return EXCEPTION;
+    }
+    initialized = true;
+    return OK;
+}
+
+static jlong nativeReadCpuStats(JNIEnv *env, [[maybe_unused]] jobject zis, jobject callback,
+                                jintArray scalingStepToPowerBracketMap,
+                                jlong lastUpdateTimestampNanos, jlongArray tempForUidStats) {
+    if (!initialized) {
+        if (init(env) == EXCEPTION) {
+            return 0L;
+        }
+    }
+
+    uint64_t newLastUpdate = lastUpdateTimestampNanos;
+    auto data = android::bpf::getUidsUpdatedCpuFreqTimes(&newLastUpdate);
+    if (!data.has_value()) return lastUpdateTimestampNanos;
+
+    ScopedIntArrayRO scopedScalingStepToPowerBracketMap(env, scalingStepToPowerBracketMap);
+
+    for (auto &[uid, times] : *data) {
+        int status =
+                extractUidStats(env, times, scopedScalingStepToPowerBracketMap, tempForUidStats);
+        if (status == EXCEPTION) {
+            return 0L;
+        }
+        env->CallVoidMethod(callback, method_KernelCpuStatsCallback_processUidStats, (jint)uid,
+                            tempForUidStats);
+    }
+    return newLastUpdate;
+}
+
+static int extractUidStats(JNIEnv *env, std::vector<std::vector<uint64_t>> &times,
+                           ScopedIntArrayRO &scopedScalingStepToPowerBracketMap,
+                           jlongArray tempForUidStats) {
+    ScopedLongArrayRW scopedTempForStats(env, tempForUidStats);
+    uint64_t *arrayForStats = reinterpret_cast<uint64_t *>(scopedTempForStats.get());
+    const uint8_t statsSize = scopedTempForStats.size();
+    memset(arrayForStats, 0, statsSize * sizeof(uint64_t));
+    const uint8_t scalingStepCount = scopedScalingStepToPowerBracketMap.size();
+
+    uint32_t scalingStep = 0;
+    for (const auto &subVec : times) {
+        for (uint32_t i = 0; i < subVec.size(); ++i) {
+            if (scalingStep >= scalingStepCount) {
+                jniThrowExceptionFmt(env, "java/lang/IndexOutOfBoundsException",
+                                     "scalingStepToPowerBracketMap is too short, "
+                                     "size=%u, scalingStep=%u",
+                                     scalingStepCount, scalingStep);
+                return EXCEPTION;
+            }
+            uint32_t bucket = scopedScalingStepToPowerBracketMap[scalingStep];
+            if (bucket >= statsSize) {
+                jniThrowExceptionFmt(env, "java/lang/IndexOutOfBoundsException",
+                                     "UidStats array is too short, length=%u, bucket[%u]=%u",
+                                     statsSize, scalingStep, bucket);
+                return EXCEPTION;
+            }
+            arrayForStats[bucket] += subVec[i] / NSEC_PER_MSEC;
+            scalingStep++;
+        }
+    }
+    return OK;
+}
+
+static const JNINativeMethod method_table[] = {
+        {"nativeReadCpuStats", "(L" JAVA_CLASS_KERNEL_CPU_STATS_CALLBACK ";[IJ[J)J",
+         (void *)nativeReadCpuStats},
+};
+
+int register_android_server_power_stats_CpuPowerStatsCollector(JNIEnv *env) {
+    return jniRegisterNativeMethods(env, JAVA_CLASS_KERNEL_CPU_STATS_READER, method_table,
+                                    NELEM(method_table));
+}
+
+} // namespace android
diff --git a/services/core/jni/onload.cpp b/services/core/jni/onload.cpp
index 290ad8d..97d7be6 100644
--- a/services/core/jni/onload.cpp
+++ b/services/core/jni/onload.cpp
@@ -30,6 +30,7 @@
 int register_android_server_LightsService(JNIEnv* env);
 int register_android_server_PowerManagerService(JNIEnv* env);
 int register_android_server_PowerStatsService(JNIEnv* env);
+int register_android_server_power_stats_CpuPowerStatsCollector(JNIEnv* env);
 int register_android_server_HintManagerService(JNIEnv* env);
 int register_android_server_storage_AppFuse(JNIEnv* env);
 int register_android_server_SerialService(JNIEnv* env);
@@ -85,6 +86,7 @@
     register_android_server_broadcastradio_Tuner(vm, env);
     register_android_server_PowerManagerService(env);
     register_android_server_PowerStatsService(env);
+    register_android_server_power_stats_CpuPowerStatsCollector(env);
     register_android_server_HintManagerService(env);
     register_android_server_SerialService(env);
     register_android_server_InputManager(env);
diff --git a/services/tests/displayservicetests/src/com/android/server/display/DisplayDeviceTest.java b/services/tests/displayservicetests/src/com/android/server/display/DisplayDeviceTest.java
new file mode 100644
index 0000000..4fd8f26
--- /dev/null
+++ b/services/tests/displayservicetests/src/com/android/server/display/DisplayDeviceTest.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.display;
+
+import static android.view.Surface.ROTATION_0;
+import static android.view.Surface.ROTATION_180;
+import static android.view.Surface.ROTATION_270;
+import static android.view.Surface.ROTATION_90;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.platform.test.annotations.Presubmit;
+import android.view.SurfaceControl;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+/**
+ * Tests for the {@link DisplayDevice} class.
+ *
+ * Build/Install/Run:
+ * atest DisplayServicesTests:DisplayDeviceTest
+ */
+@SmallTest
+@Presubmit
+@RunWith(AndroidJUnit4.class)
+public class DisplayDeviceTest {
+    private final DisplayDeviceInfo mDisplayDeviceInfo = new DisplayDeviceInfo();
+    private static final int WIDTH = 500;
+    private static final int HEIGHT = 900;
+    private static final Point PORTRAIT_SIZE = new Point(WIDTH, HEIGHT);
+    private static final Point LANDSCAPE_SIZE = new Point(HEIGHT, WIDTH);
+
+    @Mock
+    private SurfaceControl.Transaction mMockTransaction;
+
+    @Before
+    public void setup() {
+        MockitoAnnotations.initMocks(this);
+        mDisplayDeviceInfo.width = WIDTH;
+        mDisplayDeviceInfo.height = HEIGHT;
+        mDisplayDeviceInfo.rotation = ROTATION_0;
+    }
+
+    @Test
+    public void testGetDisplaySurfaceDefaultSizeLocked_notRotated() {
+        DisplayDevice displayDevice = new FakeDisplayDevice(mDisplayDeviceInfo);
+        assertThat(displayDevice.getDisplaySurfaceDefaultSizeLocked()).isEqualTo(PORTRAIT_SIZE);
+    }
+
+    @Test
+    public void testGetDisplaySurfaceDefaultSizeLocked_rotation0() {
+        DisplayDevice displayDevice = new FakeDisplayDevice(mDisplayDeviceInfo);
+        displayDevice.setProjectionLocked(mMockTransaction, ROTATION_0, new Rect(), new Rect());
+        assertThat(displayDevice.getDisplaySurfaceDefaultSizeLocked()).isEqualTo(PORTRAIT_SIZE);
+    }
+
+    @Test
+    public void testGetDisplaySurfaceDefaultSizeLocked_rotation90() {
+        DisplayDevice displayDevice = new FakeDisplayDevice(mDisplayDeviceInfo);
+        displayDevice.setProjectionLocked(mMockTransaction, ROTATION_90, new Rect(), new Rect());
+        assertThat(displayDevice.getDisplaySurfaceDefaultSizeLocked()).isEqualTo(LANDSCAPE_SIZE);
+    }
+
+    @Test
+    public void testGetDisplaySurfaceDefaultSizeLocked_rotation180() {
+        DisplayDevice displayDevice = new FakeDisplayDevice(mDisplayDeviceInfo);
+        displayDevice.setProjectionLocked(mMockTransaction, ROTATION_180, new Rect(), new Rect());
+        assertThat(displayDevice.getDisplaySurfaceDefaultSizeLocked()).isEqualTo(PORTRAIT_SIZE);
+    }
+
+    @Test
+    public void testGetDisplaySurfaceDefaultSizeLocked_rotation270() {
+        DisplayDevice displayDevice = new FakeDisplayDevice(mDisplayDeviceInfo);
+        displayDevice.setProjectionLocked(mMockTransaction, ROTATION_270, new Rect(), new Rect());
+        assertThat(displayDevice.getDisplaySurfaceDefaultSizeLocked()).isEqualTo(LANDSCAPE_SIZE);
+    }
+
+    private static class FakeDisplayDevice extends DisplayDevice {
+        private final DisplayDeviceInfo mDisplayDeviceInfo;
+
+        FakeDisplayDevice(DisplayDeviceInfo displayDeviceInfo) {
+            super(null, null, "", InstrumentationRegistry.getInstrumentation().getContext());
+            mDisplayDeviceInfo = displayDeviceInfo;
+        }
+
+        @Override
+        public boolean hasStableUniqueId() {
+            return false;
+        }
+
+        @Override
+        public DisplayDeviceInfo getDisplayDeviceInfoLocked() {
+            return mDisplayDeviceInfo;
+        }
+    }
+}
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/SettingsToPropertiesMapperTest.java b/services/tests/mockingservicestests/src/com/android/server/am/SettingsToPropertiesMapperTest.java
index de27d77..e672928 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/SettingsToPropertiesMapperTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/SettingsToPropertiesMapperTest.java
@@ -102,7 +102,7 @@
         ).when(() -> Settings.Global.getString(any(), anyString()));
 
         mTestMapper = new SettingsToPropertiesMapper(
-            mMockContentResolver, TEST_MAPPING, new String[] {});
+            mMockContentResolver, TEST_MAPPING, new String[] {}, new String[] {});
     }
 
     @After
diff --git a/services/tests/powerstatstests/Android.bp b/services/tests/powerstatstests/Android.bp
index 05acd9b..5ea1929 100644
--- a/services/tests/powerstatstests/Android.bp
+++ b/services/tests/powerstatstests/Android.bp
@@ -23,6 +23,7 @@
         "androidx.test.uiautomator_uiautomator",
         "mockito-target-minus-junit4",
         "servicestests-utils",
+        "flag-junit",
     ],
 
     libs: [
diff --git a/services/tests/powerstatstests/src/com/android/server/power/stats/CpuPowerStatsCollectorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/CpuPowerStatsCollectorTest.java
new file mode 100644
index 0000000..f2ee6db
--- /dev/null
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/CpuPowerStatsCollectorTest.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.power.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.when;
+
+import android.os.ConditionVariable;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.util.SparseArray;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.internal.os.CpuScalingPolicies;
+import com.android.internal.os.PowerProfile;
+import com.android.internal.os.PowerStats;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class CpuPowerStatsCollectorTest {
+    private final MockClock mMockClock = new MockClock();
+    private final HandlerThread mHandlerThread = new HandlerThread("test");
+    private Handler mHandler;
+    private CpuPowerStatsCollector mCollector;
+    private PowerStats mCollectedStats;
+    @Mock
+    private PowerProfile mPowerProfile;
+    @Mock
+    private CpuPowerStatsCollector.KernelCpuStatsReader mMockKernelCpuStatsReader;
+
+    @Before
+    public void setup() {
+        MockitoAnnotations.initMocks(this);
+
+        mHandlerThread.start();
+        mHandler = mHandlerThread.getThreadHandler();
+        when(mPowerProfile.getCpuPowerBracketCount()).thenReturn(2);
+        when(mPowerProfile.getCpuPowerBracketForScalingStep(0, 0)).thenReturn(0);
+        when(mPowerProfile.getCpuPowerBracketForScalingStep(0, 1)).thenReturn(1);
+        mCollector = new CpuPowerStatsCollector(new CpuScalingPolicies(
+                new SparseArray<>() {{
+                    put(0, new int[]{0});
+                }},
+                new SparseArray<>() {{
+                    put(0, new int[]{1, 12});
+                }}),
+                mPowerProfile, mHandler, mMockKernelCpuStatsReader, 60_000, mMockClock);
+        mCollector.addConsumer(stats -> mCollectedStats = stats);
+        mCollector.setEnabled(true);
+    }
+
+    @Test
+    public void collectStats() {
+        mockKernelCpuStats(new SparseArray<>() {{
+                put(42, new long[]{100, 200});
+                put(99, new long[]{300, 600});
+            }}, 0, 1234);
+
+        mMockClock.uptime = 1000;
+        mCollector.forceSchedule();
+        waitForIdle();
+
+        assertThat(mCollectedStats.durationMs).isEqualTo(1234);
+        assertThat(mCollectedStats.uidStats.get(42)).isEqualTo(new long[]{100, 200});
+        assertThat(mCollectedStats.uidStats.get(99)).isEqualTo(new long[]{300, 600});
+
+        mockKernelCpuStats(new SparseArray<>() {{
+                put(42, new long[]{123, 234});
+                put(99, new long[]{345, 678});
+            }}, 1234, 3421);
+
+        mMockClock.uptime = 2000;
+        mCollector.forceSchedule();
+        waitForIdle();
+
+        assertThat(mCollectedStats.durationMs).isEqualTo(3421 - 1234);
+        assertThat(mCollectedStats.uidStats.get(42)).isEqualTo(new long[]{23, 34});
+        assertThat(mCollectedStats.uidStats.get(99)).isEqualTo(new long[]{45, 78});
+    }
+
+    private void mockKernelCpuStats(SparseArray<long[]> uidToCpuStats,
+            long expectedLastUpdateTimestampMs, long newLastUpdateTimestampMs) {
+        when(mMockKernelCpuStatsReader.nativeReadCpuStats(
+                any(CpuPowerStatsCollector.KernelCpuStatsCallback.class),
+                any(int[].class), anyLong(), any(long[].class)))
+                .thenAnswer(invocation -> {
+                    CpuPowerStatsCollector.KernelCpuStatsCallback callback =
+                            invocation.getArgument(0);
+                    int[] powerBucketIndexes = invocation.getArgument(1);
+                    long lastTimestamp = invocation.getArgument(2);
+                    long[] tempStats = invocation.getArgument(3);
+
+                    assertThat(powerBucketIndexes).isEqualTo(new int[]{0, 1});
+                    assertThat(lastTimestamp / 1000000L).isEqualTo(expectedLastUpdateTimestampMs);
+                    assertThat(tempStats).hasLength(2);
+
+                    for (int i = 0; i < uidToCpuStats.size(); i++) {
+                        int uid = uidToCpuStats.keyAt(i);
+                        long[] cpuStats = uidToCpuStats.valueAt(i);
+                        System.arraycopy(cpuStats, 0, tempStats, 0, tempStats.length);
+                        callback.processUidStats(uid, tempStats);
+                    }
+                    return newLastUpdateTimestampMs * 1000000L; // Nanoseconds
+                });
+    }
+
+    private void waitForIdle() {
+        ConditionVariable done = new ConditionVariable();
+        mHandler.post(done::open);
+        done.block();
+    }
+}
diff --git a/services/tests/powerstatstests/src/com/android/server/power/stats/CpuPowerStatsCollectorValidationTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/CpuPowerStatsCollectorValidationTest.java
new file mode 100644
index 0000000..38a5d19
--- /dev/null
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/CpuPowerStatsCollectorValidationTest.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.power.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static junit.framework.Assert.fail;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.platform.test.annotations.RequiresFlagsEnabled;
+import android.platform.test.flag.junit.CheckFlagsRule;
+import android.platform.test.flag.junit.DeviceFlagsValueProvider;
+import android.provider.DeviceConfig;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.LargeTest;
+import androidx.test.runner.AndroidJUnit4;
+import androidx.test.uiautomator.UiDevice;
+
+import com.android.frameworks.coretests.aidl.ICmdCallback;
+import com.android.frameworks.coretests.aidl.ICmdReceiver;
+import com.android.server.power.optimization.Flags;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Arrays;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+@RunWith(AndroidJUnit4.class)
+@LargeTest
+public class CpuPowerStatsCollectorValidationTest {
+    @Rule
+    public final CheckFlagsRule mCheckFlagsRule =
+            DeviceFlagsValueProvider.createCheckFlagsRule();
+
+    private static final int WORK_DURATION_MS = 2000;
+    private static final String TEST_PKG = "com.android.coretests.apps.bstatstestapp";
+    private static final String TEST_ACTIVITY = TEST_PKG + ".TestActivity";
+    private static final String EXTRA_KEY_CMD_RECEIVER = "cmd_receiver";
+    private static final int START_ACTIVITY_TIMEOUT_MS = 2000;
+
+    private Context mContext;
+    private UiDevice mUiDevice;
+    private DeviceConfig.Properties mBackupFlags;
+    private int mTestPkgUid;
+
+    @Before
+    public void setup() throws Exception {
+        mContext = InstrumentationRegistry.getContext();
+        mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+        mTestPkgUid = mContext.getPackageManager().getPackageUid(TEST_PKG, 0);
+    }
+
+    @Test
+    @RequiresFlagsEnabled(Flags.FLAG_STREAMLINED_BATTERY_STATS)
+    public void totalTimeInPowerBrackets() throws Exception {
+        dumpCpuStats();     // For the side effect of capturing the baseline.
+
+        doSomeWork();
+
+        long duration = 0;
+        long[] stats = null;
+
+        String[] cpuStatsDump = dumpCpuStats();
+        Pattern durationPattern = Pattern.compile("duration=([0-9]*)");
+        Pattern uidPattern = Pattern.compile("UID " + mTestPkgUid + ": \\[([0-9,\\s]*)]");
+        for (String line : cpuStatsDump) {
+            Matcher durationMatcher = durationPattern.matcher(line);
+            if (durationMatcher.find()) {
+                duration = Long.parseLong(durationMatcher.group(1));
+            }
+            Matcher uidMatcher = uidPattern.matcher(line);
+            if (uidMatcher.find()) {
+                String[] strings = uidMatcher.group(1).split(", ");
+                stats = new long[strings.length];
+                for (int i = 0; i < strings.length; i++) {
+                    stats[i] = Long.parseLong(strings[i]);
+                }
+            }
+        }
+        if (stats == null) {
+            fail("No CPU stats for " + mTestPkgUid + " (" + TEST_PKG + ")");
+        }
+
+        assertThat(duration).isAtLeast(WORK_DURATION_MS);
+
+        long total = Arrays.stream(stats).sum();
+        assertThat(total).isAtLeast((long) (WORK_DURATION_MS * 0.8));
+    }
+
+    private String[] dumpCpuStats() throws Exception {
+        String dump = executeCmdSilent("dumpsys batterystats --sample");
+        String[] lines = dump.split("\n");
+        for (int i = 0; i < lines.length; i++) {
+            if (lines[i].startsWith("CpuPowerStatsCollector")) {
+                return Arrays.copyOfRange(lines, i + 1, lines.length);
+            }
+        }
+        return new String[0];
+    }
+
+    private void doSomeWork() throws Exception {
+        final ICmdReceiver receiver;
+        receiver = ICmdReceiver.Stub.asInterface(startActivity());
+        try {
+            receiver.doSomeWork(WORK_DURATION_MS);
+        } finally {
+            receiver.finishHost();
+        }
+    }
+
+    private IBinder startActivity() throws Exception {
+        final CountDownLatch latch = new CountDownLatch(1);
+        final Intent launchIntent = new Intent().setComponent(
+                new ComponentName(TEST_PKG, TEST_ACTIVITY));
+        final Bundle extras = new Bundle();
+        final IBinder[] binders = new IBinder[1];
+        extras.putBinder(EXTRA_KEY_CMD_RECEIVER, new ICmdCallback.Stub() {
+            @Override
+            public void onLaunched(IBinder receiver) {
+                binders[0] = receiver;
+                latch.countDown();
+            }
+        });
+        launchIntent.putExtras(extras).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        mContext.startActivity(launchIntent);
+        if (latch.await(START_ACTIVITY_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
+            if (binders[0] == null) {
+                fail("Receiver binder should not be null");
+            }
+            return binders[0];
+        } else {
+            fail("Timed out waiting for the test activity to start; testUid=" + mTestPkgUid);
+        }
+        return null;
+    }
+
+    private String executeCmdSilent(String cmd) throws Exception {
+        return mUiDevice.executeShellCommand(cmd).trim();
+    }
+}
diff --git a/services/tests/powerstatstests/src/com/android/server/power/stats/MockBatteryStatsImpl.java b/services/tests/powerstatstests/src/com/android/server/power/stats/MockBatteryStatsImpl.java
index 6d3f1f2..4150972a 100644
--- a/services/tests/powerstatstests/src/com/android/server/power/stats/MockBatteryStatsImpl.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/MockBatteryStatsImpl.java
@@ -119,6 +119,13 @@
         return MOBILE_RADIO_POWER_STATE_UPDATE_FREQ_MS;
     }
 
+    public MockBatteryStatsImpl setBatteryStatsConfig(BatteryStatsConfig config) {
+        synchronized (this) {
+            mBatteryStatsConfig = config;
+        }
+        return this;
+    }
+
     public MockBatteryStatsImpl setNetworkStats(NetworkStats networkStats) {
         mNetworkStats = networkStats;
         return this;
diff --git a/services/tests/powerstatstests/src/com/android/server/power/stats/PowerStatsCollectorTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/PowerStatsCollectorTest.java
new file mode 100644
index 0000000..08c8213
--- /dev/null
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/PowerStatsCollectorTest.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.power.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.os.ConditionVariable;
+import android.os.Handler;
+import android.os.HandlerThread;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.internal.os.PowerStats;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class PowerStatsCollectorTest {
+    private final MockClock mMockClock = new MockClock();
+    private final HandlerThread mHandlerThread = new HandlerThread("test");
+    private Handler mHandler;
+    private PowerStatsCollector mCollector;
+    private PowerStats mCollectedStats;
+
+    @Before
+    public void setup() {
+        mHandlerThread.start();
+        mHandler = mHandlerThread.getThreadHandler();
+        mCollector = new PowerStatsCollector(mHandler,
+                60000,
+                mMockClock) {
+            @Override
+            protected PowerStats collectStats() {
+                return new PowerStats();
+            }
+        };
+        mCollector.addConsumer(stats -> mCollectedStats = stats);
+        mCollector.setEnabled(true);
+    }
+
+    @Test
+    public void throttlePeriod() {
+        mMockClock.uptime = 1000;
+        mCollector.schedule();
+        waitForIdle();
+
+        assertThat(mCollectedStats).isNotNull();
+
+        mMockClock.uptime += 1000;
+        mCollectedStats = null;
+        mCollector.schedule();      // Should be throttled
+        waitForIdle();
+
+        assertThat(mCollectedStats).isNull();
+
+        // Should be allowed to run
+        mMockClock.uptime += 100_000;
+        mCollector.schedule();
+        waitForIdle();
+
+        assertThat(mCollectedStats).isNotNull();
+    }
+
+    private void waitForIdle() {
+        ConditionVariable done = new ConditionVariable();
+        mHandler.post(done::open);
+        done.block();
+    }
+}
diff --git a/services/tests/servicestests/Android.bp b/services/tests/servicestests/Android.bp
index 92ff7ab..20d8a5d 100644
--- a/services/tests/servicestests/Android.bp
+++ b/services/tests/servicestests/Android.bp
@@ -68,6 +68,7 @@
         "ActivityContext",
         "coretests-aidl",
         "securebox",
+        "flag-junit",
     ],
 
     libs: [
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationGestureHandlerTest.java b/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationGestureHandlerTest.java
index 0a8c570..9fe743d 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationGestureHandlerTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationGestureHandlerTest.java
@@ -30,6 +30,7 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyInt;
@@ -43,6 +44,7 @@
 
 import android.animation.ValueAnimator;
 import android.annotation.NonNull;
+import android.content.pm.PackageManager;
 import android.graphics.PointF;
 import android.graphics.Rect;
 import android.graphics.Region;
@@ -252,7 +254,11 @@
                 detectTripleTap, detectShortcutTrigger,
                 mWindowMagnificationPromptController, DISPLAY_0,
                 mMockFullScreenMagnificationVibrationHelper);
-        h.setSinglePanningEnabled(true);
+        if (isWatch()) {
+            h.setSinglePanningEnabled(true);
+        } else {
+            h.setSinglePanningEnabled(false);
+        }
         mHandler = new TestHandler(h.mDetectingState, mClock) {
             @Override
             protected String messageToString(Message m) {
@@ -569,6 +575,7 @@
 
     @Test
     public void testActionUpNotAtEdge_singlePanningState_detectingState() {
+        assumeTrue(mMgh.mIsSinglePanningEnabled);
         goFromStateIdleTo(STATE_SINGLE_PANNING);
 
         send(upEvent());
@@ -579,6 +586,7 @@
 
     @Test
     public void testScroll_SinglePanningDisabled_delegatingState() {
+        assumeTrue(mMgh.mIsSinglePanningEnabled);
         mMgh.setSinglePanningEnabled(false);
 
         goFromStateIdleTo(STATE_ACTIVATED);
@@ -591,6 +599,7 @@
     @Test
     @FlakyTest
     public void testScroll_singleHorizontalPanningAndAtEdge_leftEdgeOverscroll() {
+        assumeTrue(mMgh.mIsSinglePanningEnabled);
         goFromStateIdleTo(STATE_SINGLE_PANNING);
         float centerY =
                 (INITIAL_MAGNIFICATION_BOUNDS.top + INITIAL_MAGNIFICATION_BOUNDS.bottom) / 2.0f;
@@ -614,6 +623,7 @@
     @Test
     @FlakyTest
     public void testScroll_singleHorizontalPanningAndAtEdge_rightEdgeOverscroll() {
+        assumeTrue(mMgh.mIsSinglePanningEnabled);
         goFromStateIdleTo(STATE_SINGLE_PANNING);
         float centerY =
                 (INITIAL_MAGNIFICATION_BOUNDS.top + INITIAL_MAGNIFICATION_BOUNDS.bottom) / 2.0f;
@@ -637,6 +647,7 @@
     @Test
     @FlakyTest
     public void testScroll_singleVerticalPanningAndAtEdge_verticalOverscroll() {
+        assumeTrue(mMgh.mIsSinglePanningEnabled);
         goFromStateIdleTo(STATE_SINGLE_PANNING);
         float centerX =
                 (INITIAL_MAGNIFICATION_BOUNDS.right + INITIAL_MAGNIFICATION_BOUNDS.left) / 2.0f;
@@ -658,6 +669,7 @@
 
     @Test
     public void testScroll_singlePanningAndAtEdge_noOverscroll() {
+        assumeTrue(mMgh.mIsSinglePanningEnabled);
         goFromStateIdleTo(STATE_SINGLE_PANNING);
         float centerY =
                 (INITIAL_MAGNIFICATION_BOUNDS.top + INITIAL_MAGNIFICATION_BOUNDS.bottom) / 2.0f;
@@ -679,6 +691,7 @@
 
     @Test
     public void testScroll_singleHorizontalPanningAndAtEdge_vibrate() {
+        assumeTrue(mMgh.mIsSinglePanningEnabled);
         goFromStateIdleTo(STATE_SINGLE_PANNING);
         mFullScreenMagnificationController.setCenter(
                 DISPLAY_0,
@@ -702,6 +715,7 @@
 
     @Test
     public void testScroll_singleVerticalPanningAndAtEdge_doNotVibrate() {
+        assumeTrue(mMgh.mIsSinglePanningEnabled);
         goFromStateIdleTo(STATE_SINGLE_PANNING);
         mFullScreenMagnificationController.setCenter(
                 DISPLAY_0,
@@ -868,6 +882,10 @@
         mFullScreenMagnificationController.onUserContextChanged(DISPLAY_0);
     }
 
+    private boolean isWatch() {
+        return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);
+    }
+
     /**
      * Asserts that {@link #mMgh the handler} is in the given {@code state}
      */
diff --git a/services/tests/wmtests/src/com/android/server/policy/SingleKeyGestureTests.java b/services/tests/wmtests/src/com/android/server/policy/SingleKeyGestureTests.java
index 3bb86a7..b9492e9 100644
--- a/services/tests/wmtests/src/com/android/server/policy/SingleKeyGestureTests.java
+++ b/services/tests/wmtests/src/com/android/server/policy/SingleKeyGestureTests.java
@@ -170,10 +170,15 @@
     }
 
     private void pressKey(int keyCode, long pressTime, boolean interactive) {
+        pressKey(keyCode, pressTime, interactive, false /* defaultDisplayOn */);
+    }
+
+    private void pressKey(
+            int keyCode, long pressTime, boolean interactive, boolean defaultDisplayOn) {
         long eventTime = SystemClock.uptimeMillis();
         final KeyEvent keyDown = new KeyEvent(eventTime, eventTime, ACTION_DOWN,
                 keyCode, 0 /* repeat */, 0 /* metaState */);
-        mDetector.interceptKey(keyDown, interactive);
+        mDetector.interceptKey(keyDown, interactive, defaultDisplayOn);
 
         // keep press down.
         try {
@@ -186,7 +191,7 @@
         final KeyEvent keyUp = new KeyEvent(eventTime, eventTime, ACTION_UP,
                 keyCode, 0 /* repeat */, 0 /* metaState */);
 
-        mDetector.interceptKey(keyUp, interactive);
+        mDetector.interceptKey(keyUp, interactive, defaultDisplayOn);
     }
 
     @Test
diff --git a/services/tests/wmtests/src/com/android/server/wm/SurfaceControlViewHostTests.java b/services/tests/wmtests/src/com/android/server/wm/SurfaceControlViewHostTests.java
index ce1a46b..1f9e8c2 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SurfaceControlViewHostTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SurfaceControlViewHostTests.java
@@ -16,10 +16,8 @@
 
 package com.android.server.wm;
 
-import static android.Manifest.permission.ACCESS_SURFACE_FLINGER;
-import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
-import static android.server.wm.CtsWindowInfoUtils.waitForWindowVisible;
 import static android.server.wm.CtsWindowInfoUtils.waitForWindowFocus;
+import static android.server.wm.CtsWindowInfoUtils.waitForWindowVisible;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
 
 import static org.junit.Assert.assertTrue;
@@ -78,17 +76,11 @@
     @Before
     public void setUp() throws Exception {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
-
-        // ACCESS_SURFACE_FLINGER is necessary to call waitForWindow
-        // INTERNAL_SYSTEM_WINDOW is necessary to add SCVH with no host parent
-        mInstrumentation.getUiAutomation().adoptShellPermissionIdentity(ACCESS_SURFACE_FLINGER,
-                INTERNAL_SYSTEM_WINDOW);
         mActivity = mActivityRule.launchActivity(null);
     }
 
     @After
     public void tearDown() {
-        mInstrumentation.getUiAutomation().dropShellPermissionIdentity();
         CommonUtils.waitUntilActivityRemoved(mActivity);
     }
 
@@ -102,14 +94,15 @@
         mView2 = new Button(mActivity);
 
         mInstrumentation.runOnMainSync(() -> {
-            TestWindowlessWindowManager wwm = new TestWindowlessWindowManager(
-                    mActivity.getResources().getConfiguration(), sc, null);
-
             try {
                 mActivity.attachToSurfaceView(sc);
             } catch (InterruptedException e) {
             }
 
+            TestWindowlessWindowManager wwm = new TestWindowlessWindowManager(
+                    mActivity.getResources().getConfiguration(), sc,
+                    mActivity.mSurfaceView.getHostToken());
+
             mScvh1 = new SurfaceControlViewHost(mActivity, mActivity.getDisplay(),
                     wwm, "requestFocusWithMultipleWindows");
             mScvh2 = new SurfaceControlViewHost(mActivity, mActivity.getDisplay(),
@@ -130,11 +123,13 @@
         assertTrue("Failed to wait for view1", waitForWindowVisible(mView1));
         assertTrue("Failed to wait for view2", waitForWindowVisible(mView2));
 
-        WindowManagerGlobal.getWindowSession().grantEmbeddedWindowFocus(null /* window */,
+        IWindow window = IWindow.Stub.asInterface(mActivity.mSurfaceView.getWindowToken());
+
+        WindowManagerGlobal.getWindowSession().grantEmbeddedWindowFocus(window,
                 mScvh1.getFocusGrantToken(), true);
         assertTrue("Failed to gain focus for view1", waitForWindowFocus(mView1, true));
 
-        WindowManagerGlobal.getWindowSession().grantEmbeddedWindowFocus(null /* window */,
+        WindowManagerGlobal.getWindowSession().grantEmbeddedWindowFocus(window,
                 mScvh2.getFocusGrantToken(), true);
         assertTrue("Failed to gain focus for view2", waitForWindowFocus(mView2, true));
     }
diff --git a/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java b/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
index 07cdfaf..873d09b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
@@ -39,6 +39,7 @@
 import static android.window.TransitionInfo.FLAG_IS_WALLPAPER;
 import static android.window.TransitionInfo.FLAG_MOVED_TO_TOP;
 import static android.window.TransitionInfo.FLAG_SHOW_WALLPAPER;
+import static android.window.TransitionInfo.FLAG_SYNC;
 import static android.window.TransitionInfo.FLAG_TRANSLUCENT;
 import static android.window.TransitionInfo.isIndependent;
 
@@ -1190,6 +1191,7 @@
         final WindowState statusBar = createWindow(null, TYPE_STATUS_BAR, "statusBar");
         makeWindowVisible(statusBar);
         mDisplayContent.getDisplayPolicy().addWindowLw(statusBar, statusBar.mAttrs);
+        final WindowState navBar = createWindow(null, TYPE_NAVIGATION_BAR, "navBar");
         final ActivityRecord app = createActivityRecord(mDisplayContent);
         final Transition transition = app.mTransitionController.createTransition(TRANSIT_OPEN);
         app.mTransitionController.requestStartTransition(transition, app.getTask(),
@@ -1219,9 +1221,17 @@
         mDisplayContent.mTransitionController.dispatchLegacyAppTransitionFinished(app);
         assertTrue(mDisplayContent.hasTopFixedRotationLaunchingApp());
 
+        // The bar was invisible so it is not handled by the controller. But if it becomes visible
+        // and drawn before the transition starts,
+        assertFalse(asyncRotationController.isTargetToken(navBar.mToken));
+        navBar.finishDrawing(null /* postDrawTransaction */, Integer.MAX_VALUE);
+        assertTrue(asyncRotationController.isTargetToken(navBar.mToken));
+
         player.startTransition();
         // Non-app windows should not be collected.
         assertFalse(mDisplayContent.mTransitionController.isCollecting(statusBar.mToken));
+        // Avoid DeviceStateController disturbing the test by triggering another rotation change.
+        doReturn(false).when(mDisplayContent).updateRotationUnchecked();
 
         onRotationTransactionReady(player, mWm.mTransactionFactory.get()).onTransactionCommitted();
         assertEquals(ROTATION_ANIMATION_SEAMLESS, player.mLastReady.getChange(
@@ -2390,6 +2400,37 @@
         assertFalse(controller.isCollecting());
     }
 
+    @Test
+    public void testNoSyncFlagIfOneTrack() {
+        final TransitionController controller = mAtm.getTransitionController();
+        final TestTransitionPlayer player = registerTestTransitionPlayer();
+
+        mSyncEngine = createTestBLASTSyncEngine();
+        controller.setSyncEngine(mSyncEngine);
+
+        final Transition transitA = createTestTransition(TRANSIT_OPEN, controller);
+        final Transition transitB = createTestTransition(TRANSIT_OPEN, controller);
+        final Transition transitC = createTestTransition(TRANSIT_OPEN, controller);
+
+        controller.startCollectOrQueue(transitA, (deferred) -> {});
+        controller.startCollectOrQueue(transitB, (deferred) -> {});
+        controller.startCollectOrQueue(transitC, (deferred) -> {});
+
+        // Verify that, as-long as there is <= 1 track, we won't get a SYNC flag
+        transitA.start();
+        transitA.setAllReady();
+        mSyncEngine.tryFinishForTest(transitA.getSyncId());
+        assertTrue((player.mLastReady.getFlags() & FLAG_SYNC) == 0);
+        transitB.start();
+        transitB.setAllReady();
+        mSyncEngine.tryFinishForTest(transitB.getSyncId());
+        assertTrue((player.mLastReady.getFlags() & FLAG_SYNC) == 0);
+        transitC.start();
+        transitC.setAllReady();
+        mSyncEngine.tryFinishForTest(transitC.getSyncId());
+        assertTrue((player.mLastReady.getFlags() & FLAG_SYNC) == 0);
+    }
+
     private static void makeTaskOrganized(Task... tasks) {
         final ITaskOrganizer organizer = mock(ITaskOrganizer.class);
         for (Task t : tasks) {
diff --git a/tests/Input/src/com/android/server/input/FocusEventDebugViewTest.java b/tests/Input/src/com/android/server/input/FocusEventDebugViewTest.java
deleted file mode 100644
index 1b98887..0000000
--- a/tests/Input/src/com/android/server/input/FocusEventDebugViewTest.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.input;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import android.content.Context;
-import android.view.InputChannel;
-import android.view.InputDevice;
-import android.view.MotionEvent;
-import android.view.MotionEvent.PointerCoords;
-import android.view.MotionEvent.PointerProperties;
-import android.view.ViewConfiguration;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-/**
- * Build/Install/Run:
- * atest FocusEventDebugViewTest
- */
-@RunWith(AndroidJUnit4.class)
-public class FocusEventDebugViewTest {
-
-    private FocusEventDebugView mFocusEventDebugView;
-    private FocusEventDebugView.RotaryInputValueView mRotaryInputValueView;
-    private FocusEventDebugView.RotaryInputGraphView mRotaryInputGraphView;
-    private float mScaledVerticalScrollFactor;
-
-    @Before
-    public void setUp() throws Exception {
-        Context context = InstrumentationRegistry.getContext();
-        mScaledVerticalScrollFactor =
-                ViewConfiguration.get(context).getScaledVerticalScrollFactor();
-        InputManagerService mockService = mock(InputManagerService.class);
-        when(mockService.monitorInput(anyString(), anyInt()))
-                .thenReturn(InputChannel.openInputChannelPair("FocusEventDebugViewTest")[1]);
-
-        mRotaryInputValueView = new FocusEventDebugView.RotaryInputValueView(context);
-        mRotaryInputGraphView = new FocusEventDebugView.RotaryInputGraphView(context);
-        mFocusEventDebugView = new FocusEventDebugView(context, mockService,
-                () -> mRotaryInputValueView, () -> mRotaryInputGraphView);
-    }
-
-    @Test
-    public void startsRotaryInputValueViewWithDefaultValue() {
-        assertEquals("+0.0", mRotaryInputValueView.getText());
-    }
-
-    @Test
-    public void startsRotaryInputGraphViewWithDefaultFrameCenter() {
-        assertEquals(0, mRotaryInputGraphView.getFrameCenterPosition(), 0.01);
-    }
-
-    @Test
-    public void handleRotaryInput_updatesRotaryInputValueViewWithScrollValue() {
-        mFocusEventDebugView.handleUpdateShowRotaryInput(true);
-
-        mFocusEventDebugView.handleRotaryInput(createRotaryMotionEvent(0.5f));
-
-        assertEquals(String.format("+%.1f", 0.5f * mScaledVerticalScrollFactor),
-                mRotaryInputValueView.getText());
-    }
-
-    @Test
-    public void handleRotaryInput_translatesRotaryInputGraphViewWithHighScrollValue() {
-        mFocusEventDebugView.handleUpdateShowRotaryInput(true);
-
-        mFocusEventDebugView.handleRotaryInput(createRotaryMotionEvent(1000f));
-
-        assertTrue(mRotaryInputGraphView.getFrameCenterPosition() > 0);
-    }
-
-    @Test
-    public void updateActivityStatus_setsAndRemovesColorFilter() {
-        // It should not be active initially.
-        assertNull(mRotaryInputValueView.getBackground().getColorFilter());
-
-        mRotaryInputValueView.updateActivityStatus(true);
-        // It should be active after rotary input.
-        assertNotNull(mRotaryInputValueView.getBackground().getColorFilter());
-
-        mRotaryInputValueView.updateActivityStatus(false);
-        // It should not be active after waiting for mUpdateActivityStatusCallback.
-        assertNull(mRotaryInputValueView.getBackground().getColorFilter());
-    }
-
-    private MotionEvent createRotaryMotionEvent(float scrollAxisValue) {
-        PointerCoords pointerCoords = new PointerCoords();
-        pointerCoords.setAxisValue(MotionEvent.AXIS_SCROLL, scrollAxisValue);
-        PointerProperties pointerProperties = new PointerProperties();
-
-        return MotionEvent.obtain(
-                /* downTime */ 0,
-                /* eventTime */ 0,
-                /* action */ MotionEvent.ACTION_SCROLL,
-                /* pointerCount */ 1,
-                /* pointerProperties */ new PointerProperties[] {pointerProperties},
-                /* pointerCoords */ new PointerCoords[] {pointerCoords},
-                /* metaState */ 0,
-                /* buttonState */ 0,
-                /* xPrecision */ 0,
-                /* yPrecision */ 0,
-                /* deviceId */ 0,
-                /* edgeFlags */ 0,
-                /* source */ InputDevice.SOURCE_ROTARY_ENCODER,
-                /* flags */ 0
-        );
-    }
-}
diff --git a/tests/Input/src/com/android/server/input/debug/FocusEventDebugViewTest.java b/tests/Input/src/com/android/server/input/debug/FocusEventDebugViewTest.java
new file mode 100644
index 0000000..ae7fb3b
--- /dev/null
+++ b/tests/Input/src/com/android/server/input/debug/FocusEventDebugViewTest.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.input.debug;
+
+import static org.mockito.Mockito.anyFloat;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.anyLong;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.view.InputChannel;
+import android.view.InputDevice;
+import android.view.MotionEvent;
+import android.view.MotionEvent.PointerCoords;
+import android.view.MotionEvent.PointerProperties;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.input.InputManagerService;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Build/Install/Run:
+ * atest FocusEventDebugViewTest
+ */
+@RunWith(AndroidJUnit4.class)
+public class FocusEventDebugViewTest {
+
+    private FocusEventDebugView mFocusEventDebugView;
+    private RotaryInputValueView mRotaryInputValueView;
+    private RotaryInputGraphView mRotaryInputGraphView;
+
+    @Before
+    public void setUp() throws Exception {
+        Context context = InstrumentationRegistry.getContext();
+        InputManagerService mockService = mock(InputManagerService.class);
+        when(mockService.monitorInput(anyString(), anyInt()))
+                .thenReturn(InputChannel.openInputChannelPair("FocusEventDebugViewTest")[1]);
+
+        mRotaryInputValueView = spy(new RotaryInputValueView(context));
+        mRotaryInputGraphView = spy(new RotaryInputGraphView(context));
+        mFocusEventDebugView = new FocusEventDebugView(context, mockService,
+                () -> mRotaryInputValueView, () -> mRotaryInputGraphView);
+    }
+
+    @Test
+    public void handleRotaryInput_sendsMotionEventWhenEnabled() {
+        mFocusEventDebugView.handleUpdateShowRotaryInput(true);
+
+        mFocusEventDebugView.handleRotaryInput(createRotaryMotionEvent(0.5f,  10L));
+
+        verify(mRotaryInputGraphView).addValue(0.5f, 10L);
+        verify(mRotaryInputValueView).updateValue(0.5f);
+    }
+
+    @Test
+    public void handleRotaryInput_doesNotSendMotionEventWhenDisabled() {
+        mFocusEventDebugView.handleUpdateShowRotaryInput(false);
+
+        mFocusEventDebugView.handleRotaryInput(createRotaryMotionEvent(0.5f, 10L));
+
+        verify(mRotaryInputGraphView, never()).addValue(anyFloat(), anyLong());
+        verify(mRotaryInputValueView, never()).updateValue(anyFloat());
+    }
+
+    private MotionEvent createRotaryMotionEvent(float scrollAxisValue, long eventTime) {
+        PointerCoords pointerCoords = new PointerCoords();
+        pointerCoords.setAxisValue(MotionEvent.AXIS_SCROLL, scrollAxisValue);
+        PointerProperties pointerProperties = new PointerProperties();
+
+        return MotionEvent.obtain(
+                /* downTime */ 0,
+                /* eventTime */ eventTime,
+                /* action */ MotionEvent.ACTION_SCROLL,
+                /* pointerCount */ 1,
+                /* pointerProperties */ new PointerProperties[] {pointerProperties},
+                /* pointerCoords */ new PointerCoords[] {pointerCoords},
+                /* metaState */ 0,
+                /* buttonState */ 0,
+                /* xPrecision */ 0,
+                /* yPrecision */ 0,
+                /* deviceId */ 0,
+                /* edgeFlags */ 0,
+                /* source */ InputDevice.SOURCE_ROTARY_ENCODER,
+                /* flags */ 0
+        );
+    }
+}
diff --git a/tests/Input/src/com/android/server/input/debug/RotaryInputGraphViewTest.java b/tests/Input/src/com/android/server/input/debug/RotaryInputGraphViewTest.java
new file mode 100644
index 0000000..af6ece4
--- /dev/null
+++ b/tests/Input/src/com/android/server/input/debug/RotaryInputGraphViewTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.input.debug;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import android.content.Context;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Build/Install/Run:
+ * atest RotaryInputGraphViewTest
+ */
+@RunWith(AndroidJUnit4.class)
+public class RotaryInputGraphViewTest {
+
+    private RotaryInputGraphView mRotaryInputGraphView;
+
+    @Before
+    public void setUp() throws Exception {
+        Context context = InstrumentationRegistry.getContext();
+
+        mRotaryInputGraphView = new RotaryInputGraphView(context);
+    }
+
+    @Test
+    public void startsWithDefaultFrameCenter() {
+        assertEquals(0, mRotaryInputGraphView.getFrameCenterPosition(), 0.01);
+    }
+
+    @Test
+    public void addValue_translatesRotaryInputGraphViewWithHighScrollValue() {
+        final float scrollAxisValue = 1000f;
+        final long eventTime = 0;
+
+        mRotaryInputGraphView.addValue(scrollAxisValue, eventTime);
+
+        assertTrue(mRotaryInputGraphView.getFrameCenterPosition() > 0);
+    }
+}
diff --git a/tests/Input/src/com/android/server/input/debug/RotaryInputValueViewTest.java b/tests/Input/src/com/android/server/input/debug/RotaryInputValueViewTest.java
new file mode 100644
index 0000000..e5e3852
--- /dev/null
+++ b/tests/Input/src/com/android/server/input/debug/RotaryInputValueViewTest.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.input.debug;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import android.content.Context;
+import android.view.ViewConfiguration;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Locale;
+
+/**
+ * Build/Install/Run:
+ * atest RotaryInputValueViewTest
+ */
+@RunWith(AndroidJUnit4.class)
+public class RotaryInputValueViewTest {
+
+    private final Locale mDefaultLocale = Locale.getDefault();
+
+    private RotaryInputValueView mRotaryInputValueView;
+    private float mScaledVerticalScrollFactor;
+
+    @Before
+    public void setUp() throws Exception {
+        Context context = InstrumentationRegistry.getContext();
+        mScaledVerticalScrollFactor =
+                ViewConfiguration.get(context).getScaledVerticalScrollFactor();
+
+        mRotaryInputValueView = new RotaryInputValueView(context);
+    }
+
+    @Test
+    public void startsWithDefaultValue() {
+        assertEquals("+0.0", mRotaryInputValueView.getText().toString());
+    }
+
+    @Test
+    public void updateValue_updatesTextWithScrollValue() {
+        final float scrollAxisValue = 1000f;
+        final String expectedText = String.format(mDefaultLocale, "+%.1f",
+                scrollAxisValue * mScaledVerticalScrollFactor);
+
+        mRotaryInputValueView.updateValue(scrollAxisValue);
+
+        assertEquals(expectedText, mRotaryInputValueView.getText().toString());
+    }
+
+    @Test
+    public void updateActivityStatus_setsAndRemovesColorFilter() {
+        // It should not be active initially.
+        assertNull(mRotaryInputValueView.getBackground().getColorFilter());
+
+        mRotaryInputValueView.updateActivityStatus(true);
+        // It should be active after rotary input.
+        assertNotNull(mRotaryInputValueView.getBackground().getColorFilter());
+
+        mRotaryInputValueView.updateActivityStatus(false);
+        // It should not be active after waiting for mUpdateActivityStatusCallback.
+        assertNull(mRotaryInputValueView.getBackground().getColorFilter());
+    }
+}
diff --git a/tests/InputMethodStressTest/src/com/android/inputmethod/stresstest/ImeStressTestUtil.java b/tests/InputMethodStressTest/src/com/android/inputmethod/stresstest/ImeStressTestUtil.java
index c9b5c96..12556bc 100644
--- a/tests/InputMethodStressTest/src/com/android/inputmethod/stresstest/ImeStressTestUtil.java
+++ b/tests/InputMethodStressTest/src/com/android/inputmethod/stresstest/ImeStressTestUtil.java
@@ -154,7 +154,7 @@
      * <p>The given {@code pred} will be called on the main thread.
      */
     public static void waitOnMainUntil(String message, Callable<Boolean> pred) {
-        eventually(() -> assertWithMessage(message).that(pred.call()).isTrue(), TIMEOUT);
+        eventually(() -> assertWithMessage(message).that(callOnMainSync(pred)).isTrue(), TIMEOUT);
     }
 
     /** Waits until IME is shown, or throws on timeout. */
diff --git a/tests/WindowInsetsTests/src/com/google/android/test/windowinsetstests/ChatActivity.java b/tests/WindowInsetsTests/src/com/google/android/test/windowinsetstests/ChatActivity.java
index ba12acb..2b605c5 100644
--- a/tests/WindowInsetsTests/src/com/google/android/test/windowinsetstests/ChatActivity.java
+++ b/tests/WindowInsetsTests/src/com/google/android/test/windowinsetstests/ChatActivity.java
@@ -18,6 +18,7 @@
 
 import static android.view.WindowInsets.Type.ime;
 import static android.view.WindowInsetsAnimation.Callback.DISPATCH_MODE_STOP;
+
 import static java.lang.Math.max;
 import static java.lang.Math.min;
 
@@ -41,11 +42,11 @@
 import android.view.animation.LinearInterpolator;
 import android.widget.LinearLayout;
 
+import androidx.appcompat.app.AppCompatActivity;
+
 import java.util.ArrayList;
 import java.util.List;
 
-import androidx.appcompat.app.AppCompatActivity;
-
 public class ChatActivity extends AppCompatActivity {
 
     private View mRoot;
@@ -148,7 +149,7 @@
                 inset = min(inset, shown);
                 mAnimationController.setInsetsAndAlpha(
                         Insets.of(0, 0, 0, inset),
-                        1f, (inset - start) / (float)(end - start));
+                        1f, start == end ? 1f : (inset - start) / (float) (end - start));
             }
         });
 
diff --git a/tools/aapt/AaptAssets.cpp b/tools/aapt/AaptAssets.cpp
index 899d268..b94d14f 100644
--- a/tools/aapt/AaptAssets.cpp
+++ b/tools/aapt/AaptAssets.cpp
@@ -219,7 +219,7 @@
      if (numTags >= 1) {
          const String8& lang = parts[0];
          if (isAlpha(lang) && (lang.length() == 2 || lang.length() == 3)) {
-             setLanguage(lang.string());
+             setLanguage(lang.c_str());
              valid = true;
          }
      }
@@ -232,11 +232,11 @@
      const String8& part2 = parts[1];
      if ((part2.length() == 2 && isAlpha(part2)) ||
          (part2.length() == 3 && isNumber(part2))) {
-         setRegion(part2.string());
+         setRegion(part2.c_str());
      } else if (part2.length() == 4 && isAlpha(part2)) {
-         setScript(part2.string());
+         setScript(part2.c_str());
      } else if (part2.length() >= 4 && part2.length() <= 8) {
-         setVariant(part2.string());
+         setVariant(part2.c_str());
      } else {
          valid = false;
      }
@@ -249,9 +249,9 @@
      const String8& part3 = parts[2];
      if (((part3.length() == 2 && isAlpha(part3)) ||
          (part3.length() == 3 && isNumber(part3))) && script[0]) {
-         setRegion(part3.string());
+         setRegion(part3.c_str());
      } else if (part3.length() >= 4 && part3.length() <= 8) {
-         setVariant(part3.string());
+         setVariant(part3.c_str());
      } else {
          valid = false;
      }
@@ -262,7 +262,7 @@
 
      const String8& part4 = parts[3];
      if (part4.length() >= 4 && part4.length() <= 8) {
-         setVariant(part4.string());
+         setVariant(part4.c_str());
      } else {
          valid = false;
      }
@@ -310,7 +310,7 @@
                     break;
                 default:
                     fprintf(stderr, "ERROR: Invalid BCP 47 tag in directory name %s\n",
-                            part.string());
+                            part.c_str());
                     return -1;
             }
         } else if (subtags.size() == 3) {
@@ -324,7 +324,7 @@
             } else if (subtags[1].size() == 2 || subtags[1].size() == 3) {
                 setRegion(subtags[1]);
             } else {
-                fprintf(stderr, "ERROR: Invalid BCP 47 tag in directory name %s\n", part.string());
+                fprintf(stderr, "ERROR: Invalid BCP 47 tag in directory name %s\n", part.c_str());
                 return -1;
             }
 
@@ -341,14 +341,14 @@
             setRegion(subtags[2]);
             setVariant(subtags[3]);
         } else {
-            fprintf(stderr, "ERROR: Invalid BCP 47 tag in directory name: %s\n", part.string());
+            fprintf(stderr, "ERROR: Invalid BCP 47 tag in directory name: %s\n", part.c_str());
             return -1;
         }
 
         return ++currentIndex;
     } else {
         if ((part.length() == 2 || part.length() == 3)
-               && isAlpha(part) && strcmp("car", part.string())) {
+               && isAlpha(part) && strcmp("car", part.c_str())) {
             setLanguage(part);
             if (++currentIndex == size) {
                 return size;
@@ -358,8 +358,8 @@
         }
 
         part = parts[currentIndex];
-        if (part.string()[0] == 'r' && part.length() == 3) {
-            setRegion(part.string() + 1);
+        if (part.c_str()[0] == 'r' && part.length() == 3) {
+            setRegion(part.c_str() + 1);
             if (++currentIndex == size) {
                 return size;
             }
@@ -524,8 +524,8 @@
     ssize_t index = mFiles.indexOfKey(file->getGroupEntry());
     if (index >= 0 && overwriteDuplicate) {
         fprintf(stderr, "warning: overwriting '%s' with '%s'\n",
-                mFiles[index]->getSourceFile().string(),
-                file->getSourceFile().string());
+                mFiles[index]->getSourceFile().c_str(),
+                file->getSourceFile().c_str());
         removeFile(index);
         index = -1;
     }
@@ -545,7 +545,7 @@
     const sp<AaptFile>& originalFile = mFiles.valueAt(index);
     SourcePos(file->getSourceFile(), -1)
             .error("Duplicate file.\n%s: Original is here. %s",
-                   originalFile->getPrintableSource().string(),
+                   originalFile->getPrintableSource().c_str(),
                    (withoutVersion.version != 0) ? "The version qualifier may be implied." : "");
     return UNKNOWN_ERROR;
 }
@@ -557,21 +557,21 @@
 
 void AaptGroup::print(const String8& prefix) const
 {
-    printf("%s%s\n", prefix.string(), getPath().string());
+    printf("%s%s\n", prefix.c_str(), getPath().c_str());
     const size_t N=mFiles.size();
     size_t i;
     for (i=0; i<N; i++) {
         sp<AaptFile> file = mFiles.valueAt(i);
         const AaptGroupEntry& e = file->getGroupEntry();
         if (file->hasData()) {
-            printf("%s  Gen: (%s) %d bytes\n", prefix.string(), e.toDirName(String8()).string(),
+            printf("%s  Gen: (%s) %d bytes\n", prefix.c_str(), e.toDirName(String8()).c_str(),
                     (int)file->getSize());
         } else {
-            printf("%s  Src: (%s) %s\n", prefix.string(), e.toDirName(String8()).string(),
-                    file->getPrintableSource().string());
+            printf("%s  Src: (%s) %s\n", prefix.c_str(), e.toDirName(String8()).c_str(),
+                    file->getPrintableSource().c_str());
         }
-        //printf("%s  File Group Entry: %s\n", prefix.string(),
-        //        file->getGroupEntry().toDirName(String8()).string());
+        //printf("%s  File Group Entry: %s\n", prefix.c_str(),
+        //        file->getGroupEntry().toDirName(String8()).c_str());
     }
 }
 
@@ -660,9 +660,9 @@
     {
         DIR* dir = NULL;
 
-        dir = opendir(srcDir.string());
+        dir = opendir(srcDir.c_str());
         if (dir == NULL) {
-            fprintf(stderr, "ERROR: opendir(%s): %s\n", srcDir.string(), strerror(errno));
+            fprintf(stderr, "ERROR: opendir(%s): %s\n", srcDir.c_str(), strerror(errno));
             return UNKNOWN_ERROR;
         }
 
@@ -676,7 +676,7 @@
             if (entry == NULL)
                 break;
 
-            if (isHidden(srcDir.string(), entry->d_name))
+            if (isHidden(srcDir.c_str(), entry->d_name))
                 continue;
 
             String8 name(entry->d_name);
@@ -701,8 +701,8 @@
         String8 pathName(srcDir);
         FileType type;
 
-        pathName.appendPath(fileNames[i].string());
-        type = getFileType(pathName.string());
+        pathName.appendPath(fileNames[i].c_str());
+        type = getFileType(pathName.c_str());
         if (type == kFileTypeDirectory) {
             sp<AaptDir> subdir;
             bool notAdded = false;
@@ -732,7 +732,7 @@
 
         } else {
             if (bundle->getVerbose())
-                printf("   (ignoring non-file/dir '%s')\n", pathName.string());
+                printf("   (ignoring non-file/dir '%s')\n", pathName.c_str());
         }
     }
 
@@ -745,7 +745,7 @@
     const size_t ND = mDirs.size();
     size_t i;
     for (i = 0; i < NF; i++) {
-        if (!validateFileName(mFiles.valueAt(i)->getLeaf().string())) {
+        if (!validateFileName(mFiles.valueAt(i)->getLeaf().c_str())) {
             SourcePos(mFiles.valueAt(i)->getPrintableSource(), -1).error(
                     "Invalid filename.  Unable to add.");
             return UNKNOWN_ERROR;
@@ -753,11 +753,11 @@
 
         size_t j;
         for (j = i+1; j < NF; j++) {
-            if (strcasecmp(mFiles.valueAt(i)->getLeaf().string(),
-                           mFiles.valueAt(j)->getLeaf().string()) == 0) {
+            if (strcasecmp(mFiles.valueAt(i)->getLeaf().c_str(),
+                           mFiles.valueAt(j)->getLeaf().c_str()) == 0) {
                 SourcePos(mFiles.valueAt(i)->getPrintableSource(), -1).error(
                         "File is case-insensitive equivalent to: %s",
-                        mFiles.valueAt(j)->getPrintableSource().string());
+                        mFiles.valueAt(j)->getPrintableSource().c_str());
                 return UNKNOWN_ERROR;
             }
 
@@ -766,18 +766,18 @@
         }
 
         for (j = 0; j < ND; j++) {
-            if (strcasecmp(mFiles.valueAt(i)->getLeaf().string(),
-                           mDirs.valueAt(j)->getLeaf().string()) == 0) {
+            if (strcasecmp(mFiles.valueAt(i)->getLeaf().c_str(),
+                           mDirs.valueAt(j)->getLeaf().c_str()) == 0) {
                 SourcePos(mFiles.valueAt(i)->getPrintableSource(), -1).error(
                         "File conflicts with dir from: %s",
-                        mDirs.valueAt(j)->getPrintableSource().string());
+                        mDirs.valueAt(j)->getPrintableSource().c_str());
                 return UNKNOWN_ERROR;
             }
         }
     }
 
     for (i = 0; i < ND; i++) {
-        if (!validateFileName(mDirs.valueAt(i)->getLeaf().string())) {
+        if (!validateFileName(mDirs.valueAt(i)->getLeaf().c_str())) {
             SourcePos(mDirs.valueAt(i)->getPrintableSource(), -1).error(
                     "Invalid directory name, unable to add.");
             return UNKNOWN_ERROR;
@@ -785,11 +785,11 @@
 
         size_t j;
         for (j = i+1; j < ND; j++) {
-            if (strcasecmp(mDirs.valueAt(i)->getLeaf().string(),
-                           mDirs.valueAt(j)->getLeaf().string()) == 0) {
+            if (strcasecmp(mDirs.valueAt(i)->getLeaf().c_str(),
+                           mDirs.valueAt(j)->getLeaf().c_str()) == 0) {
                 SourcePos(mDirs.valueAt(i)->getPrintableSource(), -1).error(
                         "Directory is case-insensitive equivalent to: %s",
-                        mDirs.valueAt(j)->getPrintableSource().string());
+                        mDirs.valueAt(j)->getPrintableSource().c_str());
                 return UNKNOWN_ERROR;
             }
         }
@@ -846,12 +846,12 @@
         const AaptSymbolEntry& entry = javaSymbols->mSymbols.valueAt(i);
         ssize_t pos = mSymbols.indexOfKey(name);
         if (pos < 0) {
-            entry.sourcePos.error("Symbol '%s' declared with <java-symbol> not defined\n", name.string());
+            entry.sourcePos.error("Symbol '%s' declared with <java-symbol> not defined\n", name.c_str());
             err = UNKNOWN_ERROR;
             continue;
         }
         //printf("**** setting symbol #%d/%d %s to isJavaSymbol=%d\n",
-        //        i, N, name.string(), entry.isJavaSymbol ? 1 : 0);
+        //        i, N, name.c_str(), entry.isJavaSymbol ? 1 : 0);
         mSymbols.editValueAt(pos).isJavaSymbol = entry.isJavaSymbol;
     }
 
@@ -862,11 +862,11 @@
         ssize_t pos = mNestedSymbols.indexOfKey(name);
         if (pos < 0) {
             SourcePos pos;
-            pos.error("Java symbol dir %s not defined\n", name.string());
+            pos.error("Java symbol dir %s not defined\n", name.c_str());
             err = UNKNOWN_ERROR;
             continue;
         }
-        //printf("**** applying java symbols in dir %s\n", name.string());
+        //printf("**** applying java symbols in dir %s\n", name.c_str());
         status_t myerr = mNestedSymbols.valueAt(pos)->applyJavaSymbols(symbols);
         if (myerr != NO_ERROR) {
             err = myerr;
@@ -1131,9 +1131,9 @@
 {
     ssize_t err = 0;
 
-    DIR* dir = opendir(srcDir.string());
+    DIR* dir = opendir(srcDir.c_str());
     if (dir == NULL) {
-        fprintf(stderr, "ERROR: opendir(%s): %s\n", srcDir.string(), strerror(errno));
+        fprintf(stderr, "ERROR: opendir(%s): %s\n", srcDir.c_str(), strerror(errno));
         return UNKNOWN_ERROR;
     }
 
@@ -1149,7 +1149,7 @@
             break;
         }
 
-        if (isHidden(srcDir.string(), entry->d_name)) {
+        if (isHidden(srcDir.c_str(), entry->d_name)) {
             continue;
         }
 
@@ -1160,7 +1160,7 @@
         String8 resType;
         bool b = group.initFromDirName(entry->d_name, &resType);
         if (!b) {
-            fprintf(stderr, "invalid resource directory name: %s %s\n", srcDir.string(),
+            fprintf(stderr, "invalid resource directory name: %s %s\n", srcDir.c_str(),
                     entry->d_name);
             err = -1;
             continue;
@@ -1168,7 +1168,7 @@
 
         if (bundle->getMaxResVersion() != NULL && group.getVersionString().length() != 0) {
             int maxResInt = atoi(bundle->getMaxResVersion());
-            const char *verString = group.getVersionString().string();
+            const char *verString = group.getVersionString().c_str();
             int dirVersionInt = atoi(verString + 1); // skip 'v' in version name
             if (dirVersionInt > maxResInt) {
               fprintf(stderr, "max res %d, skipping %s\n", maxResInt, entry->d_name);
@@ -1176,7 +1176,7 @@
             }
         }
 
-        FileType type = getFileType(subdirName.string());
+        FileType type = getFileType(subdirName.c_str());
 
         if (type == kFileTypeDirectory) {
             sp<AaptDir> dir = makeDir(resType);
@@ -1200,7 +1200,7 @@
             }
         } else {
             if (bundle->getVerbose()) {
-                fprintf(stderr, "   (ignoring file '%s')\n", subdirName.string());
+                fprintf(stderr, "   (ignoring file '%s')\n", subdirName.c_str());
             }
         }
     }
@@ -1248,7 +1248,7 @@
         String8 remain;
         if (entryName.walkPath(&remain) == kResourceDir) {
             // these are the resources, pull their type out of the directory name
-            kind.initFromDirName(remain.walkPath().string(), &resType);
+            kind.initFromDirName(remain.walkPath().c_str(), &resType);
         } else {
             // these are untyped and don't have an AaptGroupEntry
         }
@@ -1263,7 +1263,7 @@
         sp<AaptFile> file = new AaptFile(entryName, kind, resType);
         status_t err = dir->addLeafFile(entryName.getPathLeaf(), file);
         if (err != NO_ERROR) {
-            fprintf(stderr, "err=%s entryName=%s\n", strerror(err), entryName.string());
+            fprintf(stderr, "err=%s entryName=%s\n", strerror(err), entryName.c_str());
             count = err;
             goto bail;
         }
@@ -1273,7 +1273,7 @@
         if (entryName == "AndroidManifest.xml") {
             printf("AndroidManifest.xml\n");
         }
-        printf("\n\nfile: %s\n", entryName.string());
+        printf("\n\nfile: %s\n", entryName.c_str());
 #endif
 
         size_t len = entry->getUncompressedLen();
@@ -1317,9 +1317,9 @@
     uint32_t preferredDensity = 0;
     if (bundle->getPreferredDensity().size() > 0) {
         ResTable_config preferredConfig;
-        if (!AaptConfig::parseDensity(bundle->getPreferredDensity().string(), &preferredConfig)) {
+        if (!AaptConfig::parseDensity(bundle->getPreferredDensity().c_str(), &preferredConfig)) {
             fprintf(stderr, "Error parsing preferred density: %s\n",
-                    bundle->getPreferredDensity().string());
+                    bundle->getPreferredDensity().c_str());
             return UNKNOWN_ERROR;
         }
         preferredDensity = preferredConfig.density;
@@ -1332,11 +1332,11 @@
     if (bundle->getVerbose()) {
         if (!reqFilter->isEmpty()) {
             printf("Applying required filter: %s\n",
-                    bundle->getConfigurations().string());
+                    bundle->getConfigurations().c_str());
         }
         if (preferredDensity > 0) {
             printf("Applying preferred density filter: %s\n",
-                    bundle->getPreferredDensity().string());
+                    bundle->getPreferredDensity().c_str());
         }
     }
 
@@ -1385,7 +1385,7 @@
                 if (!reqFilter->match(config)) {
                     if (bundle->getVerbose()) {
                         printf("Pruning unneeded resource: %s\n",
-                                file->getPrintableSource().string());
+                                file->getPrintableSource().c_str());
                     }
                     grp->removeFile(k);
                     k--;
@@ -1453,7 +1453,7 @@
                     if (bestDensity != config.density) {
                         if (bundle->getVerbose()) {
                             printf("Pruning unneeded resource: %s\n",
-                                    file->getPrintableSource().string());
+                                    file->getPrintableSource().c_str());
                         }
                         grp->removeFile(k);
                         k--;
@@ -1495,10 +1495,10 @@
         ssize_t pos = mSymbols.indexOfKey(name);
         if (pos < 0) {
             SourcePos pos;
-            pos.error("Java symbol dir %s not defined\n", name.string());
+            pos.error("Java symbol dir %s not defined\n", name.c_str());
             return UNKNOWN_ERROR;
         }
-        //printf("**** applying java symbols in dir %s\n", name.string());
+        //printf("**** applying java symbols in dir %s\n", name.c_str());
         status_t err = mSymbols.valueAt(pos)->applyJavaSymbols(symbols);
         if (err != NO_ERROR) {
             return err;
@@ -1510,7 +1510,7 @@
 
 bool AaptAssets::isJavaSymbol(const AaptSymbolEntry& sym, bool includePrivate) const {
     //printf("isJavaSymbol %s: public=%d, includePrivate=%d, isJavaSymbol=%d\n",
-    //        sym.name.string(), sym.isPublic ? 1 : 0, includePrivate ? 1 : 0,
+    //        sym.name.c_str(), sym.isPublic ? 1 : 0, includePrivate ? 1 : 0,
     //        sym.isJavaSymbol ? 1 : 0);
     if (!mHavePrivateSymbols) return true;
     if (sym.isPublic) return true;
@@ -1529,12 +1529,12 @@
     const size_t packageIncludeCount = includes.size();
     for (size_t i = 0; i < packageIncludeCount; i++) {
         if (bundle->getVerbose()) {
-            printf("Including resources from package: %s\n", includes[i].string());
+            printf("Including resources from package: %s\n", includes[i].c_str());
         }
 
         if (!mIncludedAssets.addAssetPath(includes[i], NULL)) {
             fprintf(stderr, "ERROR: Asset package include '%s' not found.\n",
-                    includes[i].string());
+                    includes[i].c_str());
             return UNKNOWN_ERROR;
         }
     }
@@ -1543,12 +1543,12 @@
     if (!featureOfBase.isEmpty()) {
         if (bundle->getVerbose()) {
             printf("Including base feature resources from package: %s\n",
-                    featureOfBase.string());
+                    featureOfBase.c_str());
         }
 
         if (!mIncludedAssets.addAssetPath(featureOfBase, NULL)) {
             fprintf(stderr, "ERROR: base feature package '%s' not found.\n",
-                    featureOfBase.string());
+                    featureOfBase.c_str());
             return UNKNOWN_ERROR;
         }
     }
@@ -1581,23 +1581,23 @@
     innerPrefix.append("  ");
     String8 innerInnerPrefix(innerPrefix);
     innerInnerPrefix.append("  ");
-    printf("%sConfigurations:\n", prefix.string());
+    printf("%sConfigurations:\n", prefix.c_str());
     const size_t N=mGroupEntries.size();
     for (size_t i=0; i<N; i++) {
         String8 cname = mGroupEntries.itemAt(i).toDirName(String8());
-        printf("%s %s\n", prefix.string(),
-                cname != "" ? cname.string() : "(default)");
+        printf("%s %s\n", prefix.c_str(),
+                cname != "" ? cname.c_str() : "(default)");
     }
 
-    printf("\n%sFiles:\n", prefix.string());
+    printf("\n%sFiles:\n", prefix.c_str());
     AaptDir::print(innerPrefix);
 
-    printf("\n%sResource Dirs:\n", prefix.string());
+    printf("\n%sResource Dirs:\n", prefix.c_str());
     const Vector<sp<AaptDir> >& resdirs = mResDirs;
     const size_t NR = resdirs.size();
     for (size_t i=0; i<NR; i++) {
         const sp<AaptDir>& d = resdirs.itemAt(i);
-        printf("%s  Type %s\n", prefix.string(), d->getLeaf().string());
+        printf("%s  Type %s\n", prefix.c_str(), d->getLeaf().c_str());
         d->print(innerInnerPrefix);
     }
 }
@@ -1631,7 +1631,7 @@
         NULL
     };
     const char*const* k = KEYWORDS;
-    const char*const s = symbol.string();
+    const char*const s = symbol.c_str();
     while (*k) {
         if (0 == strcmp(s, *k)) {
             return false;
diff --git a/tools/aapt/AaptAssets.h b/tools/aapt/AaptAssets.h
index eadd48a..498fc4e 100644
--- a/tools/aapt/AaptAssets.h
+++ b/tools/aapt/AaptAssets.h
@@ -463,7 +463,7 @@
         if (valid_symbol_name(symbol)) {
             return true;
         }
-        pos.error("invalid %s: '%s'\n", label, symbol.string());
+        pos.error("invalid %s: '%s'\n", label, symbol.c_str());
         return false;
     }
     AaptSymbolEntry& edit_symbol(const String8& symbol, const SourcePos* pos) {
diff --git a/tools/aapt/AaptConfig.cpp b/tools/aapt/AaptConfig.cpp
index 0aca45e..7578f79 100644
--- a/tools/aapt/AaptConfig.cpp
+++ b/tools/aapt/AaptConfig.cpp
@@ -39,7 +39,7 @@
     ssize_t index = 0;
     ssize_t localeIndex = 0;
     const ssize_t N = parts.size();
-    const char* part = parts[index].string();
+    const char* part = parts[index].c_str();
 
     if (str.length() == 0) {
         goto success;
@@ -50,7 +50,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseMnc(part, &config)) {
@@ -58,7 +58,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     // Locale spans a few '-' separators, so we let it
@@ -72,7 +72,7 @@
         if (index >= N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseLayoutDirection(part, &config)) {
@@ -80,7 +80,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseSmallestScreenWidthDp(part, &config)) {
@@ -88,7 +88,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenWidthDp(part, &config)) {
@@ -96,7 +96,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenHeightDp(part, &config)) {
@@ -104,7 +104,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenLayoutSize(part, &config)) {
@@ -112,7 +112,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenLayoutLong(part, &config)) {
@@ -120,7 +120,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenRound(part, &config)) {
@@ -128,7 +128,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseWideColorGamut(part, &config)) {
@@ -136,7 +136,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseHdr(part, &config)) {
@@ -144,7 +144,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseOrientation(part, &config)) {
@@ -152,7 +152,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseUiModeType(part, &config)) {
@@ -160,7 +160,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseUiModeNight(part, &config)) {
@@ -168,7 +168,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseDensity(part, &config)) {
@@ -176,7 +176,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseTouchscreen(part, &config)) {
@@ -184,7 +184,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseKeysHidden(part, &config)) {
@@ -192,7 +192,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseKeyboard(part, &config)) {
@@ -200,7 +200,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseNavHidden(part, &config)) {
@@ -208,7 +208,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseNavigation(part, &config)) {
@@ -216,7 +216,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenSize(part, &config)) {
@@ -224,7 +224,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseVersion(part, &config)) {
@@ -232,7 +232,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     // Unrecognized.
@@ -773,8 +773,8 @@
     if (y == name || *y != 0) return false;
     String8 yName(x, y-x);
 
-    uint16_t w = (uint16_t)atoi(xName.string());
-    uint16_t h = (uint16_t)atoi(yName.string());
+    uint16_t w = (uint16_t)atoi(xName.c_str());
+    uint16_t h = (uint16_t)atoi(yName.c_str());
     if (w < h) {
         return false;
     }
@@ -805,7 +805,7 @@
     String8 xName(name, x-name);
 
     if (out) {
-        out->smallestScreenWidthDp = (uint16_t)atoi(xName.string());
+        out->smallestScreenWidthDp = (uint16_t)atoi(xName.c_str());
     }
 
     return true;
@@ -827,7 +827,7 @@
     String8 xName(name, x-name);
 
     if (out) {
-        out->screenWidthDp = (uint16_t)atoi(xName.string());
+        out->screenWidthDp = (uint16_t)atoi(xName.c_str());
     }
 
     return true;
@@ -849,7 +849,7 @@
     String8 xName(name, x-name);
 
     if (out) {
-        out->screenHeightDp = (uint16_t)atoi(xName.string());
+        out->screenHeightDp = (uint16_t)atoi(xName.c_str());
     }
 
     return true;
@@ -875,7 +875,7 @@
     String8 sdkName(name, s-name);
 
     if (out) {
-        out->sdkVersion = (uint16_t)atoi(sdkName.string());
+        out->sdkVersion = (uint16_t)atoi(sdkName.c_str());
         out->minorVersion = 0;
     }
 
diff --git a/tools/aapt/AaptUtil.cpp b/tools/aapt/AaptUtil.cpp
index 293e144..e82860d 100644
--- a/tools/aapt/AaptUtil.cpp
+++ b/tools/aapt/AaptUtil.cpp
@@ -23,7 +23,7 @@
 
 Vector<String8> split(const String8& str, const char sep) {
     Vector<String8> parts;
-    const char* p = str.string();
+    const char* p = str.c_str();
     const char* q;
 
     while (true) {
@@ -41,7 +41,7 @@
 
 Vector<String8> splitAndLowerCase(const String8& str, const char sep) {
     Vector<String8> parts;
-    const char* p = str.string();
+    const char* p = str.c_str();
     const char* q;
 
     while (true) {
diff --git a/tools/aapt/ApkBuilder.cpp b/tools/aapt/ApkBuilder.cpp
index 01e02e2..335c43b 100644
--- a/tools/aapt/ApkBuilder.cpp
+++ b/tools/aapt/ApkBuilder.cpp
@@ -36,7 +36,7 @@
             if (splitConfigs.count(*iter) > 0) {
                 // Can't have overlapping configurations.
                 fprintf(stderr, "ERROR: Split configuration '%s' is already defined "
-                        "in another split.\n", iter->toString().string());
+                        "in another split.\n", iter->toString().c_str());
                 return ALREADY_EXISTS;
             }
         }
@@ -115,10 +115,10 @@
 }
 
 void ApkSplit::print() const {
-    fprintf(stderr, "APK Split '%s'\n", mName.string());
+    fprintf(stderr, "APK Split '%s'\n", mName.c_str());
 
     std::set<OutputEntry>::const_iterator iter = mFiles.begin();
     for (; iter != mFiles.end(); iter++) {
-        fprintf(stderr, "  %s (%s)\n", iter->getPath().string(), iter->getFile()->getSourceFile().string());
+        fprintf(stderr, "  %s (%s)\n", iter->getPath().c_str(), iter->getFile()->getSourceFile().c_str());
     }
 }
diff --git a/tools/aapt/CacheUpdater.h b/tools/aapt/CacheUpdater.h
index 6fa96d6..2dc143c 100644
--- a/tools/aapt/CacheUpdater.h
+++ b/tools/aapt/CacheUpdater.h
@@ -66,7 +66,7 @@
         // Check optomistically to see if all directories exist.
         // If something in the path doesn't exist, then walk the path backwards
         // and find the place to start creating directories forward.
-        if (stat(path.string(),&s) == -1) {
+        if (stat(path.c_str(),&s) == -1) {
             // Walk backwards to find place to start creating directories
             existsPath = path;
             do {
@@ -74,7 +74,7 @@
                 // the string of paths to create.
                 toCreate = existsPath.getPathLeaf().appendPath(toCreate);
                 existsPath = existsPath.getPathDir();
-            } while (stat(existsPath.string(),&s) == -1);
+            } while (stat(existsPath.c_str(),&s) == -1);
 
             // Walk forwards and build directories as we go
             do {
@@ -82,9 +82,9 @@
                 existsPath.appendPath(toCreate.walkPath(&remains));
                 toCreate = remains;
 #ifdef _WIN32
-                _mkdir(existsPath.string());
+                _mkdir(existsPath.c_str());
 #else
-                mkdir(existsPath.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
+                mkdir(existsPath.c_str(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
 #endif
             } while (remains.length() > 0);
         } //if
@@ -93,8 +93,8 @@
     // Delete a file
     virtual void deleteFile(String8 path)
     {
-        if (remove(path.string()) != 0)
-            fprintf(stderr,"ERROR DELETING %s\n",path.string());
+        if (remove(path.c_str()) != 0)
+            fprintf(stderr,"ERROR DELETING %s\n",path.c_str());
     };
 
     // Process an image from source out to dest
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index 51cf38b..5a06b10 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -240,13 +240,13 @@
     }
     if (value.dataType == Res_value::TYPE_STRING) {
         String8 result = AaptXml::getResolvedAttribute(resTable, tree, attrRes, outError);
-        printf("%s='%s'", attrLabel.string(),
-                ResTable::normalizeForOutput(result.string()).string());
+        printf("%s='%s'", attrLabel.c_str(),
+                ResTable::normalizeForOutput(result.c_str()).c_str());
     } else if (Res_value::TYPE_FIRST_INT <= value.dataType &&
             value.dataType <= Res_value::TYPE_LAST_INT) {
-        printf("%s='%d'", attrLabel.string(), value.data);
+        printf("%s='%d'", attrLabel.c_str(), value.data);
     } else {
-        printf("%s='0x%x'", attrLabel.string(), (int)value.data);
+        printf("%s='0x%x'", attrLabel.c_str(), (int)value.data);
     }
 }
 
@@ -355,21 +355,21 @@
 static void printUsesPermission(const String8& name, bool optional=false, int maxSdkVersion=-1,
         const String8& requiredFeature = String8(),
         const String8& requiredNotFeature = String8()) {
-    printf("uses-permission: name='%s'", ResTable::normalizeForOutput(name.string()).string());
+    printf("uses-permission: name='%s'", ResTable::normalizeForOutput(name.c_str()).c_str());
     if (maxSdkVersion != -1) {
          printf(" maxSdkVersion='%d'", maxSdkVersion);
     }
     if (requiredFeature.length() > 0) {
-         printf(" requiredFeature='%s'", requiredFeature.string());
+         printf(" requiredFeature='%s'", requiredFeature.c_str());
     }
     if (requiredNotFeature.length() > 0) {
-         printf(" requiredNotFeature='%s'", requiredNotFeature.string());
+         printf(" requiredNotFeature='%s'", requiredNotFeature.c_str());
     }
     printf("\n");
 
     if (optional) {
         printf("optional-permission: name='%s'",
-                ResTable::normalizeForOutput(name.string()).string());
+                ResTable::normalizeForOutput(name.c_str()).c_str());
         if (maxSdkVersion != -1) {
             printf(" maxSdkVersion='%d'", maxSdkVersion);
         }
@@ -380,7 +380,7 @@
 static void printUsesPermissionSdk23(const String8& name, int maxSdkVersion=-1) {
     printf("uses-permission-sdk-23: ");
 
-    printf("name='%s'", ResTable::normalizeForOutput(name.string()).string());
+    printf("name='%s'", ResTable::normalizeForOutput(name.c_str()).c_str());
     if (maxSdkVersion != -1) {
         printf(" maxSdkVersion='%d'", maxSdkVersion);
     }
@@ -390,11 +390,11 @@
 static void printUsesImpliedPermission(const String8& name, const String8& reason,
         const int32_t maxSdkVersion = -1) {
     printf("uses-implied-permission: name='%s'",
-            ResTable::normalizeForOutput(name.string()).string());
+            ResTable::normalizeForOutput(name.c_str()).c_str());
     if (maxSdkVersion != -1) {
         printf(" maxSdkVersion='%d'", maxSdkVersion);
     }
-    printf(" reason='%s'\n", ResTable::normalizeForOutput(reason.string()).string());
+    printf(" reason='%s'\n", ResTable::normalizeForOutput(reason.c_str()).c_str());
 }
 
 Vector<String8> getNfcAidCategories(AssetManager& assets, const String8& xmlPath, bool offHost,
@@ -556,7 +556,7 @@
 
 static void printFeatureGroupImpl(const FeatureGroup& grp,
                                   const KeyedVector<String8, ImpliedFeature>* impliedFeatures) {
-    printf("feature-group: label='%s'\n", grp.label.string());
+    printf("feature-group: label='%s'\n", grp.label.c_str());
 
     if (grp.openGLESVersion > 0) {
         printf("  uses-gl-es: '0x%x'\n", grp.openGLESVersion);
@@ -570,7 +570,7 @@
 
         const String8& featureName = grp.features.keyAt(i);
         printf("  uses-feature%s: name='%s'", (required ? "" : "-not-required"),
-                ResTable::normalizeForOutput(featureName.string()).string());
+                ResTable::normalizeForOutput(featureName.c_str()).c_str());
 
         if (version > 0) {
             printf(" version='%d'", version);
@@ -589,15 +589,15 @@
         }
 
         String8 printableFeatureName(ResTable::normalizeForOutput(
-                    impliedFeature.name.string()));
+                    impliedFeature.name.c_str()));
         const char* sdk23Suffix = impliedFeature.impliedBySdk23 ? "-sdk-23" : "";
 
-        printf("  uses-feature%s: name='%s'\n", sdk23Suffix, printableFeatureName.string());
+        printf("  uses-feature%s: name='%s'\n", sdk23Suffix, printableFeatureName.c_str());
         printf("  uses-implied-feature%s: name='%s' reason='", sdk23Suffix,
-               printableFeatureName.string());
+               printableFeatureName.c_str());
         const size_t numReasons = impliedFeature.reasons.size();
         for (size_t j = 0; j < numReasons; j++) {
-            printf("%s", impliedFeature.reasons[j].string());
+            printf("%s", impliedFeature.reasons[j].c_str());
             if (j + 2 < numReasons) {
                 printf(", ");
             } else if (j + 1 < numReasons) {
@@ -649,43 +649,43 @@
                                             bool impliedBySdk23Permission) {
     if (name == "android.permission.CAMERA") {
         addImpliedFeature(impliedFeatures, "android.hardware.camera",
-                          String8::format("requested %s permission", name.string()),
+                          String8::format("requested %s permission", name.c_str()),
                           impliedBySdk23Permission);
     } else if (name == "android.permission.ACCESS_FINE_LOCATION") {
         if (targetSdk < SDK_LOLLIPOP) {
             addImpliedFeature(impliedFeatures, "android.hardware.location.gps",
-                              String8::format("requested %s permission", name.string()),
+                              String8::format("requested %s permission", name.c_str()),
                               impliedBySdk23Permission);
             addImpliedFeature(impliedFeatures, "android.hardware.location.gps",
                               String8::format("targetSdkVersion < %d", SDK_LOLLIPOP),
                               impliedBySdk23Permission);
         }
         addImpliedFeature(impliedFeatures, "android.hardware.location",
-                String8::format("requested %s permission", name.string()),
+                String8::format("requested %s permission", name.c_str()),
                 impliedBySdk23Permission);
     } else if (name == "android.permission.ACCESS_COARSE_LOCATION") {
         if (targetSdk < SDK_LOLLIPOP) {
             addImpliedFeature(impliedFeatures, "android.hardware.location.network",
-                              String8::format("requested %s permission", name.string()),
+                              String8::format("requested %s permission", name.c_str()),
                               impliedBySdk23Permission);
             addImpliedFeature(impliedFeatures, "android.hardware.location.network",
                               String8::format("targetSdkVersion < %d", SDK_LOLLIPOP),
                               impliedBySdk23Permission);
         }
         addImpliedFeature(impliedFeatures, "android.hardware.location",
-                          String8::format("requested %s permission", name.string()),
+                          String8::format("requested %s permission", name.c_str()),
                           impliedBySdk23Permission);
     } else if (name == "android.permission.ACCESS_MOCK_LOCATION" ||
                name == "android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" ||
                name == "android.permission.INSTALL_LOCATION_PROVIDER") {
         addImpliedFeature(impliedFeatures, "android.hardware.location",
-                          String8::format("requested %s permission", name.string()),
+                          String8::format("requested %s permission", name.c_str()),
                           impliedBySdk23Permission);
     } else if (name == "android.permission.BLUETOOTH" ||
                name == "android.permission.BLUETOOTH_ADMIN") {
         if (targetSdk > SDK_DONUT) {
             addImpliedFeature(impliedFeatures, "android.hardware.bluetooth",
-                              String8::format("requested %s permission", name.string()),
+                              String8::format("requested %s permission", name.c_str()),
                               impliedBySdk23Permission);
             addImpliedFeature(impliedFeatures, "android.hardware.bluetooth",
                               String8::format("targetSdkVersion > %d", SDK_DONUT),
@@ -693,13 +693,13 @@
         }
     } else if (name == "android.permission.RECORD_AUDIO") {
         addImpliedFeature(impliedFeatures, "android.hardware.microphone",
-                          String8::format("requested %s permission", name.string()),
+                          String8::format("requested %s permission", name.c_str()),
                           impliedBySdk23Permission);
     } else if (name == "android.permission.ACCESS_WIFI_STATE" ||
                name == "android.permission.CHANGE_WIFI_STATE" ||
                name == "android.permission.CHANGE_WIFI_MULTICAST_STATE") {
         addImpliedFeature(impliedFeatures, "android.hardware.wifi",
-                          String8::format("requested %s permission", name.string()),
+                          String8::format("requested %s permission", name.c_str()),
                           impliedBySdk23Permission);
     } else if (name == "android.permission.CALL_PHONE" ||
                name == "android.permission.CALL_PRIVILEGED" ||
@@ -746,7 +746,7 @@
     for (size_t i = 0; i < bundle->getPackageIncludes().size(); i++) {
       const String8& assetPath = bundle->getPackageIncludes()[i];
       if (!assets.addAssetPath(assetPath, NULL)) {
-        fprintf(stderr, "ERROR: included asset path %s could not be loaded\n", assetPath.string());
+        fprintf(stderr, "ERROR: included asset path %s could not be loaded\n", assetPath.c_str());
         return 1;
       }
     }
@@ -890,7 +890,7 @@
                     goto bail;
                 }
                 String8 tag(ctag16);
-                //printf("Depth %d tag %s\n", depth, tag.string());
+                //printf("Depth %d tag %s\n", depth, tag.c_str());
                 if (depth == 1) {
                     if (tag != "manifest") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
@@ -898,14 +898,14 @@
                         goto bail;
                     }
                     String8 pkg = AaptXml::getAttribute(tree, NULL, "package", NULL);
-                    printf("package: %s\n", ResTable::normalizeForOutput(pkg.string()).string());
+                    printf("package: %s\n", ResTable::normalizeForOutput(pkg.c_str()).c_str());
                 } else if (depth == 2) {
                     if (tag == "permission") {
                         String8 error;
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name': %s", error.string());
+                                    "ERROR getting 'android:name': %s", error.c_str());
                             goto bail;
                         }
 
@@ -915,13 +915,13 @@
                             goto bail;
                         }
                         printf("permission: %s\n",
-                                ResTable::normalizeForOutput(name.string()).string());
+                                ResTable::normalizeForOutput(name.c_str()).c_str());
                     } else if (tag == "uses-permission") {
                         String8 error;
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
 
@@ -938,7 +938,7 @@
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
 
@@ -1138,7 +1138,7 @@
                             const size_t N = supportedInput.size();
                             for (size_t i=0; i<N; i++) {
                                 printf("%s", ResTable::normalizeForOutput(
-                                        supportedInput[i].string()).string());
+                                        supportedInput[i].c_str()).c_str());
                                 if (i != N - 1) {
                                     printf("' '");
                                 } else {
@@ -1157,27 +1157,27 @@
                                 printf("launchable-activity:");
                                 if (aName.length() > 0) {
                                     printf(" name='%s' ",
-                                            ResTable::normalizeForOutput(aName.string()).string());
+                                            ResTable::normalizeForOutput(aName.c_str()).c_str());
                                 }
                                 printf(" label='%s' icon='%s'\n",
-                                       ResTable::normalizeForOutput(activityLabel.string())
-                                                .string(),
-                                       ResTable::normalizeForOutput(activityIcon.string())
-                                                .string());
+                                       ResTable::normalizeForOutput(activityLabel.c_str())
+                                                .c_str(),
+                                       ResTable::normalizeForOutput(activityIcon.c_str())
+                                                .c_str());
                             }
                             if (isLeanbackLauncherActivity) {
                                 printf("leanback-launchable-activity:");
                                 if (aName.length() > 0) {
                                     printf(" name='%s' ",
-                                            ResTable::normalizeForOutput(aName.string()).string());
+                                            ResTable::normalizeForOutput(aName.c_str()).c_str());
                                 }
                                 printf(" label='%s' icon='%s' banner='%s'\n",
-                                       ResTable::normalizeForOutput(activityLabel.string())
-                                                .string(),
-                                       ResTable::normalizeForOutput(activityIcon.string())
-                                                .string(),
-                                       ResTable::normalizeForOutput(activityBanner.string())
-                                                .string());
+                                       ResTable::normalizeForOutput(activityLabel.c_str())
+                                                .c_str(),
+                                       ResTable::normalizeForOutput(activityIcon.c_str())
+                                                .c_str(),
+                                       ResTable::normalizeForOutput(activityBanner.c_str())
+                                                .c_str());
                             }
                         }
                         if (!hasIntentFilter) {
@@ -1265,7 +1265,7 @@
                     goto bail;
                 }
                 String8 tag(ctag16);
-                //printf("Depth %d,  %s\n", depth, tag.string());
+                //printf("Depth %d,  %s\n", depth, tag.c_str());
                 if (depth == 1) {
                     if (tag != "manifest") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
@@ -1274,13 +1274,13 @@
                     }
                     pkg = AaptXml::getAttribute(tree, NULL, "package", NULL);
                     printf("package: name='%s' ",
-                            ResTable::normalizeForOutput(pkg.string()).string());
+                            ResTable::normalizeForOutput(pkg.c_str()).c_str());
                     int32_t versionCode = AaptXml::getIntegerAttribute(tree, VERSION_CODE_ATTR,
                             &error);
                     if (error != "") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
                                 "ERROR getting 'android:versionCode' attribute: %s",
-                                error.string());
+                                error.c_str());
                         goto bail;
                     }
                     if (versionCode > 0) {
@@ -1293,16 +1293,16 @@
                     if (error != "") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
                                 "ERROR getting 'android:versionName' attribute: %s",
-                                error.string());
+                                error.c_str());
                         goto bail;
                     }
                     printf("versionName='%s'",
-                            ResTable::normalizeForOutput(versionName.string()).string());
+                            ResTable::normalizeForOutput(versionName.c_str()).c_str());
 
                     String8 splitName = AaptXml::getAttribute(tree, NULL, "split");
                     if (!splitName.isEmpty()) {
                         printf(" split='%s'", ResTable::normalizeForOutput(
-                                    splitName.string()).string());
+                                    splitName.c_str()).c_str());
                     }
 
                     // For 'platformBuildVersionName', using both string and int type as a fallback
@@ -1313,7 +1313,7 @@
                             AaptXml::getIntegerAttribute(tree, NULL, "platformBuildVersionName", 0,
                                                          NULL);
                     if (platformBuildVersionName != "") {
-                        printf(" platformBuildVersionName='%s'", platformBuildVersionName.string());
+                        printf(" platformBuildVersionName='%s'", platformBuildVersionName.c_str());
                     } else if (platformBuildVersionNameInt > 0) {
                         printf(" platformBuildVersionName='%d'", platformBuildVersionNameInt);
                     }
@@ -1326,7 +1326,7 @@
                             AaptXml::getIntegerAttribute(tree, NULL, "platformBuildVersionCode", 0,
                                                          NULL);
                     if (platformBuildVersionCode != "") {
-                        printf(" platformBuildVersionCode='%s'", platformBuildVersionCode.string());
+                        printf(" platformBuildVersionCode='%s'", platformBuildVersionCode.c_str());
                     } else if (platformBuildVersionCodeInt > 0) {
                         printf(" platformBuildVersionCode='%d'", platformBuildVersionCodeInt);
                     }
@@ -1336,7 +1336,7 @@
                     if (error != "") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
                                 "ERROR getting 'android:compileSdkVersion' attribute: %s",
-                                error.string());
+                                error.c_str());
                         goto bail;
                     }
                     if (compileSdkVersion > 0) {
@@ -1347,7 +1347,7 @@
                             COMPILE_SDK_VERSION_CODENAME_ATTR, &error);
                     if (compileSdkVersionCodename != "") {
                         printf(" compileSdkVersionCodename='%s'", ResTable::normalizeForOutput(
-                                compileSdkVersionCodename.string()).string());
+                                compileSdkVersionCodename.c_str()).c_str());
                     }
 
                     printf("\n");
@@ -1357,7 +1357,7 @@
                     if (error != "") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
                                 "ERROR getting 'android:installLocation' attribute: %s",
-                                error.string());
+                                error.c_str());
                         goto bail;
                     }
 
@@ -1387,7 +1387,7 @@
                         String8 label;
                         const size_t NL = locales.size();
                         for (size_t i=0; i<NL; i++) {
-                            const char* localeStr =  locales[i].string();
+                            const char* localeStr =  locales[i].c_str();
                             assets.setConfiguration(config, localeStr != NULL ? localeStr : "");
                             String8 llabel = AaptXml::getResolvedAttribute(res, tree, LABEL_ATTR,
                                     &error);
@@ -1395,13 +1395,13 @@
                                 if (localeStr == NULL || strlen(localeStr) == 0) {
                                     label = llabel;
                                     printf("application-label:'%s'\n",
-                                            ResTable::normalizeForOutput(llabel.string()).string());
+                                            ResTable::normalizeForOutput(llabel.c_str()).c_str());
                                 } else {
                                     if (label == "") {
                                         label = llabel;
                                     }
                                     printf("application-label-%s:'%s'\n", localeStr,
-                                           ResTable::normalizeForOutput(llabel.string()).string());
+                                           ResTable::normalizeForOutput(llabel.c_str()).c_str());
                                 }
                             }
                         }
@@ -1415,7 +1415,7 @@
                                     &error);
                             if (icon != "") {
                                 printf("application-icon-%d:'%s'\n", densities[i],
-                                        ResTable::normalizeForOutput(icon.string()).string());
+                                        ResTable::normalizeForOutput(icon.c_str()).c_str());
                             }
                         }
                         assets.setConfiguration(config);
@@ -1423,7 +1423,7 @@
                         String8 icon = AaptXml::getResolvedAttribute(res, tree, ICON_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:icon' attribute: %s", error.string());
+                                    "ERROR getting 'android:icon' attribute: %s", error.c_str());
                             goto bail;
                         }
                         int32_t testOnly = AaptXml::getIntegerAttribute(tree, TEST_ONLY_ATTR, 0,
@@ -1431,7 +1431,7 @@
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
                                     "ERROR getting 'android:testOnly' attribute: %s",
-                                    error.string());
+                                    error.c_str());
                             goto bail;
                         }
 
@@ -1439,15 +1439,15 @@
                                                                        &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:banner' attribute: %s", error.string());
+                                    "ERROR getting 'android:banner' attribute: %s", error.c_str());
                             goto bail;
                         }
                         printf("application: label='%s' ",
-                                ResTable::normalizeForOutput(label.string()).string());
-                        printf("icon='%s'", ResTable::normalizeForOutput(icon.string()).string());
+                                ResTable::normalizeForOutput(label.c_str()).c_str());
+                        printf("icon='%s'", ResTable::normalizeForOutput(icon.c_str()).c_str());
                         if (banner != "") {
                             printf(" banner='%s'",
-                                   ResTable::normalizeForOutput(banner.string()).string());
+                                   ResTable::normalizeForOutput(banner.c_str()).c_str());
                         }
                         printf("\n");
                         if (testOnly != 0) {
@@ -1458,7 +1458,7 @@
                                 ISGAME_ATTR, 0, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:isGame' attribute: %s", error.string());
+                                    "ERROR getting 'android:isGame' attribute: %s", error.c_str());
                             goto bail;
                         }
                         if (isGame != 0) {
@@ -1470,7 +1470,7 @@
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
                                     "ERROR getting 'android:debuggable' attribute: %s",
-                                    error.string());
+                                    error.c_str());
                             goto bail;
                         }
                         if (debuggable != 0) {
@@ -1500,12 +1500,12 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:minSdkVersion' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
                             if (name == "Donut") targetSdk = SDK_DONUT;
                             printf("sdkVersion:'%s'\n",
-                                    ResTable::normalizeForOutput(name.string()).string());
+                                    ResTable::normalizeForOutput(name.c_str()).c_str());
                         } else if (code != -1) {
                             targetSdk = code;
                             printf("sdkVersion:'%d'\n", code);
@@ -1522,7 +1522,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:targetSdkVersion' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
                             if (name == "Donut" && targetSdk < SDK_DONUT) {
@@ -1532,7 +1532,7 @@
                                 targetSdk = SDK_CUR_DEVELOPMENT;
                             }
                             printf("targetSdkVersion:'%s'\n",
-                                    ResTable::normalizeForOutput(name.string()).string());
+                                    ResTable::normalizeForOutput(name.c_str()).c_str());
                         } else if (code != -1) {
                             if (targetSdk < code) {
                                 targetSdk = code;
@@ -1592,7 +1592,7 @@
                         group.label = AaptXml::getResolvedAttribute(res, tree, LABEL_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:label' attribute: %s", error.string());
+                                    "ERROR getting 'android:label' attribute: %s", error.c_str());
                             goto bail;
                         }
                         featureGroups.add(group);
@@ -1608,7 +1608,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "failed to read attribute 'android:required': %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1617,7 +1617,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "failed to read attribute 'android:version': %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1638,7 +1638,7 @@
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
 
@@ -1682,7 +1682,7 @@
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
 
@@ -1701,37 +1701,37 @@
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (name != "" && error == "") {
                             printf("uses-package:'%s'\n",
-                                    ResTable::normalizeForOutput(name.string()).string());
+                                    ResTable::normalizeForOutput(name.c_str()).c_str());
                         } else {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
                     } else if (tag == "original-package") {
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (name != "" && error == "") {
                             printf("original-package:'%s'\n",
-                                    ResTable::normalizeForOutput(name.string()).string());
+                                    ResTable::normalizeForOutput(name.c_str()).c_str());
                         } else {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
                     } else if (tag == "supports-gl-texture") {
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (name != "" && error == "") {
                             printf("supports-gl-texture:'%s'\n",
-                                    ResTable::normalizeForOutput(name.string()).string());
+                                    ResTable::normalizeForOutput(name.c_str()).c_str());
                         } else {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
                     } else if (tag == "compatible-screens") {
                         printCompatibleScreens(tree, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting compatible screens: %s", error.string());
+                                    "ERROR getting compatible screens: %s", error.c_str());
                             goto bail;
                         }
                         depth--;
@@ -1742,8 +1742,8 @@
                                                                       &error);
                             if (publicKey != "" && error == "") {
                                 printf("package-verifier: name='%s' publicKey='%s'\n",
-                                        ResTable::normalizeForOutput(name.string()).string(),
-                                        ResTable::normalizeForOutput(publicKey.string()).string());
+                                        ResTable::normalizeForOutput(name.c_str()).c_str(),
+                                        ResTable::normalizeForOutput(publicKey.c_str()).c_str());
                             }
                         }
                     }
@@ -1769,7 +1769,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1778,7 +1778,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:label' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1787,7 +1787,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:icon' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1796,7 +1796,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:banner' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1824,14 +1824,14 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute for uses-library"
-                                        " %s", error.string());
+                                        " %s", error.c_str());
                                 goto bail;
                             }
                             int req = AaptXml::getIntegerAttribute(tree,
                                     REQUIRED_ATTR, 1);
                             printf("uses-library%s:'%s'\n",
                                     req ? "" : "-not-required", ResTable::normalizeForOutput(
-                                            libraryName.string()).string());
+                                            libraryName.c_str()).c_str());
                         } else if (tag == "receiver") {
                             withinReceiver = true;
                             receiverName = AaptXml::getAttribute(tree, NAME_ATTR, &error);
@@ -1839,7 +1839,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute for receiver:"
-                                        " %s", error.string());
+                                        " %s", error.c_str());
                                 goto bail;
                             }
 
@@ -1853,7 +1853,7 @@
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:permission' attribute for"
                                         " receiver '%s': %s",
-                                        receiverName.string(), error.string());
+                                        receiverName.c_str(), error.c_str());
                             }
                         } else if (tag == "service") {
                             withinService = true;
@@ -1862,7 +1862,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute for "
-                                        "service:%s", error.string());
+                                        "service:%s", error.c_str());
                                 goto bail;
                             }
 
@@ -1887,7 +1887,7 @@
                             } else {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:permission' attribute for "
-                                        "service '%s': %s", serviceName.string(), error.string());
+                                        "service '%s': %s", serviceName.c_str(), error.c_str());
                             }
                         } else if (tag == "provider") {
                             withinProvider = true;
@@ -1897,7 +1897,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:exported' attribute for provider:"
-                                        " %s", error.string());
+                                        " %s", error.c_str());
                                 goto bail;
                             }
 
@@ -1906,7 +1906,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:grantUriPermissions' attribute for "
-                                        "provider: %s", error.string());
+                                        "provider: %s", error.c_str());
                                 goto bail;
                             }
 
@@ -1915,7 +1915,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:permission' attribute for "
-                                        "provider: %s", error.string());
+                                        "provider: %s", error.c_str());
                                 goto bail;
                             }
 
@@ -1928,11 +1928,11 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute for "
-                                        "meta-data: %s", error.string());
+                                        "meta-data: %s", error.c_str());
                                 goto bail;
                             }
                             printf("meta-data: name='%s' ",
-                                    ResTable::normalizeForOutput(metaDataName.string()).string());
+                                    ResTable::normalizeForOutput(metaDataName.c_str()).c_str());
                             printResolvedResourceAttribute(res, tree, VALUE_ATTR, String8("value"),
                                     &error);
                             if (error != "") {
@@ -1944,7 +1944,7 @@
                                     SourcePos(manifestFile, tree.getLineNumber()).error(
                                             "ERROR getting 'android:value' or "
                                             "'android:resource' attribute for "
-                                            "meta-data: %s", error.string());
+                                            "meta-data: %s", error.c_str());
                                     goto bail;
                                 }
                             }
@@ -1956,7 +1956,7 @@
                             } else {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
                         }
@@ -1969,13 +1969,13 @@
                             Feature feature(true);
 
                             int32_t featureVers = AaptXml::getIntegerAttribute(
-                                    tree, androidSchema.string(), "version", 0, &error);
+                                    tree, androidSchema.c_str(), "version", 0, &error);
                             if (error == "") {
                                 feature.version = featureVers;
                             } else {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "failed to read attribute 'android:version': %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -2016,8 +2016,8 @@
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
                                     "ERROR getting 'android:name' attribute for "
-                                    "meta-data tag in service '%s': %s", serviceName.string(),
-                                    error.string());
+                                    "meta-data tag in service '%s': %s", serviceName.c_str(),
+                                    error.c_str());
                             goto bail;
                         }
 
@@ -2034,7 +2034,7 @@
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:resource' attribute for "
                                         "meta-data tag in service '%s': %s",
-                                        serviceName.string(), error.string());
+                                        serviceName.c_str(), error.c_str());
                                 goto bail;
                             }
 
@@ -2043,7 +2043,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting AID category for service '%s'",
-                                        serviceName.string());
+                                        serviceName.c_str());
                                 goto bail;
                             }
 
@@ -2064,7 +2064,7 @@
                         action = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
 
@@ -2120,7 +2120,7 @@
                         String8 category = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'name' attribute: %s", error.string());
+                                    "ERROR getting 'name' attribute: %s", error.c_str());
                             goto bail;
                         }
                         if (withinActivity) {
@@ -2352,7 +2352,7 @@
             printf("locales:");
             const size_t NL = locales.size();
             for (size_t i=0; i<NL; i++) {
-                const char* localeStr =  locales[i].string();
+                const char* localeStr =  locales[i].c_str();
                 if (localeStr == NULL || strlen(localeStr) == 0) {
                     localeStr = "--_--";
                 }
@@ -2373,7 +2373,7 @@
                     SortedVector<String8> architectures;
                     for (size_t i=0; i<dir->getFileCount(); i++) {
                         architectures.add(ResTable::normalizeForOutput(
-                                dir->getFileName(i).string()));
+                                dir->getFileName(i).c_str()));
                     }
 
                     bool outputAltNativeCode = false;
@@ -2401,7 +2401,7 @@
                         }
 
                         if (index >= 0) {
-                            printf("native-code: '%s'\n", architectures[index].string());
+                            printf("native-code: '%s'\n", architectures[index].c_str());
                             architectures.removeAt(index);
                             outputAltNativeCode = true;
                         }
@@ -2414,7 +2414,7 @@
                         }
                         printf("native-code:");
                         for (size_t i = 0; i < archCount; i++) {
-                            printf(" '%s'", architectures[i].string());
+                            printf(" '%s'", architectures[i].c_str());
                         }
                         printf("\n");
                     }
@@ -2428,7 +2428,7 @@
             res.getConfigurations(&configs);
             const size_t N = configs.size();
             for (size_t i=0; i<N; i++) {
-                printf("%s\n", configs[i].toString().string());
+                printf("%s\n", configs[i].toString().c_str());
             }
         } else {
             fprintf(stderr, "ERROR: unknown dump option '%s'\n", option);
@@ -2486,15 +2486,15 @@
     for (int i = 1; i < bundle->getFileSpecCount(); i++) {
         const char* fileName = bundle->getFileSpecEntry(i);
 
-        if (strcasecmp(String8(fileName).getPathExtension().string(), ".gz") == 0) {
+        if (strcasecmp(String8(fileName).getPathExtension().c_str(), ".gz") == 0) {
             printf(" '%s'... (from gzip)\n", fileName);
-            result = zip->addGzip(fileName, String8(fileName).getBasePath().string(), NULL);
+            result = zip->addGzip(fileName, String8(fileName).getBasePath().c_str(), NULL);
         } else {
             if (bundle->getJunkPath()) {
                 String8 storageName = String8(fileName).getPathLeaf();
                 printf(" '%s' as '%s'...\n", fileName,
-                        ResTable::normalizeForOutput(storageName.string()).string());
-                result = zip->add(fileName, storageName.string(),
+                        ResTable::normalizeForOutput(storageName.c_str()).c_str());
+                result = zip->add(fileName, storageName.c_str(),
                                   bundle->getCompressionMethod(), NULL);
             } else {
                 printf(" '%s'...\n", fileName);
@@ -2581,7 +2581,7 @@
     for (size_t i = 0; i < numDirs; i++) {
         bool ignore = ignoreConfig;
         const sp<AaptDir>& subDir = dir->getDirs().valueAt(i);
-        const char* dirStr = subDir->getLeaf().string();
+        const char* dirStr = subDir->getLeaf().c_str();
         if (!ignore && strstr(dirStr, "mipmap") == dirStr) {
             ignore = true;
         }
@@ -2604,7 +2604,7 @@
             }
             if (err != NO_ERROR) {
                 fprintf(stderr, "Failed to add %s (%s) to builder.\n",
-                        gp->getPath().string(), gp->getFiles()[j]->getPrintableSource().string());
+                        gp->getPath().c_str(), gp->getFiles()[j]->getPrintableSource().c_str());
                 return err;
             }
         }
@@ -2620,13 +2620,13 @@
     String8 ext(original.getPathExtension());
     if (ext == String8(".apk")) {
         return String8::format("%s_%s%s",
-                original.getBasePath().string(),
-                split->getDirectorySafeName().string(),
-                ext.string());
+                original.getBasePath().c_str(),
+                split->getDirectorySafeName().c_str(),
+                ext.c_str());
     }
 
-    return String8::format("%s_%s", original.string(),
-            split->getDirectorySafeName().string());
+    return String8::format("%s_%s", original.c_str(),
+            split->getDirectorySafeName().c_str());
 }
 
 /*
@@ -2712,7 +2712,7 @@
         for (size_t i = 0; i < numSplits; i++) {
             std::set<ConfigDescription> configs;
             if (!AaptConfig::parseCommaSeparatedList(splitStrs[i], &configs)) {
-                fprintf(stderr, "ERROR: failed to parse split configuration '%s'\n", splitStrs[i].string());
+                fprintf(stderr, "ERROR: failed to parse split configuration '%s'\n", splitStrs[i].c_str());
                 goto bail;
             }
 
@@ -2835,7 +2835,7 @@
             String8 outputPath = buildApkName(String8(outputAPKFile), split);
             err = writeAPK(bundle, outputPath, split);
             if (err != NO_ERROR) {
-                fprintf(stderr, "ERROR: packaging of '%s' failed\n", outputPath.string());
+                fprintf(stderr, "ERROR: packaging of '%s' failed\n", outputPath.c_str());
                 goto bail;
             }
         }
diff --git a/tools/aapt/CrunchCache.cpp b/tools/aapt/CrunchCache.cpp
index 7b8a576..1f2febe 100644
--- a/tools/aapt/CrunchCache.cpp
+++ b/tools/aapt/CrunchCache.cpp
@@ -44,7 +44,7 @@
         // This efficiently strips the source directory prefix from our path.
         // Also, String8 doesn't have a substring method so this is what we've
         // got to work with.
-        const char* rPathPtr = mSourceFiles.keyAt(0).string()+mSourcePath.length();
+        const char* rPathPtr = mSourceFiles.keyAt(0).c_str()+mSourcePath.length();
         // Strip leading slash if present
         int offset = 0;
         if (rPathPtr[0] == OS_PATH_SEPARATOR)
diff --git a/tools/aapt/DirectoryWalker.h b/tools/aapt/DirectoryWalker.h
index 88031d0..cea3a6e 100644
--- a/tools/aapt/DirectoryWalker.h
+++ b/tools/aapt/DirectoryWalker.h
@@ -57,7 +57,7 @@
     virtual bool openDir(String8 path) {
         mBasePath = path;
         dir = NULL;
-        dir = opendir(mBasePath.string() );
+        dir = opendir(mBasePath.c_str() );
 
         if (dir == NULL)
             return false;
@@ -78,7 +78,7 @@
         mEntry = *entryPtr;
         // Get stats
         String8 fullPath = mBasePath.appendPathCopy(mEntry.d_name);
-        stat(fullPath.string(),&mStats);
+        stat(fullPath.c_str(),&mStats);
         return &mEntry;
     };
     // Get the stats for the current entry
diff --git a/tools/aapt/FileFinder.cpp b/tools/aapt/FileFinder.cpp
index c9d0744..a5c19806 100644
--- a/tools/aapt/FileFinder.cpp
+++ b/tools/aapt/FileFinder.cpp
@@ -59,14 +59,14 @@
 
         String8 fullPath = basePath.appendPathCopy(entryName);
         // If this entry is a directory we'll recurse into it
-        if (isDirectory(fullPath.string()) ) {
+        if (isDirectory(fullPath.c_str()) ) {
             DirectoryWalker* copy = dw->clone();
             findFiles(fullPath, extensions, fileStore,copy);
             delete copy;
         }
 
         // If this entry is a file, we'll pass it over to checkAndAddFile
-        if (isFile(fullPath.string()) ) {
+        if (isFile(fullPath.c_str()) ) {
             checkAndAddFile(fullPath,dw->entryStats(),extensions,fileStore);
         }
     }
diff --git a/tools/aapt/Images.cpp b/tools/aapt/Images.cpp
index 627a231..c6c7e96 100644
--- a/tools/aapt/Images.cpp
+++ b/tools/aapt/Images.cpp
@@ -1328,13 +1328,13 @@
 
     png_init_io(read_ptr, fp);
 
-    read_png(printableName.string(), read_ptr, read_info, imageInfo);
+    read_png(printableName.c_str(), read_ptr, read_info, imageInfo);
 
     const size_t nameLen = file->getPath().length();
     if (nameLen > 6) {
-        const char* name = file->getPath().string();
+        const char* name = file->getPath().c_str();
         if (name[nameLen-5] == '9' && name[nameLen-6] == '.') {
-            if (do_9patch(printableName.string(), imageInfo) != NO_ERROR) {
+            if (do_9patch(printableName.c_str(), imageInfo) != NO_ERROR) {
                 return false;
             }
         }
@@ -1349,7 +1349,7 @@
         return false;
     }
 
-    write_png(printableName.string(), write_ptr, write_info, *imageInfo, bundle);
+    write_png(printableName.c_str(), write_ptr, write_info, *imageInfo, bundle);
 
     return true;
 }
@@ -1360,7 +1360,7 @@
     String8 ext(file->getPath().getPathExtension());
 
     // We currently only process PNG images.
-    if (strcmp(ext.string(), ".png") != 0) {
+    if (strcmp(ext.c_str(), ".png") != 0) {
         return NO_ERROR;
     }
 
@@ -1371,7 +1371,7 @@
     String8 printableName(file->getPrintableSource());
 
     if (bundle->getVerbose()) {
-        printf("Processing image: %s\n", printableName.string());
+        printf("Processing image: %s\n", printableName.c_str());
     }
 
     png_structp read_ptr = NULL;
@@ -1385,9 +1385,9 @@
 
     status_t error = UNKNOWN_ERROR;
 
-    fp = fopen(file->getSourceFile().string(), "rb");
+    fp = fopen(file->getSourceFile().c_str(), "rb");
     if (fp == NULL) {
-        fprintf(stderr, "%s: ERROR: Unable to open PNG file\n", printableName.string());
+        fprintf(stderr, "%s: ERROR: Unable to open PNG file\n", printableName.c_str());
         goto bail;
     }
 
@@ -1434,7 +1434,7 @@
         size_t newSize = file->getSize();
         float factor = ((float)newSize)/oldSize;
         int percent = (int)(factor*100);
-        printf("    (processed image %s: %d%% size of source)\n", printableName.string(), percent);
+        printf("    (processed image %s: %d%% size of source)\n", printableName.c_str(), percent);
     }
 
 bail:
@@ -1450,7 +1450,7 @@
 
     if (error != NO_ERROR) {
         fprintf(stderr, "ERROR: Failure processing PNG image %s\n",
-                file->getPrintableSource().string());
+                file->getPrintableSource().c_str());
     }
     return error;
 }
@@ -1470,13 +1470,13 @@
     status_t error = UNKNOWN_ERROR;
 
     if (bundle->getVerbose()) {
-        printf("Processing image to cache: %s => %s\n", source.string(), dest.string());
+        printf("Processing image to cache: %s => %s\n", source.c_str(), dest.c_str());
     }
 
     // Get a file handler to read from
-    fp = fopen(source.string(),"rb");
+    fp = fopen(source.c_str(),"rb");
     if (fp == NULL) {
-        fprintf(stderr, "%s ERROR: Unable to open PNG file\n", source.string());
+        fprintf(stderr, "%s ERROR: Unable to open PNG file\n", source.c_str());
         return error;
     }
 
@@ -1507,7 +1507,7 @@
     png_init_io(read_ptr,fp);
 
     // Actually read data from the file
-    read_png(source.string(), read_ptr, read_info, &imageInfo);
+    read_png(source.c_str(), read_ptr, read_info, &imageInfo);
 
     // We're done reading so we can clean up
     // Find old file size before releasing handle
@@ -1519,7 +1519,7 @@
     // Check to see if we're dealing with a 9-patch
     // If we are, process appropriately
     if (source.getBasePath().getPathExtension() == ".9")  {
-        if (do_9patch(source.string(), &imageInfo) != NO_ERROR) {
+        if (do_9patch(source.c_str(), &imageInfo) != NO_ERROR) {
             return error;
         }
     }
@@ -1541,9 +1541,9 @@
     }
 
     // Open up our destination file for writing
-    fp = fopen(dest.string(), "wb");
+    fp = fopen(dest.c_str(), "wb");
     if (!fp) {
-        fprintf(stderr, "%s ERROR: Unable to open PNG file\n", dest.string());
+        fprintf(stderr, "%s ERROR: Unable to open PNG file\n", dest.c_str());
         png_destroy_write_struct(&write_ptr, &write_info);
         return error;
     }
@@ -1559,11 +1559,11 @@
     }
 
     // Actually write out to the new png
-    write_png(dest.string(), write_ptr, write_info, imageInfo, bundle);
+    write_png(dest.c_str(), write_ptr, write_info, imageInfo, bundle);
 
     if (bundle->getVerbose()) {
         // Find the size of our new file
-        FILE* reader = fopen(dest.string(), "rb");
+        FILE* reader = fopen(dest.c_str(), "rb");
         fseek(reader, 0, SEEK_END);
         size_t newSize = (size_t)ftell(reader);
         fclose(reader);
@@ -1571,7 +1571,7 @@
         float factor = ((float)newSize)/oldSize;
         int percent = (int)(factor*100);
         printf("  (processed image to cache entry %s: %d%% size of source)\n",
-               dest.string(), percent);
+               dest.c_str(), percent);
     }
 
     //Clean up
@@ -1588,7 +1588,7 @@
 
     // At this point, now that we have all the resource data, all we need to
     // do is compile XML files.
-    if (strcmp(ext.string(), ".xml") == 0) {
+    if (strcmp(ext.c_str(), ".xml") == 0) {
         String16 resourceName(parseResourceName(file->getSourceFile().getPathLeaf()));
         return compileXmlFile(bundle, assets, resourceName, file, table);
     }
diff --git a/tools/aapt/Package.cpp b/tools/aapt/Package.cpp
index f06643dc..965655b 100644
--- a/tools/aapt/Package.cpp
+++ b/tools/aapt/Package.cpp
@@ -69,39 +69,39 @@
      * If "update" is set, update the contents of the existing archive.
      * Else, if "force" is set, remove the existing archive.
      */
-    FileType fileType = getFileType(outputFile.string());
+    FileType fileType = getFileType(outputFile.c_str());
     if (fileType == kFileTypeNonexistent) {
         // okay, create it below
     } else if (fileType == kFileTypeRegular) {
         if (bundle->getUpdate()) {
             // okay, open it below
         } else if (bundle->getForce()) {
-            if (unlink(outputFile.string()) != 0) {
-                fprintf(stderr, "ERROR: unable to remove '%s': %s\n", outputFile.string(),
+            if (unlink(outputFile.c_str()) != 0) {
+                fprintf(stderr, "ERROR: unable to remove '%s': %s\n", outputFile.c_str(),
                         strerror(errno));
                 goto bail;
             }
         } else {
             fprintf(stderr, "ERROR: '%s' exists (use '-f' to force overwrite)\n",
-                    outputFile.string());
+                    outputFile.c_str());
             goto bail;
         }
     } else {
-        fprintf(stderr, "ERROR: '%s' exists and is not a regular file\n", outputFile.string());
+        fprintf(stderr, "ERROR: '%s' exists and is not a regular file\n", outputFile.c_str());
         goto bail;
     }
 
     if (bundle->getVerbose()) {
         printf("%s '%s'\n", (fileType == kFileTypeNonexistent) ? "Creating" : "Opening",
-                outputFile.string());
+                outputFile.c_str());
     }
 
     status_t status;
     zip = new ZipFile;
-    status = zip->open(outputFile.string(), ZipFile::kOpenReadWrite | ZipFile::kOpenCreate);
+    status = zip->open(outputFile.c_str(), ZipFile::kOpenReadWrite | ZipFile::kOpenCreate);
     if (status != NO_ERROR) {
         fprintf(stderr, "ERROR: unable to open '%s' as Zip file for writing\n",
-                outputFile.string());
+                outputFile.c_str());
         goto bail;
     }
 
@@ -112,7 +112,7 @@
     count = processAssets(bundle, zip, outputSet);
     if (count < 0) {
         fprintf(stderr, "ERROR: unable to process assets while packaging '%s'\n",
-                outputFile.string());
+                outputFile.c_str());
         result = count;
         goto bail;
     }
@@ -124,7 +124,7 @@
     count = processJarFiles(bundle, zip);
     if (count < 0) {
         fprintf(stderr, "ERROR: unable to process jar files while packaging '%s'\n",
-                outputFile.string());
+                outputFile.c_str());
         result = count;
         goto bail;
     }
@@ -169,12 +169,12 @@
     /* anything here? */
     if (zip->getNumEntries() == 0) {
         if (bundle->getVerbose()) {
-            printf("Archive is empty -- removing %s\n", outputFile.getPathLeaf().string());
+            printf("Archive is empty -- removing %s\n", outputFile.getPathLeaf().c_str());
         }
         delete zip;        // close the file so we can remove it in Win32
         zip = NULL;
-        if (unlink(outputFile.string()) != 0) {
-            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.string());
+        if (unlink(outputFile.c_str()) != 0) {
+            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.c_str());
         }
     }
 
@@ -187,9 +187,9 @@
         String8 dependencyFile = outputFile;
         dependencyFile.append(".d");
 
-        FILE* fp = fopen(dependencyFile.string(), "a");
+        FILE* fp = fopen(dependencyFile.c_str(), "a");
         // Add this file to the dependency file
-        fprintf(fp, "%s \\\n", outputFile.string());
+        fprintf(fp, "%s \\\n", outputFile.c_str());
         fclose(fp);
     }
 
@@ -199,10 +199,10 @@
     delete zip;        // must close before remove in Win32
     if (result != NO_ERROR) {
         if (bundle->getVerbose()) {
-            printf("Removing %s due to earlier failures\n", outputFile.string());
+            printf("Removing %s due to earlier failures\n", outputFile.c_str());
         }
-        if (unlink(outputFile.string()) != 0) {
-            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.string());
+        if (unlink(outputFile.c_str()) != 0) {
+            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.c_str());
         }
     }
 
@@ -267,31 +267,31 @@
     int fileNameLen = storageName.length();
     int excludeExtensionLen = strlen(kExcludeExtension);
     if (fileNameLen > excludeExtensionLen
-            && (0 == strcmp(storageName.string() + (fileNameLen - excludeExtensionLen),
+            && (0 == strcmp(storageName.c_str() + (fileNameLen - excludeExtensionLen),
                             kExcludeExtension))) {
-        fprintf(stderr, "warning: '%s' not added to Zip\n", storageName.string());
+        fprintf(stderr, "warning: '%s' not added to Zip\n", storageName.c_str());
         return true;
     }
 
-    if (strcasecmp(storageName.getPathExtension().string(), ".gz") == 0) {
+    if (strcasecmp(storageName.getPathExtension().c_str(), ".gz") == 0) {
         fromGzip = true;
         storageName = storageName.getBasePath();
     }
 
     if (bundle->getUpdate()) {
-        entry = zip->getEntryByName(storageName.string());
+        entry = zip->getEntryByName(storageName.c_str());
         if (entry != NULL) {
             /* file already exists in archive; there can be only one */
             if (entry->getMarked()) {
                 fprintf(stderr,
                         "ERROR: '%s' exists twice (check for with & w/o '.gz'?)\n",
-                        file->getPrintableSource().string());
+                        file->getPrintableSource().c_str());
                 return false;
             }
             if (!hasData) {
                 const String8& srcName = file->getSourceFile();
                 time_t fileModWhen;
-                fileModWhen = getFileModDate(srcName.string());
+                fileModWhen = getFileModDate(srcName.c_str());
                 if (fileModWhen == (time_t) -1) { // file existence tested earlier,
                     return false;                 //  not expecting an error here
                 }
@@ -299,14 +299,14 @@
                 if (fileModWhen > entry->getModWhen()) {
                     // mark as deleted so add() will succeed
                     if (bundle->getVerbose()) {
-                        printf("      (removing old '%s')\n", storageName.string());
+                        printf("      (removing old '%s')\n", storageName.c_str());
                     }
     
                     zip->remove(entry);
                 } else {
                     // version in archive is newer
                     if (bundle->getVerbose()) {
-                        printf("      (not updating '%s')\n", storageName.string());
+                        printf("      (not updating '%s')\n", storageName.c_str());
                     }
                     entry->setMarked(true);
                     return true;
@@ -321,22 +321,22 @@
     //android_setMinPriority(NULL, ANDROID_LOG_VERBOSE);
 
     if (fromGzip) {
-        result = zip->addGzip(file->getSourceFile().string(), storageName.string(), &entry);
+        result = zip->addGzip(file->getSourceFile().c_str(), storageName.c_str(), &entry);
     } else if (!hasData) {
         /* don't compress certain files, e.g. PNGs */
         int compressionMethod = bundle->getCompressionMethod();
         if (!okayToCompress(bundle, storageName)) {
             compressionMethod = ZipEntry::kCompressStored;
         }
-        result = zip->add(file->getSourceFile().string(), storageName.string(), compressionMethod,
+        result = zip->add(file->getSourceFile().c_str(), storageName.c_str(), compressionMethod,
                             &entry);
     } else {
-        result = zip->add(file->getData(), file->getSize(), storageName.string(),
+        result = zip->add(file->getData(), file->getSize(), storageName.c_str(),
                            file->getCompressionMethod(), &entry);
     }
     if (result == NO_ERROR) {
         if (bundle->getVerbose()) {
-            printf("      '%s'%s", storageName.string(), fromGzip ? " (from .gz)" : "");
+            printf("      '%s'%s", storageName.c_str(), fromGzip ? " (from .gz)" : "");
             if (entry->getCompressionMethod() == ZipEntry::kCompressStored) {
                 printf(" (not compressed)\n");
             } else {
@@ -348,10 +348,10 @@
     } else {
         if (result == ALREADY_EXISTS) {
             fprintf(stderr, "      Unable to add '%s': file already in archive (try '-u'?)\n",
-                    file->getPrintableSource().string());
+                    file->getPrintableSource().c_str());
         } else {
             fprintf(stderr, "      Unable to add '%s': Zip add failed (%d)\n",
-                    file->getPrintableSource().string(), result);
+                    file->getPrintableSource().c_str(), result);
         }
         return false;
     }
@@ -372,7 +372,7 @@
         return true;
 
     for (i = 0; i < NELEM(kNoCompressExt); i++) {
-        if (strcasecmp(ext.string(), kNoCompressExt[i]) == 0)
+        if (strcasecmp(ext.c_str(), kNoCompressExt[i]) == 0)
             return false;
     }
 
@@ -383,7 +383,7 @@
         if (pos < 0) {
             continue;
         }
-        const char* path = pathName.string();
+        const char* path = pathName.c_str();
         if (strcasecmp(path + pos, str) == 0) {
             return false;
         }
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index dd3ebdb..4ca3a68 100644
--- a/tools/aapt/Resource.cpp
+++ b/tools/aapt/Resource.cpp
@@ -57,8 +57,8 @@
 
 String8 parseResourceName(const String8& leaf)
 {
-    const char* firstDot = strchr(leaf.string(), '.');
-    const char* str = leaf.string();
+    const char* firstDot = strchr(leaf.c_str(), '.');
+    const char* str = leaf.c_str();
 
     if (firstDot) {
         return String8(str, firstDot-str);
@@ -132,7 +132,7 @@
             mParams = file->getGroupEntry().toParams();
             if (kIsDebug) {
                 printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d ui=%d density=%d touch=%d key=%d inp=%d nav=%d\n",
-                        group->getPath().string(), mParams.mcc, mParams.mnc,
+                        group->getPath().c_str(), mParams.mcc, mParams.mnc,
                         mParams.language[0] ? mParams.language[0] : '-',
                         mParams.language[1] ? mParams.language[1] : '-',
                         mParams.country[0] ? mParams.country[0] : '-',
@@ -147,12 +147,12 @@
             mBaseName = parseResourceName(leaf);
             if (mBaseName == "") {
                 fprintf(stderr, "Error: malformed resource filename %s\n",
-                        file->getPrintableSource().string());
+                        file->getPrintableSource().c_str());
                 return UNKNOWN_ERROR;
             }
 
             if (kIsDebug) {
-                printf("file name=%s\n", mBaseName.string());
+                printf("file name=%s\n", mBaseName.c_str());
             }
 
             return NO_ERROR;
@@ -222,7 +222,7 @@
 {
     if (grp->getFiles().size() != 1) {
         fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
-                grp->getFiles().valueAt(0)->getPrintableSource().string());
+                grp->getFiles().valueAt(0)->getPrintableSource().c_str());
     }
 
     sp<AaptFile> file = grp->getFiles().valueAt(0);
@@ -243,20 +243,20 @@
     size_t len;
     if (code != ResXMLTree::START_TAG) {
         fprintf(stderr, "%s:%d: No start tag found\n",
-                file->getPrintableSource().string(), block.getLineNumber());
+                file->getPrintableSource().c_str(), block.getLineNumber());
         return UNKNOWN_ERROR;
     }
-    if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) {
+    if (strcmp16(block.getElementName(&len), String16("manifest").c_str()) != 0) {
         fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
-                file->getPrintableSource().string(), block.getLineNumber(),
-                String8(block.getElementName(&len)).string());
+                file->getPrintableSource().c_str(), block.getLineNumber(),
+                String8(block.getElementName(&len)).c_str());
         return UNKNOWN_ERROR;
     }
 
     ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
     if (nameIndex < 0) {
         fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
-                file->getPrintableSource().string(), block.getLineNumber());
+                file->getPrintableSource().c_str(), block.getLineNumber());
         return UNKNOWN_ERROR;
     }
 
@@ -264,19 +264,19 @@
 
     ssize_t revisionCodeIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "revisionCode");
     if (revisionCodeIndex >= 0) {
-        bundle->setRevisionCode(String8(block.getAttributeStringValue(revisionCodeIndex, &len)).string());
+        bundle->setRevisionCode(String8(block.getAttributeStringValue(revisionCodeIndex, &len)).c_str());
     }
 
     String16 uses_sdk16("uses-sdk");
     while ((code=block.next()) != ResXMLTree::END_DOCUMENT
            && code != ResXMLTree::BAD_DOCUMENT) {
         if (code == ResXMLTree::START_TAG) {
-            if (strcmp16(block.getElementName(&len), uses_sdk16.string()) == 0) {
+            if (strcmp16(block.getElementName(&len), uses_sdk16.c_str()) == 0) {
                 ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE,
                                                              "minSdkVersion");
                 if (minSdkIndex >= 0) {
                     const char16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len);
-                    const char* minSdk8 = strdup(String8(minSdk16).string());
+                    const char* minSdk8 = strdup(String8(minSdk16).c_str());
                     bundle->setManifestMinSdkVersion(minSdk8);
                 }
             }
@@ -305,17 +305,17 @@
     while ((res=it.next()) == NO_ERROR) {
         if (bundle->getVerbose()) {
             printf("    (new resource id %s from %s)\n",
-                   it.getBaseName().string(), it.getFile()->getPrintableSource().string());
+                   it.getBaseName().c_str(), it.getFile()->getPrintableSource().c_str());
         }
         String16 baseName(it.getBaseName());
-        const char16_t* str = baseName.string();
+        const char16_t* str = baseName.c_str();
         const char16_t* const end = str + baseName.size();
         while (str < end) {
             if (!((*str >= 'a' && *str <= 'z')
                     || (*str >= '0' && *str <= '9')
                     || *str == '_' || *str == '.')) {
                 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
-                        it.getPath().string());
+                        it.getPath().c_str());
                 hasErrors = true;
             }
             str++;
@@ -413,7 +413,7 @@
             sp<ResourceTypeSet> set = new ResourceTypeSet();
             if (kIsDebug) {
                 printf("Creating new resource type set for leaf %s with group %s (%p)\n",
-                        leafName.string(), group->getPath().string(), group.get());
+                        leafName.c_str(), group->getPath().c_str(), group.get());
             }
             set->add(leafName, group);
             resources->add(resType, set);
@@ -423,21 +423,21 @@
             if (index < 0) {
                 if (kIsDebug) {
                     printf("Adding to resource type set for leaf %s group %s (%p)\n",
-                            leafName.string(), group->getPath().string(), group.get());
+                            leafName.c_str(), group->getPath().c_str(), group.get());
                 }
                 set->add(leafName, group);
             } else {
                 sp<AaptGroup> existingGroup = set->valueAt(index);
                 if (kIsDebug) {
                     printf("Extending to resource type set for leaf %s group %s (%p)\n",
-                            leafName.string(), group->getPath().string(), group.get());
+                            leafName.c_str(), group->getPath().c_str(), group.get());
                 }
                 for (size_t j=0; j<files.size(); j++) {
                     if (kIsDebug) {
                         printf("Adding file %s in group %s resType %s\n",
-                                files.valueAt(j)->getSourceFile().string(),
-                                files.keyAt(j).toDirName(String8()).string(),
-                                resType.string());
+                                files.valueAt(j)->getSourceFile().c_str(),
+                                files.keyAt(j).toDirName(String8()).c_str(),
+                                resType.c_str());
                     }
                     existingGroup->addFile(files.valueAt(j));
                 }
@@ -455,14 +455,14 @@
     for (int i=0; i<N; i++) {
         const sp<AaptDir>& d = dirs.itemAt(i);
         if (kIsDebug) {
-            printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(),
-                    d->getLeaf().string());
+            printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().c_str(),
+                    d->getLeaf().c_str());
         }
         collect_files(d, resources);
 
         // don't try to include the res dir
         if (kIsDebug) {
-            printf("Removing dir leaf %s\n", d->getLeaf().string());
+            printf("Removing dir leaf %s\n", d->getLeaf().c_str());
         }
         ass->removeDir(d->getLeaf());
     }
@@ -490,8 +490,8 @@
             int strIdx;
             if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) {
                 fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n",
-                        path.string(), parser.getLineNumber(),
-                        String8(parser.getElementName(&len)).string(), attr,
+                        path.c_str(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).c_str(), attr,
                         value.data);
                 return ATTR_NOT_FOUND;
             }
@@ -502,12 +502,12 @@
                 str = pool->stringAt(value.data, &len);
             }
             printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr,
-                    specFlags, strIdx, str != NULL ? String8(str).string() : "???");
+                    specFlags, strIdx, str != NULL ? String8(str).c_str() : "???");
             #endif
             if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) {
                 fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n",
-                        path.string(), parser.getLineNumber(),
-                        String8(parser.getElementName(&len)).string(), attr,
+                        path.c_str(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).c_str(), attr,
                         specFlags);
                 return ATTR_NOT_FOUND;
             }
@@ -515,20 +515,20 @@
         if (value.dataType == Res_value::TYPE_STRING) {
             if (pool == NULL) {
                 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n",
-                        path.string(), parser.getLineNumber(),
-                        String8(parser.getElementName(&len)).string(), attr);
+                        path.c_str(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).c_str(), attr);
                 return ATTR_NOT_FOUND;
             }
             if ((str = UnpackOptionalString(pool->stringAt(value.data), &len)) == NULL) {
                 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
-                        path.string(), parser.getLineNumber(),
-                        String8(parser.getElementName(&len)).string(), attr);
+                        path.c_str(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).c_str(), attr);
                 return ATTR_NOT_FOUND;
             }
         } else {
             fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
-                    path.string(), parser.getLineNumber(),
-                    String8(parser.getElementName(&len)).string(), attr,
+                    path.c_str(), parser.getLineNumber(),
+                    String8(parser.getElementName(&len)).c_str(), attr,
                     value.dataType);
             return ATTR_NOT_FOUND;
         }
@@ -546,30 +546,30 @@
                 }
                 if (!okay) {
                     fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
-                            path.string(), parser.getLineNumber(),
-                            String8(parser.getElementName(&len)).string(), attr, (char)str[i]);
+                            path.c_str(), parser.getLineNumber(),
+                            String8(parser.getElementName(&len)).c_str(), attr, (char)str[i]);
                     return (int)i;
                 }
             }
         }
         if (*str == ' ') {
             fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
-                    path.string(), parser.getLineNumber(),
-                    String8(parser.getElementName(&len)).string(), attr);
+                    path.c_str(), parser.getLineNumber(),
+                    String8(parser.getElementName(&len)).c_str(), attr);
             return ATTR_LEADING_SPACES;
         }
         if (len != 0 && str[len-1] == ' ') {
             fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
-                    path.string(), parser.getLineNumber(),
-                    String8(parser.getElementName(&len)).string(), attr);
+                    path.c_str(), parser.getLineNumber(),
+                    String8(parser.getElementName(&len)).c_str(), attr);
             return ATTR_TRAILING_SPACES;
         }
         return ATTR_OKAY;
     }
     if (required) {
         fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
-                path.string(), parser.getLineNumber(),
-                String8(parser.getElementName(&len)).string(), attr);
+                path.c_str(), parser.getLineNumber(),
+                String8(parser.getElementName(&len)).c_str(), attr);
         return ATTR_NOT_FOUND;
     }
     return ATTR_OKAY;
@@ -584,7 +584,7 @@
             ssize_t index = parser.indexOfAttribute(NULL, "id");
             if (index >= 0) {
                 fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
-                        path.string(), parser.getLineNumber());
+                        path.c_str(), parser.getLineNumber());
             }
         }
     }
@@ -618,7 +618,7 @@
             size_t overlayCount = overlaySet->size();
             for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
                 if (bundle->getVerbose()) {
-                    printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).string());
+                    printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).c_str());
                 }
                 ssize_t baseIndex = -1;
                 if (baseSet->get() != NULL) {
@@ -638,11 +638,11 @@
                                 baseGroup->getFiles();
                         for (size_t i=0; i < baseFiles.size(); i++) {
                             printf("baseFile " ZD " has flavor %s\n", (ZD_TYPE) i,
-                                    baseFiles.keyAt(i).toString().string());
+                                    baseFiles.keyAt(i).toString().c_str());
                         }
                         for (size_t i=0; i < overlayFiles.size(); i++) {
                             printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i,
-                                    overlayFiles.keyAt(i).toString().string());
+                                    overlayFiles.keyAt(i).toString().c_str());
                         }
                     }
 
@@ -657,16 +657,16 @@
                             if (bundle->getVerbose()) {
                                 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
                                         (ZD_TYPE) baseFileIndex,
-                                        overlayGroup->getLeaf().string(),
-                                        overlayFiles.keyAt(overlayGroupIndex).toString().string());
+                                        overlayGroup->getLeaf().c_str(),
+                                        overlayFiles.keyAt(overlayGroupIndex).toString().c_str());
                             }
                             baseGroup->removeFile(baseFileIndex);
                         } else {
                             // didn't find a match fall through and add it..
                             if (true || bundle->getVerbose()) {
                                 printf("nothing matches overlay file %s, for flavor %s\n",
-                                        overlayGroup->getLeaf().string(),
-                                        overlayFiles.keyAt(overlayGroupIndex).toString().string());
+                                        overlayGroup->getLeaf().c_str(),
+                                        overlayFiles.keyAt(overlayGroupIndex).toString().c_str());
                             }
                         }
                         baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
@@ -728,7 +728,7 @@
         if (errorOnFailedInsert) {
             fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
                             " cannot insert new value %s.\n",
-                    String8(attr).string(), String8(ns).string(), value);
+                    String8(attr).c_str(), String8(ns).c_str(), value);
             return false;
         }
 
@@ -763,7 +763,7 @@
         // .asdf  .a.b  --> package.asdf package.a.b
         // asdf.adsf --> asdf.asdf
         String8 className;
-        const char* p = name.string();
+        const char* p = name.c_str();
         const char* q = strchr(p, '.');
         if (p == q) {
             className += package;
@@ -776,7 +776,7 @@
             className += name;
         }
         if (kIsDebug) {
-            printf("Qualifying class '%s' to '%s'", name.string(), className.string());
+            printf("Qualifying class '%s' to '%s'", name.c_str(), className.c_str());
         }
         attr->string.setTo(String16(className));
     }
@@ -810,7 +810,7 @@
   const char* err;
 
   String16 iconPackage, iconType, iconName;
-  if (!ResTable::expandResourceRef(iconRef.string(), iconRef.size(), &iconPackage, &iconType,
+  if (!ResTable::expandResourceRef(iconRef.c_str(), iconRef.size(), &iconPackage, &iconType,
                                    &iconName, NULL, &table->getAssetsPackage(), &err,
                                    &publicOnly)) {
       // Errors will be raised in later XML compilation.
@@ -824,7 +824,7 @@
   }
 
   String16 roundIconPackage, roundIconType, roundIconName;
-  if (!ResTable::expandResourceRef(roundIconRef.string(), roundIconRef.size(), &roundIconPackage,
+  if (!ResTable::expandResourceRef(roundIconRef.c_str(), roundIconRef.size(), &roundIconPackage,
                                    &roundIconType, &roundIconName, NULL, &table->getAssetsPackage(),
                                    &err, &publicOnly)) {
       // Errors will be raised in later XML compilation.
@@ -839,9 +839,9 @@
       return;
   }
 
-  String16 aliasValue = String16(String8::format("@%s:%s/%s", String8(iconPackage).string(),
-                                                 String8(iconType).string(),
-                                                 String8(iconName).string()));
+  String16 aliasValue = String16(String8::format("@%s:%s/%s", String8(iconPackage).c_str(),
+                                                 String8(iconType).c_str(),
+                                                 String8(iconName).c_str()));
 
   // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
   const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& configList =
@@ -872,7 +872,7 @@
         const XMLNode::attribute_entry* attr = root->getAttribute(
                 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionCode"));
         if (attr != NULL) {
-            bundle->setVersionCode(strdup(String8(attr->string).string()));
+            bundle->setVersionCode(strdup(String8(attr->string).c_str()));
         }
     }
 
@@ -883,7 +883,7 @@
         const XMLNode::attribute_entry* attr = root->getAttribute(
                 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionName"));
         if (attr != NULL) {
-            bundle->setVersionName(strdup(String8(attr->string).string()));
+            bundle->setVersionName(strdup(String8(attr->string).c_str()));
         }
     }
     
@@ -914,7 +914,7 @@
         const XMLNode::attribute_entry* attr = vers->getAttribute(
                 String16(RESOURCES_ANDROID_NAMESPACE), String16("minSdkVersion"));
         if (attr != NULL) {
-            bundle->setMinSdkVersion(strdup(String8(attr->string).string()));
+            bundle->setMinSdkVersion(strdup(String8(attr->string).c_str()));
         }
     }
 
@@ -970,7 +970,7 @@
         String8 origPackage(attr->string);
         attr->string.setTo(String16(manifestPackageNameOverride));
         if (kIsDebug) {
-            printf("Overriding package '%s' to be '%s'\n", origPackage.string(),
+            printf("Overriding package '%s' to be '%s'\n", origPackage.c_str(),
                     manifestPackageNameOverride);
         }
 
@@ -1071,7 +1071,7 @@
 static ssize_t extractPlatformBuildVersion(const ResTable& table, ResXMLTree& tree, Bundle* bundle) {
     // First check if we should be recording the compileSdkVersion* attributes.
     static const String16 compileSdkVersionName("android:attr/compileSdkVersion");
-    const bool useCompileSdkVersion = table.identifierForName(compileSdkVersionName.string(),
+    const bool useCompileSdkVersion = table.identifierForName(compileSdkVersionName.c_str(),
                                                               compileSdkVersionName.size()) != 0u;
 
     size_t len;
@@ -1223,7 +1223,7 @@
     // Add the 'revisionCode' attribute, which is set to the original revisionCode.
     if (bundle->getRevisionCode().size() > 0) {
         if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "revisionCode",
-                    bundle->getRevisionCode().string(), true, true)) {
+                    bundle->getRevisionCode().c_str(), true, true)) {
             return UNKNOWN_ERROR;
         }
     }
@@ -1270,7 +1270,7 @@
     }
 
     if (kIsDebug) {
-        printf("Creating resources for package %s\n", assets->getPackage().string());
+        printf("Creating resources for package %s\n", assets->getPackage().c_str());
     }
 
     // Set the private symbols package if it was declared.
@@ -1804,7 +1804,7 @@
                     flattenedTable, split->isBase());
             if (err != NO_ERROR) {
                 fprintf(stderr, "Failed to generate resource table for split '%s'\n",
-                        split->getPrintableName().string());
+                        split->getPrintableName().c_str());
                 return err;
             }
             split->addEntry(String8("resources.arsc"), flattenedTable);
@@ -1821,7 +1821,7 @@
                 err = resTable.add(flattenedTable->getData(), flattenedTable->getSize());
                 if (err != NO_ERROR) {
                     fprintf(stderr, "Generated resource table for split '%s' is corrupt.\n",
-                            split->getPrintableName().string());
+                            split->getPrintableName().c_str());
                     return err;
                 }
 
@@ -1849,7 +1849,7 @@
                             if (block < 0) {
                                 hasError = true;
                                 SourcePos().error("%s has no definition for density split '%s'",
-                                        symbol.toString().string(), config.toString().string());
+                                        symbol.toString().c_str(), config.toString().c_str());
 
                                 if (bundle->getVerbose()) {
                                     const Vector<SymbolDefinition>& defs = densityVaryingResources[k];
@@ -1857,7 +1857,7 @@
                                     for (size_t d = 0; d < defCount; d++) {
                                         const SymbolDefinition& def = defs[d];
                                         def.source.error("%s has definition for %s",
-                                                symbol.toString().string(), def.config.toString().string());
+                                                symbol.toString().c_str(), def.config.toString().c_str());
                                     }
 
                                     if (defCount < defs.size()) {
@@ -1880,7 +1880,7 @@
                         generatedManifest, &table);
                 if (err != NO_ERROR) {
                     fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n",
-                            split->getPrintableName().string());
+                            split->getPrintableName().c_str());
                     return err;
                 }
                 split->addEntry(String8("AndroidManifest.xml"), generatedManifest);
@@ -1960,7 +1960,7 @@
             if (block.getElementNamespace(&len) != NULL) {
                 continue;
             }
-            if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
+            if (strcmp16(block.getElementName(&len), manifest16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
                                  packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
@@ -1969,10 +1969,10 @@
                                  "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
-                    || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), permission16.c_str()) == 0
+                    || strcmp16(block.getElementName(&len), permission_group16.c_str()) == 0) {
                 const bool isGroup = strcmp16(block.getElementName(&len),
-                        permission_group16.string()) == 0;
+                        permission_group16.c_str()) == 0;
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", isGroup ? packageIdentCharsWithTheStupid
                                  : packageIdentChars, true) != ATTR_OKAY) {
@@ -2002,8 +2002,8 @@
                 const char16_t* id = block.getAttributeStringValue(index, &len);
                 if (id == NULL) {
                     fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n", 
-                            manifestPath.string(), block.getLineNumber(),
-                            String8(block.getElementName(&len)).string());
+                            manifestPath.c_str(), block.getLineNumber(),
+                            String8(block.getElementName(&len)).c_str());
                     hasErrors = true;
                     break;
                 }
@@ -2038,23 +2038,23 @@
                 if (begins_with_digit || (e != p && *(e-1) != '.')) {
                   fprintf(stderr,
                           "%s:%d: Permission name <%s> is not a valid Java symbol\n",
-                          manifestPath.string(), block.getLineNumber(), idStr.string());
+                          manifestPath.c_str(), block.getLineNumber(), idStr.c_str());
                   hasErrors = true;
                 }
                 syms->addStringSymbol(String8(e), idStr, srcPos);
                 const char16_t* cmt = block.getComment(&len);
                 if (cmt != NULL && *cmt != 0) {
-                    //printf("Comment of %s: %s\n", String8(e).string(),
-                    //        String8(cmt).string());
+                    //printf("Comment of %s: %s\n", String8(e).c_str(),
+                    //        String8(cmt).c_str());
                     syms->appendComment(String8(e), String16(cmt), srcPos);
                 }
                 syms->makeSymbolPublic(String8(e), srcPos);
-            } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), uses_permission16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), instrumentation16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", classIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
@@ -2064,7 +2064,7 @@
                                  packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), application16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", classIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
@@ -2084,7 +2084,7 @@
                                  processIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), provider16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", classIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
@@ -2104,9 +2104,9 @@
                                  processIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
-                       || strcmp16(block.getElementName(&len), receiver16.string()) == 0
-                       || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), service16.c_str()) == 0
+                       || strcmp16(block.getElementName(&len), receiver16.c_str()) == 0
+                       || strcmp16(block.getElementName(&len), activity16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", classIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
@@ -2126,14 +2126,14 @@
                                  processIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
-                       || strcmp16(block.getElementName(&len), category16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), action16.c_str()) == 0
+                       || strcmp16(block.getElementName(&len), category16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "name",
                                  packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), data16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "mimeType",
                                  typeIdentChars, true) != ATTR_OKAY) {
@@ -2144,13 +2144,13 @@
                                  schemeIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), feature_group16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), feature_group16.c_str()) == 0) {
                 int depth = 1;
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
                        && code > ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::START_TAG) {
                         depth++;
-                        if (strcmp16(block.getElementName(&len), uses_feature16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), uses_feature16.c_str()) == 0) {
                             ssize_t idx = block.indexOfAttribute(
                                     RESOURCES_ANDROID_NAMESPACE, "required");
                             if (idx < 0) {
@@ -2162,7 +2162,7 @@
                                 fprintf(stderr, "%s:%d: Tag <uses-feature> can not have "
                                         "android:required=\"false\" when inside a "
                                         "<feature-group> tag.\n",
-                                        manifestPath.string(), block.getLineNumber());
+                                        manifestPath.c_str(), block.getLineNumber());
                                 hasErrors = true;
                             }
                         }
@@ -2222,7 +2222,7 @@
 static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
     ssize_t colon = symbol.find(":", 0);
     if (colon >= 0) {
-        return String8(symbol.string(), colon);
+        return String8(symbol.c_str(), colon);
     }
     return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
 }
@@ -2230,7 +2230,7 @@
 static String8 getSymbolName(const String8& symbol) {
     ssize_t colon = symbol.find(":", 0);
     if (colon >= 0) {
-        return String8(symbol.string() + colon + 1);
+        return String8(symbol.c_str() + colon + 1);
     }
     return symbol;
 }
@@ -2245,7 +2245,7 @@
         asym = asym->getNestedSymbols().valueFor(String8("attr"));
         if (asym != NULL) {
             //printf("Got attrs symbols! comment %s=%s\n",
-            //     name.string(), String8(asym->getComment(name)).string());
+            //     name.c_str(), String8(asym->getComment(name)).c_str());
             if (outTypeComment != NULL) {
                 *outTypeComment = asym->getTypeComment(name);
             }
@@ -2276,8 +2276,8 @@
                 "%sfor(int i = 0; i < styleable.%s.length; ++i) {\n"
                 "%sstyleable.%s[i] = (styleable.%s[i] & 0x00ffffff) | (packageId << 24);\n"
                 "%s}\n",
-                indentStr, nclassName.string(),
-                getIndentSpace(indent+1), nclassName.string(), nclassName.string(),
+                indentStr, nclassName.c_str(),
+                getIndentSpace(indent+1), nclassName.c_str(), nclassName.c_str(),
                 indentStr);
     }
 
@@ -2303,8 +2303,8 @@
         String8 flat_name(flattenSymbol(sym.name));
         fprintf(fp,
                 "%s%s.%s = (%s.%s & 0x00ffffff) | (packageId << 24);\n",
-                getIndentSpace(indent), className.string(), flat_name.string(),
-                className.string(), flat_name.string());
+                getIndentSpace(indent), className.c_str(), flat_name.c_str(),
+                className.c_str(), flat_name.c_str());
     }
 
     N = symbols->getNestedSymbols().size();
@@ -2365,12 +2365,12 @@
                 String16 name16(sym.name);
                 uint32_t typeSpecFlags;
                 code = assets->getIncludedResources().identifierForName(
-                    name16.string(), name16.size(),
-                    attr16.string(), attr16.size(),
-                    package16.string(), package16.size(), &typeSpecFlags);
+                    name16.c_str(), name16.size(),
+                    attr16.c_str(), attr16.size(),
+                    package16.c_str(), package16.size(), &typeSpecFlags);
                 if (code == 0) {
                     fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
-                            nclassName.string(), sym.name.string());
+                            nclassName.c_str(), sym.name.c_str());
                     hasErrors = true;
                 }
                 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
@@ -2388,9 +2388,9 @@
         if (comment.size() > 0) {
             String8 cmt(comment);
             ann.preprocessComment(cmt);
-            fprintf(fp, "%s\n", cmt.string());
+            fprintf(fp, "%s\n", cmt.c_str());
         } else {
-            fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
+            fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.c_str());
         }
         bool hasTable = false;
         for (a=0; a<NA; a++) {
@@ -2423,7 +2423,7 @@
                     continue;
                 }
                 if (comment.size() > 0) {
-                    const char16_t* p = comment.string();
+                    const char16_t* p = comment.c_str();
                     while (*p != 0 && *p != '.') {
                         if (*p == '{') {
                             while (*p != 0 && *p != '}') {
@@ -2436,14 +2436,14 @@
                     if (*p == '.') {
                         p++;
                     }
-                    comment = String16(comment.string(), p-comment.string());
+                    comment = String16(comment.c_str(), p-comment.c_str());
                 }
                 fprintf(fp, "%s   <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
-                        indentStr, nclassName.string(),
-                        flattenSymbol(name8).string(),
-                        getSymbolPackage(name8, assets, true).string(),
-                        getSymbolName(name8).string(),
-                        String8(comment).string());
+                        indentStr, nclassName.c_str(),
+                        flattenSymbol(name8).c_str(),
+                        getSymbolPackage(name8, assets, true).c_str(),
+                        getSymbolName(name8).c_str(),
+                        String8(comment).c_str());
             }
         }
         if (hasTable) {
@@ -2457,8 +2457,8 @@
                     continue;
                 }
                 fprintf(fp, "%s   @see #%s_%s\n",
-                        indentStr, nclassName.string(),
-                        flattenSymbol(sym.name).string());
+                        indentStr, nclassName.c_str(),
+                        flattenSymbol(sym.name).c_str());
             }
         }
         fprintf(fp, "%s */\n", getIndentSpace(indent));
@@ -2468,7 +2468,7 @@
         fprintf(fp,
                 "%spublic static final int[] %s = {\n"
                 "%s",
-                indentStr, nclassName.string(),
+                indentStr, nclassName.c_str(),
                 getIndentSpace(indent+1));
 
         for (a=0; a<NA; a++) {
@@ -2503,11 +2503,11 @@
                 uint32_t typeSpecFlags = 0;
                 String16 name16(sym.name);
                 assets->getIncludedResources().identifierForName(
-                    name16.string(), name16.size(),
-                    attr16.string(), attr16.size(),
-                    package16.string(), package16.size(), &typeSpecFlags);
-                //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
-                //    String8(attr16).string(), String8(name16).string(), typeSpecFlags);
+                    name16.c_str(), name16.size(),
+                    attr16.c_str(), attr16.size(),
+                    package16.c_str(), package16.size(), &typeSpecFlags);
+                //printf("%s:%s/%s: 0x%08x\n", String8(package16).c_str(),
+                //    String8(attr16).c_str(), String8(name16).c_str(), typeSpecFlags);
                 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
 
                 AnnotationProcessor ann;
@@ -2516,20 +2516,20 @@
                     String8 cmt(comment);
                     ann.preprocessComment(cmt);
                     fprintf(fp, "%s  <p>\n%s  @attr description\n", indentStr, indentStr);
-                    fprintf(fp, "%s  %s\n", indentStr, cmt.string());
+                    fprintf(fp, "%s  %s\n", indentStr, cmt.c_str());
                 } else {
                     fprintf(fp,
                             "%s  <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
                             "%s  attribute's value can be found in the {@link #%s} array.\n",
                             indentStr,
-                            getSymbolPackage(name8, assets, pub).string(),
-                            getSymbolName(name8).string(),
-                            indentStr, nclassName.string());
+                            getSymbolPackage(name8, assets, pub).c_str(),
+                            getSymbolName(name8).c_str(),
+                            indentStr, nclassName.c_str());
                 }
                 if (typeComment.size() > 0) {
                     String8 cmt(typeComment);
                     ann.preprocessComment(cmt);
-                    fprintf(fp, "\n\n%s  %s\n", indentStr, cmt.string());
+                    fprintf(fp, "\n\n%s  %s\n", indentStr, cmt.c_str());
                 }
                 if (comment.size() > 0) {
                     if (pub) {
@@ -2537,16 +2537,16 @@
                                 "%s  <p>This corresponds to the global attribute\n"
                                 "%s  resource symbol {@link %s.R.attr#%s}.\n",
                                 indentStr, indentStr,
-                                getSymbolPackage(name8, assets, true).string(),
-                                getSymbolName(name8).string());
+                                getSymbolPackage(name8, assets, true).c_str(),
+                                getSymbolName(name8).c_str());
                     } else {
                         fprintf(fp,
                                 "%s  <p>This is a private symbol.\n", indentStr);
                     }
                 }
                 fprintf(fp, "%s  @attr name %s:%s\n", indentStr,
-                        getSymbolPackage(name8, assets, pub).string(),
-                        getSymbolName(name8).string());
+                        getSymbolPackage(name8, assets, pub).c_str(),
+                        getSymbolName(name8).c_str());
                 fprintf(fp, "%s*/\n", indentStr);
                 ann.printAnnotations(fp, indentStr);
 
@@ -2556,8 +2556,8 @@
 
                 fprintf(fp,
                         id_format,
-                        indentStr, nclassName.string(),
-                        flattenSymbol(name8).string(), (int)pos);
+                        indentStr, nclassName.c_str(),
+                        flattenSymbol(name8).c_str(), (int)pos);
             }
         }
     }
@@ -2598,12 +2598,12 @@
                 String16 name16(sym.name);
                 uint32_t typeSpecFlags;
                 code = assets->getIncludedResources().identifierForName(
-                    name16.string(), name16.size(),
-                    attr16.string(), attr16.size(),
-                    package16.string(), package16.size(), &typeSpecFlags);
+                    name16.c_str(), name16.size(),
+                    attr16.c_str(), attr16.size(),
+                    package16.c_str(), package16.size(), &typeSpecFlags);
                 if (code == 0) {
                     fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
-                            nclassName.string(), sym.name.string());
+                            nclassName.c_str(), sym.name.c_str());
                     hasErrors = true;
                 }
                 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
@@ -2615,7 +2615,7 @@
 
         NA = idents.size();
 
-        fprintf(fp, "int[] styleable %s {", nclassName.string());
+        fprintf(fp, "int[] styleable %s {", nclassName.c_str());
 
         for (a=0; a<NA; a++) {
             if (a != 0) {
@@ -2645,17 +2645,17 @@
                 uint32_t typeSpecFlags = 0;
                 String16 name16(sym.name);
                 assets->getIncludedResources().identifierForName(
-                    name16.string(), name16.size(),
-                    attr16.string(), attr16.size(),
-                    package16.string(), package16.size(), &typeSpecFlags);
-                //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
-                //    String8(attr16).string(), String8(name16).string(), typeSpecFlags);
+                    name16.c_str(), name16.size(),
+                    attr16.c_str(), attr16.size(),
+                    package16.c_str(), package16.size(), &typeSpecFlags);
+                //printf("%s:%s/%s: 0x%08x\n", String8(package16).c_str(),
+                //    String8(attr16).c_str(), String8(name16).c_str(), typeSpecFlags);
                 //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
 
                 fprintf(fp,
                         "int styleable %s_%s %d\n",
-                        nclassName.string(),
-                        flattenSymbol(name8).string(), (int)pos);
+                        nclassName.c_str(),
+                        flattenSymbol(name8).c_str(), (int)pos);
             }
         }
     }
@@ -2670,7 +2670,7 @@
 {
     fprintf(fp, "%spublic %sfinal class %s {\n",
             getIndentSpace(indent),
-            indent != 0 ? "static " : "", className.string());
+            indent != 0 ? "static " : "", className.c_str());
     indent++;
 
     size_t i;
@@ -2699,7 +2699,7 @@
             ann.preprocessComment(cmt);
             fprintf(fp,
                     "%s/** %s\n",
-                    getIndentSpace(indent), cmt.string());
+                    getIndentSpace(indent), cmt.c_str());
         }
         String16 typeComment(sym.typeComment);
         if (typeComment.size() > 0) {
@@ -2708,10 +2708,10 @@
             if (!haveComment) {
                 haveComment = true;
                 fprintf(fp,
-                        "%s/** %s\n", getIndentSpace(indent), cmt.string());
+                        "%s/** %s\n", getIndentSpace(indent), cmt.c_str());
             } else {
                 fprintf(fp,
-                        "%s %s\n", getIndentSpace(indent), cmt.string());
+                        "%s %s\n", getIndentSpace(indent), cmt.c_str());
             }
         }
         if (haveComment) {
@@ -2720,7 +2720,7 @@
         ann.printAnnotations(fp, getIndentSpace(indent));
         fprintf(fp, id_format,
                 getIndentSpace(indent),
-                flattenSymbol(name8).string(), (int)sym.int32Val);
+                flattenSymbol(name8).c_str(), (int)sym.int32Val);
     }
 
     for (i=0; i<N; i++) {
@@ -2740,13 +2740,13 @@
             fprintf(fp,
                     "%s/** %s\n"
                      "%s */\n",
-                    getIndentSpace(indent), cmt.string(),
+                    getIndentSpace(indent), cmt.c_str(),
                     getIndentSpace(indent));
         }
         ann.printAnnotations(fp, getIndentSpace(indent));
         fprintf(fp, "%spublic static final String %s=\"%s\";\n",
                 getIndentSpace(indent),
-                flattenSymbol(name8).string(), sym.stringVal.string());
+                flattenSymbol(name8).c_str(), sym.stringVal.c_str());
     }
 
     sp<AaptSymbols> styleableSymbols;
@@ -2805,8 +2805,8 @@
 
         String8 name8(sym.name);
         fprintf(fp, "int %s %s 0x%08x\n",
-                className.string(),
-                flattenSymbol(name8).string(), (int)sym.int32Val);
+                className.c_str(),
+                flattenSymbol(name8).c_str(), (int)sym.int32Val);
     }
 
     N = symbols->getNestedSymbols().size();
@@ -2844,7 +2844,7 @@
 
         if (bundle->getMakePackageDirs()) {
             const String8& pkg(package);
-            const char* last = pkg.string();
+            const char* last = pkg.c_str();
             const char* s = last-1;
             do {
                 s++;
@@ -2852,9 +2852,9 @@
                     String8 part(last, s-last);
                     dest.appendPath(part);
 #ifdef _WIN32
-                    _mkdir(dest.string());
+                    _mkdir(dest.c_str());
 #else
-                    mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
+                    mkdir(dest.c_str(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
 #endif
                     last = s+1;
                 }
@@ -2862,14 +2862,14 @@
         }
         dest.appendPath(className);
         dest.append(".java");
-        FILE* fp = fopen(dest.string(), "w+");
+        FILE* fp = fopen(dest.c_str(), "w+");
         if (fp == NULL) {
             fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
-                    dest.string(), strerror(errno));
+                    dest.c_str(), strerror(errno));
             return UNKNOWN_ERROR;
         }
         if (bundle->getVerbose()) {
-            printf("  Writing symbols for class %s.\n", className.string());
+            printf("  Writing symbols for class %s.\n", className.c_str());
         }
 
         fprintf(fp,
@@ -2880,7 +2880,7 @@
             " * should not be modified by hand.\n"
             " */\n"
             "\n"
-            "package %s;\n\n", package.string());
+            "package %s;\n\n", package.c_str());
 
         status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
                 className, 0, bundle->getNonConstantId(), emitCallback);
@@ -2894,14 +2894,14 @@
             textDest.appendPath(className);
             textDest.append(".txt");
 
-            FILE* fp = fopen(textDest.string(), "w+");
+            FILE* fp = fopen(textDest.c_str(), "w+");
             if (fp == NULL) {
                 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
-                        textDest.string(), strerror(errno));
+                        textDest.c_str(), strerror(errno));
                 return UNKNOWN_ERROR;
             }
             if (bundle->getVerbose()) {
-                printf("  Writing text symbols for class %s.\n", className.string());
+                printf("  Writing text symbols for class %s.\n", className.c_str());
             }
 
             status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
@@ -2919,8 +2919,8 @@
             String8 dependencyFile(bundle->getRClassDir());
             dependencyFile.appendPath("R.java.d");
 
-            FILE *fp = fopen(dependencyFile.string(), "a");
-            fprintf(fp,"%s \\\n", dest.string());
+            FILE *fp = fopen(dependencyFile.c_str(), "a");
+            fprintf(fp,"%s \\\n", dest.c_str());
             fclose(fp);
         }
     }
@@ -2956,7 +2956,7 @@
         // asdf     --> package.asdf
         // .asdf  .a.b  --> package.asdf package.a.b
         // asdf.adsf --> asdf.asdf
-        const char* p = className.string();
+        const char* p = className.c_str();
         const char* q = strchr(p, '.');
         if (p == q) {
             className = pkg;
@@ -3023,7 +3023,7 @@
 
     if (assGroup->getFiles().size() != 1) {
         fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
-                assGroup->getFiles().valueAt(0)->getPrintableSource().string());
+                assGroup->getFiles().valueAt(0)->getPrintableSource().c_str());
     }
 
     assFile = assGroup->getFiles().valueAt(0);
@@ -3048,7 +3048,7 @@
         }
         depth++;
         String8 tag(tree.getElementName(&len));
-        // printf("Depth %d tag %s\n", depth, tag.string());
+        // printf("Depth %d tag %s\n", depth, tag.c_str());
         bool keepTag = false;
         if (depth == 1) {
             if (tag != "manifest") {
@@ -3065,7 +3065,7 @@
                         "http://schemas.android.com/apk/res/android",
                         "backupAgent", &error);
                 if (agent.length() > 0) {
-                    addProguardKeepRule(keep, agent, pkg.string(),
+                    addProguardKeepRule(keep, agent, pkg.c_str(),
                             assFile->getPrintableSource(), tree.getLineNumber());
                 }
 
@@ -3073,7 +3073,7 @@
                     defaultProcess = AaptXml::getAttribute(tree,
                             "http://schemas.android.com/apk/res/android", "process", &error);
                     if (error != "") {
-                        fprintf(stderr, "ERROR: %s\n", error.string());
+                        fprintf(stderr, "ERROR: %s\n", error.c_str());
                         return -1;
                     }
                 }
@@ -3089,7 +3089,7 @@
                     String8 componentProcess = AaptXml::getAttribute(tree,
                             "http://schemas.android.com/apk/res/android", "process", &error);
                     if (error != "") {
-                        fprintf(stderr, "ERROR: %s\n", error.string());
+                        fprintf(stderr, "ERROR: %s\n", error.c_str());
                         return -1;
                     }
 
@@ -3103,14 +3103,14 @@
             String8 name = AaptXml::getAttribute(tree,
                     "http://schemas.android.com/apk/res/android", "name", &error);
             if (error != "") {
-                fprintf(stderr, "ERROR: %s\n", error.string());
+                fprintf(stderr, "ERROR: %s\n", error.c_str());
                 return -1;
             }
 
             keepTag = name.length() > 0;
 
             if (keepTag) {
-                addProguardKeepRule(keep, name, pkg.string(),
+                addProguardKeepRule(keep, name, pkg.c_str(),
                         assFile->getPrintableSource(), tree.getLineNumber());
             }
         }
@@ -3170,7 +3170,7 @@
         String8 tag(tree.getElementName(&len));
 
         // If there is no '.', we'll assume that it's one of the built in names.
-        if (strchr(tag.string(), '.')) {
+        if (strchr(tag.c_str(), '.')) {
             addProguardKeepRule(keep, tag, NULL,
                     layoutFile->getPrintableSource(), tree.getLineNumber());
         } else if (tagAttrPairs != NULL) {
@@ -3183,8 +3183,8 @@
                     ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
                     if (attrIndex < 0) {
                         // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
-                        //        layoutFile->getPrintableSource().string(), tree.getLineNumber(),
-                        //        tag.string(), nsAttr.ns, nsAttr.attr);
+                        //        layoutFile->getPrintableSource().c_str(), tree.getLineNumber(),
+                        //        tag.c_str(), nsAttr.ns, nsAttr.attr);
                     } else {
                         size_t len;
                         addProguardKeepRule(keep,
@@ -3242,7 +3242,7 @@
 
     // tag:attribute pairs that should be checked in transition files.
     KeyedVector<String8, Vector<NamespaceAttributePair> > kTransitionTagAttrPairs;
-    addTagAttrPair(&kTransitionTagAttrPairs, kTransition.string(), NULL, kClass);
+    addTagAttrPair(&kTransitionTagAttrPairs, kTransition.c_str(), NULL, kClass);
     addTagAttrPair(&kTransitionTagAttrPairs, "pathMotion", NULL, kClass);
 
     const Vector<sp<AaptDir> >& dirs = assets->resDirs();
@@ -3252,16 +3252,16 @@
         const String8& dirName = d->getLeaf();
         Vector<String8> startTags;
         const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
-        if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
+        if ((dirName == String8("layout")) || (strncmp(dirName.c_str(), "layout-", 7) == 0)) {
             tagAttrPairs = &kLayoutTagAttrPairs;
-        } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
+        } else if ((dirName == String8("xml")) || (strncmp(dirName.c_str(), "xml-", 4) == 0)) {
             startTags.add(String8("PreferenceScreen"));
             startTags.add(String8("preference-headers"));
             tagAttrPairs = &kXmlTagAttrPairs;
-        } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) {
+        } else if ((dirName == String8("menu")) || (strncmp(dirName.c_str(), "menu-", 5) == 0)) {
             startTags.add(String8("menu"));
             tagAttrPairs = NULL;
-        } else if (dirName == kTransition || (strncmp(dirName.string(), kTransitionPrefix.string(),
+        } else if (dirName == kTransition || (strncmp(dirName.c_str(), kTransitionPrefix.c_str(),
                         kTransitionPrefix.size()) == 0)) {
             tagAttrPairs = &kTransitionTagAttrPairs;
         } else {
@@ -3307,9 +3307,9 @@
         const SortedVector<String8>& locations = rules.valueAt(i);
         const size_t M = locations.size();
         for (size_t j=0; j<M; j++) {
-            fprintf(fp, "# %s\n", locations.itemAt(j).string());
+            fprintf(fp, "# %s\n", locations.itemAt(j).c_str());
         }
-        fprintf(fp, "%s\n\n", rules.keyAt(i).string());
+        fprintf(fp, "%s\n\n", rules.keyAt(i).c_str());
     }
     fclose(fp);
 
@@ -3366,7 +3366,7 @@
     status_t deps = -1;
     for (size_t file_i = 0; file_i < files->size(); ++file_i) {
         // Add the full file path to the dependency file
-        fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
+        fprintf(fp, "%s \\\n", files->itemAt(file_i).c_str());
         deps++;
     }
     return deps;
diff --git a/tools/aapt/ResourceFilter.cpp b/tools/aapt/ResourceFilter.cpp
index ed06f60..cc8dce7e 100644
--- a/tools/aapt/ResourceFilter.cpp
+++ b/tools/aapt/ResourceFilter.cpp
@@ -32,7 +32,7 @@
             // only specify locale in the standard 'en_US' format.
             val.writeTo(&entry.first);
         } else if (!AaptConfig::parse(part, &entry.first)) {
-            fprintf(stderr, "Invalid configuration: %s\n", part.string());
+            fprintf(stderr, "Invalid configuration: %s\n", part.c_str());
             return UNKNOWN_ERROR;
         }
 
@@ -43,7 +43,7 @@
 
         // Ignore any densities. Those are best handled in --preferred-density
         if ((entry.second & ResTable_config::CONFIG_DENSITY) != 0) {
-            fprintf(stderr, "warning: ignoring flag -c %s. Use --preferred-density instead.\n", entry.first.toString().string());
+            fprintf(stderr, "warning: ignoring flag -c %s. Use --preferred-density instead.\n", entry.first.toString().c_str());
             entry.first.density = 0;
             entry.second &= ~ResTable_config::CONFIG_DENSITY;
         }
@@ -148,7 +148,7 @@
     mConfigs.clear();
     for (size_t i = 0; i < configStrs.size(); i++) {
         if (!AaptConfig::parse(configStrs[i], &config)) {
-            fprintf(stderr, "Invalid configuration: %s\n", configStrs[i].string());
+            fprintf(stderr, "Invalid configuration: %s\n", configStrs[i].c_str());
             return UNKNOWN_ERROR;
         }
         mConfigs.insert(config);
diff --git a/tools/aapt/ResourceIdCache.cpp b/tools/aapt/ResourceIdCache.cpp
index 8835fb0..1c7788d 100644
--- a/tools/aapt/ResourceIdCache.cpp
+++ b/tools/aapt/ResourceIdCache.cpp
@@ -37,7 +37,7 @@
 
 static uint32_t hash(const android::String16& hashableString) {
     uint32_t hash = 5381;
-    const char16_t* str = hashableString.string();
+    const char16_t* str = hashableString.c_str();
     while (int c = *str++) hash = hashround(hash, c);
     return hash;
 }
diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp
index 4e597fb..2344007 100644
--- a/tools/aapt/ResourceTable.cpp
+++ b/tools/aapt/ResourceTable.cpp
@@ -361,10 +361,10 @@
     ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
     if (typeIdx >= 0) {
         String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
-        attr.type = parse_flags(typeStr.string(), typeStr.size(), gFormatFlags);
+        attr.type = parse_flags(typeStr.c_str(), typeStr.size(), gFormatFlags);
         if (attr.type == 0) {
             attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
-                    String8(typeStr).string());
+                    String8(typeStr).c_str());
             attr.hasErrors = true;
         }
         attr.createIfNeeded(outTable);
@@ -374,14 +374,14 @@
         attr.createIfNeeded(outTable);
     }
 
-    //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).string(), attr.type);
+    //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).c_str(), attr.type);
 
     ssize_t minIdx = block.indexOfAttribute(NULL, "min");
     if (minIdx >= 0) {
         String16 val = String16(block.getAttributeStringValue(minIdx, &len));
-        if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
+        if (!ResTable::stringToInt(val.c_str(), val.size(), NULL)) {
             attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
-                    String8(val).string());
+                    String8(val).c_str());
             attr.hasErrors = true;
         }
         attr.createIfNeeded(outTable);
@@ -397,9 +397,9 @@
     ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
     if (maxIdx >= 0) {
         String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
-        if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
+        if (!ResTable::stringToInt(val.c_str(), val.size(), NULL)) {
             attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
-                    String8(val).string());
+                    String8(val).c_str());
             attr.hasErrors = true;
         }
         attr.createIfNeeded(outTable);
@@ -422,7 +422,7 @@
         uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
         if (error) {
             attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
-                    String8(str).string());
+                    String8(str).c_str());
             attr.hasErrors = true;
         }
         attr.createIfNeeded(outTable);
@@ -442,14 +442,14 @@
     while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
         if (code == ResXMLTree::START_TAG) {
             uint32_t localType = 0;
-            if (strcmp16(block.getElementName(&len), enum16.string()) == 0) {
+            if (strcmp16(block.getElementName(&len), enum16.c_str()) == 0) {
                 localType = ResTable_map::TYPE_ENUM;
-            } else if (strcmp16(block.getElementName(&len), flag16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), flag16.c_str()) == 0) {
                 localType = ResTable_map::TYPE_FLAGS;
             } else {
                 SourcePos(in->getPrintableSource(), block.getLineNumber())
                         .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
-                        String8(block.getElementName(&len)).string());
+                        String8(block.getElementName(&len)).c_str());
                 return UNKNOWN_ERROR;
             }
 
@@ -505,11 +505,11 @@
                         .error("A 'value' attribute is required for <enum> or <flag>\n");
                 attr.hasErrors = true;
             }
-            if (!attr.hasErrors && !ResTable::stringToInt(value.string(), value.size(), NULL)) {
+            if (!attr.hasErrors && !ResTable::stringToInt(value.c_str(), value.size(), NULL)) {
                 SourcePos(in->getPrintableSource(), block.getLineNumber())
                         .error("Tag <enum> or <flag> 'value' attribute must be a number,"
                         " not \"%s\"\n",
-                        String8(value).string());
+                        String8(value).c_str());
                 attr.hasErrors = true;
             }
 
@@ -546,21 +546,21 @@
                 }
             }
         } else if (code == ResXMLTree::END_TAG) {
-            if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
+            if (strcmp16(block.getElementName(&len), attr16.c_str()) == 0) {
                 break;
             }
             if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
-                if (strcmp16(block.getElementName(&len), enum16.string()) != 0) {
+                if (strcmp16(block.getElementName(&len), enum16.c_str()) != 0) {
                     SourcePos(in->getPrintableSource(), block.getLineNumber())
                             .error("Found tag </%s> where </enum> is expected\n",
-                            String8(block.getElementName(&len)).string());
+                            String8(block.getElementName(&len)).c_str());
                     return UNKNOWN_ERROR;
                 }
             } else {
-                if (strcmp16(block.getElementName(&len), flag16.string()) != 0) {
+                if (strcmp16(block.getElementName(&len), flag16.c_str()) != 0) {
                     SourcePos(in->getPrintableSource(), block.getLineNumber())
                             .error("Found tag </%s> where </flag> is expected\n",
-                            String8(block.getElementName(&len)).string());
+                            String8(block.getElementName(&len)).c_str());
                     return UNKNOWN_ERROR;
                 }
             }
@@ -606,7 +606,7 @@
 
     String16 str;
     Vector<StringPool::entry_style_span> spans;
-    err = parseStyledString(bundle, in->getPrintableSource().string(),
+    err = parseStyledString(bundle, in->getPrintableSource().c_str(),
                             block, item16, &str, &spans, isFormatted,
                             pseudolocalize);
     if (err != NO_ERROR) {
@@ -619,10 +619,10 @@
                 config.language[0], config.language[1],
                 config.country[0], config.country[1],
                 config.orientation, config.density,
-                String8(parentIdent).string(),
-                String8(ident).string(),
-                String8(itemIdent).string(),
-                String8(str).string());
+                String8(parentIdent).c_str(),
+                String8(ident).c_str(),
+                String8(itemIdent).c_str(),
+                String8(str).c_str());
     }
 
     err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
@@ -636,8 +636,8 @@
  * haystack, false otherwise.
  */
 bool isInProductList(const String16& needle, const String16& haystack) {
-    const char16_t *needle2 = needle.string();
-    const char16_t *haystack2 = haystack.string();
+    const char16_t *needle2 = needle.c_str();
+    const char16_t *haystack2 = haystack.c_str();
     size_t needlesize = needle.size();
 
     while (*haystack2 != '\0') {
@@ -703,7 +703,7 @@
 
     String16 str;
     Vector<StringPool::entry_style_span> spans;
-    err = parseStyledString(bundle, in->getPrintableSource().string(), block,
+    err = parseStyledString(bundle, in->getPrintableSource().c_str(), block,
                             curTag, &str, curIsStyled ? &spans : NULL,
                             isFormatted, pseudolocalize);
 
@@ -730,7 +730,7 @@
          */
 
         if (bundleProduct[0] == '\0') {
-            if (strcmp16(String16("default").string(), product.string()) != 0) {
+            if (strcmp16(String16("default").c_str(), product.c_str()) != 0) {
                 /*
                  * This string has a product other than 'default'. Do not add it,
                  * but record it so that if we do not see the same string with
@@ -750,7 +750,7 @@
 
             if (isInProductList(product, String16(bundleProduct))) {
                 ;
-            } else if (strcmp16(String16("default").string(), product.string()) == 0 &&
+            } else if (strcmp16(String16("default").c_str(), product.c_str()) == 0 &&
                        !outTable->hasBagOrEntry(myPackage, curType, ident, config)) {
                 ;
             } else {
@@ -764,7 +764,7 @@
                 config.language[0], config.language[1],
                 config.country[0], config.country[1],
                 config.orientation, config.density,
-                String8(ident).string(), String8(str).string());
+                String8(ident).c_str(), String8(str).c_str());
     }
 
     err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
@@ -847,7 +847,7 @@
     bool hasErrors = false;
 
     bool fileIsTranslatable = true;
-    if (strstr(in->getPrintableSource().string(), "donottranslate") != NULL) {
+    if (strstr(in->getPrintableSource().c_str(), "donottranslate") != NULL) {
         fileIsTranslatable = false;
     }
 
@@ -869,9 +869,9 @@
                 "No start tag found\n");
         return UNKNOWN_ERROR;
     }
-    if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
+    if (strcmp16(block.getElementName(&len), resources16.c_str()) != 0) {
         SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
-                "Invalid start tag %s\n", String8(block.getElementName(&len)).string());
+                "Invalid start tag %s\n", String8(block.getElementName(&len)).c_str());
         return UNKNOWN_ERROR;
     }
 
@@ -900,7 +900,7 @@
         SourcePos(in->getPrintableSource(), 0).warning(
                 "Resource file %s is skipped as pseudolocalization"
                 " was done automatically.",
-                in->getPrintableSource().string());
+                in->getPrintableSource().c_str());
         return NO_ERROR;
     }
 
@@ -917,29 +917,29 @@
             bool curIsFormatted = fileIsTranslatable;
             bool localHasErrors = false;
 
-            if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
+            if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
                         && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
                         && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), public16.c_str()) == 0) {
                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
             
                 String16 type;
@@ -965,7 +965,7 @@
                     Res_value identValue;
                     if (!ResTable::stringToInt(identStr, len, &identValue)) {
                         srcPos.error("Given 'id' attribute is not an integer: %s\n",
-                                String8(block.getAttributeStringValue(identIdx, &len)).string());
+                                String8(block.getAttributeStringValue(identIdx, &len)).c_str());
                         hasErrors = localHasErrors = true;
                     } else {
                         ident = identValue.data;
@@ -1004,14 +1004,14 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), public16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), public_padding16.c_str()) == 0) {
                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
             
                 String16 type;
@@ -1037,7 +1037,7 @@
                     Res_value startValue;
                     if (!ResTable::stringToInt(startStr, len, &startValue)) {
                         srcPos.error("Given 'start' attribute is not an integer: %s\n",
-                                String8(block.getAttributeStringValue(startIdx, &len)).string());
+                                String8(block.getAttributeStringValue(startIdx, &len)).c_str());
                         hasErrors = localHasErrors = true;
                     } else {
                         start = startValue.data;
@@ -1057,7 +1057,7 @@
                     Res_value endValue;
                     if (!ResTable::stringToInt(endStr, len, &endValue)) {
                         srcPos.error("Given 'end' attribute is not an integer: %s\n",
-                                String8(block.getAttributeStringValue(endIdx, &len)).string());
+                                String8(block.getAttributeStringValue(endIdx, &len)).c_str());
                         hasErrors = localHasErrors = true;
                     } else {
                         end = endValue.data;
@@ -1114,14 +1114,14 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), public_padding16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), private_symbols16.c_str()) == 0) {
                 String16 pkg;
                 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
                 if (pkgIdx < 0) {
@@ -1144,14 +1144,14 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), private_symbols16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), java_symbol16.c_str()) == 0) {
                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
             
                 String16 type;
@@ -1186,7 +1186,7 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), java_symbol16.c_str()) == 0) {
                             break;
                         }
                     }
@@ -1194,7 +1194,7 @@
                 continue;
 
 
-            } else if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), add_resource16.c_str()) == 0) {
                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
             
                 String16 typeName;
@@ -1217,14 +1217,14 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), add_resource16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
                 
-            } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), declare_styleable16.c_str()) == 0) {
                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
                                 
                 String16 ident;
@@ -1258,30 +1258,30 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::START_TAG) {
-                        if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
                             while ((code=block.next()) != ResXMLTree::END_DOCUMENT
                                    && code != ResXMLTree::BAD_DOCUMENT) {
                                 if (code == ResXMLTree::END_TAG) {
-                                    if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
+                                    if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
                                         break;
                                     }
                                 }
                             }
                             continue;
-                        } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
+                        } else if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
                             while ((code=block.next()) != ResXMLTree::END_DOCUMENT
                                    && code != ResXMLTree::BAD_DOCUMENT) {
                                 if (code == ResXMLTree::END_TAG) {
-                                    if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
+                                    if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
                                         break;
                                     }
                                 }
                             }
                             continue;
-                        } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
+                        } else if (strcmp16(block.getElementName(&len), attr16.c_str()) != 0) {
                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                     "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
-                                    String8(block.getElementName(&len)).string());
+                                    String8(block.getElementName(&len)).c_str());
                             return UNKNOWN_ERROR;
                         }
 
@@ -1297,30 +1297,30 @@
                             SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
                             symbols->addSymbol(String8(itemIdent), 0, srcPos);
                             symbols->appendComment(String8(itemIdent), comment, srcPos);
-                            //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
-                            //     String8(comment).string());
+                            //printf("Attribute %s comment: %s\n", String8(itemIdent).c_str(),
+                            //     String8(comment).c_str());
                         }
                     } else if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), declare_styleable16.c_str()) == 0) {
                             break;
                         }
 
                         SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                 "Found tag </%s> where </attr> is expected\n",
-                                String8(block.getElementName(&len)).string());
+                                String8(block.getElementName(&len)).c_str());
                         return UNKNOWN_ERROR;
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), attr16.c_str()) == 0) {
                 err = compileAttribute(in, block, myPackage, outTable, NULL);
                 if (err != NO_ERROR) {
                     hasErrors = true;
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), item16.c_str()) == 0) {
                 curTag = &item16;
                 ssize_t attri = block.indexOfAttribute(NULL, "type");
                 if (attri >= 0) {
@@ -1333,12 +1333,12 @@
                     if (formatIdx >= 0) {
                         String16 formatStr = String16(block.getAttributeStringValue(
                                 formatIdx, &len));
-                        curFormat = parse_flags(formatStr.string(), formatStr.size(),
+                        curFormat = parse_flags(formatStr.c_str(), formatStr.size(),
                                                 gFormatFlags);
                         if (curFormat == 0) {
                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                     "Tag <item> 'format' attribute value \"%s\" not valid\n",
-                                    String8(formatStr).string());
+                                    String8(formatStr).c_str());
                             hasErrors = localHasErrors = true;
                         }
                     }
@@ -1348,7 +1348,7 @@
                     hasErrors = localHasErrors = true;
                 }
                 curIsStyled = true;
-            } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), string16.c_str()) == 0) {
                 // Note the existence and locale of every string we process
                 char rawLocale[RESTABLE_MAX_LOCALE_LEN];
                 curParams.getBcp47Locale(rawLocale);
@@ -1361,11 +1361,11 @@
                 for (size_t i = 0; i < n; i++) {
                     size_t length;
                     const char16_t* attr = block.getAttributeName(i, &length);
-                    if (strcmp16(attr, name16.string()) == 0) {
+                    if (strcmp16(attr, name16.c_str()) == 0) {
                         name.setTo(block.getAttributeStringValue(i, &length));
-                    } else if (strcmp16(attr, translatable16.string()) == 0) {
+                    } else if (strcmp16(attr, translatable16.c_str()) == 0) {
                         translatable.setTo(block.getAttributeStringValue(i, &length));
-                    } else if (strcmp16(attr, formatted16.string()) == 0) {
+                    } else if (strcmp16(attr, formatted16.c_str()) == 0) {
                         formatted.setTo(block.getAttributeStringValue(i, &length));
                     }
                 }
@@ -1380,8 +1380,8 @@
                         if (locale.size() > 0) {
                             SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
                                     "string '%s' marked untranslatable but exists in locale '%s'\n",
-                                    String8(name).string(),
-                                    locale.string());
+                                    String8(name).c_str(),
+                                    locale.c_str());
                             // hasErrors = localHasErrors = true;
                         } else {
                             // Intentionally empty block:
@@ -1407,31 +1407,31 @@
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
                 curIsStyled = true;
                 curIsPseudolocalizable = fileIsTranslatable && (translatable != false16);
-            } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), drawable16.c_str()) == 0) {
                 curTag = &drawable16;
                 curType = drawable16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
-            } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), color16.c_str()) == 0) {
                 curTag = &color16;
                 curType = color16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
-            } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), bool16.c_str()) == 0) {
                 curTag = &bool16;
                 curType = bool16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
-            } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), integer16.c_str()) == 0) {
                 curTag = &integer16;
                 curType = integer16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
-            } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), dimen16.c_str()) == 0) {
                 curTag = &dimen16;
                 curType = dimen16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
-            } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), fraction16.c_str()) == 0) {
                 curTag = &fraction16;
                 curType = fraction16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
-            } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), bag16.c_str()) == 0) {
                 curTag = &bag16;
                 curIsBag = true;
                 ssize_t attri = block.indexOfAttribute(NULL, "type");
@@ -1442,16 +1442,16 @@
                             "A 'type' attribute is required for <bag>\n");
                     hasErrors = localHasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), style16.c_str()) == 0) {
                 curTag = &style16;
                 curType = style16;
                 curIsBag = true;
-            } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), plurals16.c_str()) == 0) {
                 curTag = &plurals16;
                 curType = plurals16;
                 curIsBag = true;
                 curIsPseudolocalizable = fileIsTranslatable;
-            } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), array16.c_str()) == 0) {
                 curTag = &array16;
                 curType = array16;
                 curIsBag = true;
@@ -1460,16 +1460,16 @@
                 if (formatIdx >= 0) {
                     String16 formatStr = String16(block.getAttributeStringValue(
                             formatIdx, &len));
-                    curFormat = parse_flags(formatStr.string(), formatStr.size(),
+                    curFormat = parse_flags(formatStr.c_str(), formatStr.size(),
                                             gFormatFlags);
                     if (curFormat == 0) {
                         SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                 "Tag <array> 'format' attribute value \"%s\" not valid\n",
-                                String8(formatStr).string());
+                                String8(formatStr).c_str());
                         hasErrors = localHasErrors = true;
                     }
                 }
-            } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), string_array16.c_str()) == 0) {
                 // Check whether these strings need valid formats.
                 // (simplified form of what string16 does above)
                 bool isTranslatable = false;
@@ -1480,14 +1480,14 @@
                 for (size_t i = 0; i < n; i++) {
                     size_t length;
                     const char16_t* attr = block.getAttributeName(i, &length);
-                    if (strcmp16(attr, formatted16.string()) == 0) {
+                    if (strcmp16(attr, formatted16.c_str()) == 0) {
                         const char16_t* value = block.getAttributeStringValue(i, &length);
-                        if (strcmp16(value, false16.string()) == 0) {
+                        if (strcmp16(value, false16.c_str()) == 0) {
                             curIsFormatted = false;
                         }
-                    } else if (strcmp16(attr, translatable16.string()) == 0) {
+                    } else if (strcmp16(attr, translatable16.c_str()) == 0) {
                         const char16_t* value = block.getAttributeStringValue(i, &length);
-                        if (strcmp16(value, false16.string()) == 0) {
+                        if (strcmp16(value, false16.c_str()) == 0) {
                             isTranslatable = false;
                         }
                     }
@@ -1499,7 +1499,7 @@
                 curIsBag = true;
                 curIsBagReplaceOnOverwrite = true;
                 curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
-            } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), integer_array16.c_str()) == 0) {
                 curTag = &integer_array16;
                 curType = array16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
@@ -1508,7 +1508,7 @@
             } else {
                 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                         "Found tag %s where item is expected\n",
-                        String8(block.getElementName(&len)).string());
+                        String8(block.getElementName(&len)).c_str());
                 return UNKNOWN_ERROR;
             }
 
@@ -1519,7 +1519,7 @@
             } else {
                 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                         "A 'name' attribute is required for <%s>\n",
-                        String8(*curTag).string());
+                        String8(*curTag).c_str());
                 hasErrors = localHasErrors = true;
             }
 
@@ -1560,11 +1560,11 @@
                         && code != ResXMLTree::BAD_DOCUMENT) {
 
                     if (code == ResXMLTree::START_TAG) {
-                        if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
+                        if (strcmp16(block.getElementName(&len), item16.c_str()) != 0) {
                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                     "Tag <%s> can not appear inside <%s>, only <item>\n",
-                                    String8(block.getElementName(&len)).string(),
-                                    String8(*curTag).string());
+                                    String8(block.getElementName(&len)).c_str(),
+                                    String8(*curTag).c_str());
                             return UNKNOWN_ERROR;
                         }
 
@@ -1647,11 +1647,11 @@
                             hasErrors = localHasErrors = true;
                         }
                     } else if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
+                        if (strcmp16(block.getElementName(&len), curTag->c_str()) != 0) {
                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                     "Found tag </%s> where </%s> is expected\n",
-                                    String8(block.getElementName(&len)).string(),
-                                    String8(*curTag).string());
+                                    String8(block.getElementName(&len)).c_str(),
+                                    String8(*curTag).c_str());
                             return UNKNOWN_ERROR;
                         }
                         break;
@@ -1700,9 +1700,9 @@
 
 #if 0
             if (comment.size() > 0) {
-                printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
-                       String8(curType).string(), String8(ident).string(),
-                       String8(comment).string());
+                printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).c_str(),
+                       String8(curType).c_str(), String8(ident).c_str(),
+                       String8(comment).c_str());
             }
 #endif
             if (!localHasErrors) {
@@ -1710,9 +1710,9 @@
             }
         }
         else if (code == ResXMLTree::END_TAG) {
-            if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
+            if (strcmp16(block.getElementName(&len), resources16.c_str()) != 0) {
                 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
-                        "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
+                        "Unexpected end tag %s\n", String8(block.getElementName(&len)).c_str());
                 return UNKNOWN_ERROR;
             }
         }
@@ -1724,7 +1724,7 @@
             }
             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                     "Found text \"%s\" where item tag is expected\n",
-                    String8(block.getText(&len)).string());
+                    String8(block.getText(&len)).c_str());
             return UNKNOWN_ERROR;
         }
     }
@@ -1740,13 +1740,13 @@
                 const char* bundleProduct =
                         (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
                 fprintf(stderr, "In resource file %s: %s\n",
-                        in->getPrintableSource().string(),
-                        curParams.toString().string());
+                        in->getPrintableSource().c_str(),
+                        curParams.toString().c_str());
 
                 fprintf(stderr, "\t%s '%s' does not match product %s.\n"
                         "\tYou may have forgotten to include a 'default' product variant"
                         " of the resource.\n",
-                        String8(p.type).string(), String8(p.ident).string(),
+                        String8(p.type).c_str(), String8(p.ident).c_str(),
                         bundleProduct[0] == 0 ? "default" : bundleProduct);
                 return UNKNOWN_ERROR;
             }
@@ -1816,7 +1816,7 @@
         AssetManager featureAssetManager;
         if (!featureAssetManager.addAssetPath(featureAfter, NULL)) {
             fprintf(stderr, "ERROR: Feature package '%s' not found.\n",
-                    featureAfter.string());
+                    featureAfter.c_str());
             return UNKNOWN_ERROR;
         }
 
@@ -1835,13 +1835,13 @@
                                   const uint32_t ident)
 {
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size());
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size());
     if (rid != 0) {
         sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
-                String8(type).string(), String8(name).string(),
-                String8(package).string());
+                String8(type).c_str(), String8(name).c_str(),
+                String8(package).c_str());
         return UNKNOWN_ERROR;
     }
 
@@ -1864,12 +1864,12 @@
                                  const bool overwrite)
 {
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size());
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size());
     if (rid != 0) {
         sourcePos.error("Resource entry %s/%s is already defined in package %s.",
-                String8(type).string(), String8(name).string(), String8(package).string());
+                String8(type).c_str(), String8(name).c_str(), String8(package).c_str());
         return UNKNOWN_ERROR;
     }
     
@@ -1899,12 +1899,12 @@
     // Check for adding entries in other packages...  for now we do
     // nothing.  We need to do the right thing here to support skinning.
     uint32_t rid = mAssets->getIncludedResources()
-    .identifierForName(name.string(), name.size(),
-                       type.string(), type.size(),
-                       package.string(), package.size());
+    .identifierForName(name.c_str(), name.size(),
+                       type.c_str(), type.size(),
+                       package.c_str(), package.size());
     if (rid != 0) {
         sourcePos.error("Resource entry %s/%s is already defined in package %s.",
-                String8(type).string(), String8(name).string(), String8(package).string());
+                String8(type).c_str(), String8(name).c_str(), String8(package).c_str());
         return UNKNOWN_ERROR;
     }
 
@@ -1921,7 +1921,7 @@
         }
         if (!canAdd) {
             sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
-                            String8(name).string());
+                            String8(name).c_str());
             return UNKNOWN_ERROR;
         }
     }
@@ -1959,9 +1959,9 @@
     // Check for adding entries in other packages...  for now we do
     // nothing.  We need to do the right thing here to support skinning.
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size());
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size());
     if (rid != 0) {
         return NO_ERROR;
     }
@@ -1969,7 +1969,7 @@
 #if 0
     if (name == String16("left")) {
         printf("Adding bag left: file=%s, line=%d, type=%s\n",
-               sourcePos.file.striing(), sourcePos.line, String8(type).string());
+               sourcePos.file.striing(), sourcePos.line, String8(type).c_str());
     }
 #endif
     sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
@@ -1996,9 +1996,9 @@
 {
     // First look for this in the included resources...
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size());
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size());
     if (rid != 0) {
         return true;
     }
@@ -2022,9 +2022,9 @@
 {
     // First look for this in the included resources...
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size());
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size());
     if (rid != 0) {
         return true;
     }
@@ -2051,7 +2051,7 @@
                                   const String16* defPackage)
 {
     String16 package, type, name;
-    if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
+    if (!ResTable::expandResourceRef(ref.c_str(), ref.size(), &package, &type, &name,
                 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
         return false;
     }
@@ -2115,17 +2115,17 @@
 
     // First look for this in the included resources...
     uint32_t rid = mAssets->getIncludedResources()
-            .identifierForName(name.string(), name.size(),
-                               attr16.string(), attr16.size(),
-                               package.string(), package.size());
+            .identifierForName(name.c_str(), name.size(),
+                               attr16.c_str(), attr16.size(),
+                               package.c_str(), package.size());
     if (rid != 0) {
-        source.error("Attribute \"%s\" has already been defined", String8(name).string());
+        source.error("Attribute \"%s\" has already been defined", String8(name).c_str());
         return false;
     }
 
     sp<ResourceTable::Entry> entry = getEntry(package, attr16, name, source, false);
     if (entry == NULL) {
-        source.error("Failed to create entry attr/%s", String8(name).string());
+        source.error("Failed to create entry attr/%s", String8(name).c_str());
         return false;
     }
 
@@ -2146,7 +2146,7 @@
                 formatItem.value != formatValue16) {
             source.error("Attribute \"%s\" already defined with incompatible format.\n"
                          "%s:%d: Original attribute defined here.",
-                         String8(name).string(), formatItem.sourcePos.file.string(),
+                         String8(name).c_str(), formatItem.sourcePos.file.c_str(),
                          formatItem.sourcePos.line);
             return false;
         }
@@ -2207,9 +2207,9 @@
     // First look for this in the included resources...
     uint32_t specFlags = 0;
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size(),
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size(),
                            &specFlags);
     if (rid != 0) {
         if (onlyPublic && (specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
@@ -2253,27 +2253,27 @@
     String16 package, type, name;
     bool refOnlyPublic = true;
     if (!ResTable::expandResourceRef(
-        ref.string(), ref.size(), &package, &type, &name,
+        ref.c_str(), ref.size(), &package, &type, &name,
         defType, defPackage ? defPackage:&mAssetsPackage,
         outErrorMsg, &refOnlyPublic)) {
         if (kIsDebug) {
-            printf("Expanding resource: ref=%s\n", String8(ref).string());
+            printf("Expanding resource: ref=%s\n", String8(ref).c_str());
             printf("Expanding resource: defType=%s\n",
-                    defType ? String8(*defType).string() : "NULL");
+                    defType ? String8(*defType).c_str() : "NULL");
             printf("Expanding resource: defPackage=%s\n",
-                    defPackage ? String8(*defPackage).string() : "NULL");
-            printf("Expanding resource: ref=%s\n", String8(ref).string());
+                    defPackage ? String8(*defPackage).c_str() : "NULL");
+            printf("Expanding resource: ref=%s\n", String8(ref).c_str());
             printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
-                    String8(package).string(), String8(type).string(),
-                    String8(name).string());
+                    String8(package).c_str(), String8(type).c_str(),
+                    String8(name).c_str());
         }
         return 0;
     }
     uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
     if (kIsDebug) {
         printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
-                String8(package).string(), String8(type).string(),
-                String8(name).string(), res);
+                String8(package).c_str(), String8(type).c_str(),
+                String8(name).c_str(), res);
     }
     if (res == 0) {
         if (outErrorMsg)
@@ -2284,7 +2284,7 @@
 
 bool ResourceTable::isValidResourceName(const String16& s)
 {
-    const char16_t* p = s.string();
+    const char16_t* p = s.c_str();
     bool first = true;
     while (*p) {
         if ((*p >= 'a' && *p <= 'z')
@@ -2315,7 +2315,7 @@
     if (style == NULL || style->size() == 0) {
         // Text is not styled so it can be any type...  let's figure it out.
         res = mAssets->getIncludedResources()
-            .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
+            .stringToValue(outValue, &finalStr, str.c_str(), str.size(), preserveSpaces,
                             coerceType, attrID, NULL, &mAssetsPackage, this,
                            accessorCookie, attrType);
     } else {
@@ -2344,7 +2344,7 @@
             if (kIsDebug) {
                 printf("Adding to pool string style #%zu config %s: %s\n",
                         style != NULL ? style->size() : 0U,
-                        configStr.string(), String8(finalStr).string());
+                        configStr.c_str(), String8(finalStr).c_str());
             }
             if (style != NULL && style->size() > 0) {
                 outValue->data = pool->add(finalStr, *style, configTypeName, config);
@@ -2368,8 +2368,8 @@
 uint32_t ResourceTable::getCustomResource(
     const String16& package, const String16& type, const String16& name) const
 {
-    //printf("getCustomResource: %s %s %s\n", String8(package).string(),
-    //       String8(type).string(), String8(name).string());
+    //printf("getCustomResource: %s %s %s\n", String8(package).c_str(),
+    //       String8(type).c_str(), String8(name).c_str());
     sp<Package> p = mPackages.valueFor(package);
     if (p == NULL) return 0;
     sp<Type> t = p->getTypes().valueFor(type);
@@ -2400,7 +2400,7 @@
 
     if (mAssetsPackage != package) {
         mCurrentXmlPos.error("creating resource for external package %s: %s/%s.",
-                String8(package).string(), String8(type).string(), String8(name).string());
+                String8(package).c_str(), String8(type).c_str(), String8(name).c_str());
         if (package == String16("android")) {
             mCurrentXmlPos.printf("did you mean to use @+id instead of @+android:id?");
         }
@@ -2427,7 +2427,7 @@
     Res_value value;
     if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
         //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
-        //       String8(getEntry(attrID)->getName()).string(), value.data);
+        //       String8(getEntry(attrID)->getName()).c_str(), value.data);
         *outType = value.data;
         return true;
     }
@@ -2481,7 +2481,7 @@
         vsnprintf(buf, sizeof(buf), fmt, ap);
         va_end(ap);
         ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
-                            buf, ac->attr.string(), ac->value.string());
+                            buf, ac->attr.c_str(), ac->value.c_str());
     }
 }
 
@@ -2493,7 +2493,7 @@
         const size_t N = e->getBag().size();
         for (size_t i=0; i<N; i++) {
             const String16& key = e->getBag().keyAt(i);
-            if (key.size() > 0 && key.string()[0] != '^') {
+            if (key.size() > 0 && key.c_str()[0] != '^') {
                 outKeys->add(key);
             }
         }
@@ -2506,14 +2506,14 @@
     uint32_t attrID, const char16_t* name, size_t nameLen,
     Res_value* outValue)
 {
-    //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
+    //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).c_str());
     String16 nameStr(name, nameLen);
     sp<const Entry> e = getEntry(attrID);
     if (e != NULL) {
         const size_t N = e->getBag().size();
         for (size_t i=0; i<N; i++) {
-            //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
-            //       String8(e->getBag().keyAt(i)).string());
+            //printf("Comparing %s to %s\n", String8(name, nameLen).c_str(),
+            //       String8(e->getBag().keyAt(i)).c_str());
             if (e->getBag().keyAt(i) == nameStr) {
                 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
             }
@@ -2529,7 +2529,7 @@
     outValue->dataType = Res_value::TYPE_INT_HEX;
     outValue->data = 0;
 
-    //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
+    //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).c_str());
     String16 nameStr(name, nameLen);
     sp<const Entry> e = getEntry(attrID);
     if (e != NULL) {
@@ -2546,8 +2546,8 @@
             String16 nameStr(start, pos-start);
             size_t i;
             for (i=0; i<N; i++) {
-                //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
-                //       String8(e->getBag().keyAt(i)).string());
+                //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).c_str(),
+                //       String8(e->getBag().keyAt(i)).c_str());
                 if (e->getBag().keyAt(i) == nameStr) {
                     Res_value val;
                     bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
@@ -2753,7 +2753,7 @@
                         if (mHasDefaultLocalization.find(c->getName())
                                 == mHasDefaultLocalization.end()) {
                             // printf("Skip symbol [%08x] %s\n", rid,
-                            //          String8(c->getName()).string());
+                            //          String8(c->getName()).c_str());
                             continue;
                         }
                     }
@@ -2763,7 +2763,7 @@
                     String16 comment(c->getComment());
                     typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
                     //printf("Type symbol [%08x] %s comment: %s\n", rid,
-                    //        String8(c->getName()).string(), String8(comment).string());
+                    //        String8(c->getName()).c_str(), String8(comment).c_str());
                     comment = c->getTypeComment();
                     typeSymbols->appendTypeComment(String8(c->getName()), comment);
                 }
@@ -2809,10 +2809,10 @@
         // Look for strings with no default localization
         if (configSrcMap.count(defaultLocale) == 0) {
             SourcePos().warning("string '%s' has no default translation.",
-                    String8(nameIter.first).string());
+                    String8(nameIter.first).c_str());
             if (mBundle->getVerbose()) {
                 for (const auto& locale : configSrcMap) {
-                    locale.second.printf("locale %s found", locale.first.string());
+                    locale.second.printf("locale %s found", locale.first.c_str());
                 }
             }
             // !!! TODO: throw an error here in some circumstances
@@ -2820,7 +2820,7 @@
 
         // Check that all requested localizations are present for this string
         if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
-            const char* allConfigs = mBundle->getConfigurations().string();
+            const char* allConfigs = mBundle->getConfigurations().c_str();
             const char* start = allConfigs;
             const char* comma;
 
@@ -2847,7 +2847,7 @@
                         // requiring a specific regional localization [e.g. de_DE] but there is an
                         // available string in the generic language localization [e.g. de];
                         // consider that string to have fulfilled the localization requirement.
-                        String8 region(config.string(), 2);
+                        String8 region(config.c_str(), 2);
                         if (configSrcMap.find(region) == configSrcMap.end() &&
                                 configSrcMap.count(defaultLocale) == 0) {
                             missingConfigs.insert(config);
@@ -2859,12 +2859,12 @@
             if (!missingConfigs.empty()) {
                 String8 configStr;
                 for (const auto& iter : missingConfigs) {
-                    configStr.appendFormat(" %s", iter.string());
+                    configStr.appendFormat(" %s", iter.c_str());
                 }
                 SourcePos().warning("string '%s' is missing %u required localizations:%s",
-                        String8(nameIter.first).string(),
+                        String8(nameIter.first).c_str(),
                         (unsigned int)missingConfigs.size(),
-                        configStr.string());
+                        configStr.c_str());
             }
         }
     }
@@ -3021,7 +3021,7 @@
         header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
         header->header.headerSize = htods(sizeof(*header));
         header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
-        strcpy16_htod(header->name, p->getName().string());
+        strcpy16_htod(header->name, p->getName().c_str());
 
         // Write the string blocks.
         const size_t typeStringsStart = data->getSize();
@@ -3061,7 +3061,7 @@
             sp<Type> t = p->getTypes().valueFor(typeName);
             LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
                                 "Type name %s not found",
-                                String8(typeName).string());
+                                String8(typeName).c_str());
             if (t == NULL) {
                 continue;
             }
@@ -3260,7 +3260,7 @@
                         sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
                         if (c != NULL) {
                             fprintf(stderr, "%s: no entries written for %s/%s (0x%08zx)\n", log_prefix,
-                                    String8(typeName).string(), String8(c->getName()).string(),
+                                    String8(typeName).c_str(), String8(c->getName()).c_str(),
                                     Res_MAKEID(p->getAssignedId() - 1, ti, i));
                         }
                         missing_entry = true;
@@ -3359,7 +3359,7 @@
             sp<Package> libPackage = libs[i];
             if (kIsDebug) {
                 fprintf(stderr, "  Entry %s -> 0x%02x\n",
-                        String8(libPackage->getName()).string(),
+                        String8(libPackage->getName()).c_str(),
                         (uint8_t)libPackage->getAssignedId());
             }
 
@@ -3367,7 +3367,7 @@
                     entryStart, sizeof(ResTable_lib_entry));
             memset(entry, 0, sizeof(*entry));
             entry->packageId = htodl(libPackage->getAssignedId());
-            strcpy16_htod(entry->packageName, libPackage->getName().string());
+            strcpy16_htod(entry->packageName, libPackage->getName().c_str());
         }
     }
     return NO_ERROR;
@@ -3435,13 +3435,13 @@
                         const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
                         if (pos.file != "") {
                             fprintf(fp,"  <!-- Declared at %s:%d -->\n",
-                                    pos.file.string(), pos.line);
+                                    pos.file.c_str(), pos.line);
                         }
                     }
                 }
                 fprintf(fp, "  <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
-                        String8(t->getName()).string(),
-                        String8(c->getName()).string(),
+                        String8(t->getName()).c_str(),
+                        String8(c->getName()).c_str(),
                         getResId(pkg, t, c->getEntryIndex()));
             }
         }
@@ -3501,8 +3501,8 @@
     }
     sourcePos.error("Resource entry %s is already defined as a single item.\n"
                     "%s:%d: Originally defined here.\n",
-                    String8(mName).string(),
-                    mItem.sourcePos.file.string(), mItem.sourcePos.line);
+                    String8(mName).c_str(),
+                    mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
     return UNKNOWN_ERROR;
 }
 
@@ -3517,21 +3517,21 @@
     if (mType == TYPE_BAG) {
         if (mBag.size() == 0) {
             sourcePos.error("Resource entry %s is already defined as a bag.",
-                    String8(mName).string());
+                    String8(mName).c_str());
         } else {
             const Item& item(mBag.valueAt(0));
             sourcePos.error("Resource entry %s is already defined as a bag.\n"
                             "%s:%d: Originally defined here.\n",
-                            String8(mName).string(),
-                            item.sourcePos.file.string(), item.sourcePos.line);
+                            String8(mName).c_str(),
+                            item.sourcePos.file.c_str(), item.sourcePos.line);
         }
         return UNKNOWN_ERROR;
     }
     if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
         sourcePos.error("Resource entry %s is already defined.\n"
                         "%s:%d: Originally defined here.\n",
-                        String8(mName).string(),
-                        mItem.sourcePos.file.string(), mItem.sourcePos.line);
+                        String8(mName).c_str(),
+                        mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
         return UNKNOWN_ERROR;
     }
 
@@ -3562,12 +3562,12 @@
             const Item& item(mBag.valueAt(origKey));
             sourcePos.error("Resource entry %s already has bag item %s.\n"
                     "%s:%d: Originally defined here.\n",
-                    String8(mName).string(), String8(key).string(),
-                    item.sourcePos.file.string(), item.sourcePos.line);
+                    String8(mName).c_str(), String8(key).c_str(),
+                    item.sourcePos.file.c_str(), item.sourcePos.line);
             return UNKNOWN_ERROR;
         }
         //printf("Replacing %s with %s\n",
-        //       String8(mBag.valueFor(key).value).string(), String8(value).string());
+        //       String8(mBag.valueFor(key).value).c_str(), String8(value).c_str());
         mBag.replaceValueFor(key, item);
     }
 
@@ -3611,8 +3611,8 @@
                 String16 value("false");
                 if (kIsDebug) {
                     fprintf(stderr, "Generating %s:id/%s\n",
-                            String8(package).string(),
-                            String8(key).string());
+                            String8(package).c_str(),
+                            String8(key).c_str());
                 }
                 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
                                                id16, key, value);
@@ -3624,10 +3624,10 @@
 
 #if 1
 //             fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
-//                     String8(key).string());
+//                     String8(key).c_str());
 //             const Item& item(mBag.valueAt(i));
 //             fprintf(stderr, "Referenced from file %s line %d\n",
-//                     item.sourcePos.file.string(), item.sourcePos.line);
+//                     item.sourcePos.file.c_str(), item.sourcePos.line);
 //             return UNKNOWN_ERROR;
 #else
             char numberStr[16];
@@ -3660,7 +3660,7 @@
             mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
             if (mParentId == 0) {
                 mPos.error("Error retrieving parent for item: %s '%s'.\n",
-                        errorMsg, String8(mParent).string());
+                        errorMsg, String8(mParent).c_str());
                 hasErrors = true;
             }
         }
@@ -3670,11 +3670,11 @@
             Item& it = mBag.editValueAt(i);
             it.bagKeyId = table->getResId(key,
                     it.isId ? &id16 : &attr16, NULL, &errorMsg);
-            //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
+            //printf("Bag key of %s: #%08x\n", String8(key).c_str(), it.bagKeyId);
             if (it.bagKeyId == 0) {
                 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
-                        String8(it.isId ? id16 : attr16).string(),
-                        String8(key).string());
+                        String8(it.isId ? id16 : attr16).c_str(),
+                        String8(key).c_str());
                 hasErrors = true;
             }
         }
@@ -3709,7 +3709,7 @@
         }
     } else {
         mPos.error("Error: entry %s is not a single item or a bag.\n",
-                   String8(mName).string());
+                   String8(mName).c_str());
         return UNKNOWN_ERROR;
     }
     return NO_ERROR;
@@ -3732,7 +3732,7 @@
         }
     } else {
         mPos.error("Error: entry %s is not a single item or a bag.\n",
-                   String8(mName).string());
+                   String8(mName).c_str());
         return UNKNOWN_ERROR;
     }
     return NO_ERROR;
@@ -3768,7 +3768,7 @@
         par.data = htodl(it.parsedValue.data);
         #if 0
         printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
-               String8(mName).string(), it.parsedValue.dataType,
+               String8(mName).c_str(), it.parsedValue.dataType,
                it.parsedValue.data, par.res0);
         #endif
         err = data->writeData(&par, it.parsedValue.size);
@@ -3852,7 +3852,7 @@
     int32_t entryIdx = Res_GETENTRY(ident);
     if (entryIdx < 0) {
         sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
-                String8(mName).string(), String8(name).string(), ident);
+                String8(mName).c_str(), String8(name).c_str(), ident);
         return UNKNOWN_ERROR;
     }
     #endif
@@ -3863,7 +3863,7 @@
         if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
             sourcePos.error("Public resource %s/%s has conflicting type codes for its"
                     " public identifiers (0x%x vs 0x%x).\n",
-                    String8(mName).string(), String8(name).string(),
+                    String8(mName).c_str(), String8(name).c_str(),
                     mPublicIndex, typeIdx);
             return UNKNOWN_ERROR;
         }
@@ -3882,8 +3882,8 @@
             sourcePos.error("Public resource %s/%s has conflicting public identifiers"
                     " (0x%08x vs 0x%08x).\n"
                     "%s:%d: Originally defined here.\n",
-                    String8(mName).string(), String8(name).string(), p.ident, ident,
-                    p.sourcePos.file.string(), p.sourcePos.line);
+                    String8(mName).c_str(), String8(name).c_str(), p.ident, ident,
+                    p.sourcePos.file.c_str(), p.sourcePos.line);
             return UNKNOWN_ERROR;
         }
     }
@@ -3909,7 +3909,7 @@
         if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
             sourcePos.error("Resource at %s appears in overlay but not"
                             " in the base package; use <add-resource> to add.\n",
-                            String8(entry).string());
+                            String8(entry).c_str());
             return NULL;
         }
         c = new ConfigList(entry, sourcePos);
@@ -3931,7 +3931,7 @@
                 printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
                     "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
                     "sw%ddp w%ddp h%ddp layout:%d\n",
-                      sourcePos.file.string(), sourcePos.line,
+                      sourcePos.file.c_str(), sourcePos.line,
                       config->mcc, config->mnc,
                       config->language[0] ? config->language[0] : '-',
                       config->language[1] ? config->language[1] : '-',
@@ -3951,7 +3951,7 @@
                       config->screenLayout);
             } else {
                 printf("New entry at %s:%d: NULL config\n",
-                        sourcePos.file.string(), sourcePos.line);
+                        sourcePos.file.c_str(), sourcePos.line);
             }
         }
         e = new Entry(entry, sourcePos);
@@ -4032,11 +4032,11 @@
         const Public& p = mPublic.valueAt(j);
         int32_t idx = Res_GETENTRY(p.ident);
         //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
-        //       String8(mName).string(), String8(name).string(), p.ident, N);
+        //       String8(mName).c_str(), String8(name).c_str(), p.ident, N);
         bool found = false;
         for (i=0; i<N; i++) {
             sp<ConfigList> e = origOrder.itemAt(i);
-            //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
+            //printf("#%d: \"%s\"\n", i, String8(e->getName()).c_str());
             if (e->getName() == name) {
                 if (idx >= (int32_t)mOrderedConfigs.size()) {
                     mOrderedConfigs.resize(idx + 1);
@@ -4056,10 +4056,10 @@
                     p.sourcePos.error("Multiple entry names declared for public entry"
                             " identifier 0x%x in type %s (%s vs %s).\n"
                             "%s:%d: Originally defined here.",
-                            idx+1, String8(mName).string(),
-                            String8(oe->getName()).string(),
-                            String8(name).string(),
-                            oe->getPublicSourcePos().file.string(),
+                            idx+1, String8(mName).c_str(),
+                            String8(oe->getName()).c_str(),
+                            String8(name).c_str(),
+                            oe->getPublicSourcePos().file.c_str(),
                             oe->getPublicSourcePos().line);
                     hasError = true;
                 }
@@ -4068,7 +4068,7 @@
 
         if (!found) {
             p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
-                    String8(mName).string(), String8(name).string());
+                    String8(mName).c_str(), String8(name).c_str());
             hasError = true;
         }
     }
@@ -4189,9 +4189,9 @@
                 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
                         " identifier 0x%x (%s vs %s).\n"
                         "%s:%d: Originally defined here.",
-                        idx, String8(ot->getName()).string(),
-                        String8(t->getName()).string(),
-                        ot->getFirstPublicSourcePos().file.string(),
+                        idx, String8(ot->getName()).c_str(),
+                        String8(t->getName()).c_str(),
+                        ot->getFirstPublicSourcePos().file.c_str(),
                         ot->getFirstPublicSourcePos().line);
                 return UNKNOWN_ERROR;
             }
@@ -4399,8 +4399,8 @@
         const Item& it = e->getBag().valueAt(i);
         if (it.bagKeyId == 0) {
             fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
-                    String8(e->getName()).string(),
-                    String8(e->getBag().keyAt(i)).string());
+                    String8(e->getName()).c_str(),
+                    String8(e->getBag().keyAt(i)).c_str());
         }
         if (it.bagKeyId == attrID) {
             return &it;
@@ -4427,8 +4427,8 @@
                 }
             }
             fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
-                    String8(e->getName()).string(),
-                    String8(e->getBag().keyAt(i)).string());
+                    String8(e->getName()).c_str(),
+                    String8(e->getBag().keyAt(i)).c_str());
             return false;
         }
         item->evaluating = true;
@@ -4436,7 +4436,7 @@
         if (kIsDebug) {
             if (res) {
                 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
-                       resID, attrID, String8(getEntry(resID)->getName()).string(),
+                       resID, attrID, String8(getEntry(resID)->getName()).c_str(),
                        outValue->dataType, outValue->data);
             } else {
                 printf("getItemValue of #%08x[#%08x]: failed\n",
@@ -4713,10 +4713,10 @@
                         entriesToAdd[i].value->getPos()
                                 .printf("using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
                                         entriesToAdd[i].key.sdkVersion,
-                                        String8(p->getName()).string(),
-                                        String8(t->getName()).string(),
-                                        String8(entriesToAdd[i].value->getName()).string(),
-                                        entriesToAdd[i].key.toString().string());
+                                        String8(p->getName()).c_str(),
+                                        String8(t->getName()).c_str(),
+                                        String8(entriesToAdd[i].value->getName()).c_str(),
+                                        entriesToAdd[i].key.toString().c_str());
                     }
 
                     sp<Entry> newEntry = t->getEntry(c->getName(),
@@ -4801,8 +4801,8 @@
     sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
             AaptGroupEntry(newConfig), target->getResourceType());
     String8 resPath = String8::format("res/%s/%s.xml",
-            newFile->getGroupEntry().toDirName(target->getResourceType()).string(),
-            String8(resourceName).string());
+            newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
+            String8(resourceName).c_str());
     resPath.convertToResPath();
 
     // Add a resource table entry.
@@ -4893,10 +4893,10 @@
                 if (bundle->getVerbose()) {
                     SourcePos(node->getFilename(), node->getStartLineNumber()).printf(
                             "removing attribute %s%s%s from <%s>",
-                            String8(attr.ns).string(),
+                            String8(attr.ns).c_str(),
                             (attr.ns.size() == 0 ? "" : ":"),
-                            String8(attr.name).string(),
-                            String8(node->getElementName()).string());
+                            String8(attr.name).c_str(),
+                            String8(node->getElementName()).c_str());
                 }
                 node->removeAttribute(i);
                 i--;
@@ -4925,8 +4925,8 @@
         sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
                 AaptGroupEntry(newConfig), target->getResourceType());
         String8 resPath = String8::format("res/%s/%s.xml",
-                newFile->getGroupEntry().toDirName(target->getResourceType()).string(),
-                String8(resourceName).string());
+                newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
+                String8(resourceName).c_str());
         resPath.convertToResPath();
 
         // Add a resource table entry.
@@ -4934,10 +4934,10 @@
             SourcePos(target->getSourceFile(), -1).printf(
                     "using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
                     newConfig.sdkVersion,
-                    mAssets->getPackage().string(),
-                    newFile->getResourceType().string(),
-                    String8(resourceName).string(),
-                    newConfig.toString().string());
+                    mAssets->getPackage().c_str(),
+                    newFile->getResourceType().c_str(),
+                    String8(resourceName).c_str(),
+                    newConfig.toString().c_str());
         }
 
         addEntry(SourcePos(),
@@ -5114,8 +5114,8 @@
         sp<XMLNode> nestedRoot = findOnlyChildElement(child);
         if (nestedRoot == NULL) {
             source.error("<%s:%s> must have exactly one child element",
-                         String8(child->getElementNamespace()).string(),
-                         String8(child->getElementName()).string());
+                         String8(child->getElementNamespace()).c_str(),
+                         String8(child->getElementName()).c_str());
             return UNKNOWN_ERROR;
         }
 
@@ -5130,7 +5130,7 @@
         // Parse the attribute name.
         const char* errorMsg = NULL;
         String16 attrPackage, attrType, attrName;
-        bool result = ResTable::expandResourceRef(attr->string.string(),
+        bool result = ResTable::expandResourceRef(attr->string.c_str(),
                                                   attr->string.size(),
                                                   &attrPackage, &attrType, &attrName,
                                                   &kAttr16, &kAssetPackage16,
@@ -5156,11 +5156,11 @@
             // This child element will be extracted into its own resource file.
             // Generate a name and path for it from its parent.
             nestedResourceName = String8::format("%s_%d",
-                        String8(resourceName).string(), suffix++);
+                        String8(resourceName).c_str(), suffix++);
             nestedResourcePath = String8::format("res/%s/%s.xml",
                         target->getGroupEntry().toDirName(target->getResourceType())
-                                               .string(),
-                        nestedResourceName.string());
+                                               .c_str(),
+                        nestedResourceName.c_str());
 
             // Lookup or create the entry for this name.
             sp<Entry> entry = getEntry(kAssetPackage16,
@@ -5187,20 +5187,20 @@
 
         if (bundle->getVerbose()) {
             source.printf("generating nested resource %s:%s/%s",
-                    mAssets->getPackage().string(), target->getResourceType().string(),
-                    nestedResourceName.string());
+                    mAssets->getPackage().c_str(), target->getResourceType().c_str(),
+                    nestedResourceName.c_str());
         }
 
         // Build the attribute reference and assign it to the parent.
         String16 nestedResourceRef = String16(String8::format("@%s:%s/%s",
-                    mAssets->getPackage().string(), target->getResourceType().string(),
-                    nestedResourceName.string()));
+                    mAssets->getPackage().c_str(), target->getResourceType().c_str(),
+                    nestedResourceName.c_str()));
 
         String16 attrNs = buildNamespace(attrPackage);
         if (parent->getAttribute(attrNs, attrName) != NULL) {
             SourcePos(parent->getFilename(), parent->getStartLineNumber())
                     .error("parent of nested resource already defines attribute '%s:%s'",
-                           String8(attrPackage).string(), String8(attrName).string());
+                           String8(attrPackage).c_str(), String8(attrName).c_str());
             return UNKNOWN_ERROR;
         }
 
diff --git a/tools/aapt/SourcePos.cpp b/tools/aapt/SourcePos.cpp
index 3864320..e130286 100644
--- a/tools/aapt/SourcePos.cpp
+++ b/tools/aapt/SourcePos.cpp
@@ -80,12 +80,12 @@
     
     if (!this->file.isEmpty()) {
         if (this->line >= 0) {
-            fprintf(to, "%s:%d: %s%s\n", this->file.string(), this->line, type, this->error.string());
+            fprintf(to, "%s:%d: %s%s\n", this->file.c_str(), this->line, type, this->error.c_str());
         } else {
-            fprintf(to, "%s: %s%s\n", this->file.string(), type, this->error.string());
+            fprintf(to, "%s: %s%s\n", this->file.c_str(), type, this->error.c_str());
         }
     } else {
-        fprintf(to, "%s%s\n", type, this->error.string());
+        fprintf(to, "%s%s\n", type, this->error.c_str());
     }
 }
 
diff --git a/tools/aapt/StringPool.cpp b/tools/aapt/StringPool.cpp
index 6cacd32..8d02683 100644
--- a/tools/aapt/StringPool.cpp
+++ b/tools/aapt/StringPool.cpp
@@ -67,7 +67,7 @@
     const size_t NS = pool->size();
     for (size_t s=0; s<NS; s++) {
         auto str = pool->string8ObjectAt(s);
-        printf("String #" ZD ": %s\n", (ZD_TYPE) s, (str.has_value() ? str->string() : ""));
+        printf("String #" ZD ": %s\n", (ZD_TYPE) s, (str.has_value() ? str->c_str() : ""));
     }
 }
 
@@ -139,7 +139,7 @@
     if (eidx < 0) {
         eidx = mEntries.add(entry(value));
         if (eidx < 0) {
-            fprintf(stderr, "Failure adding string %s\n", String8(value).string());
+            fprintf(stderr, "Failure adding string %s\n", String8(value).c_str());
             return eidx;
         }
     }
@@ -148,7 +148,7 @@
         entry& ent = mEntries.editItemAt(eidx);
         if (kIsDebug) {
             printf("*** adding config type name %s, was %s\n",
-                    configTypeName->string(), ent.configTypeName.string());
+                    configTypeName->c_str(), ent.configTypeName.c_str());
         }
         if (ent.configTypeName.size() <= 0) {
             ent.configTypeName = *configTypeName;
@@ -166,7 +166,7 @@
             if (cmp >= 0) {
                 if (cmp > 0) {
                     if (kIsDebug) {
-                        printf("*** inserting config: %s\n", config->toString().string());
+                        printf("*** inserting config: %s\n", config->toString().c_str());
                     }
                     ent.configs.insertAt(*config, addPos);
                 }
@@ -175,7 +175,7 @@
         }
         if (addPos >= ent.configs.size()) {
             if (kIsDebug) {
-                printf("*** adding config: %s\n", config->toString().string());
+                printf("*** adding config: %s\n", config->toString().c_str());
             }
             ent.configs.add(*config);
         }
@@ -195,7 +195,7 @@
 
     if (kIsDebug) {
         printf("Adding string %s to pool: pos=%zd eidx=%zd vidx=%zd\n",
-                String8(value).string(), pos, eidx, vidx);
+                String8(value).c_str(), pos, eidx, vidx);
     }
 
     return pos;
@@ -286,13 +286,13 @@
 
     for (size_t i=0; i<N; i++) {
         printf("#%d was %d: %s\n", i, newPosToOriginalPos[i],
-                mEntries[mEntryArray[newPosToOriginalPos[i]]].makeConfigsString().string());
+                mEntries[mEntryArray[newPosToOriginalPos[i]]].makeConfigsString().c_str());
         entries.add(mEntries[mEntryArray[i]]);
     }
 
     for (size_t i=0; i<entries.size(); i++) {
         printf("Sorted config #%d: %s\n", i,
-                entries[i].makeConfigsString().string());
+                entries[i].makeConfigsString().c_str());
     }
 #endif
 
@@ -363,8 +363,8 @@
     printf("FINAL SORTED STRING CONFIGS:\n");
     for (size_t i=0; i<mEntries.size(); i++) {
         const entry& ent = mEntries[i];
-        printf("#" ZD " %s: %s\n", (ZD_TYPE)i, ent.makeConfigsString().string(),
-                String8(ent.value).string());
+        printf("#" ZD " %s: %s\n", (ZD_TYPE)i, ent.makeConfigsString().c_str(),
+                String8(ent.value).c_str());
     }
 #endif
 }
@@ -415,7 +415,7 @@
             ssize_t idx = add(span.name, true);
             if (idx < 0) {
                 fprintf(stderr, "Error adding span for style tag '%s'\n",
-                        String8(span.name).string());
+                        String8(span.name).c_str());
                 return idx;
             }
             span.span.name.index = (uint32_t)idx;
@@ -571,7 +571,7 @@
         if (kIsDebug) {
             printf("Writing entry #%zu: \"%s\" ent=%zu off=%zu\n",
                     i,
-                    String8(ent.value).string(),
+                    String8(ent.value).c_str(),
                     mEntryArray[i],
                     ent.offset);
         }
@@ -591,8 +591,8 @@
     const Vector<size_t>* indices = offsetsForString(val);
     ssize_t res = indices != NULL && indices->size() > 0 ? indices->itemAt(0) : -1;
     if (kIsDebug) {
-        printf("Offset for string %s: %zd (%s)\n", String8(val).string(), res,
-                res >= 0 ? String8(mEntries[mEntryArray[res]].value).string() : String8());
+        printf("Offset for string %s: %zd (%s)\n", String8(val).c_str(), res,
+                res >= 0 ? String8(mEntries[mEntryArray[res]].value).c_str() : String8());
     }
     return res;
 }
diff --git a/tools/aapt/Symbol.h b/tools/aapt/Symbol.h
index e157541..de1d60c 100644
--- a/tools/aapt/Symbol.h
+++ b/tools/aapt/Symbol.h
@@ -68,9 +68,9 @@
 
 android::String8 Symbol::toString() const {
     return android::String8::format("%s:%s/%s (0x%08x)",
-            android::String8(package).string(),
-            android::String8(type).string(),
-            android::String8(name).string(),
+            android::String8(package).c_str(),
+            android::String8(type).c_str(),
+            android::String8(name).c_str(),
             (int) id);
 }
 
diff --git a/tools/aapt/XMLNode.cpp b/tools/aapt/XMLNode.cpp
index 69392d6..e270a73 100644
--- a/tools/aapt/XMLNode.cpp
+++ b/tools/aapt/XMLNode.cpp
@@ -66,14 +66,14 @@
 
 String16 getNamespaceResourcePackage(const String16& appPackage, const String16& namespaceUri, bool* outIsPublic)
 {
-    //printf("%s starts with %s?\n", String8(namespaceUri).string(),
-    //       String8(RESOURCES_PREFIX).string());
+    //printf("%s starts with %s?\n", String8(namespaceUri).c_str(),
+    //       String8(RESOURCES_PREFIX).c_str());
     size_t prefixSize;
     bool isPublic = true;
     if(namespaceUri.startsWith(RESOURCES_PREFIX_AUTO_PACKAGE)) {
         if (kIsDebug) {
-            printf("Using default application package: %s -> %s\n", String8(namespaceUri).string(),
-                   String8(appPackage).string());
+            printf("Using default application package: %s -> %s\n", String8(namespaceUri).c_str(),
+                   String8(appPackage).c_str());
         }
         isPublic = true;
         return appPackage;
@@ -88,7 +88,7 @@
     }
 
     //printf("YES!\n");
-    //printf("namespace: %s\n", String8(String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize)).string());
+    //printf("namespace: %s\n", String8(String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize)).c_str());
     if (outIsPublic) *outIsPublic = isPublic;
     return String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize);
 }
@@ -97,7 +97,7 @@
                                ResXMLTree* inXml,
                                const String16& str16)
 {
-    const char16_t* str = str16.string();
+    const char16_t* str = str16.c_str();
     const char16_t* p = str;
     const char16_t* end = str + str16.size();
 
@@ -223,7 +223,7 @@
             String16 text(inXml->getText(&len));
             if (firstTime && text.size() > 0) {
                 firstTime = false;
-                if (text.string()[0] == '@') {
+                if (text.c_str()[0] == '@') {
                     // If this is a resource reference, don't do the pseudoloc.
                     pseudolocalize = NO_PSEUDOLOCALIZATION;
                     pseudo.setMethod(pseudolocalize);
@@ -263,7 +263,7 @@
                 {
                     SourcePos(String8(fileName), inXml->getLineNumber()).error(
                             "Found unsupported XLIFF tag <%s>\n",
-                            element8.string());
+                            element8.c_str());
                     return UNKNOWN_ERROR;
                 }
 moveon:
@@ -272,14 +272,14 @@
 
             if (outSpans == NULL) {
                 SourcePos(String8(fileName), inXml->getLineNumber()).error(
-                        "Found style tag <%s> where styles are not allowed\n", element8.string());
+                        "Found style tag <%s> where styles are not allowed\n", element8.c_str());
                 return UNKNOWN_ERROR;
             }
 
-            if (!ResTable::collectString(outString, curString.string(),
+            if (!ResTable::collectString(outString, curString.c_str(),
                                          curString.size(), false, &errorMsg, true)) {
                 SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
-                        errorMsg, String8(curString).string());
+                        errorMsg, String8(curString).c_str());
                 return UNKNOWN_ERROR;
             }
             rawString.append(curString);
@@ -295,7 +295,7 @@
                 str = inXml->getAttributeStringValue(ai, &len);
                 span.name.append(str, len);
             }
-            //printf("Span: %s\n", String8(span.name).string());
+            //printf("Span: %s\n", String8(span.name).c_str());
             span.span.firstChar = span.span.lastChar = outString->size();
             spanStack.push(span);
 
@@ -311,21 +311,21 @@
                 xliffDepth--;
                 continue;
             }
-            if (!ResTable::collectString(outString, curString.string(),
+            if (!ResTable::collectString(outString, curString.c_str(),
                                          curString.size(), false, &errorMsg, true)) {
                 SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
-                        errorMsg, String8(curString).string());
+                        errorMsg, String8(curString).c_str());
                 return UNKNOWN_ERROR;
             }
             rawString.append(curString);
             curString = String16();
 
             if (spanStack.size() == 0) {
-                if (strcmp16(inXml->getElementName(&len), endTag.string()) != 0) {
+                if (strcmp16(inXml->getElementName(&len), endTag.c_str()) != 0) {
                     SourcePos(String8(fileName), inXml->getLineNumber()).error(
                             "Found tag %s where <%s> close is expected\n",
-                            String8(inXml->getElementName(&len)).string(),
-                            String8(endTag).string());
+                            String8(inXml->getElementName(&len)).c_str(),
+                            String8(endTag).c_str());
                     return UNKNOWN_ERROR;
                 }
                 break;
@@ -334,15 +334,15 @@
             String16 spanTag;
             ssize_t semi = span.name.findFirst(';');
             if (semi >= 0) {
-                spanTag.setTo(span.name.string(), semi);
+                spanTag.setTo(span.name.c_str(), semi);
             } else {
                 spanTag.setTo(span.name);
             }
-            if (strcmp16(inXml->getElementName(&len), spanTag.string()) != 0) {
+            if (strcmp16(inXml->getElementName(&len), spanTag.c_str()) != 0) {
                 SourcePos(String8(fileName), inXml->getLineNumber()).error(
                         "Found close tag %s where close tag %s is expected\n",
-                        String8(inXml->getElementName(&len)).string(),
-                        String8(spanTag).string());
+                        String8(inXml->getElementName(&len)).c_str(),
+                        String8(spanTag).c_str());
                 return UNKNOWN_ERROR;
             }
             bool empty = true;
@@ -363,7 +363,7 @@
             if (0 && empty) {
                 fprintf(stderr, "%s:%d: warning: empty '%s' span found in text '%s'\n",
                         fileName, inXml->getLineNumber(),
-                        String8(spanTag).string(), String8(*outString).string());
+                        String8(spanTag).c_str(), String8(*outString).c_str());
 
             }
         } else if (code == ResXMLTree::START_NAMESPACE) {
@@ -380,11 +380,11 @@
 
     if (outSpans != NULL && outSpans->size() > 0) {
         if (curString.size() > 0) {
-            if (!ResTable::collectString(outString, curString.string(),
+            if (!ResTable::collectString(outString, curString.c_str(),
                                          curString.size(), false, &errorMsg, true)) {
                 SourcePos(String8(fileName), inXml->getLineNumber()).error(
                         "%s (in %s)\n",
-                        errorMsg, String8(curString).string());
+                        errorMsg, String8(curString).c_str());
                 return UNKNOWN_ERROR;
             }
         }
@@ -450,10 +450,10 @@
             String8 elemNs = build_namespace(namespaces, ns16);
             const char16_t* com16 = block->getComment(&len);
             if (com16) {
-                printf("%s <!-- %s -->\n", prefix.string(), String8(com16).string());
+                printf("%s <!-- %s -->\n", prefix.c_str(), String8(com16).c_str());
             }
-            printf("%sE: %s%s (line=%d)\n", prefix.string(), elemNs.string(),
-                   String8(block->getElementName(&len)).string(),
+            printf("%sE: %s%s (line=%d)\n", prefix.c_str(), elemNs.c_str(),
+                   String8(block->getElementName(&len)).c_str(),
                    block->getLineNumber());
             int N = block->getAttributeCount();
             depth++;
@@ -463,11 +463,11 @@
                 ns16 = block->getAttributeNamespace(i, &len);
                 String8 ns = build_namespace(namespaces, ns16);
                 String8 name(block->getAttributeName(i, &len));
-                printf("%sA: ", prefix.string());
+                printf("%sA: ", prefix.c_str());
                 if (res) {
-                    printf("%s%s(0x%08x)", ns.string(), name.string(), res);
+                    printf("%s%s(0x%08x)", ns.c_str(), name.c_str(), res);
                 } else {
-                    printf("%s%s", ns.string(), name.string());
+                    printf("%s%s", ns.c_str(), name.c_str());
                 }
                 Res_value value;
                 block->getAttributeValue(i, &value);
@@ -480,14 +480,14 @@
                 } else if (value.dataType == Res_value::TYPE_STRING) {
                     printf("=\"%s\"",
                             ResTable::normalizeForOutput(String8(block->getAttributeStringValue(i,
-                                        &len)).string()).string());
+                                        &len)).c_str()).c_str());
                 } else {
                     printf("=(type 0x%x)0x%x", (int)value.dataType, (int)value.data);
                 }
                 const char16_t* val = block->getAttributeStringValue(i, &len);
                 if (val != NULL) {
-                    printf(" (Raw: \"%s\")", ResTable::normalizeForOutput(String8(val).string()).
-                            string());
+                    printf(" (Raw: \"%s\")", ResTable::normalizeForOutput(String8(val).c_str()).
+                            c_str());
                 }
                 printf("\n");
             }
@@ -509,8 +509,8 @@
             }
             ns.uri = String8(block->getNamespaceUri(&len));
             namespaces.push(ns);
-            printf("%sN: %s=%s\n", prefix.string(), ns.prefix.string(),
-                    ns.uri.string());
+            printf("%sN: %s=%s\n", prefix.c_str(), ns.prefix.c_str(),
+                    ns.uri.c_str());
             depth++;
         } else if (code == ResXMLTree::END_NAMESPACE) {
             if (--depth < 0) {
@@ -529,19 +529,19 @@
             if (ns.prefix != pr) {
                 prefix = make_prefix(depth);
                 printf("%s*** BAD END NS PREFIX: found=%s, expected=%s\n",
-                        prefix.string(), pr.string(), ns.prefix.string());
+                        prefix.c_str(), pr.c_str(), ns.prefix.c_str());
             }
             String8 uri = String8(block->getNamespaceUri(&len));
             if (ns.uri != uri) {
                 prefix = make_prefix(depth);
                 printf("%s *** BAD END NS URI: found=%s, expected=%s\n",
-                        prefix.string(), uri.string(), ns.uri.string());
+                        prefix.c_str(), uri.c_str(), ns.uri.c_str());
             }
             namespaces.pop();
         } else if (code == ResXMLTree::TEXT) {
             size_t len;
-            printf("%sC: \"%s\"\n", prefix.string(),
-                    ResTable::normalizeForOutput(String8(block->getText(&len)).string()).string());
+            printf("%sC: \"%s\"\n", prefix.c_str(),
+                    ResTable::normalizeForOutput(String8(block->getText(&len)).c_str()).c_str());
         }
     }
 
@@ -583,7 +583,7 @@
 sp<XMLNode> XMLNode::parse(const sp<AaptFile>& file)
 {
     char buf[16384];
-    int fd = open(file->getSourceFile().string(), O_RDONLY | O_BINARY);
+    int fd = open(file->getSourceFile().c_str(), O_RDONLY | O_BINARY);
     if (fd < 0) {
         SourcePos(file->getSourceFile(), -1).error("Unable to open file for read: %s",
                 strerror(errno));
@@ -875,9 +875,9 @@
     }
     if (kIsDebug) {
         printf("Elem %s %s=\"%s\": set res id = 0x%08x\n",
-                String8(getElementName()).string(),
-                String8(mAttributes.itemAt(attrIdx).name).string(),
-                String8(mAttributes.itemAt(attrIdx).string).string(),
+                String8(getElementName()).c_str(),
+                String8(mAttributes.itemAt(attrIdx).name).c_str(),
+                String8(mAttributes.itemAt(attrIdx).string).c_str(),
                 resId);
     }
     mAttributes.editItemAt(attrIdx).nameResId = resId;
@@ -915,7 +915,7 @@
 
 void XMLNode::removeWhitespace(bool stripAll, const char** cDataTags)
 {
-    //printf("Removing whitespace in %s\n", String8(mElementName).string());
+    //printf("Removing whitespace in %s\n", String8(mElementName).c_str());
     size_t N = mChildren.size();
     if (cDataTags) {
         String8 tag(mElementName);
@@ -931,13 +931,13 @@
         sp<XMLNode> node = mChildren.itemAt(i);
         if (node->getType() == TYPE_CDATA) {
             // This is a CDATA node...
-            const char16_t* p = node->mChars.string();
+            const char16_t* p = node->mChars.c_str();
             while (*p != 0 && *p < 128 && isspace(*p)) {
                 p++;
             }
             //printf("Space ends at %d in \"%s\"\n",
-            //       (int)(p-node->mChars.string()),
-            //       String8(node->mChars).string());
+            //       (int)(p-node->mChars.c_str()),
+            //       String8(node->mChars).c_str());
             if (*p == 0) {
                 if (stripAll) {
                     // Remove this node!
@@ -949,18 +949,18 @@
                 }
             } else {
                 // Compact leading/trailing whitespace.
-                const char16_t* e = node->mChars.string()+node->mChars.size()-1;
+                const char16_t* e = node->mChars.c_str()+node->mChars.size()-1;
                 while (e > p && *e < 128 && isspace(*e)) {
                     e--;
                 }
-                if (p > node->mChars.string()) {
+                if (p > node->mChars.c_str()) {
                     p--;
                 }
-                if (e < (node->mChars.string()+node->mChars.size()-1)) {
+                if (e < (node->mChars.c_str()+node->mChars.size()-1)) {
                     e++;
                 }
-                if (p > node->mChars.string() ||
-                    e < (node->mChars.string()+node->mChars.size()-1)) {
+                if (p > node->mChars.c_str() ||
+                    e < (node->mChars.c_str()+node->mChars.size()-1)) {
                     String16 tmp(p, e-p+1);
                     node->mChars = tmp;
                 }
@@ -986,14 +986,14 @@
             table->setCurrentXmlPos(SourcePos(mFilename, getStartLineNumber()));
             if (!assets->getIncludedResources()
                     .stringToValue(&e.value, &e.string,
-                                  e.string.string(), e.string.size(), true, true,
+                                  e.string.c_str(), e.string.size(), true, true,
                                   e.nameResId, NULL, &defPackage, table, &ac)) {
                 hasErrors = true;
             }
             if (kIsDebug) {
                 printf("Attr %s: type=0x%x, str=%s\n",
-                        String8(e.name).string(), e.value.dataType,
-                        String8(e.string).string());
+                        String8(e.name).c_str(), e.value.dataType,
+                        String8(e.string).c_str());
             }
         }
     }
@@ -1023,30 +1023,30 @@
             String16 pkg(getNamespaceResourcePackage(String16(assets->getPackage()), e.ns, &nsIsPublic));
             if (kIsDebug) {
                 printf("Elem %s %s=\"%s\": namespace(%s) %s ===> %s\n",
-                        String8(getElementName()).string(),
-                        String8(e.name).string(),
-                        String8(e.string).string(),
-                        String8(e.ns).string(),
+                        String8(getElementName()).c_str(),
+                        String8(e.name).c_str(),
+                        String8(e.string).c_str(),
+                        String8(e.ns).c_str(),
                         (nsIsPublic) ? "public" : "private",
-                        String8(pkg).string());
+                        String8(pkg).c_str());
             }
             if (pkg.size() <= 0) continue;
             uint32_t res = table != NULL
                 ? table->getResId(e.name, &attr, &pkg, &errorMsg, nsIsPublic)
                 : assets->getIncludedResources().
-                    identifierForName(e.name.string(), e.name.size(),
-                                      attr.string(), attr.size(),
-                                      pkg.string(), pkg.size());
+                    identifierForName(e.name.c_str(), e.name.size(),
+                                      attr.c_str(), attr.size(),
+                                      pkg.c_str(), pkg.size());
             if (res != 0) {
                 if (kIsDebug) {
                     printf("XML attribute name %s: resid=0x%08x\n",
-                            String8(e.name).string(), res);
+                            String8(e.name).c_str(), res);
                 }
                 setAttributeResID(i, res);
             } else {
                 SourcePos(mFilename, getStartLineNumber()).error(
                         "No resource identifier found for attribute '%s' in package '%s'\n",
-                        String8(e.name).string(), String8(pkg).string());
+                        String8(e.name).c_str(), String8(pkg).c_str());
                 hasErrors = true;
             }
         }
@@ -1137,7 +1137,7 @@
     if (kPrintStringMetrics) {
         fprintf(stderr, "**** total xml size: %zu / %zu%% strings (in %s)\n",
                 dest->getSize(), (stringPool->getSize()*100)/dest->getSize(),
-                dest->getPath().string());
+                dest->getPath().c_str());
     }
 
     return NO_ERROR;
@@ -1155,8 +1155,8 @@
         if (elemNs.size() > 0) {
             elemNs.append(":");
         }
-        printf("%s E: %s%s", prefix.string(),
-               elemNs.string(), String8(getElementName()).string());
+        printf("%s E: %s%s", prefix.c_str(),
+               elemNs.c_str(), String8(getElementName()).c_str());
         int N = mAttributes.size();
         for (i=0; i<N; i++) {
             ssize_t idx = mAttributeOrder.valueAt(i);
@@ -1171,21 +1171,21 @@
                 attrNs.append(":");
             }
             if (attr.nameResId) {
-                printf("%s%s(0x%08x)", attrNs.string(),
-                       String8(attr.name).string(), attr.nameResId);
+                printf("%s%s(0x%08x)", attrNs.c_str(),
+                       String8(attr.name).c_str(), attr.nameResId);
             } else {
-                printf("%s%s", attrNs.string(), String8(attr.name).string());
+                printf("%s%s", attrNs.c_str(), String8(attr.name).c_str());
             }
-            printf("=%s", String8(attr.string).string());
+            printf("=%s", String8(attr.string).c_str());
         }
         printf("\n");
     } else if (getType() == TYPE_NAMESPACE) {
-        printf("%s N: %s=%s\n", prefix.string(),
+        printf("%s N: %s=%s\n", prefix.c_str(),
                getNamespacePrefix().size() > 0
-                    ? String8(getNamespacePrefix()).string() : "<DEF>",
-               String8(getNamespaceUri()).string());
+                    ? String8(getNamespacePrefix()).c_str() : "<DEF>",
+               String8(getNamespaceUri()).c_str());
     } else {
-        printf("%s C: \"%s\"\n", prefix.string(), String8(getCData()).string());
+        printf("%s C: \"%s\"\n", prefix.c_str(), String8(getCData()).c_str());
     }
     int N = mChildren.size();
     for (i=0; i<N; i++) {
@@ -1258,7 +1258,7 @@
 XMLNode::characterData(void *userData, const XML_Char *s, int len)
 {
     if (kIsDebugParse) {
-        printf("CDATA: \"%s\"\n", String8(s, len).string());
+        printf("CDATA: \"%s\"\n", String8(s, len).c_str());
     }
     ParseState* st = (ParseState*)userData;
     sp<XMLNode> node = NULL;
@@ -1423,7 +1423,7 @@
                 idx = outPool->add(attr.name);
                 if (kIsDebug) {
                     printf("Adding attr %s (resid 0x%08x) to pool: idx=%zd\n",
-                            String8(attr.name).string(), id, idx);
+                            String8(attr.name).c_str(), id, idx);
                 }
                 if (id != 0) {
                     while ((ssize_t)outResIds->size() <= idx) {
@@ -1434,7 +1434,7 @@
             }
             attr.namePoolIdx = idx;
             if (kIsDebug) {
-                printf("String %s offset=0x%08zd\n", String8(attr.name).string(), idx);
+                printf("String %s offset=0x%08zd\n", String8(attr.name).c_str(), idx);
             }
         }
     }
@@ -1488,7 +1488,7 @@
         node.comment.index = htodl(
             mComment.size() > 0 ? strings.offsetForString(mComment) : -1);
         //if (mComment.size() > 0) {
-        //  printf("Flattening comment: %s\n", String8(mComment).string());
+        //  printf("Flattening comment: %s\n", String8(mComment).c_str());
         //}
     } else {
         node.comment.index = htodl((uint32_t)-1);
diff --git a/tools/aapt/pseudolocalize.cpp b/tools/aapt/pseudolocalize.cpp
index 4e8dcb1..fc2ed98 100644
--- a/tools/aapt/pseudolocalize.cpp
+++ b/tools/aapt/pseudolocalize.cpp
@@ -42,7 +42,7 @@
   size_t depth = mLastDepth;
   size_t lastpos, pos;
   const size_t length= text.size();
-  const char16_t* str = text.string();
+  const char16_t* str = text.c_str();
   bool escaped = false;
   for (lastpos = pos = 0; pos < length; pos++) {
     char16_t c = str[pos];
@@ -181,7 +181,7 @@
 
 static String16 pseudo_generate_expansion(const unsigned int length) {
     String16 result = k_expansion_string;
-    const char16_t* s = result.string();
+    const char16_t* s = result.c_str();
     if (result.size() < length) {
         result += String16(" ");
         result += pseudo_generate_expansion(length - result.size());
@@ -237,7 +237,7 @@
  */
 String16 PseudoMethodAccent::text(const String16& source)
 {
-    const char16_t* s = source.string();
+    const char16_t* s = source.c_str();
     String16 result;
     const size_t I = source.size();
     bool lastspace = true;
@@ -357,7 +357,7 @@
 
 String16 PseudoMethodBidi::text(const String16& source)
 {
-    const char16_t* s = source.string();
+    const char16_t* s = source.c_str();
     String16 result;
     bool lastspace = true;
     bool space = true;
diff --git a/tools/aapt2/Debug.cpp b/tools/aapt2/Debug.cpp
index cac4edd..6a17ef8 100644
--- a/tools/aapt2/Debug.cpp
+++ b/tools/aapt2/Debug.cpp
@@ -457,7 +457,7 @@
   const size_t NS = pool->size();
   for (size_t s=0; s<NS; s++) {
     auto str = pool->string8ObjectAt(s);
-    printer->Print(StringPrintf("String #%zd : %s\n", s, str.has_value() ? str->string() : ""));
+    printer->Print(StringPrintf("String #%zd : %s\n", s, str.has_value() ? str->c_str() : ""));
   }
 }
 
diff --git a/tools/aapt2/cmd/Util.cpp b/tools/aapt2/cmd/Util.cpp
index 1671e1e..a92f24b 100644
--- a/tools/aapt2/cmd/Util.cpp
+++ b/tools/aapt2/cmd/Util.cpp
@@ -215,7 +215,7 @@
   }
   std::vector<std::string> sanitized_config_names;
   for (const auto &config : constraints.configs) {
-    sanitized_config_names.push_back(MakePackageSafeName(config.toString().string()));
+    sanitized_config_names.push_back(MakePackageSafeName(config.toString().c_str()));
   }
   split_name << "config." << util::Joiner(sanitized_config_names, "_");
 
diff --git a/tools/aapt2/format/binary/BinaryResourceParser.cpp b/tools/aapt2/format/binary/BinaryResourceParser.cpp
index 75dcba5..2e20e81 100644
--- a/tools/aapt2/format/binary/BinaryResourceParser.cpp
+++ b/tools/aapt2/format/binary/BinaryResourceParser.cpp
@@ -453,7 +453,7 @@
   const size_t count = entries.size();
   for (size_t i = 0; i < count; i++) {
     table_->included_packages_[entries.valueAt(i)] =
-        android::util::Utf16ToUtf8(StringPiece16(entries.keyAt(i).string()));
+        android::util::Utf16ToUtf8(StringPiece16(entries.keyAt(i).c_str()));
   }
   return true;
 }
diff --git a/tools/split-select/Grouper_test.cpp b/tools/split-select/Grouper_test.cpp
index 7294a86..a8b78cd 100644
--- a/tools/split-select/Grouper_test.cpp
+++ b/tools/split-select/Grouper_test.cpp
@@ -179,7 +179,7 @@
             errorMessage.append("\n");
         }
     }
-    ADD_FAILURE() << errorMessage.string();
+    ADD_FAILURE() << errorMessage.c_str();
 }
 
 void GrouperTest::addSplit(Vector<SplitDescription>& splits, const char* str) {
diff --git a/tools/split-select/Main.cpp b/tools/split-select/Main.cpp
index e6966db..1e75117 100644
--- a/tools/split-select/Main.cpp
+++ b/tools/split-select/Main.cpp
@@ -99,8 +99,7 @@
         }
         masterRule = Rule::simplify(masterRule);
         fprintf(stdout, "  {\n    \"path\": \"%s\",\n    \"rules\": %s\n  }",
-                splits.keyAt(i).string(),
-                masterRule->toJson(2).string());
+                splits.keyAt(i).c_str(), masterRule->toJson(2).c_str());
     }
     fprintf(stdout, "\n]\n");
 }
@@ -158,25 +157,23 @@
         const char16_t* name = xml.getElementName(&len);
         String16 name16(name, len);
         if (name16 == kManifestTag) {
-            ssize_t idx = xml.indexOfAttribute(
-                    kAndroidNamespace.string(), kAndroidNamespace.size(),
-                    kVersionCodeAttr.string(), kVersionCodeAttr.size());
+            ssize_t idx = xml.indexOfAttribute(kAndroidNamespace.c_str(), kAndroidNamespace.size(),
+                                               kVersionCodeAttr.c_str(), kVersionCodeAttr.size());
             if (idx >= 0) {
                 outInfo.versionCode = xml.getAttributeData(idx);
             }
 
         } else if (name16 == kApplicationTag) {
-            ssize_t idx = xml.indexOfAttribute(
-                    kAndroidNamespace.string(), kAndroidNamespace.size(),
-                    kMultiArchAttr.string(), kMultiArchAttr.size());
+            ssize_t idx = xml.indexOfAttribute(kAndroidNamespace.c_str(), kAndroidNamespace.size(),
+                                               kMultiArchAttr.c_str(), kMultiArchAttr.size());
             if (idx >= 0) {
                 outInfo.multiArch = xml.getAttributeData(idx) != 0;
             }
 
         } else if (name16 == kUsesSdkTag) {
-            ssize_t idx = xml.indexOfAttribute(
-                    kAndroidNamespace.string(), kAndroidNamespace.size(),
-                    kMinSdkVersionAttr.string(), kMinSdkVersionAttr.size());
+            ssize_t idx =
+                    xml.indexOfAttribute(kAndroidNamespace.c_str(), kAndroidNamespace.size(),
+                                         kMinSdkVersionAttr.c_str(), kMinSdkVersionAttr.size());
             if (idx >= 0) {
                 uint16_t type = xml.getAttributeDataType(idx);
                 if (type >= Res_value::TYPE_FIRST_INT && type <= Res_value::TYPE_LAST_INT) {
@@ -187,10 +184,10 @@
                         fprintf(stderr, "warning: failed to retrieve android:minSdkVersion.\n");
                     } else {
                         char *endPtr;
-                        int minSdk = strtol(minSdk8->string(), &endPtr, 10);
-                        if (endPtr != minSdk8->string() + minSdk8->size()) {
+                        int minSdk = strtol(minSdk8->c_str(), &endPtr, 10);
+                        if (endPtr != minSdk8->c_str() + minSdk8->size()) {
                             fprintf(stderr, "warning: failed to parse android:minSdkVersion '%s'\n",
-                                    minSdk8->string());
+                                    minSdk8->c_str());
                         } else {
                             outInfo.minSdkVersion = minSdk;
                         }
@@ -232,7 +229,7 @@
             splits.add();
             Vector<String8> parts = AaptUtil::splitAndLowerCase(dir->getFileName(i), '-');
             if (parseAbi(parts, 0, &splits.editTop()) < 0) {
-                fprintf(stderr, "Malformed library %s\n", dir->getFileName(i).string());
+                fprintf(stderr, "Malformed library %s\n", dir->getFileName(i).c_str());
                 splits.pop();
             }
         }
@@ -291,7 +288,7 @@
             help();
             return 0;
         } else {
-            fprintf(stderr, "error: unknown argument '%s'.\n", arg.string());
+            fprintf(stderr, "error: unknown argument '%s'.\n", arg.c_str());
             usage();
             return 1;
         }
@@ -313,15 +310,14 @@
     // Find out some details about the base APK.
     AppInfo baseAppInfo;
     if (!getAppInfo(baseApkPath, baseAppInfo)) {
-        fprintf(stderr, "error: unable to read base APK: '%s'.\n", baseApkPath.string());
+        fprintf(stderr, "error: unable to read base APK: '%s'.\n", baseApkPath.c_str());
         return 1;
     }
 
     SplitDescription targetSplit;
     if (!generateFlag) {
         if (!SplitDescription::parse(targetConfigStr, &targetSplit)) {
-            fprintf(stderr, "error: invalid --target config: '%s'.\n",
-                    targetConfigStr.string());
+            fprintf(stderr, "error: invalid --target config: '%s'.\n", targetConfigStr.c_str());
             usage();
             return 1;
         }
@@ -341,7 +337,7 @@
         Vector<SplitDescription> splits = extractSplitDescriptionsFromApk(splitApkPaths[i]);
         if (splits.isEmpty()) {
             fprintf(stderr, "error: invalid --split path: '%s'. No splits found.\n",
-                    splitApkPaths[i].string());
+                    splitApkPaths[i].c_str());
             usage();
             return 1;
         }
@@ -364,7 +360,7 @@
         const size_t matchingSplitApkPathCount = matchingSplitPaths.size();
         for (size_t i = 0; i < matchingSplitApkPathCount; i++) {
             if (matchingSplitPaths[i] != baseApkPath) {
-                fprintf(stdout, "%s\n", matchingSplitPaths[i].string());
+                fprintf(stdout, "%s\n", matchingSplitPaths[i].c_str());
             }
         }
     } else {
diff --git a/tools/split-select/Rule_test.cpp b/tools/split-select/Rule_test.cpp
index c6cff0d..c78533f 100644
--- a/tools/split-select/Rule_test.cpp
+++ b/tools/split-select/Rule_test.cpp
@@ -68,7 +68,7 @@
     expected.erase(std::remove_if(expected.begin(), expected.end(), ::isspace), expected.end());
 
     // Result
-    std::string result(rule.toJson().string());
+    std::string result(rule.toJson().c_str());
     result.erase(std::remove_if(result.begin(), result.end(), ::isspace), result.end());
 
     ASSERT_EQ(expected, result);
diff --git a/tools/split-select/SplitDescription.cpp b/tools/split-select/SplitDescription.cpp
index 99bc23d..4e2b48e 100644
--- a/tools/split-select/SplitDescription.cpp
+++ b/tools/split-select/SplitDescription.cpp
@@ -134,8 +134,8 @@
     String8 configStr;
     String8 extensionStr;
     if (index >= 0) {
-        configStr.setTo(str.string(), index);
-        extensionStr.setTo(str.string() + index + 1);
+        configStr.setTo(str.c_str(), index);
+        extensionStr.setTo(str.c_str() + index + 1);
     } else {
         configStr.setTo(str);
     }
diff --git a/tools/split-select/TestRules.cpp b/tools/split-select/TestRules.cpp
index 86ccd6a..ca3c56f 100644
--- a/tools/split-select/TestRules.cpp
+++ b/tools/split-select/TestRules.cpp
@@ -78,9 +78,8 @@
     const String8 actualStr(actual != NULL ? actual->toJson() : String8());
 
     if (expectedStr != actualStr) {
-        return ::testing::AssertionFailure()
-                << "Expected: " << expectedStr.string() << "\n"
-                << "  Actual: " << actualStr.string();
+        return ::testing::AssertionFailure() << "Expected: " << expectedStr.c_str() << "\n"
+                                             << "  Actual: " << actualStr.c_str();
     }
     return ::testing::AssertionSuccess();
 }