Merge "Lock screen string change" into qt-r1-dev
diff --git a/config/preloaded-classes b/config/preloaded-classes
index 91cb47b..b4fd031 100644
--- a/config/preloaded-classes
+++ b/config/preloaded-classes
@@ -1105,7 +1105,6 @@
 android.database.sqlite.SQLiteDatabaseConfiguration
 android.database.sqlite.SQLiteDatabaseCorruptException
 android.database.sqlite.SQLiteDatabaseLockedException
-android.database.sqlite.SQLiteDebug$Consts
 android.database.sqlite.SQLiteDebug$DbStats
 android.database.sqlite.SQLiteDebug$PagerStats
 android.database.sqlite.SQLiteDebug
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index c08ed26..2eb0902 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -3681,7 +3681,7 @@
             ActivityTaskManager.getService().onBackPressedOnTaskRoot(mToken,
                     new IRequestFinishCallback.Stub() {
                         public void requestFinish() {
-                            finishAfterTransition();
+                            mHandler.post(() -> finishAfterTransition());
                         }
                     });
         } catch (RemoteException e) {
diff --git a/core/java/android/database/sqlite/SQLiteConnection.java b/core/java/android/database/sqlite/SQLiteConnection.java
index 3844794..f722275 100644
--- a/core/java/android/database/sqlite/SQLiteConnection.java
+++ b/core/java/android/database/sqlite/SQLiteConnection.java
@@ -19,8 +19,8 @@
 import android.database.Cursor;
 import android.database.CursorWindow;
 import android.database.DatabaseUtils;
-import android.database.sqlite.SQLiteDebug.Consts;
 import android.database.sqlite.SQLiteDebug.DbStats;
+import android.database.sqlite.SQLiteDebug.NoPreloadHolder;
 import android.os.CancellationSignal;
 import android.os.OperationCanceledException;
 import android.os.ParcelFileDescriptor;
@@ -214,7 +214,7 @@
         try {
             mConnectionPtr = nativeOpen(mConfiguration.path, mConfiguration.openFlags,
                     mConfiguration.label,
-                    SQLiteDebug.Consts.DEBUG_SQL_STATEMENTS, SQLiteDebug.Consts.DEBUG_SQL_TIME,
+                    NoPreloadHolder.DEBUG_SQL_STATEMENTS, NoPreloadHolder.DEBUG_SQL_TIME,
                     mConfiguration.lookasideSlotSize, mConfiguration.lookasideSlotCount);
         } finally {
             mRecentOperations.endOperation(cookie);
@@ -1500,7 +1500,7 @@
                 operation.mFinished = true;
                 final long execTime = operation.mEndTime - operation.mStartTime;
                 mPool.onStatementExecuted(execTime);
-                return SQLiteDebug.Consts.DEBUG_LOG_SLOW_QUERIES && SQLiteDebug.shouldLogSlowQuery(
+                return NoPreloadHolder.DEBUG_LOG_SLOW_QUERIES && SQLiteDebug.shouldLogSlowQuery(
                         execTime);
             }
             return false;
@@ -1608,7 +1608,7 @@
             if (mSql != null) {
                 msg.append(", sql=\"").append(trimSqlForDisplay(mSql)).append("\"");
             }
-            final boolean dumpDetails = allowDetailedLog && Consts.DEBUG_LOG_DETAILED
+            final boolean dumpDetails = allowDetailedLog && NoPreloadHolder.DEBUG_LOG_DETAILED
                     && mBindArgs != null && mBindArgs.size() != 0;
             if (dumpDetails) {
                 msg.append(", bindArgs=[");
diff --git a/core/java/android/database/sqlite/SQLiteDebug.java b/core/java/android/database/sqlite/SQLiteDebug.java
index 4fc7f5d..a231a92 100644
--- a/core/java/android/database/sqlite/SQLiteDebug.java
+++ b/core/java/android/database/sqlite/SQLiteDebug.java
@@ -39,7 +39,7 @@
      *
      * {@hide}
      */
-    public static final class Consts {
+    public static final class NoPreloadHolder {
         /**
          * Controls the printing of informational SQL log messages.
          *
@@ -103,8 +103,9 @@
      */
     public static boolean shouldLogSlowQuery(long elapsedTimeMillis) {
         final int slowQueryMillis = Math.min(
-                SystemProperties.getInt(Consts.SLOW_QUERY_THRESHOLD_PROP, Integer.MAX_VALUE),
-                SystemProperties.getInt(Consts.SLOW_QUERY_THRESHOLD_UID_PROP,
+                SystemProperties.getInt(NoPreloadHolder.SLOW_QUERY_THRESHOLD_PROP,
+                        Integer.MAX_VALUE),
+                SystemProperties.getInt(NoPreloadHolder.SLOW_QUERY_THRESHOLD_UID_PROP,
                         Integer.MAX_VALUE));
         return elapsedTimeMillis >= slowQueryMillis;
     }
diff --git a/core/java/android/net/NetworkAgent.java b/core/java/android/net/NetworkAgent.java
index f416fc7..9cd4f53 100644
--- a/core/java/android/net/NetworkAgent.java
+++ b/core/java/android/net/NetworkAgent.java
@@ -434,7 +434,24 @@
      * {@link #saveAcceptUnvalidated} to respect the user's choice.
      */
     public void explicitlySelected(boolean acceptUnvalidated) {
-        queueOrSendMessage(EVENT_SET_EXPLICITLY_SELECTED, acceptUnvalidated ? 1 : 0, 0);
+        explicitlySelected(true /* explicitlySelected */, acceptUnvalidated);
+    }
+
+    /**
+     * Called by the bearer to indicate this network was manually selected by the user.
+     * This should be called before the NetworkInfo is marked CONNECTED so that this
+     * Network can be given special treatment at that time. If {@code acceptUnvalidated} is
+     * {@code true}, then the system will switch to this network. If it is {@code false} and the
+     * network cannot be validated, the system will ask the user whether to switch to this network.
+     * If the user confirms and selects "don't ask again", then the system will call
+     * {@link #saveAcceptUnvalidated} to persist the user's choice. Thus, if the transport ever
+     * calls this method with {@code acceptUnvalidated} set to {@code false}, it must also implement
+     * {@link #saveAcceptUnvalidated} to respect the user's choice.
+     */
+    public void explicitlySelected(boolean explicitlySelected, boolean acceptUnvalidated) {
+        queueOrSendMessage(EVENT_SET_EXPLICITLY_SELECTED,
+                explicitlySelected ? 1 : 0,
+                acceptUnvalidated ? 1 : 0);
     }
 
     /**
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index e52f8e1..c2e37d5 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -188,6 +188,7 @@
     static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
 
     private static final double MILLISECONDS_IN_HOUR = 3600 * 1000;
+    private static final long MILLISECONDS_IN_YEAR = 365 * 24 * 3600 * 1000L;
 
     private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
     private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
@@ -3955,25 +3956,11 @@
         addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
     }
 
-    boolean ensureStartClockTime(final long currentTime) {
-        final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
-        if ((currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR))
-                || (mStartClockTime > currentTime)) {
-            // If the start clock time has changed by more than a year, then presumably
-            // the previous time was completely bogus.  So we are going to figure out a
-            // new time based on how much time has elapsed since we started counting.
-            mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
-            return true;
-        }
-        return false;
-    }
-
     public void noteCurrentTimeChangedLocked() {
         final long currentTime = System.currentTimeMillis();
         final long elapsedRealtime = mClocks.elapsedRealtime();
         final long uptime = mClocks.uptimeMillis();
         recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
-        ensureStartClockTime(currentTime);
     }
 
     public void noteProcessStartLocked(String name, int uid) {
@@ -6452,9 +6439,15 @@
 
     @Override public long getStartClockTime() {
         final long currentTime = System.currentTimeMillis();
-        if (ensureStartClockTime(currentTime)) {
+        if ((currentTime > MILLISECONDS_IN_YEAR
+                && mStartClockTime < (currentTime - MILLISECONDS_IN_YEAR))
+                || (mStartClockTime > currentTime)) {
+            // If the start clock time has changed by more than a year, then presumably
+            // the previous time was completely bogus.  So we are going to figure out a
+            // new time based on how much time has elapsed since we started counting.
             recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
                     mClocks.uptimeMillis());
+            return currentTime - (mClocks.elapsedRealtime() - (mRealtimeStart / 1000));
         }
         return mStartClockTime;
     }
@@ -14022,7 +14015,7 @@
 
         // Pull the clock time.  This may update the time and make a new history entry
         // if we had originally pulled a time before the RTC was set.
-        long startClockTime = getStartClockTime();
+        getStartClockTime();
 
         final long NOW_SYS = mClocks.uptimeMillis() * 1000;
         final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
@@ -14046,7 +14039,7 @@
         out.writeInt(mStartCount);
         out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
         out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
-        out.writeLong(startClockTime);
+        out.writeLong(mStartClockTime);
         out.writeString(mStartPlatformVersion);
         out.writeString(mEndPlatformVersion);
         mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
@@ -14759,7 +14752,7 @@
 
         // Pull the clock time.  This may update the time and make a new history entry
         // if we had originally pulled a time before the RTC was set.
-        long startClockTime = getStartClockTime();
+        getStartClockTime();
 
         final long uSecUptime = mClocks.uptimeMillis() * 1000;
         final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
@@ -14772,7 +14765,7 @@
         mBatteryStatsHistory.writeToParcel(out);
 
         out.writeInt(mStartCount);
-        out.writeLong(startClockTime);
+        out.writeLong(mStartClockTime);
         out.writeString(mStartPlatformVersion);
         out.writeString(mEndPlatformVersion);
         out.writeLong(mUptime);
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index f266502..cd0b340 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -250,6 +250,11 @@
 // Flag to pass to the runtime when using the apex image.
 static const char* kApexImageOption = "-Ximage:/system/framework/apex.art";
 
+// Feature flag name for disabling lock profiling.
+static const char* DISABLE_LOCK_PROFILING = "disable_lock_profiling";
+// Runtime option disabling lock profiling.
+static const char* kLockProfThresholdRuntimeOption = "-Xlockprofthreshold:0";
+
 static AndroidRuntime* gCurRuntime = NULL;
 
 /*
@@ -698,6 +703,17 @@
         ALOGI("Using default boot image");
     }
 
+    std::string disable_lock_profiling =
+        server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
+                                                             DISABLE_LOCK_PROFILING,
+                                                             /*default_value=*/ "");
+    if (disable_lock_profiling == "true") {
+        addOption(kLockProfThresholdRuntimeOption);
+        ALOGI("Disabling lock profiling: '%s'\n", kLockProfThresholdRuntimeOption);
+    } else {
+        ALOGI("Leaving lock profiling enabled");
+    }
+
     bool checkJni = false;
     property_get("dalvik.vm.checkjni", propBuf, "");
     if (strcmp(propBuf, "true") == 0) {
diff --git a/core/jni/android_os_Debug.cpp b/core/jni/android_os_Debug.cpp
index a67cb34..842679e 100644
--- a/core/jni/android_os_Debug.cpp
+++ b/core/jni/android_os_Debug.cpp
@@ -289,14 +289,14 @@
         } else if (base::EndsWith(name, ".oat")) {
             which_heap = HEAP_OAT;
             is_swappable = true;
-        } else if (base::EndsWith(name, ".art")) {
+        } else if (base::EndsWith(name, ".art") || base::EndsWith(name, ".art]")) {
             which_heap = HEAP_ART;
             // Handle system@framework@boot* and system/framework/boot*
             if ((strstr(name.c_str(), "@boot") != nullptr) ||
                     (strstr(name.c_str(), "/boot"))) {
-                sub_heap = HEAP_DEX_BOOT_VDEX;
+                sub_heap = HEAP_ART_BOOT;
             } else {
-                sub_heap = HEAP_DEX_APP_VDEX;
+                sub_heap = HEAP_ART_APP;
             }
             is_swappable = true;
         } else if (base::StartsWith(name, "/dev/")) {
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java
index 240691b..db13ef4 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java
@@ -61,12 +61,14 @@
     public static final int SYSUI_STATE_A11Y_BUTTON_CLICKABLE = 1 << 4;
     // The navigation bar a11y button shortcut is available
     public static final int SYSUI_STATE_A11Y_BUTTON_LONG_CLICKABLE = 1 << 5;
-    // The keyguard is showing
+    // The keyguard is showing and not occluded
     public static final int SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING = 1 << 6;
     // The recents feature is disabled (either by SUW/SysUI/device policy)
     public static final int SYSUI_STATE_OVERVIEW_DISABLED = 1 << 7;
     // The home feature is disabled (either by SUW/SysUI/device policy)
     public static final int SYSUI_STATE_HOME_DISABLED = 1 << 8;
+    // The keyguard is showing, but occluded
+    public static final int SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED = 1 << 9;
 
     @Retention(RetentionPolicy.SOURCE)
     @IntDef({SYSUI_STATE_SCREEN_PINNING,
@@ -76,6 +78,7 @@
             SYSUI_STATE_A11Y_BUTTON_CLICKABLE,
             SYSUI_STATE_A11Y_BUTTON_LONG_CLICKABLE,
             SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING,
+            SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED,
             SYSUI_STATE_OVERVIEW_DISABLED,
             SYSUI_STATE_HOME_DISABLED
     })
@@ -89,6 +92,8 @@
         str.add((flags & SYSUI_STATE_NAV_BAR_HIDDEN) != 0 ? "navbar_hidden" : "");
         str.add((flags & SYSUI_STATE_NOTIFICATION_PANEL_EXPANDED) != 0 ? "notif_visible" : "");
         str.add((flags & SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING) != 0 ? "keygrd_visible" : "");
+        str.add((flags & SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED) != 0
+                ? "keygrd_occluded" : "");
         str.add((flags & SYSUI_STATE_BOUNCER_SHOWING) != 0 ? "bouncer_visible" : "");
         str.add((flags & SYSUI_STATE_A11Y_BUTTON_CLICKABLE) != 0 ? "a11y_click" : "");
         str.add((flags & SYSUI_STATE_A11Y_BUTTON_LONG_CLICKABLE) != 0 ? "a11y_long_click" : "");
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/SmallClockPosition.java b/packages/SystemUI/src/com/android/keyguard/clock/SmallClockPosition.java
index 9b15dc6..60ca945 100644
--- a/packages/SystemUI/src/com/android/keyguard/clock/SmallClockPosition.java
+++ b/packages/SystemUI/src/com/android/keyguard/clock/SmallClockPosition.java
@@ -67,7 +67,8 @@
      */
     int getPreferredY() {
         // On AOD, clock needs to appear below the status bar with enough room for pixel shifting
-        int aodY = mStatusBarHeight + mKeyguardLockPadding + mBurnInOffsetY;
+        int aodY = mStatusBarHeight + mKeyguardLockHeight + 2 * mKeyguardLockPadding
+                + mBurnInOffsetY;
         // On lock screen, clock needs to appear below the lock icon
         int lockY =  mStatusBarHeight + mKeyguardLockHeight + 2 * mKeyguardLockPadding;
         return (int) MathUtils.lerp(lockY, aodY, mDarkAmount);
diff --git a/packages/SystemUI/src/com/android/systemui/CornerHandleView.java b/packages/SystemUI/src/com/android/systemui/CornerHandleView.java
index 691c3f9..54a3635 100644
--- a/packages/SystemUI/src/com/android/systemui/CornerHandleView.java
+++ b/packages/SystemUI/src/com/android/systemui/CornerHandleView.java
@@ -20,8 +20,8 @@
 import android.content.Context;
 import android.graphics.Canvas;
 import android.graphics.Paint;
+import android.graphics.Path;
 import android.graphics.RectF;
-import android.os.SystemProperties;
 import android.util.AttributeSet;
 import android.util.DisplayMetrics;
 import android.view.ContextThemeWrapper;
@@ -34,17 +34,19 @@
  * corners.
  */
 public class CornerHandleView extends View {
-    private static final boolean ALLOW_TUNING = false;
-    private static final int ANGLE_DEGREES = 50;
-    private static final float STROKE_DP = 2.5f;
+    private static final float STROKE_DP_LARGE = 2f;
+    private static final float STROKE_DP_SMALL = 1.95f;
     // Radius to use if none is available.
     private static final int FALLBACK_RADIUS_DP = 15;
+    private static final float MARGIN_DP = 8;
+    private static final int MAX_ARC_DEGREES = 90;
+    // Arc length along the phone's perimeter used to measure the desired angle.
+    private static final float ARC_LENGTH_DP = 31f;
 
     private Paint mPaint;
     private int mLightColor;
     private int mDarkColor;
-    private RectF mOval;
-
+    private Path mPath;
 
     public CornerHandleView(Context context, AttributeSet attrs) {
         super(context, attrs);
@@ -55,18 +57,46 @@
         mPaint.setStrokeCap(Paint.Cap.ROUND);
         mPaint.setStrokeWidth(getStrokePx());
 
-        final int dualToneDarkTheme = Utils.getThemeAttr(mContext,
-                R.attr.darkIconTheme);
-        final int dualToneLightTheme = Utils.getThemeAttr(mContext,
-                R.attr.lightIconTheme);
+        final int dualToneDarkTheme = Utils.getThemeAttr(mContext, R.attr.darkIconTheme);
+        final int dualToneLightTheme = Utils.getThemeAttr(mContext, R.attr.lightIconTheme);
         Context lightContext = new ContextThemeWrapper(mContext, dualToneLightTheme);
         Context darkContext = new ContextThemeWrapper(mContext, dualToneDarkTheme);
-        mLightColor = Utils.getColorAttrDefaultColor(lightContext,
-                R.attr.singleToneColor);
-        mDarkColor = Utils.getColorAttrDefaultColor(darkContext,
-                R.attr.singleToneColor);
+        mLightColor = Utils.getColorAttrDefaultColor(lightContext, R.attr.singleToneColor);
+        mDarkColor = Utils.getColorAttrDefaultColor(darkContext, R.attr.singleToneColor);
 
-        updateOval();
+        updatePath();
+    }
+
+    private void updatePath() {
+        mPath = new Path();
+
+        float marginPx = getMarginPx();
+        float radiusPx = getInnerRadiusPx();
+        float halfStrokePx = getStrokePx() / 2f;
+        float angle = getAngle();
+        float startAngle = 180 + ((90 - angle) / 2);
+        RectF circle = new RectF(marginPx + halfStrokePx,
+                marginPx + halfStrokePx,
+                marginPx + 2 * radiusPx - halfStrokePx,
+                marginPx + 2 * radiusPx - halfStrokePx);
+
+        if (angle >= 90f) {
+            float innerCircumferenceDp = convertPixelToDp(radiusPx * 2 * (float) Math.PI,
+                    mContext);
+            float arcDp = innerCircumferenceDp * getAngle() / 360f;
+            // Add additional "arms" to the two ends of the arc. The length computation is
+            // hand-tuned.
+            float lineLengthPx = convertDpToPixel((ARC_LENGTH_DP - arcDp - MARGIN_DP) / 2,
+                    mContext);
+
+            mPath.moveTo(marginPx + halfStrokePx, marginPx + radiusPx + lineLengthPx);
+            mPath.lineTo(marginPx + halfStrokePx, marginPx + radiusPx);
+            mPath.arcTo(circle, startAngle, angle);
+            mPath.moveTo(marginPx + radiusPx, marginPx + halfStrokePx);
+            mPath.lineTo(marginPx + radiusPx + lineLengthPx, marginPx + halfStrokePx);
+        } else {
+            mPath.arcTo(circle, startAngle, angle);
+        }
     }
 
     /**
@@ -83,50 +113,40 @@
     @Override
     public void onDraw(Canvas canvas) {
         super.onDraw(canvas);
-
-        if (ALLOW_TUNING) {
-            mPaint.setStrokeWidth(getStrokePx());
-            updateOval();
-        }
-
-        canvas.drawArc(mOval, 180 + ((90 - getAngle()) / 2), getAngle(), false,
-                mPaint);
+        canvas.drawPath(mPath, mPaint);
     }
 
-    // TODO(b/133834204): Remove tweaking of corner handles
     private static float convertDpToPixel(float dp, Context context) {
         return dp * ((float) context.getResources().getDisplayMetrics().densityDpi
                 / DisplayMetrics.DENSITY_DEFAULT);
     }
 
-    private void updateOval() {
-        mOval = new RectF(getMarginPx() - (getStrokePx() / 2.f),
-                getMarginPx() - (getStrokePx() / 2.f),
-                getMarginPx() + (2 * (getRadiusPx()) + (getStrokePx() / 2.f)),
-                getMarginPx() + 2 * getRadiusPx() + (getStrokePx() / 2.f));
+    private static float convertPixelToDp(float px, Context context) {
+        return px * DisplayMetrics.DENSITY_DEFAULT
+                / ((float) context.getResources().getDisplayMetrics().densityDpi);
     }
 
-    private int getAngle() {
-        if (ALLOW_TUNING) {
-            return SystemProperties.getInt("CORNER_HANDLE_ANGLE_DEGREES", ANGLE_DEGREES);
-        } else {
-            return ANGLE_DEGREES;
+    private float getAngle() {
+        // Measure a length of ARC_LENGTH_DP along the *screen's* perimeter, get the angle and cap
+        // it at 90.
+        float circumferenceDp = convertPixelToDp((
+                getOuterRadiusPx()) * 2 * (float) Math.PI, mContext);
+        float angleDeg = (ARC_LENGTH_DP / circumferenceDp) * 360;
+        if (angleDeg > MAX_ARC_DEGREES) {
+            angleDeg = MAX_ARC_DEGREES;
         }
+        return angleDeg;
     }
 
-    private int getMarginPx() {
-        // Hand-derived function to map radiusPx to the margin amount.
-        // https://www.wolframalpha.com/input/?i=0.001402+*+x+%5E2%E2%88%920.08661+*+x%2B17.20+from+40+to+180
-        int radius = getRadiusPx();
-        int marginPx = (int) (0.001402f * radius * radius - 0.08661f * radius + 17.2f);
-        if (ALLOW_TUNING) {
-            return SystemProperties.getInt("CORNER_HANDLE_MARGIN_PX", marginPx);
-        } else {
-            return marginPx;
-        }
+    private float getMarginPx() {
+        return convertDpToPixel(MARGIN_DP, mContext);
     }
 
-    private int getRadiusPx() {
+    private float getInnerRadiusPx() {
+        return getOuterRadiusPx() - getMarginPx();
+    }
+
+    private float getOuterRadiusPx() {
         // Attempt to get the bottom corner radius, otherwise fall back on the generic or top
         // values. If none are available, use the FALLBACK_RADIUS_DP.
         int radius = getResources().getDimensionPixelSize(
@@ -142,19 +162,12 @@
         if (radius == 0) {
             radius = (int) convertDpToPixel(FALLBACK_RADIUS_DP, mContext);
         }
-        if (ALLOW_TUNING) {
-            return SystemProperties.getInt("CORNER_HANDLE_RADIUS_PX", radius);
-        } else {
-            return radius;
-        }
+        return radius;
     }
 
-    private int getStrokePx() {
-        if (ALLOW_TUNING) {
-            return SystemProperties.getInt("CORNER_HANDLE_STROKE_PX",
-                    (int) convertDpToPixel(STROKE_DP, getContext()));
-        } else {
-            return (int) convertDpToPixel(STROKE_DP, getContext());
-        }
+    private float getStrokePx() {
+        // Use a slightly smaller stroke if we need to cover the full corner angle.
+        return convertDpToPixel((getAngle() < 90) ? STROKE_DP_LARGE : STROKE_DP_SMALL,
+                getContext());
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java b/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
index c7c10f1..97b6e7c 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
@@ -258,7 +258,7 @@
         }
         int phoneState = mPhoneStateMonitor.getPhoneState();
         args.putInt(INVOCATION_PHONE_STATE_KEY, phoneState);
-        args.putLong(INVOCATION_TIME_MS_KEY, SystemClock.uptimeMillis());
+        args.putLong(INVOCATION_TIME_MS_KEY, SystemClock.elapsedRealtime());
         logStartAssist(invocationType, phoneState);
         startAssistInternal(args, assistComponent, isService);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/BiometricDialogView.java b/packages/SystemUI/src/com/android/systemui/biometrics/BiometricDialogView.java
index 5717a54..499fe8d 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/BiometricDialogView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/BiometricDialogView.java
@@ -16,6 +16,8 @@
 
 package com.android.systemui.biometrics;
 
+import static android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE;
+
 import android.app.admin.DevicePolicyManager;
 import android.content.Context;
 import android.graphics.PixelFormat;
@@ -36,6 +38,7 @@
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.WindowManager;
+import android.view.accessibility.AccessibilityEvent;
 import android.view.animation.Interpolator;
 import android.widget.Button;
 import android.widget.ImageView;
@@ -280,6 +283,7 @@
         final CharSequence subtitleText = mBundle.getCharSequence(BiometricPrompt.KEY_SUBTITLE);
         if (TextUtils.isEmpty(subtitleText)) {
             mSubtitleText.setVisibility(View.GONE);
+            announceAccessibilityEvent();
         } else {
             mSubtitleText.setVisibility(View.VISIBLE);
             mSubtitleText.setText(subtitleText);
@@ -289,6 +293,7 @@
                 mBundle.getCharSequence(BiometricPrompt.KEY_DESCRIPTION);
         if (TextUtils.isEmpty(descriptionText)) {
             mDescriptionText.setVisibility(View.GONE);
+            announceAccessibilityEvent();
         } else {
             mDescriptionText.setVisibility(View.VISIBLE);
             mDescriptionText.setText(descriptionText);
@@ -447,12 +452,14 @@
         if (newState == STATE_PENDING_CONFIRMATION) {
             mHandler.removeMessages(MSG_RESET_MESSAGE);
             mErrorText.setVisibility(View.INVISIBLE);
+            announceAccessibilityEvent();
             mPositiveButton.setVisibility(View.VISIBLE);
             mPositiveButton.setEnabled(true);
         } else if (newState == STATE_AUTHENTICATED) {
             mPositiveButton.setVisibility(View.GONE);
             mNegativeButton.setVisibility(View.GONE);
             mErrorText.setVisibility(View.INVISIBLE);
+            announceAccessibilityEvent();
         }
 
         if (newState == STATE_PENDING_CONFIRMATION || newState == STATE_AUTHENTICATED) {
@@ -471,14 +478,20 @@
 
     public void restoreState(Bundle bundle) {
         mRestoredState = bundle;
-        mTryAgainButton.setVisibility(bundle.getInt(KEY_TRY_AGAIN_VISIBILITY));
-        mPositiveButton.setVisibility(bundle.getInt(KEY_CONFIRM_VISIBILITY));
+        final int tryAgainVisibility = bundle.getInt(KEY_TRY_AGAIN_VISIBILITY);
+        mTryAgainButton.setVisibility(tryAgainVisibility);
+        final int confirmVisibility = bundle.getInt(KEY_CONFIRM_VISIBILITY);
+        mPositiveButton.setVisibility(confirmVisibility);
         mState = bundle.getInt(KEY_STATE);
         mErrorText.setText(bundle.getCharSequence(KEY_ERROR_TEXT_STRING));
         mErrorText.setContentDescription(bundle.getCharSequence(KEY_ERROR_TEXT_STRING));
-        mErrorText.setVisibility(bundle.getInt(KEY_ERROR_TEXT_VISIBILITY));
+        final int errorTextVisibility = bundle.getInt(KEY_ERROR_TEXT_VISIBILITY);
+        mErrorText.setVisibility(errorTextVisibility);
+        if (errorTextVisibility == View.INVISIBLE || tryAgainVisibility == View.INVISIBLE
+                || confirmVisibility == View.INVISIBLE) {
+            announceAccessibilityEvent();
+        }
         mErrorText.setTextColor(bundle.getInt(KEY_ERROR_TEXT_COLOR));
-
         if (bundle.getBoolean(KEY_ERROR_TEXT_IS_TEMPORARY)) {
             mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_RESET_MESSAGE),
                     BiometricPrompt.HIDE_DIALOG_DELAY);
@@ -501,4 +514,16 @@
         lp.token = mWindowToken;
         return lp;
     }
+
+    // Every time a view becomes invisible we need to announce an accessibility event.
+    // This is due to an issue in the framework, b/132298701 recommended this workaround.
+    protected void announceAccessibilityEvent() {
+        AccessibilityEvent event = AccessibilityEvent.obtain();
+        event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
+        event.setContentChangeTypes(CONTENT_CHANGE_TYPE_SUBTREE);
+        mDialog.sendAccessibilityEventUnchecked(event);
+        mDialog.notifySubtreeAccessibilityStateChanged(mDialog, mDialog,
+                CONTENT_CHANGE_TYPE_SUBTREE);
+        event.recycle();
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/FaceDialogView.java b/packages/SystemUI/src/com/android/systemui/biometrics/FaceDialogView.java
index 8f26f18..91124cb 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/FaceDialogView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/FaceDialogView.java
@@ -149,6 +149,7 @@
     private final Runnable mErrorToIdleAnimationRunnable = () -> {
         updateState(STATE_IDLE);
         mErrorText.setVisibility(View.INVISIBLE);
+        announceAccessibilityEvent();
     };
 
     public FaceDialogView(Context context,
@@ -188,6 +189,7 @@
             mDialog.invalidateOutline();
 
             mSize = newSize;
+            announceAccessibilityEvent();
         } else if (mSize == SIZE_SMALL && newSize == SIZE_BIG) {
             mSize = SIZE_GROWING;
 
@@ -294,6 +296,7 @@
             mErrorText.setVisibility(View.VISIBLE);
         } else {
             mErrorText.setVisibility(View.INVISIBLE);
+            announceAccessibilityEvent();
         }
     }
 
@@ -368,11 +371,13 @@
                 mTryAgainButton.setVisibility(View.VISIBLE);
             } else {
                 mTryAgainButton.setVisibility(View.GONE);
+                announceAccessibilityEvent();
             }
         }
 
         if (show) {
             mPositiveButton.setVisibility(View.GONE);
+            announceAccessibilityEvent();
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
index 1848219..b0f77ce 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
@@ -41,7 +41,6 @@
 import android.hardware.input.InputManager;
 import android.os.Binder;
 import android.os.Bundle;
-import android.os.Debug;
 import android.os.Handler;
 import android.os.IBinder;
 import android.os.Looper;
@@ -69,6 +68,7 @@
 import com.android.systemui.statusbar.phone.NavigationBarView;
 import com.android.systemui.statusbar.phone.NavigationModeController;
 import com.android.systemui.statusbar.phone.StatusBar;
+import com.android.systemui.statusbar.phone.StatusBarWindowController;
 import com.android.systemui.statusbar.policy.CallbackController;
 import com.android.systemui.statusbar.policy.DeviceProvisionedController;
 import com.android.systemui.statusbar.policy.DeviceProvisionedController.DeviceProvisionedListener;
@@ -516,7 +516,8 @@
         final NavigationBarController navBar = Dependency.get(NavigationBarController.class);
         final NavigationBarFragment navBarFragment = navBar.getDefaultNavigationBarFragment();
         final NavigationBarView navBarView = navBar.getNavigationBarView(mContext.getDisplayId());
-        final StatusBar statusBar = SysUiServiceProvider.getComponent(mContext, StatusBar.class);
+        final StatusBarWindowController statusBarController =
+                Dependency.get(StatusBarWindowController.class);
 
         mSysUiStateFlags = 0;
         if (navBarFragment != null) {
@@ -525,8 +526,8 @@
         if (navBarView != null) {
             navBarView.updateSystemUiStateFlags();
         }
-        if (statusBar != null) {
-            statusBar.updateSystemUiStateFlags();
+        if (statusBarController != null) {
+            statusBarController.updateSystemUiStateFlags();
         }
         notifySystemUiStateFlags(mSysUiStateFlags);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithm.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithm.java
index 579d1ab..c477162 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithm.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithm.java
@@ -176,7 +176,7 @@
     }
 
     private int getExpandedPreferredClockY() {
-        return (mHasCustomClock && !mHasVisibleNotifs) ? getPreferredClockY()
+        return (mHasCustomClock && (!mHasVisibleNotifs || mPositionLikeDark)) ? getPreferredClockY()
                 : getExpandedClockPosition();
     }
 
@@ -218,7 +218,7 @@
         float clockY = MathUtils.lerp(clockYBouncer, clockYRegular, shadeExpansion);
         clockYDark = MathUtils.lerp(clockYBouncer, clockYDark, shadeExpansion);
 
-        float darkAmount = mPositionLikeDark ? 1.0f : mDarkAmount;
+        float darkAmount = mPositionLikeDark && !mHasCustomClock ? 1.0f : mDarkAmount;
         return (int) (MathUtils.lerp(clockY, clockYDark, darkAmount) + mEmptyDragAmount);
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
index b3cbf08..1d1ae37 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
@@ -686,6 +686,7 @@
                     mClockPositionResult.clockX, CLOCK_ANIMATION_PROPERTIES, animateClock);
             PropertyAnimator.setProperty(mKeyguardStatusView, AnimatableProperty.Y,
                     mClockPositionResult.clockY, CLOCK_ANIMATION_PROPERTIES, animateClock);
+            updateNotificationTranslucency();
             updateClock();
             stackScrollerPadding = mClockPositionResult.stackScrollerPaddingExpanded;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
index 7f20d8c..9536be3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
@@ -30,8 +30,6 @@
 import static com.android.systemui.keyguard.WakefulnessLifecycle.WAKEFULNESS_ASLEEP;
 import static com.android.systemui.keyguard.WakefulnessLifecycle.WAKEFULNESS_AWAKE;
 import static com.android.systemui.keyguard.WakefulnessLifecycle.WAKEFULNESS_WAKING;
-import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_BOUNCER_SHOWING;
-import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING;
 import static com.android.systemui.shared.system.WindowManagerWrapper.NAV_BAR_POS_INVALID;
 import static com.android.systemui.shared.system.WindowManagerWrapper.NAV_BAR_POS_LEFT;
 import static com.android.systemui.statusbar.NotificationLockscreenUserManager.PERMISSION_SELF;
@@ -169,7 +167,6 @@
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.qs.QSFragment;
 import com.android.systemui.qs.QSPanel;
-import com.android.systemui.recents.OverviewProxyService;
 import com.android.systemui.recents.Recents;
 import com.android.systemui.recents.ScreenPinningRequest;
 import com.android.systemui.shared.system.WindowManagerWrapper;
@@ -788,8 +785,6 @@
         int disabledFlags2 = result.mDisabledFlags2;
         Dependency.get(InitController.class).addPostInitTask(
                 () -> setUpDisableFlags(disabledFlags1, disabledFlags2));
-
-        updateSystemUiStateFlags();
     }
 
     // ================================================================================
@@ -3423,7 +3418,6 @@
         updateDozingState();
         checkBarModes();
         updateScrimController();
-        updateSystemUiStateFlags();
         mPresenter.updateMediaMetaData(false, mState != StatusBarState.KEYGUARD);
         mKeyguardMonitor.notifyKeyguardState(mStatusBarKeyguardViewManager.isShowing(),
                 mUnlockMethodCache.isMethodSecure(),
@@ -3590,16 +3584,6 @@
         if (!mBouncerShowing) {
             updatePanelExpansionForKeyguard();
         }
-        updateSystemUiStateFlags();
-    }
-
-    public void updateSystemUiStateFlags() {
-        OverviewProxyService overviewProxyService = Dependency.get(OverviewProxyService.class);
-        overviewProxyService.setSystemUiStateFlag(SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING,
-                mStatusBarStateController.getState() == StatusBarState.KEYGUARD,
-                mDisplayId);
-        overviewProxyService.setSystemUiStateFlag(SYSUI_STATE_BOUNCER_SHOWING,
-                isBouncerShowing(), mDisplayId);
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java
index f08db1b..3d3abe3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java
@@ -18,6 +18,9 @@
 
 import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
 
+import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_BOUNCER_SHOWING;
+import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING;
+import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED;
 import static com.android.systemui.statusbar.NotificationRemoteInputManager.ENABLE_REMOTE_INPUT;
 
 import android.app.ActivityManager;
@@ -45,6 +48,7 @@
 import com.android.systemui.keyguard.KeyguardViewMediator;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.plugins.statusbar.StatusBarStateController.StateListener;
+import com.android.systemui.recents.OverviewProxyService;
 import com.android.systemui.statusbar.RemoteInputController.Callback;
 import com.android.systemui.statusbar.StatusBarState;
 import com.android.systemui.statusbar.SysuiStatusBarStateController;
@@ -316,6 +320,18 @@
             }
             mHasTopUi = mHasTopUiChanged;
         }
+        updateSystemUiStateFlags();
+    }
+
+    public void updateSystemUiStateFlags() {
+        int displayId = mContext.getDisplayId();
+        OverviewProxyService overviewProxyService = Dependency.get(OverviewProxyService.class);
+        overviewProxyService.setSystemUiStateFlag(SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING,
+                mCurrentState.keyguardShowing && !mCurrentState.keyguardOccluded, displayId);
+        overviewProxyService.setSystemUiStateFlag(SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED,
+                mCurrentState.keyguardShowing && mCurrentState.keyguardOccluded, displayId);
+        overviewProxyService.setSystemUiStateFlag(SYSUI_STATE_BOUNCER_SHOWING,
+                mCurrentState.bouncerShowing, displayId);
     }
 
     private void applyForceStatusBarVisibleFlag(State state) {
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/clock/SmallClockPositionTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/clock/SmallClockPositionTest.kt
index f4d59cc..456f32b 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/clock/SmallClockPositionTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/clock/SmallClockPositionTest.kt
@@ -52,8 +52,8 @@
     fun darkPosition() {
         // GIVEN on AOD
         position.setDarkAmount(1f)
-        // THEN Y position is statusBarHeight + lockPadding + burnInY (100 + 15 + 20 = 135)
-        assertThat(position.preferredY).isEqualTo(135)
+        // THEN Y is sum of statusBarHeight, lockPadding, lockHeight, lockPadding, burnInY
+        assertThat(position.preferredY).isEqualTo(185)
     }
 
     @Test
@@ -64,4 +64,4 @@
         // (100 + 15 + 35 + 15 = 165)
         assertThat(position.preferredY).isEqualTo(165)
     }
-}
\ No newline at end of file
+}
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 39ce4a0..7a2aa7e 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -2577,11 +2577,11 @@
                     break;
                 }
                 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
-                    if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
-                        loge("ERROR: already-connected network explicitly selected.");
+                    if (nai.everConnected) {
+                        loge("ERROR: cannot call explicitlySelected on already-connected network");
                     }
-                    nai.networkMisc.explicitlySelected = true;
-                    nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
+                    nai.networkMisc.explicitlySelected = (msg.arg1 == 1);
+                    nai.networkMisc.acceptUnvalidated = (msg.arg1 == 1) && (msg.arg2 == 1);
                     // Mark the network as temporarily accepting partial connectivity so that it
                     // will be validated (and possibly become default) even if it only provides
                     // partial internet access. Note that if user connects to partial connectivity
@@ -2589,7 +2589,7 @@
                     // out of wifi coverage) and if the same wifi is available again, the device
                     // will auto connect to this wifi even though the wifi has "no internet".
                     // TODO: Evaluate using a separate setting in IpMemoryStore.
-                    nai.networkMisc.acceptPartialConnectivity = msg.arg1 == 1;
+                    nai.networkMisc.acceptPartialConnectivity = (msg.arg2 == 1);
                     break;
                 }
                 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
diff --git a/services/core/java/com/android/server/LocationManagerService.java b/services/core/java/com/android/server/LocationManagerService.java
index ae04f76..78f0603 100644
--- a/services/core/java/com/android/server/LocationManagerService.java
+++ b/services/core/java/com/android/server/LocationManagerService.java
@@ -2962,11 +2962,11 @@
             gnssDataListeners.put(binder, linkedListener);
             long identity = Binder.clearCallingIdentity();
             try {
-                if (gnssDataProvider == mGnssNavigationMessageProvider
+                if (gnssDataProvider == mGnssMeasurementsProvider
                         || gnssDataProvider == mGnssStatusProvider) {
                     mLocationUsageLogger.logLocationApiUsage(
                             LocationStatsEnums.USAGE_STARTED,
-                            gnssDataProvider == mGnssNavigationMessageProvider
+                            gnssDataProvider == mGnssMeasurementsProvider
                                 ? LocationStatsEnums.API_ADD_GNSS_MEASUREMENTS_LISTENER
                                 : LocationStatsEnums.API_REGISTER_GNSS_STATUS_CALLBACK,
                             packageName,
@@ -3003,11 +3003,11 @@
             }
             long identity = Binder.clearCallingIdentity();
             try {
-                if (gnssDataProvider == mGnssNavigationMessageProvider
+                if (gnssDataProvider == mGnssMeasurementsProvider
                         || gnssDataProvider == mGnssStatusProvider) {
                     mLocationUsageLogger.logLocationApiUsage(
                             LocationStatsEnums.USAGE_ENDED,
-                            gnssDataProvider == mGnssNavigationMessageProvider
+                            gnssDataProvider == mGnssMeasurementsProvider
                                 ? LocationStatsEnums.API_ADD_GNSS_MEASUREMENTS_LISTENER
                                 : LocationStatsEnums.API_REGISTER_GNSS_STATUS_CALLBACK,
                             linkedListener.mCallerIdentity.mPackageName,
diff --git a/services/core/java/com/android/server/attention/AttentionManagerService.java b/services/core/java/com/android/server/attention/AttentionManagerService.java
index 3b19d08..1b45eb4 100644
--- a/services/core/java/com/android/server/attention/AttentionManagerService.java
+++ b/services/core/java/com/android/server/attention/AttentionManagerService.java
@@ -190,9 +190,7 @@
 
             final UserState userState = getOrCreateCurrentUserStateLocked();
             // lazily start the service, which should be very lightweight to start
-            if (!userState.bindLocked()) {
-                return false;
-            }
+            userState.bindLocked();
 
             // throttle frequent requests
             final AttentionCheckCache cache = userState.mAttentionCheckCache;
@@ -310,7 +308,7 @@
     protected UserState getOrCreateUserStateLocked(int userId) {
         UserState result = mUserStates.get(userId);
         if (result == null) {
-            result = new UserState(userId, mContext, mLock, mComponentName);
+            result = new UserState(userId, mContext, mLock, mAttentionHandler, mComponentName);
             mUserStates.put(userId, result);
         }
         return result;
@@ -456,31 +454,33 @@
 
     @VisibleForTesting
     protected static class UserState {
-        final ComponentName mComponentName;
-        final AttentionServiceConnection mConnection = new AttentionServiceConnection();
+        private final ComponentName mComponentName;
+        private final AttentionServiceConnection mConnection = new AttentionServiceConnection();
 
         @GuardedBy("mLock")
         IAttentionService mService;
         @GuardedBy("mLock")
-        boolean mBinding;
-        @GuardedBy("mLock")
         AttentionCheck mCurrentAttentionCheck;
         @GuardedBy("mLock")
         AttentionCheckCache mAttentionCheckCache;
+        @GuardedBy("mLock")
+        private boolean mBinding;
 
         @UserIdInt
-        final int mUserId;
-        final Context mContext;
-        final Object mLock;
+        private final int mUserId;
+        private final Context mContext;
+        private final Object mLock;
+        private final Handler mAttentionHandler;
 
-        UserState(int userId, Context context, Object lock, ComponentName componentName) {
+        UserState(int userId, Context context, Object lock, Handler handler,
+                ComponentName componentName) {
             mUserId = userId;
             mContext = Preconditions.checkNotNull(context);
             mLock = Preconditions.checkNotNull(lock);
             mComponentName = Preconditions.checkNotNull(componentName);
+            mAttentionHandler = handler;
         }
 
-
         @GuardedBy("mLock")
         private void handlePendingCallbackLocked() {
             if (!mCurrentAttentionCheck.mIsDispatched) {
@@ -499,26 +499,25 @@
 
         /** Binds to the system's AttentionService which provides an actual implementation. */
         @GuardedBy("mLock")
-        private boolean bindLocked() {
+        private void bindLocked() {
             // No need to bind if service is binding or has already been bound.
             if (mBinding || mService != null) {
-                return true;
+                return;
             }
 
-            final boolean willBind;
-            final long identity = Binder.clearCallingIdentity();
-
-            try {
-                final Intent mServiceIntent = new Intent(
+            mBinding = true;
+            // mContext.bindServiceAsUser() calls into ActivityManagerService which it may already
+            // hold the lock and had called into PowerManagerService, which holds a lock.
+            // That would create a deadlock. To solve that, putting it on a handler.
+            mAttentionHandler.post(() -> {
+                final Intent serviceIntent = new Intent(
                         AttentionService.SERVICE_INTERFACE).setComponent(
                         mComponentName);
-                willBind = mContext.bindServiceAsUser(mServiceIntent, mConnection,
+                // Note: no reason to clear the calling identity, we won't have one in a handler.
+                mContext.bindServiceAsUser(serviceIntent, mConnection,
                         Context.BIND_AUTO_CREATE, UserHandle.CURRENT);
-                mBinding = willBind;
-            } finally {
-                Binder.restoreCallingIdentity(identity);
-            }
-            return willBind;
+
+            });
         }
 
         private void dump(IndentingPrintWriter pw) {
@@ -587,6 +586,7 @@
             super(Looper.myLooper());
         }
 
+        @Override
         public void handleMessage(Message msg) {
             switch (msg.what) {
                 // Do not occupy resources when not in use - unbind proactively.
@@ -651,7 +651,12 @@
                 return;
             }
 
-            mContext.unbindService(userState.mConnection);
+            mAttentionHandler.post(() -> mContext.unbindService(userState.mConnection));
+            // Note: this will set mBinding to false even though it could still be trying to bind
+            // (i.e. the runnable was posted in bindLocked but then cancelAndUnbindLocked was
+            // called before it's run yet). This is a safe state at the moment,
+            // since it will eventually, but feels like a source for confusion down the road and
+            // may cause some expensive and unnecessary work to be done.
             userState.mConnection.cleanupService();
             mUserStates.remove(userState.mUserId);
         }
diff --git a/services/core/java/com/android/server/locksettings/LockSettingsService.java b/services/core/java/com/android/server/locksettings/LockSettingsService.java
index 107e1fbb..1e0a3d5 100644
--- a/services/core/java/com/android/server/locksettings/LockSettingsService.java
+++ b/services/core/java/com/android/server/locksettings/LockSettingsService.java
@@ -2548,9 +2548,8 @@
             // Reset lockout only if user has enrolled templates
             if (mInjector.hasEnrolledBiometrics()) {
                 BiometricManager bm = mContext.getSystemService(BiometricManager.class);
-                Slog.i(TAG, "Resetting lockout, length: "
-                        + authResult.gkResponse.getPayload().length);
-                bm.resetLockout(authResult.gkResponse.getPayload());
+                Slog.i(TAG, "Resetting lockout, length: " + response.getPayload().length);
+                bm.resetLockout(response.getPayload());
 
                 if (!hasChallenge && pm.hasSystemFeature(PackageManager.FEATURE_FACE)) {
                     mContext.getSystemService(FaceManager.class).revokeChallenge();
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 5958715..4a5e61b 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -18050,9 +18050,15 @@
                 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling verity to " + filePath);
                 final FileDescriptor fd = result.getUnownedFileDescriptor();
                 try {
-                    mInstaller.installApkVerity(filePath, fd, result.getContentSize());
                     final byte[] rootHash = VerityUtils.generateApkVerityRootHash(filePath);
-                    mInstaller.assertFsverityRootHashMatches(filePath, rootHash);
+                    try {
+                        // A file may already have fs-verity, e.g. when reused during a split
+                        // install. If the measurement succeeds, no need to attempt to set up.
+                        mInstaller.assertFsverityRootHashMatches(filePath, rootHash);
+                    } catch (InstallerException e) {
+                        mInstaller.installApkVerity(filePath, fd, result.getContentSize());
+                        mInstaller.assertFsverityRootHashMatches(filePath, rootHash);
+                    }
                 } finally {
                     IoUtils.closeQuietly(fd);
                 }
diff --git a/services/core/java/com/android/server/uri/UriGrantsManagerInternal.java b/services/core/java/com/android/server/uri/UriGrantsManagerInternal.java
index 94a1baa..2f50fcb 100644
--- a/services/core/java/com/android/server/uri/UriGrantsManagerInternal.java
+++ b/services/core/java/com/android/server/uri/UriGrantsManagerInternal.java
@@ -43,14 +43,14 @@
             int callingUid, String targetPkg, Uri uri, int modeFlags, int userId);
     NeededUriGrants checkGrantUriPermissionFromIntent(int callingUid,
             String targetPkg, Intent intent, int mode, NeededUriGrants needed, int targetUserId);
-    NeededUriGrants checkGrantUriPermissionFromIntent(int callingUid,
-            Intent intent, String targetPkg, int targetUserId);
     /**
      * Grant Uri permissions from one app to another. This method only extends
      * permission grants if {@code callingUid} has permission to them.
      */
     void grantUriPermissionFromIntent(int callingUid,
             String targetPkg, Intent intent, int targetUserId);
+    void grantUriPermissionFromIntent(int callingUid,
+            String targetPkg, Intent intent, UriPermissionOwner owner, int targetUserId);
     void grantUriPermissionUncheckedFromIntent(
             NeededUriGrants needed, UriPermissionOwner owner);
     IBinder newUriPermissionOwner(String name);
diff --git a/services/core/java/com/android/server/uri/UriGrantsManagerService.java b/services/core/java/com/android/server/uri/UriGrantsManagerService.java
index 04f7c7e..8b332d2 100644
--- a/services/core/java/com/android/server/uri/UriGrantsManagerService.java
+++ b/services/core/java/com/android/server/uri/UriGrantsManagerService.java
@@ -1362,16 +1362,6 @@
         }
 
         @Override
-        public NeededUriGrants checkGrantUriPermissionFromIntent(int callingUid, Intent intent,
-                String targetPkg, int targetUserId) {
-            synchronized (mLock) {
-                final int mode = (intent != null) ? intent.getFlags() : 0;
-                return UriGrantsManagerService.this.checkGrantUriPermissionFromIntent(
-                        callingUid, targetPkg, intent, mode, null, targetUserId);
-            }
-        }
-
-        @Override
         public void grantUriPermissionFromIntent(int callingUid, String targetPkg, Intent intent,
                 int targetUserId) {
             synchronized (mLock) {
@@ -1381,6 +1371,15 @@
         }
 
         @Override
+        public void grantUriPermissionFromIntent(int callingUid, String targetPkg, Intent intent,
+                UriPermissionOwner owner, int targetUserId) {
+            synchronized (mLock) {
+                UriGrantsManagerService.this.grantUriPermissionFromIntent(
+                        callingUid, targetPkg, intent, owner, targetUserId);
+            }
+        }
+
+        @Override
         public void grantUriPermissionUncheckedFromIntent(NeededUriGrants needed,
                 UriPermissionOwner owner) {
             synchronized (mLock) {
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index 7c4b571..1344727 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -215,7 +215,6 @@
 import com.android.server.AttributeCache.Entry;
 import com.android.server.am.AppTimeTracker;
 import com.android.server.am.PendingIntentRecord;
-import com.android.server.uri.NeededUriGrants;
 import com.android.server.uri.UriPermissionOwner;
 import com.android.server.wm.ActivityMetricsLogger.WindowingModeTransitionInfoSnapshot;
 import com.android.server.wm.ActivityStack.ActivityState;
@@ -1600,11 +1599,10 @@
      * Deliver a new Intent to an existing activity, so that its onNewIntent()
      * method will be called at the proper time.
      */
-    final void deliverNewIntentLocked(int callingUid, Intent intent, NeededUriGrants intentGrants,
-            String referrer) {
+    final void deliverNewIntentLocked(int callingUid, Intent intent, String referrer) {
         // The activity now gets access to the data associated with this Intent.
-        mAtmService.mUgmInternal.grantUriPermissionUncheckedFromIntent(intentGrants,
-                getUriPermissionsLocked());
+        mAtmService.mUgmInternal.grantUriPermissionFromIntent(callingUid, packageName,
+                intent, getUriPermissionsLocked(), mUserId);
         final ReferrerIntent rintent = new ReferrerIntent(intent, referrer);
         boolean unsent = true;
         final boolean isTopActivityWhileSleeping = isTopRunningActivity() && isSleeping();
diff --git a/services/core/java/com/android/server/wm/ActivityStack.java b/services/core/java/com/android/server/wm/ActivityStack.java
index 94c4a61..b3b6efe 100644
--- a/services/core/java/com/android/server/wm/ActivityStack.java
+++ b/services/core/java/com/android/server/wm/ActivityStack.java
@@ -163,7 +163,6 @@
 import com.android.server.am.AppTimeTracker;
 import com.android.server.am.EventLogTags;
 import com.android.server.am.PendingIntentRecord;
-import com.android.server.uri.NeededUriGrants;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
@@ -2782,7 +2781,7 @@
             if (DEBUG_STATES) Slog.d(TAG_STATES,
                     "no-history finish of " + mLastNoHistoryActivity + " on new resume");
             requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
-                    null, null, "resume-no-history", false);
+                    null, "resume-no-history", false);
             mLastNoHistoryActivity = null;
         }
 
@@ -3016,7 +3015,7 @@
                 // If any exception gets thrown, toss away this
                 // activity and try the next one.
                 Slog.w(TAG, "Exception thrown during resume of " + next, e);
-                requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null, null,
+                requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
                         "resume-exception", true);
                 return true;
             }
@@ -3426,7 +3425,7 @@
                     if (DEBUG_TASKS) Slog.w(TAG_TASKS,
                             "resetTaskIntendedTask: calling finishActivity on " + p);
                     if (finishActivityLocked(
-                            p, Activity.RESULT_CANCELED, null, null, "reset-task", false)) {
+                            p, Activity.RESULT_CANCELED, null, "reset-task", false)) {
                         end--;
                         srcPos--;
                     }
@@ -3505,7 +3504,7 @@
                             continue;
                         }
                         finishActivityLocked(
-                                p, Activity.RESULT_CANCELED, null, null, "move-affinity", false);
+                                p, Activity.RESULT_CANCELED, null, "move-affinity", false);
                     }
                 } else {
                     if (taskInsertionPoint < 0) {
@@ -3539,8 +3538,8 @@
                         if (targetNdx > 0) {
                             ActivityRecord p = taskActivities.get(targetNdx - 1);
                             if (p.intent.getComponent().equals(target.intent.getComponent())) {
-                                finishActivityLocked(p, Activity.RESULT_CANCELED, null, null,
-                                        "replace", false);
+                                finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace",
+                                        false);
                             }
                         }
                     }
@@ -3600,21 +3599,22 @@
         return taskTop;
     }
 
-    void sendActivityResultLocked(int callingUid, ActivityRecord r, String resultWho,
-            int requestCode, int resultCode, Intent resultData, NeededUriGrants resultGrants) {
+    void sendActivityResultLocked(int callingUid, ActivityRecord r,
+            String resultWho, int requestCode, int resultCode, Intent data) {
+
         if (callingUid > 0) {
-            mService.mUgmInternal.grantUriPermissionUncheckedFromIntent(resultGrants,
-                    r.getUriPermissionsLocked());
+            mService.mUgmInternal.grantUriPermissionFromIntent(callingUid, r.packageName,
+                    data, r.getUriPermissionsLocked(), r.mUserId);
         }
 
         if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
                 + " : who=" + resultWho + " req=" + requestCode
-                + " res=" + resultCode + " data=" + resultData);
+                + " res=" + resultCode + " data=" + data);
         if (mResumedActivity == r && r.attachedToProcess()) {
             try {
                 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
                 list.add(new ResultInfo(resultWho, requestCode,
-                        resultCode, resultData));
+                        resultCode, data));
                 mService.getLifecycleManager().scheduleTransaction(r.app.getThread(), r.appToken,
                         ActivityResultItem.obtain(list));
                 return;
@@ -3623,7 +3623,7 @@
             }
         }
 
-        r.addResultLocked(null, resultWho, requestCode, resultCode, resultData);
+        r.addResultLocked(null, resultWho, requestCode, resultCode, data);
     }
 
     /** Returns true if the task is one of the task finishing on-top of the top running task. */
@@ -3730,8 +3730,8 @@
             if (!r.finishing) {
                 if (!shouldSleepActivities()) {
                     if (DEBUG_STATES) Slog.d(TAG_STATES, "no-history finish of " + r);
-                    if (requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED,
-                            null, null, "stop-no-history", false)) {
+                    if (requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
+                            "stop-no-history", false)) {
                         // If {@link requestFinishActivityLocked} returns {@code true},
                         // {@link adjustFocusedActivityStack} would have been already called.
                         r.resumeKeyDispatchingLocked();
@@ -3787,7 +3787,7 @@
      * some reason it is being left as-is.
      */
     final boolean requestFinishActivityLocked(IBinder token, int resultCode,
-            Intent resultData, NeededUriGrants resultGrants, String reason, boolean oomAdj) {
+            Intent resultData, String reason, boolean oomAdj) {
         ActivityRecord r = isInStackLocked(token);
         if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(TAG_STATES,
                 "Finishing activity token=" + token + " r="
@@ -3797,7 +3797,7 @@
             return false;
         }
 
-        finishActivityLocked(r, resultCode, resultData, resultGrants, reason, oomAdj);
+        finishActivityLocked(r, resultCode, resultData, reason, oomAdj);
         return true;
     }
 
@@ -3809,8 +3809,8 @@
                 if (r.resultTo == self && r.requestCode == requestCode) {
                     if ((r.resultWho == null && resultWho == null) ||
                         (r.resultWho != null && r.resultWho.equals(resultWho))) {
-                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, null,
-                                "request-sub", false);
+                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub",
+                                false);
                     }
                 }
             }
@@ -3840,7 +3840,7 @@
         int activityNdx = task.mActivities.indexOf(r);
         getDisplay().mDisplayContent.prepareAppTransition(
                 TRANSIT_CRASHING_ACTIVITY_CLOSE, false /* alwaysKeepCurrent */);
-        finishActivityLocked(r, Activity.RESULT_CANCELED, null, null, reason, false);
+        finishActivityLocked(r, Activity.RESULT_CANCELED, null, reason, false);
         finishedTask = task;
         // Also terminate any activities below it that aren't yet
         // stopped, to avoid a situation where one will get
@@ -3861,7 +3861,7 @@
                 if (!r.isActivityTypeHome() || mService.mHomeProcess != r.app) {
                     Slog.w(TAG, "  Force finishing activity "
                             + r.intent.getComponent().flattenToShortString());
-                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, null, reason, false);
+                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, reason, false);
                 }
             }
         }
@@ -3877,8 +3877,8 @@
                 for (int activityNdx = tr.mActivities.size() - 1; activityNdx >= 0; --activityNdx) {
                     ActivityRecord r = tr.mActivities.get(activityNdx);
                     if (!r.finishing) {
-                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, null,
-                                "finish-voice", false);
+                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "finish-voice",
+                                false);
                         didOne = true;
                     }
                 }
@@ -3914,14 +3914,12 @@
             if (!Objects.equals(cur.taskAffinity, r.taskAffinity)) {
                 break;
             }
-            finishActivityLocked(cur, Activity.RESULT_CANCELED, null, null,
-                    "request-affinity", true);
+            finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity", true);
         }
         return true;
     }
 
-    private void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData,
-            NeededUriGrants resultGrants) {
+    private void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
         // send the result
         ActivityRecord resultTo = r.resultTo;
         if (resultTo != null) {
@@ -3934,8 +3932,9 @@
                 }
             }
             if (r.info.applicationInfo.uid > 0) {
-                mService.mUgmInternal.grantUriPermissionUncheckedFromIntent(resultGrants,
-                        resultTo.getUriPermissionsLocked());
+                mService.mUgmInternal.grantUriPermissionFromIntent(r.info.applicationInfo.uid,
+                        resultTo.packageName, resultData,
+                        resultTo.getUriPermissionsLocked(), resultTo.mUserId);
             }
             resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode, resultData);
             r.resultTo = null;
@@ -3951,10 +3950,12 @@
         r.icicle = null;
     }
 
+    /**
+     * See {@link #finishActivityLocked(ActivityRecord, int, Intent, String, boolean, boolean)}
+     */
     final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
-            NeededUriGrants resultGrants, String reason, boolean oomAdj) {
-        return finishActivityLocked(r, resultCode, resultData, resultGrants, reason, oomAdj,
-                !PAUSE_IMMEDIATELY);
+            String reason, boolean oomAdj) {
+        return finishActivityLocked(r, resultCode, resultData, reason, oomAdj, !PAUSE_IMMEDIATELY);
     }
 
     /**
@@ -3962,7 +3963,7 @@
      * list, or false if it is still in the list and will be removed later.
      */
     final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
-            NeededUriGrants resultGrants, String reason, boolean oomAdj, boolean pauseImmediately) {
+            String reason, boolean oomAdj, boolean pauseImmediately) {
         if (r.finishing) {
             Slog.w(TAG, "Duplicate finish request for " + r);
             return false;
@@ -3992,7 +3993,7 @@
 
             adjustFocusedActivityStack(r, "finishActivity");
 
-            finishActivityResultsLocked(r, resultCode, resultData, resultGrants);
+            finishActivityResultsLocked(r, resultCode, resultData);
 
             final boolean endTask = index <= 0 && !task.isClearingToReuseTask();
             final int transit = endTask ? TRANSIT_TASK_CLOSE : TRANSIT_ACTIVITY_CLOSE;
@@ -4225,9 +4226,8 @@
         return false;
     }
 
-    final boolean navigateUpToLocked(ActivityRecord srec, Intent destIntent,
-            NeededUriGrants destGrants, int resultCode, Intent resultData,
-            NeededUriGrants resultGrants) {
+    final boolean navigateUpToLocked(ActivityRecord srec, Intent destIntent, int resultCode,
+            Intent resultData) {
         final TaskRecord task = srec.getTaskRecord();
         final ArrayList<ActivityRecord> activities = task.mActivities;
         final int start = activities.indexOf(srec);
@@ -4274,8 +4274,7 @@
         final long origId = Binder.clearCallingIdentity();
         for (int i = start; i > finishTo; i--) {
             ActivityRecord r = activities.get(i);
-            requestFinishActivityLocked(r.appToken, resultCode, resultData, resultGrants,
-                    "navigate-up", true);
+            requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true);
             // Only return the supplied result for the first activity finished
             resultCode = Activity.RESULT_CANCELED;
             resultData = null;
@@ -4289,7 +4288,7 @@
                     parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
                     (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
                 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent,
-                        destGrants, srec.packageName);
+                        srec.packageName);
             } else {
                 try {
                     ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
@@ -4313,7 +4312,7 @@
                     foundParentInTask = false;
                 }
                 requestFinishActivityLocked(parent.appToken, resultCode,
-                        resultData, resultGrants, "navigate-top", true);
+                        resultData, "navigate-top", true);
             }
         }
         Binder.restoreCallingIdentity(origId);
@@ -4398,7 +4397,7 @@
     }
 
     private void removeActivityFromHistoryLocked(ActivityRecord r, String reason) {
-        finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null, null);
+        finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
         r.makeFinishingLocked();
         if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE,
                 "Removing activity " + r + " from stack callers=" + Debug.getCallers(5));
@@ -5130,8 +5129,7 @@
             for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
                 final ActivityRecord r = activities.get(activityNdx);
                 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
-                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, null,
-                            "close-sys", true);
+                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true);
                 }
             }
         }
@@ -5175,8 +5173,8 @@
                     didSomething = true;
                     Slog.i(TAG, "  Force finishing activity " + r);
                     lastTask = r.getTaskRecord();
-                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, null,
-                            "force-stop", true);
+                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop",
+                            true);
                 }
             }
         }
@@ -5230,8 +5228,8 @@
             final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities;
             int activityTop = activities.size() - 1;
             if (activityTop >= 0) {
-                finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED,
-                        null, null, "unhandled-back", true);
+                finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null,
+                        "unhandled-back", true);
             }
         }
     }
diff --git a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
index 8d2a92a..c992a69 100644
--- a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
@@ -140,7 +140,6 @@
 import com.android.server.am.ActivityManagerService;
 import com.android.server.am.EventLogTags;
 import com.android.server.am.UserState;
-import com.android.server.uri.NeededUriGrants;
 
 import java.io.FileDescriptor;
 import java.io.IOException;
@@ -404,17 +403,14 @@
         final int startFlags;
         final ActivityStack stack;
         final WindowProcessController callerApp;
-        final NeededUriGrants neededGrants;
 
-        PendingActivityLaunch(ActivityRecord r, ActivityRecord sourceRecord,
-                int startFlags, ActivityStack stack, WindowProcessController callerApp,
-                NeededUriGrants neededGrants) {
-            this.r = r;
-            this.sourceRecord = sourceRecord;
-            this.startFlags = startFlags;
-            this.stack = stack;
-            this.callerApp = callerApp;
-            this.neededGrants = neededGrants;
+        PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord,
+                int _startFlags, ActivityStack _stack, WindowProcessController app) {
+            r = _r;
+            sourceRecord = _sourceRecord;
+            startFlags = _startFlags;
+            stack = _stack;
+            callerApp = app;
         }
 
         void sendErrorResult(String message) {
@@ -878,8 +874,8 @@
                     Slog.e(TAG, "Second failure launching "
                             + r.intent.getComponent().flattenToShortString() + ", giving up", e);
                     proc.appDied();
-                    stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED,
-                            null, null, "2nd-crash", false);
+                    stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
+                            "2nd-crash", false);
                     return false;
                 }
 
@@ -1024,7 +1020,7 @@
             if (resultRecord != null) {
                 resultStack.sendActivityResultLocked(-1,
                         resultRecord, resultWho, requestCode,
-                        Activity.RESULT_CANCELED, null, null);
+                        Activity.RESULT_CANCELED, null);
             }
             final String msg;
             if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
diff --git a/services/core/java/com/android/server/wm/ActivityStartController.java b/services/core/java/com/android/server/wm/ActivityStartController.java
index 738d143..919141c 100644
--- a/services/core/java/com/android/server/wm/ActivityStartController.java
+++ b/services/core/java/com/android/server/wm/ActivityStartController.java
@@ -462,7 +462,7 @@
                     "pendingActivityLaunch");
             try {
                 starter.startResolvedActivity(pal.r, pal.sourceRecord, null, null, pal.startFlags,
-                        resume, pal.r.pendingOptions, null, pal.neededGrants);
+                        resume, pal.r.pendingOptions, null);
             } catch (Exception e) {
                 Slog.e(TAG, "Exception during pending activity launch pal=" + pal, e);
                 pal.sendErrorResult(e.getMessage());
diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java
index 9873a95..5c55c2e 100644
--- a/services/core/java/com/android/server/wm/ActivityStarter.java
+++ b/services/core/java/com/android/server/wm/ActivityStarter.java
@@ -124,7 +124,6 @@
 import com.android.server.am.EventLogTags;
 import com.android.server.am.PendingIntentRecord;
 import com.android.server.pm.InstantAppResolver;
-import com.android.server.uri.NeededUriGrants;
 import com.android.server.wm.ActivityStackSupervisor.PendingActivityLaunch;
 import com.android.server.wm.LaunchParamsController.LaunchParams;
 
@@ -547,8 +546,7 @@
      */
     int startResolvedActivity(final ActivityRecord r, ActivityRecord sourceRecord,
             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
-            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
-            NeededUriGrants neededGrants) {
+            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) {
         try {
             mSupervisor.getActivityMetricsLogger().notifyActivityLaunching(r.intent);
             mLastStartReason = "startResolvedActivity";
@@ -556,7 +554,7 @@
             mLastStartActivityRecord[0] = r;
             mLastStartActivityResult = startActivity(r, sourceRecord, voiceSession, voiceInteractor,
                     startFlags, doResume, options, inTask, mLastStartActivityRecord,
-                    false /* restrictedBgActivity */, neededGrants);
+                    false /* restrictedBgActivity */);
             mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(mLastStartActivityResult,
                     mLastStartActivityRecord[0]);
             return mLastStartActivityResult;
@@ -575,33 +573,6 @@
             boolean allowPendingRemoteAnimationRegistryLookup,
             PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
 
-        // Carefully collect grants without holding lock
-        NeededUriGrants neededGrants = null;
-        if (aInfo != null) {
-            neededGrants = mService.mUgmInternal.checkGrantUriPermissionFromIntent(
-                resolveCallingUid(mRequest.caller), intent, aInfo.applicationInfo.packageName,
-                UserHandle.getUserId(aInfo.applicationInfo.uid));
-        }
-
-        return startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
-                voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
-                callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
-                ignoreTargetSecurity, componentSpecified, outActivity, inTask, reason,
-                allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
-                allowBackgroundActivityStart, neededGrants);
-    }
-
-    private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
-            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
-            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
-            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
-            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
-            SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
-            ActivityRecord[] outActivity, TaskRecord inTask, String reason,
-            boolean allowPendingRemoteAnimationRegistryLookup,
-            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart,
-            NeededUriGrants neededGrants) {
-
         if (TextUtils.isEmpty(reason)) {
             throw new IllegalArgumentException("Need to specify a reason.");
         }
@@ -614,7 +585,7 @@
                 callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                 options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                 inTask, allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
-                allowBackgroundActivityStart, neededGrants);
+                allowBackgroundActivityStart);
 
         if (outActivity != null) {
             // mLastStartActivityRecord[0] is set in the call to startActivity above.
@@ -645,8 +616,7 @@
             SafeActivityOptions options,
             boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
             TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup,
-            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart,
-            NeededUriGrants neededGrants) {
+            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
         mSupervisor.getActivityMetricsLogger().notifyActivityLaunching(intent);
         int err = ActivityManager.START_SUCCESS;
         // Pull the optional Ephemeral Installer-only bundle out of the options early.
@@ -781,7 +751,7 @@
         if (err != START_SUCCESS) {
             if (resultRecord != null) {
                 resultStack.sendActivityResultLocked(
-                        -1, resultRecord, resultWho, requestCode, RESULT_CANCELED, null, null);
+                        -1, resultRecord, resultWho, requestCode, RESULT_CANCELED, null);
             }
             SafeActivityOptions.abort(options);
             return err;
@@ -841,16 +811,12 @@
             callingPid = mInterceptor.mCallingPid;
             callingUid = mInterceptor.mCallingUid;
             checkedOptions = mInterceptor.mActivityOptions;
-
-            // The interception target shouldn't get any permission grants
-            // intended for the original destination
-            neededGrants = null;
         }
 
         if (abort) {
             if (resultRecord != null) {
                 resultStack.sendActivityResultLocked(-1, resultRecord, resultWho, requestCode,
-                        RESULT_CANCELED, null, null);
+                        RESULT_CANCELED, null);
             }
             // We pretend to the caller that it was really started, but
             // they will just get a cancel result.
@@ -906,10 +872,6 @@
                 aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags,
                         null /*profilerInfo*/);
 
-                // The permissions review target shouldn't get any permission
-                // grants intended for the original destination
-                neededGrants = null;
-
                 if (DEBUG_PERMISSIONS_REVIEW) {
                     final ActivityStack focusedStack =
                             mRootActivityContainer.getTopDisplayFocusedStack();
@@ -932,10 +894,6 @@
             callingPid = realCallingPid;
 
             aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, null /*profilerInfo*/);
-
-            // The ephemeral installer shouldn't get any permission grants
-            // intended for the original destination
-            neededGrants = null;
         }
 
         ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
@@ -962,7 +920,7 @@
                     realCallingPid, realCallingUid, "Activity start")) {
                 if (!(restrictedBgActivity && handleBackgroundActivityAbort(r))) {
                     mController.addPendingActivityLaunch(new PendingActivityLaunch(r,
-                            sourceRecord, startFlags, stack, callerApp, neededGrants));
+                            sourceRecord, startFlags, stack, callerApp));
                 }
                 ActivityOptions.abort(checkedOptions);
                 return ActivityManager.START_SWITCHES_CANCELED;
@@ -973,8 +931,7 @@
         mController.doPendingActivityLaunches(false);
 
         final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
-                true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity,
-                neededGrants);
+                true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
         mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
         return res;
     }
@@ -1254,15 +1211,9 @@
                 }
             }
         }
-
         // Collect information about the target of the Intent.
         ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
 
-        // Carefully collect grants without holding lock
-        NeededUriGrants neededGrants = mService.mUgmInternal.checkGrantUriPermissionFromIntent(
-                resolveCallingUid(mRequest.caller), intent, aInfo.applicationInfo.packageName,
-                UserHandle.getUserId(aInfo.applicationInfo.uid));
-
         synchronized (mService.mGlobalLock) {
             final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
             stack.mConfigWillChange = globalConfig != null
@@ -1339,7 +1290,7 @@
                     callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
                     ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
                     allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
-                    allowBackgroundActivityStart, neededGrants);
+                    allowBackgroundActivityStart);
 
             Binder.restoreCallingIdentity(origId);
 
@@ -1434,16 +1385,14 @@
 
     private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
-            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
-            ActivityRecord[] outActivity, boolean restrictedBgActivity,
-            NeededUriGrants neededGrants) {
+                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
+                ActivityRecord[] outActivity, boolean restrictedBgActivity) {
         int result = START_CANCELED;
         final ActivityStack startedActivityStack;
         try {
             mService.mWindowManager.deferSurfaceLayout();
             result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
-                    startFlags, doResume, options, inTask, outActivity, restrictedBgActivity,
-                    neededGrants);
+                    startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
         } finally {
             final ActivityStack currentStack = r.getActivityStack();
             startedActivityStack = currentStack != null ? currentStack : mTargetStack;
@@ -1468,8 +1417,7 @@
                 final ActivityStack stack = mStartActivity.getActivityStack();
                 if (stack != null) {
                     stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
-                            null /* resultData */, null /* resultGrants */,
-                            "startActivity", true /* oomAdj */);
+                            null /* intentResultData */, "startActivity", true /* oomAdj */);
                 }
             }
             mService.mWindowManager.continueSurfaceLayout();
@@ -1497,7 +1445,7 @@
         if (resultRecord != null) {
             ActivityStack resultStack = resultRecord.getActivityStack();
             resultStack.sendActivityResultLocked(-1, resultRecord, resultWho, requestCode,
-                    RESULT_CANCELED, null, null);
+                    RESULT_CANCELED, null);
         }
         // We pretend to the caller that it was really started to make it backward compatible, but
         // they will just get a cancel result.
@@ -1509,8 +1457,7 @@
     private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
             int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
-            ActivityRecord[] outActivity, boolean restrictedBgActivity,
-            NeededUriGrants neededGrants) {
+            ActivityRecord[] outActivity, boolean restrictedBgActivity) {
         setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
                 voiceInteractor, restrictedBgActivity);
 
@@ -1660,7 +1607,7 @@
             if (sourceStack != null) {
                 sourceStack.sendActivityResultLocked(-1 /* callingUid */, mStartActivity.resultTo,
                         mStartActivity.resultWho, mStartActivity.requestCode, RESULT_CANCELED,
-                        null /* resultData */, null /* resultGrants */);
+                        null /* data */);
             }
             ActivityOptions.abort(mOptions);
             return START_CLASS_NOT_FOUND;
@@ -1727,8 +1674,8 @@
             return result;
         }
 
-        mService.mUgmInternal.grantUriPermissionUncheckedFromIntent(neededGrants,
-                mStartActivity.getUriPermissionsLocked());
+        mService.mUgmInternal.grantUriPermissionFromIntent(mCallingUid, mStartActivity.packageName,
+                mIntent, mStartActivity.getUriPermissionsLocked(), mStartActivity.mUserId);
         mService.getPackageManagerInternalLocked().grantEphemeralAccess(
                 mStartActivity.mUserId, mIntent, UserHandle.getAppId(mStartActivity.appInfo.uid),
                 UserHandle.getAppId(mCallingUid));
@@ -1964,7 +1911,7 @@
             Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
             sourceStack.sendActivityResultLocked(-1 /* callingUid */, mStartActivity.resultTo,
                     mStartActivity.resultWho, mStartActivity.requestCode, RESULT_CANCELED,
-                    null /* resultData */, null /* resultGrants */);
+                    null /* data */);
             mStartActivity.resultTo = null;
         }
     }
@@ -2393,13 +2340,8 @@
         }
 
         ActivityStack.logStartActivity(AM_NEW_INTENT, activity, activity.getTaskRecord());
-
-        Intent intent = mStartActivity.intent;
-        NeededUriGrants intentGrants = mService.mUgmInternal.checkGrantUriPermissionFromIntent(
-                mCallingUid, intent, activity.packageName, activity.mUserId);
-        activity.deliverNewIntentLocked(mCallingUid, intent, intentGrants,
+        activity.deliverNewIntentLocked(mCallingUid, mStartActivity.intent,
                 mStartActivity.launchedFromPackage);
-
         mIntentDelivered = true;
     }
 
@@ -2778,18 +2720,6 @@
         }
     }
 
-    private int resolveCallingUid(IApplicationThread caller) {
-        if (caller != null) {
-            synchronized (mService.mGlobalLock) {
-                final WindowProcessController callerApp = mService.getProcessController(caller);
-                if (callerApp != null) {
-                    return callerApp.mInfo.uid;
-                }
-            }
-        }
-        return -1;
-    }
-
     private boolean isLaunchModeOneOf(int mode1, int mode2) {
         return mode1 == mLaunchMode || mode2 == mLaunchMode;
     }
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
index 1b9b6b1..8ba7ca1 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@@ -265,7 +265,6 @@
 import com.android.server.firewall.IntentFirewall;
 import com.android.server.pm.UserManagerService;
 import com.android.server.policy.PermissionPolicyInternal;
-import com.android.server.uri.NeededUriGrants;
 import com.android.server.uri.UriGrantsManagerInternal;
 import com.android.server.vr.VrManagerInternal;
 
@@ -1547,19 +1546,11 @@
             throw new IllegalArgumentException("File descriptors passed in Intent");
         }
 
-        final ActivityRecord r;
         synchronized (mGlobalLock) {
-            r = ActivityRecord.isInStackLocked(token);
+            ActivityRecord r = ActivityRecord.isInStackLocked(token);
             if (r == null) {
                 return true;
             }
-        }
-
-        // Carefully collect grants without holding lock
-        final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
-                Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
-
-        synchronized (mGlobalLock) {
             // Keep track of the root activity of the task before we finish it
             final TaskRecord tr = r.getTaskRecord();
             ActivityRecord rootR = tr.getRootActivity();
@@ -1621,7 +1612,7 @@
                     r.mRelaunchReason = RELAUNCH_REASON_NONE;
                 } else {
                     res = tr.getStack().requestFinishActivityLocked(token, resultCode,
-                            resultData, resultGrants, "app-request", true);
+                            resultData, "app-request", true);
                     if (!res) {
                         Slog.i(TAG, "Failed to finish by app-request");
                     }
@@ -2147,23 +2138,14 @@
     @Override
     public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
             Intent resultData) {
-        final ActivityRecord r;
+
         synchronized (mGlobalLock) {
-            r = ActivityRecord.isInStackLocked(token);
-            if (r == null) {
-                return false;
+            final ActivityRecord r = ActivityRecord.forTokenLocked(token);
+            if (r != null) {
+                return r.getActivityStack().navigateUpToLocked(
+                        r, destIntent, resultCode, resultData);
             }
-        }
-
-        // Carefully collect grants without holding lock
-        final NeededUriGrants destGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
-                Binder.getCallingUid(), destIntent, r.packageName, r.mUserId);
-        final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
-                Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
-
-        synchronized (mGlobalLock) {
-            return r.getActivityStack().navigateUpToLocked(
-                    r, destIntent, destGrants, resultCode, resultData, resultGrants);
+            return false;
         }
     }
 
@@ -6617,23 +6599,14 @@
 
         @Override
         public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
-                int requestCode, int resultCode, Intent resultData) {
-            final ActivityRecord r;
+                int requestCode, int resultCode, Intent data) {
             synchronized (mGlobalLock) {
-                r = ActivityRecord.isInStackLocked(activityToken);
-                if (r == null || r.getActivityStack() == null) {
-                    return;
+                final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
+                if (r != null && r.getActivityStack() != null) {
+                    r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
+                            requestCode, resultCode, data);
                 }
             }
-
-            // Carefully collect grants without holding lock
-            final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
-                    Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
-
-            synchronized (mGlobalLock) {
-                r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
-                        requestCode, resultCode, resultData, resultGrants);
-            }
         }
 
         @Override
diff --git a/services/core/java/com/android/server/wm/BoundsAnimationController.java b/services/core/java/com/android/server/wm/BoundsAnimationController.java
index b5e7067..5dc88b3 100644
--- a/services/core/java/com/android/server/wm/BoundsAnimationController.java
+++ b/services/core/java/com/android/server/wm/BoundsAnimationController.java
@@ -410,7 +410,7 @@
         @VisibleForTesting
         boolean animatingToLargerSize() {
             // TODO: Fix this check for aspect ratio changes
-            return (mFrom.width() * mFrom.height() <= mTo.width() * mTo.height());
+            return (mFrom.width() * mFrom.height() < mTo.width() * mTo.height());
         }
 
         @Override
@@ -453,16 +453,10 @@
             boolean moveFromFullscreen, boolean moveToFullscreen,
             @AnimationType int animationType) {
         final BoundsAnimator existing = mRunningAnimations.get(target);
-        // animateBoundsImpl gets called twice for each animation. The second time we get the final
-        // to rect that respects the shelf, which is when we want to resize. Our signal for fade in
-        // comes in from how to enter into pip, but we also need to use the to and from rect to
-        // decide which animation we want to run finally.
-        boolean shouldResize = false;
-        if (isRunningFadeInAnimation(target)) {
-            shouldResize = true;
-            if (from.contains(to)) {
-                animationType = FADE_IN;
-            }
+
+        if (isRunningFadeInAnimation(target) && from.width() == to.width()
+                && from.height() == to.height()) {
+            animationType = FADE_IN;
         }
         final boolean replacing = existing != null;
         @SchedulePipModeChangedState int prevSchedulePipModeChangedState =
@@ -523,9 +517,10 @@
             // Since we are replacing, we skip both animation start and end callbacks
             existing.cancel();
         }
-        if (shouldResize) {
+        if (animationType == FADE_IN) {
             target.setPinnedStackSize(to, null);
         }
+
         final BoundsAnimator animator = new BoundsAnimator(target, animationType, from, to,
                 schedulePipModeChangedState, prevSchedulePipModeChangedState,
                 moveFromFullscreen, moveToFullscreen, frozenTask);
diff --git a/services/core/java/com/android/server/wm/TaskRecord.java b/services/core/java/com/android/server/wm/TaskRecord.java
index 4a0bf02a..298b302 100644
--- a/services/core/java/com/android/server/wm/TaskRecord.java
+++ b/services/core/java/com/android/server/wm/TaskRecord.java
@@ -1442,7 +1442,7 @@
                 mActivities.remove(activityNdx);
                 --activityNdx;
                 --numActivities;
-            } else if (mStack.finishActivityLocked(r, Activity.RESULT_CANCELED, null, null,
+            } else if (mStack.finishActivityLocked(r, Activity.RESULT_CANCELED, null,
                     reason, false, pauseImmediately)) {
                 --activityNdx;
                 --numActivities;
@@ -1497,8 +1497,8 @@
                     if (opts != null) {
                         ret.updateOptionsLocked(opts);
                     }
-                    if (mStack != null && mStack.finishActivityLocked(r, Activity.RESULT_CANCELED,
-                            null, null, "clear-task-stack", false)) {
+                    if (mStack != null && mStack.finishActivityLocked(
+                            r, Activity.RESULT_CANCELED, null, "clear-task-stack", false)) {
                         --activityNdx;
                         --numActivities;
                     }
@@ -1512,8 +1512,8 @@
                         && !ActivityStarter.isDocumentLaunchesIntoExisting(launchFlags)) {
                     if (!ret.finishing) {
                         if (mStack != null) {
-                            mStack.finishActivityLocked(ret, Activity.RESULT_CANCELED,
-                                    null, null, "clear-task-top", false);
+                            mStack.finishActivityLocked(
+                                    ret, Activity.RESULT_CANCELED, null, "clear-task-top", false);
                         }
                         return null;
                     }
diff --git a/services/core/java/com/android/server/wm/WindowProcessController.java b/services/core/java/com/android/server/wm/WindowProcessController.java
index 55b2886..bc5e328 100644
--- a/services/core/java/com/android/server/wm/WindowProcessController.java
+++ b/services/core/java/com/android/server/wm/WindowProcessController.java
@@ -629,7 +629,7 @@
             final ActivityRecord r = activities.get(i);
             if (!r.finishing && r.isInStackLocked()) {
                 r.getActivityStack().finishActivityLocked(r, Activity.RESULT_CANCELED,
-                        null, null, "finish-heavy", true);
+                        null, "finish-heavy", true);
             }
         }
     }
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index ac7c16e..ba59cdb 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -6654,7 +6654,7 @@
      */
     @Override
     public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
-        if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
+        if (!mLockPatternUtils.hasSecureLockScreen()) {
             return;
         }
         enforceFullCrossUsersPermission(userHandle);
diff --git a/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java
index bb9f49e..184dc3d 100644
--- a/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java
@@ -86,6 +86,7 @@
         UserState mUserState = new UserState(0,
                 mContext,
                 mLock,
+                mMockHandler,
                 componentName);
         mUserState.mService = new MockIAttentionService();
         mSpyUserState = spy(mUserState);
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
index 4c0b582..757267e5 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
@@ -940,8 +940,7 @@
         homeStask.removeTask(homeTask, "testAdjustFocusedStack", REMOVE_TASK_MODE_DESTROYING);
 
         // Finish the only activity.
-        mStack.finishActivityLocked(topActivity, 0 /* resultCode */,
-                null /* resultData */, null /* resultGrants */,
+        mStack.finishActivityLocked(topActivity, 0 /* resultCode */, null /* resultData */,
                 "testAdjustFocusedStack", false /* oomAdj */);
         // Although home stack is empty, it should still be the focused stack.
         assertEquals(homeStask, mDefaultDisplay.getFocusedStack());
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStartControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStartControllerTests.java
index 2d12006..a7bbe6e 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStartControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStartControllerTests.java
@@ -82,12 +82,12 @@
         wpc.setThread(mock(IApplicationThread.class));
 
         mController.addPendingActivityLaunch(
-                new PendingActivityLaunch(activity, source, startFlags, stack, wpc, null));
+                new PendingActivityLaunch(activity, source, startFlags, stack, wpc));
         final boolean resume = random.nextBoolean();
         mController.doPendingActivityLaunches(resume);
 
         verify(mStarter, times(1)).startResolvedActivity(eq(activity), eq(source), eq(null),
-                eq(null), eq(startFlags), eq(resume), eq(null), eq(null), eq(null));
+                eq(null), eq(startFlags), eq(resume), eq(null), eq(null));
     }