Merge "[DO NOT MERGE] Compatibilize with git_master" into udc-dev
diff --git a/boot/OWNERS b/boot/OWNERS
index 0e258d0..3fe1a41 100644
--- a/boot/OWNERS
+++ b/boot/OWNERS
@@ -2,5 +2,5 @@
 file:platform/build/soong:/OWNERS
 
 # art-team@ manages the boot image profiles for frameworks
-per-file boot-* = calin@google.com, yawanng@google.com, ngeoffray@google.com
-per-file preloaded-classes* = calin@google.com, yawanng@google.com, ngeoffray@google.com
+per-file boot-* = islamelbanna@google.com, ngeoffray@google.com, vmarko@google.com
+per-file preloaded-classes* = islamelbanna@google.com, ngeoffray@google.com, vmarko@google.com
diff --git a/config/OWNERS b/config/OWNERS
index 74813bc..6a5df76 100644
--- a/config/OWNERS
+++ b/config/OWNERS
@@ -1,8 +1,8 @@
 include /ZYGOTE_OWNERS
 
 # art-team@ manages the boot image profiles
-per-file boot-* = ngeoffray@google.com, vmarko@google.com
-per-file dirty-image-objects = ngeoffray@google.com, vmarko@google.com
-per-file generate-preloaded-classes.sh = ngeoffray@google.com, vmarko@google.com
-per-file preloaded-classes* = ngeoffray@google.com, vmarko@google.com
+per-file boot-* = islamelbanna@google.com, ngeoffray@google.com, vmarko@google.com
+per-file dirty-image-objects = ishcheikin@google.com, ngeoffray@google.com, vmarko@google.com
+per-file generate-preloaded-classes.sh = islamelbanna@google.com, ngeoffray@google.com, vmarko@google.com
+per-file preloaded-classes* = islamelbanna@google.com, ngeoffray@google.com, vmarko@google.com
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java
index be1f800b..b18e21c 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java
@@ -276,15 +276,14 @@
             Rect pipBounds) {
         ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
                 "%s: resizePipMenu: %s", TAG, pipBounds.toShortString());
+
         if (pipBounds.isEmpty()) {
             return;
         }
-
-        if (!isMenuReadyToMove()) {
+        if (!isMenuAttached()) {
             return;
         }
 
-
         final SurfaceControl frontSurface = getSurfaceControl(mPipMenuView);
         final SurfaceControl backSurface = getSurfaceControl(mPipBackgroundView);
         final Rect menuBounds = calculateMenuSurfaceBounds(pipBounds);
@@ -321,7 +320,7 @@
             }
             return;
         }
-        if (!isMenuReadyToMove()) {
+        if (!isMenuAttached()) {
             return;
         }
 
@@ -344,12 +343,12 @@
         syncGroup.markSyncReady();
     }
 
-    private boolean isMenuReadyToMove() {
+    private boolean isMenuAttached() {
         final boolean ready = mPipMenuView != null && mPipMenuView.getViewRootImpl() != null
                 && mPipBackgroundView != null && mPipBackgroundView.getViewRootImpl() != null;
         if (!ready) {
             ProtoLog.v(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
-                    "%s: Not going to move PiP, either menu or its parent is not created.", TAG);
+                    "%s: the menu surfaces are not attached.", TAG);
         }
         return ready;
     }
@@ -368,6 +367,9 @@
 
     @Override
     public void updateMenuBounds(Rect pipBounds) {
+        if (!isMenuAttached()) {
+            return;
+        }
         final Rect menuBounds = calculateMenuSurfaceBounds(pipBounds);
         ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
                 "%s: updateMenuBounds: %s", TAG, menuBounds.toShortString());
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/OpenActivityFromBubbleOnLocksreenTest.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/OpenActivityFromBubbleOnLocksreenTest.kt
index 416315e..18a3aa7 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/OpenActivityFromBubbleOnLocksreenTest.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/OpenActivityFromBubbleOnLocksreenTest.kt
@@ -18,6 +18,7 @@
 
 import android.platform.test.annotations.FlakyTest
 import android.platform.test.annotations.Postsubmit
+import android.tools.common.datatypes.component.ComponentNameMatcher
 import android.tools.device.flicker.junit.FlickerParametersRunnerFactory
 import android.tools.device.flicker.legacy.FlickerBuilder
 import android.tools.device.flicker.legacy.FlickerTest
@@ -29,6 +30,7 @@
 import com.android.server.wm.flicker.navBarLayerIsVisibleAtEnd
 import com.android.server.wm.flicker.navBarLayerPositionAtEnd
 import org.junit.Assume
+import org.junit.Ignore
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.junit.runners.Parameterized
@@ -137,4 +139,23 @@
         Assume.assumeTrue(flicker.scenario.isGesturalNavigation)
         super.navBarWindowIsAlwaysVisible()
     }
+
+    /** {@inheritDoc} */
+    @Test
+    @Ignore("Not applicable to this CUJ. Taskbar is not shown on lock screen")
+    override fun taskBarLayerIsVisibleAtStartAndEnd() {}
+
+    @Test
+    @Ignore("Not applicable to this CUJ. Taskbar is not shown on lock screen")
+    override fun taskBarWindowIsAlwaysVisible() {}
+
+    /**
+     * Checks that the [ComponentNameMatcher.TASK_BAR] is visible at the end of the transition
+     */
+    @Postsubmit
+    @Test
+    fun taskBarLayerIsVisibleAtEnd() {
+        Assume.assumeTrue(flicker.scenario.isTablet)
+        flicker.assertLayersEnd { this.isVisible(ComponentNameMatcher.TASK_BAR) }
+    }
 }
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index d43687b..fc581ee 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -7545,6 +7545,7 @@
         DEVICE_MEDIA_UNMUTED_ON_PLUG_SET.add(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
         DEVICE_MEDIA_UNMUTED_ON_PLUG_SET.add(AudioSystem.DEVICE_OUT_LINE);
         DEVICE_MEDIA_UNMUTED_ON_PLUG_SET.addAll(AudioSystem.DEVICE_OUT_ALL_A2DP_SET);
+        DEVICE_MEDIA_UNMUTED_ON_PLUG_SET.addAll(AudioSystem.DEVICE_OUT_ALL_BLE_SET);
         DEVICE_MEDIA_UNMUTED_ON_PLUG_SET.addAll(AudioSystem.DEVICE_OUT_ALL_USB_SET);
         DEVICE_MEDIA_UNMUTED_ON_PLUG_SET.add(AudioSystem.DEVICE_OUT_HDMI);
     }
diff --git a/services/core/java/com/android/server/display/DisplayPowerController2.java b/services/core/java/com/android/server/display/DisplayPowerController2.java
index 5306ac0..8ce4b66 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController2.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController2.java
@@ -1206,14 +1206,15 @@
         // actual state instead of the desired one.
         animateScreenStateChange(state, mDisplayStateController.shouldPerformScreenOffTransition());
         state = mPowerState.getScreenState();
+        final boolean userSetBrightnessChanged = mDisplayBrightnessController
+                .updateUserSetScreenBrightness();
 
         DisplayBrightnessState displayBrightnessState = mDisplayBrightnessController
                 .updateBrightness(mPowerRequest, state);
         float brightnessState = displayBrightnessState.getBrightness();
         float rawBrightnessState = displayBrightnessState.getBrightness();
         mBrightnessReasonTemp.set(displayBrightnessState.getBrightnessReason());
-        final boolean userSetBrightnessChanged = mDisplayBrightnessController
-                .updateUserSetScreenBrightness();
+
         // Take note if the short term model was already active before applying the current
         // request changes.
         final boolean wasShortTermModelActive =
diff --git a/services/core/java/com/android/server/wm/LetterboxUiController.java b/services/core/java/com/android/server/wm/LetterboxUiController.java
index a1e6cd7..b0c384d 100644
--- a/services/core/java/com/android/server/wm/LetterboxUiController.java
+++ b/services/core/java/com/android/server/wm/LetterboxUiController.java
@@ -126,7 +126,8 @@
 final class LetterboxUiController {
 
     private static final Predicate<ActivityRecord> FIRST_OPAQUE_NOT_FINISHING_ACTIVITY_PREDICATE =
-            activityRecord -> activityRecord.fillsParent() && !activityRecord.isFinishing();
+            activityRecord -> activityRecord.fillsParent() && !activityRecord.isFinishing()
+                    && activityRecord.nowVisible;
 
     private static final String TAG = TAG_WITH_CLASS_NAME ? "LetterboxUiController" : TAG_ATM;
 
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyEngine.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyEngine.java
index 7eeb51c..d4f4b72 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyEngine.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyEngine.java
@@ -23,7 +23,6 @@
 import static android.app.admin.PolicyUpdateResult.RESULT_POLICY_CLEARED;
 import static android.app.admin.PolicyUpdateResult.RESULT_POLICY_SET;
 import static android.content.pm.UserProperties.INHERIT_DEVICE_POLICY_FROM_PARENT;
-import static android.provider.DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER;
 
 import android.Manifest;
 import android.annotation.NonNull;
@@ -47,7 +46,6 @@
 import android.os.Environment;
 import android.os.UserHandle;
 import android.os.UserManager;
-import android.provider.DeviceConfig;
 import android.telephony.TelephonyManager;
 import android.util.AtomicFile;
 import android.util.Log;
@@ -86,9 +84,6 @@
             DevicePolicyIdentifiers.getIdentifierForUserRestriction(
                     UserManager.DISALLOW_CELLULAR_2G);
 
-    private static final String ENABLE_COEXISTENCE_FLAG = "enable_coexistence";
-    private static final boolean DEFAULT_ENABLE_COEXISTENCE_FLAG = true;
-
     private final Context mContext;
     private final UserManager mUserManager;
 
@@ -771,28 +766,31 @@
         Intent intent = new Intent(PolicyUpdateReceiver.ACTION_DEVICE_POLICY_SET_RESULT);
         intent.setPackage(admin.getPackageName());
 
-        List<ResolveInfo> receivers = mContext.getPackageManager().queryBroadcastReceiversAsUser(
-                intent,
-                PackageManager.ResolveInfoFlags.of(PackageManager.GET_RECEIVERS),
-                admin.getUserId());
-        if (receivers.isEmpty()) {
-            Log.i(TAG, "Couldn't find any receivers that handle ACTION_DEVICE_POLICY_SET_RESULT"
-                    + "in package " + admin.getPackageName());
-            return;
-        }
+        Binder.withCleanCallingIdentity(() -> {
+            List<ResolveInfo> receivers =
+                    mContext.getPackageManager().queryBroadcastReceiversAsUser(
+                            intent,
+                            PackageManager.ResolveInfoFlags.of(PackageManager.GET_RECEIVERS),
+                            admin.getUserId());
+            if (receivers.isEmpty()) {
+                Log.i(TAG, "Couldn't find any receivers that handle ACTION_DEVICE_POLICY_SET_RESULT"
+                        + "in package " + admin.getPackageName());
+                return;
+            }
 
-        Bundle extras = new Bundle();
-        policyDefinition.getPolicyKey().writeToBundle(extras);
-        extras.putInt(
-                EXTRA_POLICY_TARGET_USER_ID,
-                getTargetUser(admin.getUserId(), userId));
-        extras.putInt(
-                EXTRA_POLICY_UPDATE_RESULT_KEY,
-                result);
+            Bundle extras = new Bundle();
+            policyDefinition.getPolicyKey().writeToBundle(extras);
+            extras.putInt(
+                    EXTRA_POLICY_TARGET_USER_ID,
+                    getTargetUser(admin.getUserId(), userId));
+            extras.putInt(
+                    EXTRA_POLICY_UPDATE_RESULT_KEY,
+                    result);
 
-        intent.putExtras(extras);
+            intent.putExtras(extras);
 
-        maybeSendIntentToAdminReceivers(intent, UserHandle.of(admin.getUserId()), receivers);
+            maybeSendIntentToAdminReceivers(intent, UserHandle.of(admin.getUserId()), receivers);
+        });
     }
 
     // TODO(b/261430877): Finalise the decision on which admins to send the updates to.
@@ -821,27 +819,30 @@
         Intent intent = new Intent(PolicyUpdateReceiver.ACTION_DEVICE_POLICY_CHANGED);
         intent.setPackage(admin.getPackageName());
 
-        List<ResolveInfo> receivers = mContext.getPackageManager().queryBroadcastReceiversAsUser(
-                intent,
-                PackageManager.ResolveInfoFlags.of(PackageManager.GET_RECEIVERS),
-                admin.getUserId());
-        if (receivers.isEmpty()) {
-            Log.i(TAG, "Couldn't find any receivers that handle ACTION_DEVICE_POLICY_CHANGED"
-                    + "in package " + admin.getPackageName());
-            return;
-        }
+        Binder.withCleanCallingIdentity(() -> {
+            List<ResolveInfo> receivers =
+                    mContext.getPackageManager().queryBroadcastReceiversAsUser(
+                            intent,
+                            PackageManager.ResolveInfoFlags.of(PackageManager.GET_RECEIVERS),
+                            admin.getUserId());
+            if (receivers.isEmpty()) {
+                Log.i(TAG, "Couldn't find any receivers that handle ACTION_DEVICE_POLICY_CHANGED"
+                        + "in package " + admin.getPackageName());
+                return;
+            }
 
-        Bundle extras = new Bundle();
-        policyDefinition.getPolicyKey().writeToBundle(extras);
-        extras.putInt(
-                EXTRA_POLICY_TARGET_USER_ID,
-                getTargetUser(admin.getUserId(), userId));
-        extras.putInt(EXTRA_POLICY_UPDATE_RESULT_KEY, reason);
-        intent.putExtras(extras);
-        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
+            Bundle extras = new Bundle();
+            policyDefinition.getPolicyKey().writeToBundle(extras);
+            extras.putInt(
+                    EXTRA_POLICY_TARGET_USER_ID,
+                    getTargetUser(admin.getUserId(), userId));
+            extras.putInt(EXTRA_POLICY_UPDATE_RESULT_KEY, reason);
+            intent.putExtras(extras);
+            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
 
-        maybeSendIntentToAdminReceivers(
-                intent, UserHandle.of(admin.getUserId()), receivers);
+            maybeSendIntentToAdminReceivers(
+                    intent, UserHandle.of(admin.getUserId()), receivers);
+        });
     }
 
     private void maybeSendIntentToAdminReceivers(
@@ -1146,38 +1147,6 @@
         return mEnforcingAdmins.size() > 0;
     }
 
-    /**
-     * Returns {@code true} if the coexistence flag is enabled or:
-     * <ul>
-     * <li>If the provided package is an admin with existing policies
-     * <li>A new admin and no other admin have policies set
-     * <li>More than one admin have policies set
-     */
-    boolean canAdminAddPolicies(String packageName, int userId) {
-        if (isCoexistenceFlagEnabled()) {
-            return true;
-        }
-
-        if (mEnforcingAdmins.contains(userId)
-                && mEnforcingAdmins.get(userId).stream().anyMatch(admin ->
-                admin.getPackageName().equals(packageName))) {
-            return true;
-        }
-
-        int numOfEnforcingAdmins = 0;
-        for (int i = 0; i < mEnforcingAdmins.size(); i++) {
-            numOfEnforcingAdmins += mEnforcingAdmins.get(i).size();
-        }
-        return numOfEnforcingAdmins == 0 || numOfEnforcingAdmins > 1;
-    }
-
-    private boolean isCoexistenceFlagEnabled() {
-        return DeviceConfig.getBoolean(
-                NAMESPACE_DEVICE_POLICY_MANAGER,
-                ENABLE_COEXISTENCE_FLAG,
-                DEFAULT_ENABLE_COEXISTENCE_FLAG);
-    }
-
     private <V> boolean checkFor2gFailure(@NonNull PolicyDefinition<V> policyDefinition,
             @NonNull EnforcingAdmin enforcingAdmin) {
         if (!policyDefinition.getPolicyKey().getIdentifier().equals(
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index 96cc36bb..7388c76 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -836,18 +836,13 @@
                     + "management app's authentication policy";
     private static final String NOT_SYSTEM_CALLER_MSG = "Only the system can %s";
 
-    // ENABLE_DEVICE_POLICY_ENGINE_FLAG must be enabled before this could be enabled.
     private static final String PERMISSION_BASED_ACCESS_EXPERIMENT_FLAG =
             "enable_permission_based_access";
     private static final boolean DEFAULT_VALUE_PERMISSION_BASED_ACCESS_FLAG = false;
 
-    // This must be enabled before PERMISSION_BASED_ACCESS_EXPERIMENT_FLAG is enabled, the reason
-    // we're not just relying on PERMISSION_BASED_ACCESS_EXPERIMENT_FLAG to enable the policy engine
-    // is that we might want to enable it before the permission changes are ready if we want to test
-    // it on DPCs.
-    // Once this is enabled, it can no longer be disabled in production
-    private static final String ENABLE_DEVICE_POLICY_ENGINE_FLAG = "enable_device_policy_engine";
-    private static final boolean DEFAULT_ENABLE_DEVICE_POLICY_ENGINE_FLAG = false;
+    private static final String ENABLE_DEVICE_POLICY_ENGINE_FOR_FINANCE_FLAG =
+            "enable_device_policy_engine";
+    private static final boolean DEFAULT_ENABLE_DEVICE_POLICY_ENGINE_FOR_FINANCE_FLAG = false;
 
     // TODO(b/265683382) remove the flag after rollout.
     private static final String KEEP_PROFILES_RUNNING_FLAG = "enable_keep_profiles_running";
@@ -1414,10 +1409,7 @@
                     && (owner.getPackageName().equals(packageName))) {
                 startOwnerService(userHandle, "package-broadcast");
             }
-            if (shouldMigrateToDevicePolicyEngine()) {
-                migratePoliciesToDevicePolicyEngine();
-            }
-            if (isDevicePolicyEngineEnabled()) {
+            if (isPermissionCheckFlagEnabled()) {
                 mDevicePolicyEngine.handlePackageChanged(packageName, userHandle);
             }
             // Persist updates if the removed package was an admin or delegate.
@@ -2121,7 +2113,7 @@
         mUserManagerInternal.addUserLifecycleListener(new UserLifecycleListener());
 
         mDeviceManagementResourcesProvider.load();
-        if (isDevicePolicyEngineEnabled()) {
+        if (isPermissionCheckFlagEnabled()) {
             mDevicePolicyEngine.load();
         }
 
@@ -2315,7 +2307,6 @@
      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
      */
     private CallerIdentity getCallerIdentity(@Nullable String callerPackage) {
-
         return getCallerIdentity(null, callerPackage);
     }
 
@@ -2618,7 +2609,7 @@
             ActiveAdmin profileOwner, boolean newOwner) {
         if (newOwner || mInjector.settingsSecureGetIntForUser(
                 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
-            if (isDevicePolicyEngineEnabled()) {
+            if (isPermissionCheckFlagEnabled()) {
                 mDevicePolicyEngine.setLocalPolicy(
                         PolicyDefinition.getPolicyDefinitionForUserRestriction(
                                 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
@@ -2646,7 +2637,7 @@
         if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
             return; // The same set of default restrictions has been already applied.
         }
-        if (isDevicePolicyEngineEnabled()) {
+        if (isPermissionCheckFlagEnabled()) {
             for (String restriction : defaultRestrictions) {
                 mDevicePolicyEngine.setLocalPolicy(
                         PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction),
@@ -3562,7 +3553,7 @@
         }
 
         startOwnerService(userId, "start-user");
-        if (isDevicePolicyEngineEnabled()) {
+        if (isPermissionCheckFlagEnabled()) {
             mDevicePolicyEngine.handleStartUser(userId);
         }
     }
@@ -3589,7 +3580,7 @@
 
     void handleUnlockUser(int userId) {
         startOwnerService(userId, "unlock-user");
-        if (isDevicePolicyEngineEnabled()) {
+        if (isPermissionCheckFlagEnabled()) {
             mDevicePolicyEngine.handleUnlockUser(userId);
         }
     }
@@ -3601,7 +3592,7 @@
     void handleStopUser(int userId) {
         updateNetworkPreferenceForUser(userId, List.of(PreferentialNetworkServiceConfig.DEFAULT));
         mDeviceAdminServiceController.stopServicesForUser(userId, /* actionForLog= */ "stop-user");
-        if (isDevicePolicyEngineEnabled()) {
+        if (isPermissionCheckFlagEnabled()) {
             mDevicePolicyEngine.handleStopUser(userId);
         }
     }
@@ -3727,11 +3718,6 @@
         synchronized (getLockObject()) {
             checkActiveAdminPrecondition(adminReceiver, info, policy);
             mInjector.binderWithCleanCallingIdentity(() -> {
-                if (!canAddActiveAdminIfPolicyEngineEnabled(
-                        adminReceiver.getPackageName(), userHandle)) {
-                    throw new IllegalStateException("Can't add non-coexistable admin.");
-                }
-
                 final ActiveAdmin existingAdmin
                         = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
                 if (!refreshing && existingAdmin != null) {
@@ -5305,11 +5291,8 @@
         Preconditions.checkArgument(allowedModes.contains(passwordComplexity),
                 "Provided complexity is not one of the allowed values.");
 
-        CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
-            caller = getCallerIdentity(callerPackageName);
-        } else {
-            caller = getCallerIdentity();
+        CallerIdentity caller = getCallerIdentity(callerPackageName);
+        if (!isPermissionCheckFlagEnabled()) {
             Preconditions.checkCallAuthorization(
                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
             Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller));
@@ -7486,7 +7469,7 @@
             return;
         }
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(callerPackageName);
         }  else {
             caller = getCallerIdentity();
@@ -7495,7 +7478,7 @@
 
         boolean calledByProfileOwnerOnOrgOwnedDevice =
                 isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId());
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     /*admin=*/ null,
                     MANAGE_DEVICE_POLICY_WIPE_DATA,
@@ -8852,7 +8835,7 @@
             caller = getCallerIdentity(who);
         }
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPermissionCheckFlagEnabled()) {
             // The effect of this policy is device-wide.
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     who,
@@ -9196,7 +9179,7 @@
         final int userHandle = caller.getUserId();
         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
         synchronized (getLockObject()) {
-            if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+            if (isPermissionCheckFlagEnabled()) {
                 // SUPPORT USES_POLICY_DISABLE_KEYGUARD_FEATURES
                 EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
                         who, MANAGE_DEVICE_POLICY_KEYGUARD, caller.getPackageName(),
@@ -9275,7 +9258,7 @@
 
         synchronized (getLockObject()) {
             if (who != null) {
-                if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+                if (isPermissionCheckFlagEnabled()) {
                     EnforcingAdmin admin = getEnforcingAdminForCaller(
                             who, who.getPackageName());
                     Integer features = mDevicePolicyEngine.getLocalPolicySetByAdmin(
@@ -9289,7 +9272,7 @@
                 }
             }
 
-            if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+            if (isPermissionCheckFlagEnabled()) {
                 Integer features = mDevicePolicyEngine.getResolvedPolicy(
                         PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
                         affectedUserId);
@@ -11215,14 +11198,14 @@
     public void addPersistentPreferredActivity(ComponentName who, String callerPackageName,
             IntentFilter filter, ComponentName activity) {
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
         }
 
         final int userId = caller.getUserId();
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin;
             if (who == null) {
                 enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
@@ -11270,14 +11253,14 @@
     public void clearPackagePersistentPreferredActivities(ComponentName who,
             String callerPackageName, String packageName) {
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
         }
         final int userId = caller.getUserId();
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin;
             if (who == null) {
                 enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
@@ -11469,7 +11452,7 @@
         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_RESTRICTIONS);
 
-        if (useDevicePolicyEngine(caller, DELEGATION_APP_RESTRICTIONS)) {
+        if (isPermissionCheckFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     who,
                     MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
@@ -12465,7 +12448,7 @@
 
         final int userId = user.id;
 
-        if (isDevicePolicyEngineEnabled()) {
+        if (isPermissionCheckFlagEnabled()) {
             mDevicePolicyEngine.handleUserCreated(user);
         }
 
@@ -12834,7 +12817,7 @@
             String packageName) {
         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
 
-        if (useDevicePolicyEngine(caller, DELEGATION_APP_RESTRICTIONS)) {
+        if (isPermissionCheckFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforceCanQueryAndGetEnforcingAdmin(
                     who,
                     MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
@@ -13063,7 +13046,7 @@
             boolean parent) {
 
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackage);
         } else {
             caller = getCallerIdentity(who);
@@ -13075,7 +13058,7 @@
         }
         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION);
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             int affectedUserId = parent ? getProfileParentId(userId) : userId;
             EnforcingAdmin admin = enforcePermissionForUserRestriction(
                     who,
@@ -13175,14 +13158,14 @@
             return;
         }
 
-        int userHandle = caller.getUserId();
         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION);
 
-        if (!useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
-            throw new IllegalStateException("One or more admins are not targeting Android 14.");
+        if (!isPolicyEngineForFinanceFlagEnabled()) {
+            throw new IllegalStateException("Feature flag is not enabled.");
         }
+
         EnforcingAdmin admin = enforcePermissionForUserRestriction(
-                /*who=*/ null,
+                /* who= */ null,
                 key,
                 caller.getPackageName(),
                 caller.getUserId()
@@ -13215,7 +13198,7 @@
     }
 
     private void saveUserRestrictionsLocked(int userId) {
-        if (isDevicePolicyEngineEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             // User restrictions are handled in the policy engine
             return;
         }
@@ -13233,6 +13216,10 @@
      * will be the target user id.
      */
     private void pushUserRestrictions(int originatingUserId) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
+            // User restrictions are handled in the policy engine
+            return;
+        }
         final Bundle global;
         final RestrictionsSet local = new RestrictionsSet();
         final boolean isDeviceOwner;
@@ -13285,13 +13272,13 @@
             return null;
         }
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackage);
         } else {
             caller = getCallerIdentity(who);
         }
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
             return getUserRestrictionsFromPolicyEngine(
                     admin,
@@ -13479,8 +13466,8 @@
             return null;
         }
         final CallerIdentity caller = getCallerIdentity(callerPackage);
-        if (!useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
-            throw new IllegalStateException("One or more admins are not targeting Android 14.");
+        if (!isPolicyEngineForFinanceFlagEnabled()) {
+            throw new IllegalStateException("Feature flag is not enabled.");
         }
 
         EnforcingAdmin admin = getEnforcingAdminForCaller(/*who=*/ null, caller.getPackageName());
@@ -13548,8 +13535,31 @@
                 Slogf.v(LOG_TAG, "calling pm.setApplicationHiddenSettingAsUser(%s, %b, %d)",
                         packageName, hidden, userId);
             }
-            result = mInjector.binderWithCleanCallingIdentity(() -> mIPackageManager
-                    .setApplicationHiddenSettingAsUser(packageName, hidden, userId));
+            if (isPermissionCheckFlagEnabled()) {
+                EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
+                mDevicePolicyEngine.setLocalPolicy(
+                        PolicyDefinition.APPLICATION_HIDDEN(packageName),
+                        admin,
+                        new BooleanPolicyValue(hidden),
+                        userId);
+                Boolean resolvedPolicy = mDevicePolicyEngine.getResolvedPolicy(
+                        PolicyDefinition.APPLICATION_HIDDEN(packageName), userId);
+                result = mInjector.binderWithCleanCallingIdentity(() -> {
+                    try {
+                        // This is a best effort to continue returning the same value that was
+                        // returned before the policy engine migration.
+                        return mInjector.getIPackageManager().getPackageInfo(
+                                packageName, MATCH_UNINSTALLED_PACKAGES, userId) != null
+                                && (mIPackageManager.getApplicationHiddenSettingAsUser(
+                                        packageName, userId) == hidden);
+                    } catch (RemoteException e) {
+                        return false;
+                    }
+                });
+            } else {
+                result = mInjector.binderWithCleanCallingIdentity(() -> mIPackageManager
+                        .setApplicationHiddenSettingAsUser(packageName, hidden, userId));
+            }
         }
         DevicePolicyEventLogger
                 .createEvent(DevicePolicyEnums.SET_APPLICATION_HIDDEN)
@@ -13865,7 +13875,7 @@
             boolean uninstallBlocked) {
         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
 
-        if (useDevicePolicyEngine(caller, DELEGATION_BLOCK_UNINSTALL)) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     who,
                     MANAGE_DEVICE_POLICY_APPS_CONTROL,
@@ -14419,14 +14429,14 @@
             throws SecurityException {
         Objects.requireNonNull(packages, "packages is null");
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
         }
         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_PACKAGES);
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin;
             synchronized (getLockObject()) {
                 enforcingAdmin = enforceCanCallLockTaskLocked(who, callerPackageName);
@@ -14477,14 +14487,14 @@
     @Override
     public String[] getLockTaskPackages(ComponentName who, String callerPackageName) {
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
         }
         final int userHandle = caller.getUserId();
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             synchronized (getLockObject()) {
                 enforceCanQueryLockTaskLocked(who, caller.getPackageName());
             }
@@ -14517,8 +14527,7 @@
         }
 
         final int userId = mInjector.userHandleGetCallingUserId();
-        // Is it ok to just check that no active policies exist currently?
-        if (isDevicePolicyEngineFlagEnabled() && mDevicePolicyEngine.hasActivePolicies()) {
+        if (isPermissionCheckFlagEnabled()) {
             LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
                     PolicyDefinition.LOCK_TASK, userId);
             if (policy == null) {
@@ -14544,7 +14553,7 @@
             "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME");
 
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
@@ -14554,7 +14563,7 @@
             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_FEATURES);
         }
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin;
             synchronized (getLockObject()) {
                 enforcingAdmin = enforceCanCallLockTaskLocked(who,
@@ -14597,14 +14606,14 @@
     @Override
     public int getLockTaskFeatures(ComponentName who, String callerPackageName) {
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
         }
         final int userHandle = caller.getUserId();
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             synchronized (getLockObject()) {
                 enforceCanQueryLockTaskLocked(who, caller.getPackageName());
             }
@@ -16364,7 +16373,7 @@
                 enforcePermissionGrantStateOnFinancedDevice(packageName, permission);
             }
         }
-        if (useDevicePolicyEngine(caller, DELEGATION_PERMISSION_GRANT)) {
+        if (isPermissionCheckFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     admin,
                     MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
@@ -17869,11 +17878,6 @@
         // The removed admin might have disabled camera, so update user
         // restrictions.
         pushUserRestrictions(userHandle);
-
-        // The removed admin might've been stopping the migration if it was targeting pre Android U
-        if (shouldMigrateToDevicePolicyEngine()) {
-            migratePoliciesToDevicePolicyEngine();
-        }
     }
 
     @Override
@@ -18551,7 +18555,7 @@
         }
         final int userId = caller.getUserId();
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPermissionCheckFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     admin,
                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
@@ -18615,7 +18619,7 @@
         final int userId = caller.getUserId();
         boolean result = false;
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPermissionCheckFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     admin,
                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
@@ -18661,7 +18665,7 @@
         }
         int userId = caller.getUserId();
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPermissionCheckFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     admin,
                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
@@ -18713,7 +18717,7 @@
         boolean result = false;
         final String password = passwordOrNull != null ? passwordOrNull : "";
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPermissionCheckFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     admin,
                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
@@ -19902,7 +19906,7 @@
             List<String> packages) {
         Objects.requireNonNull(packages, "packages is null");
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
@@ -19910,7 +19914,7 @@
         checkCanExecuteOrThrowUnsafe(
                 DevicePolicyManager.OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES);
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     who,
                     MANAGE_DEVICE_POLICY_APPS_CONTROL,
@@ -19984,13 +19988,13 @@
     public List<String> getUserControlDisabledPackages(ComponentName who,
             String callerPackageName) {
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
         }
 
-        if (useDevicePolicyEngine(caller, /* delegateScope= */ null)) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             enforceCanQuery(
                     MANAGE_DEVICE_POLICY_APPS_CONTROL,
                     caller.getPackageName(),
@@ -22073,7 +22077,7 @@
         }
 
         private void handleFinancedDeviceKioskRoleChange() {
-            if (!isDevicePolicyEngineEnabled()) {
+            if (!isPermissionCheckFlagEnabled()) {
                 return;
             }
             Slog.i(LOG_TAG, "Handling action " + ACTION_DEVICE_FINANCING_STATE_CHANGED);
@@ -22852,6 +22856,13 @@
                 DEFAULT_VALUE_PERMISSION_BASED_ACCESS_FLAG);
     }
 
+    private boolean isPolicyEngineForFinanceFlagEnabled() {
+        return DeviceConfig.getBoolean(
+                NAMESPACE_DEVICE_POLICY_MANAGER,
+                ENABLE_DEVICE_POLICY_ENGINE_FOR_FINANCE_FLAG,
+                DEFAULT_ENABLE_DEVICE_POLICY_ENGINE_FOR_FINANCE_FLAG);
+    }
+
     private static boolean isKeepProfilesRunningFlagEnabled() {
         return DeviceConfig.getBoolean(
                 NAMESPACE_DEVICE_POLICY_MANAGER,
@@ -23190,36 +23201,9 @@
         });
     }
 
-    // TODO(b/266808047): handle DeviceAdmin migration when there is no DPCs on the device
     private boolean shouldMigrateToDevicePolicyEngine() {
-        return mInjector.binderWithCleanCallingIdentity(() -> {
-            if (!isDevicePolicyEngineFlagEnabled()) {
-                return false;
-            }
-            if (mOwners.isMigratedToPolicyEngine()) {
-                return false;
-            }
-            // We're only checking if existing DPCs are not targeting U, regardless of what
-            // DeviceAdmins are targeting, as they can access very limited APIs, and we'll ensure
-            // that these APIs maintain the current behaviour of strictest applies.
-            boolean hasDPCs = false;
-            for (UserInfo userInfo : mUserManager.getUsers()) {
-                List<ComponentName> activeAdmins = getActiveAdmins(userInfo.id);
-                if (activeAdmins == null) {
-                    continue;
-                }
-                for (ComponentName admin : activeAdmins) {
-                    if ((isProfileOwner(admin, userInfo.id) || isDeviceOwner(admin, userInfo.id))) {
-                        if (!mInjector.isChangeEnabled(ENABLE_COEXISTENCE_CHANGE,
-                                admin.getPackageName(), userInfo.id)) {
-                            return false;
-                        }
-                        hasDPCs = true;
-                    }
-                }
-            }
-            return hasDPCs;
-        });
+        return mInjector.binderWithCleanCallingIdentity(() ->
+                isPermissionCheckFlagEnabled() && !mOwners.isMigratedToPolicyEngine());
     }
 
     /**
@@ -23433,40 +23417,6 @@
         return admins;
     }
 
-    private boolean useDevicePolicyEngine(CallerIdentity caller, @Nullable String delegateScope) {
-        return isDevicePolicyEngineEnabled();
-    }
-
-    private boolean isDevicePolicyEngineEnabled() {
-        return isDevicePolicyEngineFlagEnabled() && isPermissionCheckFlagEnabled();
-    }
-
-    private boolean isDevicePolicyEngineFlagEnabled() {
-        return DeviceConfig.getBoolean(
-                NAMESPACE_DEVICE_POLICY_MANAGER,
-                ENABLE_DEVICE_POLICY_ENGINE_FLAG,
-                DEFAULT_ENABLE_DEVICE_POLICY_ENGINE_FLAG);
-    }
-
-    private boolean hasDPCsNotSupportingCoexistence() {
-        return mInjector.binderWithCleanCallingIdentity(() -> {
-            for (UserInfo userInfo : mUserManager.getUsers()) {
-                List<ComponentName> activeAdmins = getActiveAdmins(userInfo.id);
-                if (activeAdmins == null) {
-                    continue;
-                }
-                for (ComponentName admin : activeAdmins) {
-                    if ((isProfileOwner(admin, userInfo.id) || isDeviceOwner(admin, userInfo.id))
-                            && !mInjector.isChangeEnabled(ENABLE_COEXISTENCE_CHANGE,
-                            admin.getPackageName(), userInfo.id)) {
-                        return true;
-                    }
-                }
-            }
-            return false;
-        });
-    }
-
     // TODO: this can actually accept an EnforcingAdmin that gets created in the permission
     //  check method.
     private boolean isCallerActiveAdminOrDelegate(
@@ -23504,25 +23454,6 @@
         }
     }
 
-    // TODO(b/266808047): This will return false for DeviceAdmins not targetting U, which is
-    //  inconsistent with the migration logic that allows migration with old DeviceAdmins.
-    private boolean canAddActiveAdminIfPolicyEngineEnabled(String packageName, int userId) {
-        if (!isDevicePolicyEngineFlagEnabled()) {
-            return true;
-        }
-        if (hasDPCsNotSupportingCoexistence()) {
-            return true;
-        }
-        if (mInjector.isChangeEnabled(ENABLE_COEXISTENCE_CHANGE, packageName, userId)) {
-            // This will always return true unless we turn off coexistence, in which case it will
-            // return true if no current admins exist, or more than one admin exist
-            return mDevicePolicyEngine.canAdminAddPolicies(packageName, userId);
-        }
-        // Is it ok to just check that no active policies exist currently, or should we return false
-        // if the policy engine was ever used?
-        return !mDevicePolicyEngine.hasActivePolicies();
-    }
-
     @Override
     public boolean isDeviceFinanced(String callerPackageName) {
         CallerIdentity caller = getCallerIdentity(callerPackageName);
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyDefinition.java b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyDefinition.java
index 8812c3d..a15aa53 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyDefinition.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyDefinition.java
@@ -226,8 +226,7 @@
      * Passing in {@code null} for {@code packageName} will return
      * {@link #GENERIC_APPLICATION_RESTRICTIONS}.
      */
-    static PolicyDefinition<Bundle> APPLICATION_RESTRICTIONS(
-            String packageName) {
+    static PolicyDefinition<Bundle> APPLICATION_RESTRICTIONS(String packageName) {
         if (packageName == null) {
             return GENERIC_APPLICATION_RESTRICTIONS;
         }
@@ -254,6 +253,34 @@
             (Integer value, Context context, Integer userId, PolicyKey policyKey) -> true,
             new IntegerPolicySerializer());
 
+    // This is saved in the static map sPolicyDefinitions so that we're able to reconstruct the
+    // actual policy with the correct arguments (i.e. packageName) when reading the policies from
+    // xml.
+    static PolicyDefinition<Boolean> GENERIC_APPLICATION_HIDDEN =
+            new PolicyDefinition<>(
+                    new PackagePolicyKey(
+                            DevicePolicyIdentifiers.APPLICATION_HIDDEN_POLICY),
+                    // TODO(b/276713779): Don't need to take in a resolution mechanism since its
+                    //  never used, but might need some refactoring to not always assume a non-null
+                    //  mechanism.
+                    TRUE_MORE_RESTRICTIVE,
+                    POLICY_FLAG_LOCAL_ONLY_POLICY,
+                    PolicyEnforcerCallbacks::setApplicationHidden,
+                    new BooleanPolicySerializer());
+
+    /**
+     * Passing in {@code null} for {@code packageName} will return
+     * {@link #GENERIC_APPLICATION_HIDDEN}.
+     */
+    static PolicyDefinition<Boolean> APPLICATION_HIDDEN(String packageName) {
+        if (packageName == null) {
+            return GENERIC_APPLICATION_HIDDEN;
+        }
+        return GENERIC_APPLICATION_HIDDEN.createPolicyDefinition(
+                new PackagePolicyKey(
+                        DevicePolicyIdentifiers.APPLICATION_HIDDEN_POLICY, packageName));
+    }
+
     private static final Map<String, PolicyDefinition<?>> POLICY_DEFINITIONS = new HashMap<>();
     private static Map<String, Integer> USER_RESTRICTION_FLAGS = new HashMap<>();
 
@@ -272,6 +299,10 @@
                 GENERIC_APPLICATION_RESTRICTIONS);
         POLICY_DEFINITIONS.put(DevicePolicyIdentifiers.RESET_PASSWORD_TOKEN_POLICY,
                 RESET_PASSWORD_TOKEN);
+        POLICY_DEFINITIONS.put(DevicePolicyIdentifiers.KEYGUARD_DISABLED_FEATURES_POLICY,
+                KEYGUARD_DISABLED_FEATURES);
+        POLICY_DEFINITIONS.put(DevicePolicyIdentifiers.APPLICATION_HIDDEN_POLICY,
+                GENERIC_APPLICATION_HIDDEN);
 
         // User Restriction Policies
         USER_RESTRICTION_FLAGS.put(UserManager.DISALLOW_MODIFY_ACCOUNTS, /* flags= */ 0);
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyEnforcerCallbacks.java b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyEnforcerCallbacks.java
index fd91249..d65d366 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyEnforcerCallbacks.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyEnforcerCallbacks.java
@@ -73,7 +73,7 @@
         return Boolean.TRUE.equals(Binder.withCleanCallingIdentity(() -> {
             if (!(policyKey instanceof PackagePermissionPolicyKey)) {
                 throw new IllegalArgumentException("policyKey is not of type "
-                        + "PermissionGrantStatePolicyKey");
+                        + "PermissionGrantStatePolicyKey, passed in policyKey is: " + policyKey);
             }
             PackagePermissionPolicyKey parsedKey = (PackagePermissionPolicyKey) policyKey;
             Objects.requireNonNull(parsedKey.getPermissionName());
@@ -165,7 +165,7 @@
             try {
                 if (!(policyKey instanceof IntentFilterPolicyKey)) {
                     throw new IllegalArgumentException("policyKey is not of type "
-                            + "IntentFilterPolicyKey");
+                            + "IntentFilterPolicyKey, passed in policyKey is: " + policyKey);
                 }
                 IntentFilterPolicyKey parsedKey =
                         (IntentFilterPolicyKey) policyKey;
@@ -193,7 +193,7 @@
         return Boolean.TRUE.equals(Binder.withCleanCallingIdentity(() -> {
             if (!(policyKey instanceof PackagePolicyKey)) {
                 throw new IllegalArgumentException("policyKey is not of type "
-                        + "PackagePolicyKey");
+                        + "PackagePolicyKey, passed in policyKey is: " + policyKey);
             }
             PackagePolicyKey parsedKey = (PackagePolicyKey) policyKey;
             String packageName = Objects.requireNonNull(parsedKey.getPackageName());
@@ -211,7 +211,7 @@
         return Boolean.TRUE.equals(Binder.withCleanCallingIdentity(() -> {
             if (!(policyKey instanceof UserRestrictionPolicyKey)) {
                 throw new IllegalArgumentException("policyKey is not of type "
-                        + "UserRestrictionPolicyKey");
+                        + "UserRestrictionPolicyKey, passed in policyKey is: " + policyKey);
             }
             UserRestrictionPolicyKey parsedKey =
                     (UserRestrictionPolicyKey) policyKey;
@@ -221,4 +221,20 @@
             return true;
         }));
     }
+
+    static boolean setApplicationHidden(
+            @Nullable Boolean hide, @NonNull Context context, int userId,
+            @NonNull PolicyKey policyKey) {
+        return Boolean.TRUE.equals(Binder.withCleanCallingIdentity(() -> {
+            if (!(policyKey instanceof PackagePolicyKey)) {
+                throw new IllegalArgumentException("policyKey is not of type "
+                        + "PackagePolicyKey, passed in policyKey is: " + policyKey);
+            }
+            PackagePolicyKey parsedKey = (PackagePolicyKey) policyKey;
+            String packageName = Objects.requireNonNull(parsedKey.getPackageName());
+            IPackageManager packageManager = AppGlobals.getPackageManager();
+            return packageManager.setApplicationHiddenSettingAsUser(
+                    packageName, hide != null && hide, userId);
+        }));
+    }
 }
diff --git a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
index de41117..a646d01 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
@@ -178,6 +178,44 @@
     }
 
     @Test
+    public void testActivityInHistoryAndNotVisibleIsNotUsedAsOpaqueForTranslucentActivities() {
+        mWm.mLetterboxConfiguration.setTranslucentLetterboxingOverrideEnabled(true);
+        setUpDisplaySizeWithApp(2000, 1000);
+        prepareUnresizable(mActivity, SCREEN_ORIENTATION_PORTRAIT);
+        mActivity.mDisplayContent.setIgnoreOrientationRequest(true /* ignoreOrientationRequest */);
+        mActivity.nowVisible = false;
+        // Translucent Activity
+        final ActivityRecord translucentActivity = new ActivityBuilder(mAtm)
+                .setLaunchedFromUid(mActivity.getUid())
+                .setScreenOrientation(SCREEN_ORIENTATION_PORTRAIT)
+                .build();
+        doReturn(false).when(translucentActivity).fillsParent();
+
+        mTask.addChild(translucentActivity);
+
+        assertFalse(translucentActivity.mLetterboxUiController.hasInheritedLetterboxBehavior());
+    }
+
+    @Test
+    public void testActivityInHistoryAndVisibleIsUsedAsOpaqueForTranslucentActivities() {
+        mWm.mLetterboxConfiguration.setTranslucentLetterboxingOverrideEnabled(true);
+        setUpDisplaySizeWithApp(2000, 1000);
+        prepareUnresizable(mActivity, SCREEN_ORIENTATION_PORTRAIT);
+        mActivity.mDisplayContent.setIgnoreOrientationRequest(true /* ignoreOrientationRequest */);
+        mActivity.nowVisible = true;
+        // Translucent Activity
+        final ActivityRecord translucentActivity = new ActivityBuilder(mAtm)
+                .setLaunchedFromUid(mActivity.getUid())
+                .setScreenOrientation(SCREEN_ORIENTATION_PORTRAIT)
+                .build();
+        doReturn(false).when(translucentActivity).fillsParent();
+
+        mTask.addChild(translucentActivity);
+
+        assertTrue(translucentActivity.mLetterboxUiController.hasInheritedLetterboxBehavior());
+    }
+
+    @Test
     public void testCleanLetterboxConfigListenerWhenTranslucentIsDestroyed() {
         mWm.mLetterboxConfiguration.setTranslucentLetterboxingOverrideEnabled(true);
         setUpDisplaySizeWithApp(2000, 1000);
@@ -201,6 +239,7 @@
     public void testHorizontalReachabilityEnabledForTranslucentActivities() {
         setUpDisplaySizeWithApp(2500, 1000);
         mActivity.mDisplayContent.setIgnoreOrientationRequest(true /* ignoreOrientationRequest */);
+        mActivity.nowVisible = true;
         final LetterboxConfiguration config = mWm.mLetterboxConfiguration;
         config.setTranslucentLetterboxingOverrideEnabled(true);
         config.setLetterboxHorizontalPositionMultiplier(0.5f);
@@ -276,6 +315,7 @@
     public void testVerticalReachabilityEnabledForTranslucentActivities() {
         setUpDisplaySizeWithApp(1000, 2500);
         mActivity.mDisplayContent.setIgnoreOrientationRequest(true /* ignoreOrientationRequest */);
+        mActivity.nowVisible = true;
         final LetterboxConfiguration config = mWm.mLetterboxConfiguration;
         config.setTranslucentLetterboxingOverrideEnabled(true);
         config.setLetterboxVerticalPositionMultiplier(0.5f);
@@ -354,6 +394,7 @@
         prepareUnresizable(mActivity, 1.5f /* maxAspect */, SCREEN_ORIENTATION_PORTRAIT);
         mActivity.info.setMinAspectRatio(1.2f);
         mActivity.mDisplayContent.setIgnoreOrientationRequest(true /* ignoreOrientationRequest */);
+        mActivity.nowVisible = true;
         // Translucent Activity
         final ActivityRecord translucentActivity = new ActivityBuilder(mAtm)
                 .setLaunchedFromUid(mActivity.getUid())
@@ -410,6 +451,7 @@
         prepareUnresizable(mActivity, 1.5f /* maxAspect */, SCREEN_ORIENTATION_PORTRAIT);
         mActivity.info.setMinAspectRatio(1.2f);
         mActivity.mDisplayContent.setIgnoreOrientationRequest(true /* ignoreOrientationRequest */);
+        mActivity.nowVisible = true;
         // Translucent Activity
         final ActivityRecord translucentActivity = new ActivityBuilder(mAtm)
                 .setLaunchedFromUid(mActivity.getUid())
@@ -503,6 +545,7 @@
                 true /* ignoreOrientationRequest */);
         mActivity.mWmService.mLetterboxConfiguration.setLetterboxHorizontalPositionMultiplier(
                 1.0f /*letterboxVerticalPositionMultiplier*/);
+        mActivity.nowVisible = true;
         prepareUnresizable(mActivity, SCREEN_ORIENTATION_PORTRAIT);
         // We launch a transparent activity
         final ActivityRecord translucentActivity = new ActivityBuilder(mAtm)
@@ -535,6 +578,7 @@
         mWm.mLetterboxConfiguration.setTranslucentLetterboxingOverrideEnabled(true);
         setUpDisplaySizeWithApp(2800, 1400);
         mActivity.mDisplayContent.setIgnoreOrientationRequest(true /* ignoreOrientationRequest */);
+        mActivity.nowVisible = true;
         prepareUnresizable(mActivity, -1f /* maxAspect */, SCREEN_ORIENTATION_PORTRAIT);
         // Rotate to put activity in size compat mode.
         rotateDisplay(mActivity.mDisplayContent, ROTATION_90);