Merge "Fix flakiness in VDM CTS" into main
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioDataPathsBaseActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioDataPathsBaseActivity.java
index a49d7b0..ab7c917 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioDataPathsBaseActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioDataPathsBaseActivity.java
@@ -247,8 +247,9 @@
         TestResults[] mTestResults;
 
         // Pass/Fail criteria (with defaults)
-        double mMinPassMagnitude = 0.01;
-        double mMaxPassJitter = 0.1;
+        static final double MIN_SIGNAL_PASS_MAGNITUDE = 0.01;
+        static final double MAX_SIGNAL_PASS_JITTER = 0.1;
+        static final double MAX_XTALK_PASS_MAGNITUDE = 0.02;
 
         TestModule(int outDeviceType, int outSampleRate, int outChannelCount,
                    int inDeviceType, int inSampleRate, int inChannelCount) {
@@ -394,10 +395,10 @@
             boolean passed = false;
             if (hasRun(api)) {
                 if (mAnalysisType == TYPE_SIGNAL_PRESENCE) {
-                    passed = mTestResults[api].mMaxMagnitude >= mMinPassMagnitude
-                            && mTestResults[api].mPhaseJitter <= mMaxPassJitter;
+                    passed = mTestResults[api].mMaxMagnitude >= MIN_SIGNAL_PASS_MAGNITUDE
+                            && mTestResults[api].mPhaseJitter <= MAX_SIGNAL_PASS_JITTER;
                 } else {
-                    passed = mTestResults[api].mMaxMagnitude <= mMinPassMagnitude;
+                    passed = mTestResults[api].mMaxMagnitude <= MAX_XTALK_PASS_MAGNITUDE;
                 }
             }
             return passed;
@@ -568,12 +569,12 @@
                         locale, "jitter:%.5f ", results.mPhaseJitter);
 
                 boolean passMagnitude = mAnalysisType == TYPE_SIGNAL_PRESENCE
-                        ? results.mMaxMagnitude >= mMinPassMagnitude
-                        : results.mMaxMagnitude <= mMinPassMagnitude;
+                        ? results.mMaxMagnitude >= MIN_SIGNAL_PASS_MAGNITUDE
+                        : results.mMaxMagnitude <= MAX_XTALK_PASS_MAGNITUDE;
 
                 // Do we want a threshold value for jitter in crosstalk tests?
                 boolean passJitter =
-                        results.mPhaseJitter <= mMaxPassJitter;
+                        results.mPhaseJitter <= MAX_SIGNAL_PASS_JITTER;
 
                 // Values / Criteria
                 // NOTE: The criteria is why the test passed or failed, not what
@@ -586,12 +587,12 @@
                     htmlFormatter.appendText(maxMagString
                             + String.format(locale,
                             passMagnitude ? " >= %.5f " : " < %.5f ",
-                            mMinPassMagnitude));
+                            MIN_SIGNAL_PASS_MAGNITUDE));
                 } else {
                     htmlFormatter.appendText(maxMagString
                             + String.format(locale,
                             passMagnitude ? " <= %.5f " : " > %.5f ",
-                            mMinPassMagnitude));
+                            MAX_XTALK_PASS_MAGNITUDE));
                 }
                 htmlFormatter.closeTextColor();
 
@@ -599,7 +600,7 @@
                 if (mAnalysisType == TYPE_SIGNAL_PRESENCE) {
                     htmlFormatter.appendText(phaseJitterString
                                     + String.format(locale, passJitter ? " <= %.5f" : " > %.5f",
-                                    mMaxPassJitter));
+                                    MAX_SIGNAL_PASS_JITTER));
                 } else {
                     htmlFormatter.appendText(phaseJitterString);
                 }
diff --git a/hostsidetests/credentials/src/android/cts/credentials/backuprestore/CredentialManagerRestoreSettingsHostSideTest.java b/hostsidetests/credentials/src/android/cts/credentials/backuprestore/CredentialManagerRestoreSettingsHostSideTest.java
index 6e92af1..b145b24 100644
--- a/hostsidetests/credentials/src/android/cts/credentials/backuprestore/CredentialManagerRestoreSettingsHostSideTest.java
+++ b/hostsidetests/credentials/src/android/cts/credentials/backuprestore/CredentialManagerRestoreSettingsHostSideTest.java
@@ -109,6 +109,10 @@
 
         BackupHostSideUtils.checkSetupComplete(getDevice());
 
+        mBackupUtils.enableBackup(true);
+        mBackupUtils.activateBackupForUser(true, 0);
+        mBackupUtils.setBackupTransportForUser(mBackupUtils.getLocalTransportName(), 0);
+
         // Check that the backup wasn't disabled and the transport wasn't switched unexpectedly.
         assertTrue(
                 "Backup was unexpectedly disabled during the module test run",
@@ -130,10 +134,6 @@
 
     @Test
     public void testSettingsAreRestoredCorrectly() throws Exception {
-        mBackupUtils.enableBackup(true);
-        mBackupUtils.activateBackupForUser(true, 0);
-        mBackupUtils.setBackupTransportForUser(mBackupUtils.getLocalTransportName(), 0);
-
         // 1. Set the CredMan settings before backup.
         setSecureSettingValue(AUTOFILL_SETTING_NAME, AUTOFILL_TEST_SERVICE);
         setSecureSettingValue(CREDMAN_SETTING_NAME, CREDMAN_TEST_SERVICE);
@@ -165,10 +165,6 @@
 
     @Test
     public void testSettingsAreNotRestoredIfUserHasChangedThem() throws Exception {
-        mBackupUtils.enableBackup(true);
-        mBackupUtils.activateBackupForUser(true, 0);
-        mBackupUtils.setBackupTransportForUser(mBackupUtils.getLocalTransportName(), 0);
-
         // 1. Set the CredMan settings before backup.
         setSecureSettingValue(AUTOFILL_SETTING_NAME, AUTOFILL_TEST_SERVICE);
         setSecureSettingValue(CREDMAN_SETTING_NAME, CREDMAN_TEST_SERVICE);
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/PreDeviceOwnerTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/PreDeviceOwnerTest.java
index 450b996..b713f8d 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/PreDeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/PreDeviceOwnerTest.java
@@ -47,11 +47,6 @@
                 .isProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE));
     }
 
-    public void testIsProvisioningNotAllowedForManagedProfileAction() {
-        assertFalse(mDevicePolicyManager
-                .isProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE));
-    }
-
     public void testListForegroundAffiliatedUsers_notDeviceOwner() throws Exception {
         assertThrows(SecurityException.class,
                 () -> mDevicePolicyManager.listForegroundAffiliatedUsers());
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
index 8f20891..ee0620b 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
@@ -16,7 +16,6 @@
 
 package com.android.cts.devicepolicy;
 
-import static com.android.cts.devicepolicy.DeviceAdminFeaturesCheckerRule.FEATURE_MANAGED_USERS;
 import static com.android.cts.devicepolicy.metrics.DevicePolicyEventLogVerifier.assertMetricsLogged;
 
 import static org.junit.Assert.assertEquals;
@@ -31,7 +30,6 @@
 import android.stats.devicepolicy.EventId;
 
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
-import com.android.cts.devicepolicy.DeviceAdminFeaturesCheckerRule.RequiresAdditionalFeatures;
 import com.android.cts.devicepolicy.metrics.DevicePolicyEventWrapper;
 import com.android.tradefed.log.LogUtil.CLog;
 
@@ -487,16 +485,6 @@
         executeDeviceTestMethod(".PreDeviceOwnerTest", "testIsProvisioningAllowedFalse");
     }
 
-    /**
-     * Can provision Managed Profile when DO is set by default if they are the same admin.
-     */
-    @Test
-    @RequiresAdditionalFeatures({FEATURE_MANAGED_USERS})
-    public void testIsManagedProfileProvisioningAllowed_deviceOwnerIsSet() throws Exception {
-        executeDeviceTestMethod(".PreDeviceOwnerTest",
-                "testIsProvisioningNotAllowedForManagedProfileAction");
-    }
-
     @FlakyTest(bugId = 137096267)
     @Test
     public void testAdminActionBookkeeping() throws Exception {
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecAvbToTvTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecAvbToTvTest.java
index 3772dd05..a46fe9e 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecAvbToTvTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecAvbToTvTest.java
@@ -18,6 +18,8 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.junit.Assume.assumeFalse;
+
 import android.hdmicec.cts.AudioManagerHelper;
 import android.hdmicec.cts.BaseHdmiCecAbsoluteVolumeBehaviorTest;
 import android.hdmicec.cts.BaseHdmiCecCtsTest;
@@ -107,6 +109,9 @@
      */
     @Test
     public void testEnableDisableAvb_triggeredByAvbSupportChanged() throws Exception {
+        assumeFalse("Skip for audio system devices (b/323469502)",
+                hasDeviceType(HdmiCecConstants.CEC_DEVICE_TYPE_AUDIO_SYSTEM));
+
         setSettingsValue(HdmiCecConstants.SETTING_VOLUME_CONTROL_ENABLED,
                 HdmiCecConstants.VOLUME_CONTROL_ENABLED);
 
@@ -139,6 +144,9 @@
      */
     @Test
     public void testEnableAndDisableAvb_triggeredByVolumeControlSettingChange() throws Exception {
+        assumeFalse("Skip for audio system devices (b/323469502)",
+                hasDeviceType(HdmiCecConstants.CEC_DEVICE_TYPE_AUDIO_SYSTEM));
+
         enableSystemAudioModeIfApplicable();
 
         // System audio device reports support for <Set Audio Volume Level>
@@ -170,6 +178,9 @@
      */
     @Test
     public void testOutgoingVolumeUpdates() throws Exception {
+        assumeFalse("Skip for audio system devices (b/323469502)",
+                hasDeviceType(HdmiCecConstants.CEC_DEVICE_TYPE_AUDIO_SYSTEM));
+
         // Enable AVB
         setSettingsValue(HdmiCecConstants.SETTING_VOLUME_CONTROL_ENABLED,
                 HdmiCecConstants.VOLUME_CONTROL_ENABLED);
@@ -207,6 +218,9 @@
      */
     @Test
     public void testIncomingVolumeUpdates() throws Exception {
+        assumeFalse("Skip for audio system devices (b/323469502)",
+                hasDeviceType(HdmiCecConstants.CEC_DEVICE_TYPE_AUDIO_SYSTEM));
+
         // Enable AVB
         setSettingsValue(HdmiCecConstants.SETTING_VOLUME_CONTROL_ENABLED,
                 HdmiCecConstants.VOLUME_CONTROL_ENABLED);
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecRemoteControlPassThroughTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecRemoteControlPassThroughTest.java
index d0f26e9..c8d0d03 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecRemoteControlPassThroughTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecRemoteControlPassThroughTest.java
@@ -19,6 +19,7 @@
 import static com.google.common.truth.Truth.assertThat;
 import static com.google.common.truth.Truth.assertWithMessage;
 
+import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
 
 import android.hdmicec.cts.BaseHdmiCecCtsTest;
@@ -208,6 +209,9 @@
      */
     @Test
     public void cect_sendVolumeKeyPressToTv() throws Exception {
+        assumeFalse("Skip for audio system devices (b/323469502)",
+                hasDeviceType(HdmiCecConstants.CEC_DEVICE_TYPE_AUDIO_SYSTEM));
+
         // The DUT won't send <User Control Pressed> messages if this condition is not met.
         assumeTrue(isPlayingStreamMusicOnHdmiOut());
 
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemAudioControlTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemAudioControlTest.java
index 3f3b55f..f357a6b 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemAudioControlTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemAudioControlTest.java
@@ -18,6 +18,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
 
 import android.hdmicec.cts.BaseHdmiCecCtsTest;
@@ -62,6 +63,8 @@
     public void cect_hf4_10_5_RemoteControlCommandsWithSystemAudioControlProperty()
             throws Exception {
         setCec20();
+        assumeFalse("Skip for audio system devices (b/323469502)",
+                hasDeviceType(HdmiCecConstants.CEC_DEVICE_TYPE_AUDIO_SYSTEM));
         // The DUT won't send <User Control Pressed> messages if this condition is not met.
         assumeTrue(isPlayingStreamMusicOnHdmiOut());
 
diff --git a/hostsidetests/scopedstorage/general/src/android/scopedstorage/cts/general/ScopedStorageDeviceTest.java b/hostsidetests/scopedstorage/general/src/android/scopedstorage/cts/general/ScopedStorageDeviceTest.java
index 70363bd..ebb360c 100644
--- a/hostsidetests/scopedstorage/general/src/android/scopedstorage/cts/general/ScopedStorageDeviceTest.java
+++ b/hostsidetests/scopedstorage/general/src/android/scopedstorage/cts/general/ScopedStorageDeviceTest.java
@@ -145,6 +145,7 @@
 import android.util.Log;
 
 import androidx.annotation.Nullable;
+import androidx.test.filters.FlakyTest;
 import androidx.test.filters.SdkSuppress;
 
 import com.android.compatibility.common.util.FeatureUtil;
@@ -1316,6 +1317,7 @@
                 /* permission */ null, AppOpsManager.OPSTR_WRITE_MEDIA_VIDEO, /* forWrite */ true);
     }
 
+    @FlakyTest(bugId = 324388050)
     @Test
     public void testAccessMediaLocationInvalidation() throws Exception {
         File imgFile = new File(getDcimDir(), "access_media_location.jpg");
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/BaseJobSchedulerTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/BaseJobSchedulerTest.java
index 369d7e6..93f37ec 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/BaseJobSchedulerTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/BaseJobSchedulerTest.java
@@ -124,6 +124,7 @@
         super.setUp();
         mDeviceConfigStateHelper =
                 new DeviceConfigStateHelper(DeviceConfig.NAMESPACE_JOB_SCHEDULER);
+        SystemUtil.runShellCommand("cmd jobscheduler cache-config-changes on");
         // Disable batching behavior.
         mDeviceConfigStateHelper.set("min_ready_cpu_only_jobs_count", "0");
         mDeviceConfigStateHelper.set("min_ready_non_active_jobs_count", "0");
@@ -151,6 +152,7 @@
     @CallSuper
     @Override
     public void tearDown() throws Exception {
+        SystemUtil.runShellCommand("cmd jobscheduler cache-config-changes off");
         SystemUtil.runShellCommand(getInstrumentation(), "cmd jobscheduler monitor-battery off");
         SystemUtil.runShellCommand(getInstrumentation(), "cmd battery reset");
         Settings.Global.putString(mContext.getContentResolver(),
@@ -272,6 +274,28 @@
         mActivityStarted = false;
     }
 
+    void setDeviceConfigFlag(String key, String value, boolean waitForConfirmation)
+            throws Exception {
+        mDeviceConfigStateHelper.set(key, value);
+        if (waitForConfirmation) {
+            waitUntil("Config didn't update appropriately to '" + value
+                            + "'. Current value=" + getConfigValue(key),
+                    5 /* seconds */,
+                    () -> {
+                        final String curVal = getConfigValue(key);
+                        if (value == null) {
+                            return "null".equals(curVal);
+                        } else {
+                            return curVal.equals(value);
+                        }
+                    });
+        }
+    }
+
+    static String getConfigValue(String key) {
+        return SystemUtil.runShellCommand("cmd jobscheduler get-config-value " + key).trim();
+    }
+
     String getJobState(int jobId) throws Exception {
         return SystemUtil.runShellCommand(getInstrumentation(),
                 "cmd jobscheduler get-job-state --user cur "
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/FlexibilityConstraintTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/FlexibilityConstraintTest.java
index 6840db9..3874da2 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/FlexibilityConstraintTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/FlexibilityConstraintTest.java
@@ -16,6 +16,8 @@
 
 package android.jobscheduler.cts;
 
+import static com.android.compatibility.common.util.TestUtils.waitUntil;
+
 import android.app.job.JobInfo;
 import android.content.pm.PackageManager;
 import android.jobscheduler.cts.jobtestapp.TestJobSchedulerReceiver;
@@ -86,21 +88,32 @@
         //  * CONSTRAINT_CHARGING
         //  * CONSTRAINT_CONNECTIVITY
         //  * CONSTRAINT_IDLE
-        mDeviceConfigStateHelper.set("fc_applied_constraints", "268435463");
-        mDeviceConfigStateHelper.set("fc_flexibility_deadline_proximity_limit_ms", "0");
+        setDeviceConfigFlag("fc_applied_constraints", "268435463", false);
+        setDeviceConfigFlag("fc_flexibility_deadline_proximity_limit_ms", "0", false);
         // Using jobs with no deadline, but having a short fallback deadline, lets us test jobs
         // whose lifecycle is smaller than the minimum allowed by JobStatus.
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=100000,400=100000,300=100000,200=100000,100=100000");
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadline_scores",
-                "500=0,400=0,300=0,200=0,100=0");
-        mDeviceConfigStateHelper.set("fc_min_time_between_flexibility_alarms_ms", "0");
-        mDeviceConfigStateHelper.set("fc_percents_to_drop_flexible_constraints",
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=100000,400=100000,300=100000,200=100000,100=100000", false);
+        setDeviceConfigFlag("fc_fallback_flexibility_deadline_scores",
+                "500=0,400=0,300=0,200=0,100=0", false);
+        setDeviceConfigFlag("fc_min_time_between_flexibility_alarms_ms", "0", false);
+        setDeviceConfigFlag("fc_percents_to_drop_flexible_constraints",
                 "500=3|6|12|25"
                         + ",400=3|6|12|25"
                         + ",300=3|6|12|25"
                         + ",200=3|6|12|25"
-                        + ",100=3|6|12|25");
+                        + ",100=3|6|12|25",
+                false);
+        waitUntil("Config didn't update appropriately", 10 /* seconds */,
+                () -> "268435463".equals(getConfigValue("fc_applied_constraints"))
+                && "0".equals(getConfigValue("fc_flexibility_deadline_proximity_limit_ms"))
+                && "500=100000,400=100000,300=100000,200=100000,100=100000"
+                        .equals(getConfigValue("fc_fallback_flexibility_deadlines"))
+                && "500=0,400=0,300=0,200=0,100=0"
+                        .equals(getConfigValue("fc_fallback_flexibility_deadline_scores"))
+                && "0".equals(getConfigValue("fc_min_time_between_flexibility_alarms_ms"))
+                && "500=3|6|12|25,400=3|6|12|25,300=3|6|12|25,200=3|6|12|25,100=3|6|12|25"
+                        .equals(getConfigValue("fc_percents_to_drop_flexible_constraints")));
 
         // Disable power save mode.
         mPreviousLowPowerTriggerLevel = Settings.Global.getString(getContext().getContentResolver(),
@@ -145,12 +158,13 @@
             return;
         }
         // Make it so that constraints won't drop in time.
-        mDeviceConfigStateHelper.set("fc_percents_to_drop_flexible_constraints",
+        setDeviceConfigFlag("fc_percents_to_drop_flexible_constraints",
                 "500=25|30|35|50"
                         + ",400=25|30|35|50"
                         + ",300=25|30|35|50"
                         + ",200=25|30|35|50"
-                        + ",100=25|30|35|50");
+                        + ",100=25|30|35|50",
+                true);
         scheduleJobToExecute();
 
         // Job should fire even though constraints haven't dropped.
@@ -169,8 +183,9 @@
             return;
         }
         // Increase timeouts to make sure the test doesn't start passing because of transpired time.
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000");
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000",
+                true);
         scheduleJobToExecute();
 
         assertJobNotReady();
@@ -192,12 +207,13 @@
             return;
         }
         // Increase timeouts to make sure the test doesn't start passing because of transpired time.
-        mDeviceConfigStateHelper.set("fc_percents_to_drop_flexible_constraints",
+        setDeviceConfigFlag("fc_percents_to_drop_flexible_constraints",
                 "500=900000|1800000|3600000|7200000"
                         + ",400=900000|1800000|3600000|7200000"
                         + ",300=900000|1800000|3600000|7200000"
                         + ",200=900000|1800000|3600000|7200000"
-                        + ",100=900000|1800000|3600000|7200000");
+                        + ",100=900000|1800000|3600000|7200000",
+                true);
         scheduleJobToExecute();
 
         assertJobNotReady();
@@ -219,8 +235,9 @@
             return;
         }
         // Increase timeouts to make sure the test doesn't start passing because of transpired time.
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000");
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000",
+                true);
         scheduleJobToExecute();
 
         assertJobNotReady();
@@ -242,12 +259,13 @@
             Log.d(TAG, "Skipping test since device doesn't support any constraints");
             return;
         }
-        mDeviceConfigStateHelper.set("fc_percents_to_drop_flexible_constraints",
+        setDeviceConfigFlag("fc_percents_to_drop_flexible_constraints",
                 "500=3|5|7|50"
                         + ",400=3|5|7|50"
                         + ",300=3|5|7|50"
                         + ",200=3|5|7|50"
-                        + ",100=3|5|7|50");
+                        + ",100=3|5|7|50",
+                true);
         try (TestAppInterface testAppInterface =
                      new TestAppInterface(getContext(), FLEXIBLE_JOB_ID)) {
             testAppInterface.scheduleJob(Collections.emptyMap(), Collections.emptyMap());
@@ -302,8 +320,9 @@
             return;
         }
         // Increase timeouts to make sure the test doesn't start passing because of transpired time.
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000");
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000",
+                true);
 
         scheduleJobToExecute();
 
@@ -312,7 +331,7 @@
         assertJobNotReady();
 
         // CONSTRAINT_BATTERY_NOT_LOW
-        mDeviceConfigStateHelper.set("fc_applied_constraints", "2");
+        setDeviceConfigFlag("fc_applied_constraints", "2", true);
 
         runJob();
         assertTrue("Job did not fire when applied constraints were satisfied",
@@ -342,8 +361,9 @@
             return;
         }
         // Increase timeouts to make sure the test doesn't start passing because of transpired time.
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000");
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000",
+                true);
         mNetworkingHelper.setWifiState(false);
 
         final int connectivityJobId = FLEXIBLE_JOB_ID;
@@ -367,7 +387,7 @@
             testAppInterface.assertJobNotReady(connectivityJobId);
 
             // CONSTRAINT_BATTERY_NOT_LOW
-            mDeviceConfigStateHelper.set("fc_applied_constraints", "2");
+            setDeviceConfigFlag("fc_applied_constraints", "2", true);
 
             satisfySystemWideConstraints(false, true, false);
 
@@ -381,7 +401,7 @@
 
             // CONSTRAINT_BATTERY_NOT_LOW | CONSTRAINT_CONNECTIVITY
             // Connectivity job needs both to run
-            mDeviceConfigStateHelper.set("fc_applied_constraints", "268435458");
+            setDeviceConfigFlag("fc_applied_constraints", "268435458", true);
             mNetworkingHelper.setWifiState(true);
 
             testAppInterface.runSatisfiedJob(connectivityJobId);
@@ -406,8 +426,9 @@
             return;
         }
         // Increase timeouts to make sure the test doesn't start passing because of transpired time.
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000");
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000",
+                true);
 
         scheduleJobToExecute();
 
@@ -416,7 +437,7 @@
         assertJobNotReady();
 
         // CONSTRAINT_CHARGING
-        mDeviceConfigStateHelper.set("fc_applied_constraints", "1");
+        setDeviceConfigFlag("fc_applied_constraints", "1", true);
 
         runJob();
         assertTrue("Job did not fire when applied constraints were satisfied",
@@ -445,8 +466,9 @@
             return;
         }
         // Increase timeouts to make sure the test doesn't start passing because of transpired time.
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000");
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000",
+                true);
         mNetworkingHelper.setWifiState(false);
 
         mBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
@@ -457,7 +479,7 @@
         assertJobNotReady();
 
         // CONSTRAINT_CONNECTIVITY
-        mDeviceConfigStateHelper.set("fc_applied_constraints", "268435456");
+        setDeviceConfigFlag("fc_applied_constraints", "268435456", true);
 
         runJob();
         assertTrue("Job did not fire when applied constraints were satisfied",
@@ -480,8 +502,9 @@
             return;
         }
         // Increase timeouts to make sure the test doesn't start passing because of transpired time.
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000");
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000",
+                true);
 
         scheduleJobToExecute();
 
@@ -490,7 +513,7 @@
         assertJobNotReady();
 
         // CONSTRAINT_IDLE
-        mDeviceConfigStateHelper.set("fc_applied_constraints", "4");
+        setDeviceConfigFlag("fc_applied_constraints", "4", true);
 
         runJob();
         assertTrue("Job did not fire when applied constraints were satisfied",
@@ -522,8 +545,9 @@
         }
 
         // Increase timeouts to make sure the test doesn't start passing because of transpired time.
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000");
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000",
+                true);
         satisfySystemWideConstraints(false, false, false);
 
         final int jobIdHigh = FLEXIBLE_JOB_ID;
@@ -580,8 +604,9 @@
         }
 
         // Increase timeouts to make sure the test doesn't start passing because of transpired time.
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000");
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000",
+                true);
         satisfySystemWideConstraints(false, false, false);
 
         final int jobIdHigh = FLEXIBLE_JOB_ID;
@@ -635,8 +660,9 @@
      */
     public void testTopBypassesFlexibility() throws Exception {
         // Increase timeouts to make sure the test doesn't start passing because of transpired time.
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000");
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=360000000,400=360000000,300=360000000,200=360000000,100=360000000",
+                true);
         satisfySystemWideConstraints(false, false, false);
         toggleScreenOn(true);
 
@@ -692,7 +718,7 @@
             Log.d(TAG, "Skipping test that requires device support required constraints");
             return;
         }
-        mDeviceConfigStateHelper.set("fc_flexibility_deadline_proximity_limit_ms", "95000");
+        setDeviceConfigFlag("fc_flexibility_deadline_proximity_limit_ms", "95000", true);
         // Let Flexibility Controller update.
         Thread.sleep(1_000L);
 
@@ -935,14 +961,14 @@
             Log.d(TAG, "Skipping test since device doesn't support any constraints");
             return;
         }
-        mDeviceConfigStateHelper.set("fc_percents_to_drop_flexible_constraints",
+        setDeviceConfigFlag("fc_percents_to_drop_flexible_constraints",
                 "500=3|5|7|50"
                         + ",400=3|5|7|50"
                         + ",300=3|5|7|50"
                         + ",200=3|5|7|50"
-                        + ",100=3|5|7|50");
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=100000,400=100000,300=360000000,200=360000000,100=360000000");
+                        + ",100=3|5|7|50", true);
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=100000,400=100000,300=360000000,200=360000000,100=360000000", true);
         final int jobIdHigh = FLEXIBLE_JOB_ID;
         final int jobIdDefault = FLEXIBLE_JOB_ID + 1;
         try (TestAppInterface testAppInterface =
@@ -990,14 +1016,15 @@
             Log.d(TAG, "Skipping test since device doesn't support any constraints");
             return;
         }
-        mDeviceConfigStateHelper.set("fc_percents_to_drop_flexible_constraints",
+        setDeviceConfigFlag("fc_percents_to_drop_flexible_constraints",
                 "500=3|5|7|50"
                         + ",400=3|5|7|50"
                         + ",300=90|92|95|99"
                         + ",200=90|92|95|99"
-                        + ",100=90|92|95|99");
-        mDeviceConfigStateHelper.set("fc_fallback_flexibility_deadlines",
-                "500=100000,400=100000,300=100000,200=100000,100=100000");
+                        + ",100=90|92|95|99",
+                true);
+        setDeviceConfigFlag("fc_fallback_flexibility_deadlines",
+                "500=100000,400=100000,300=100000,200=100000,100=100000", true);
         final int jobIdHigh = FLEXIBLE_JOB_ID;
         final int jobIdDefault = FLEXIBLE_JOB_ID + 1;
         try (TestAppInterface testAppInterface =
diff --git a/tests/app/Android.bp b/tests/app/Android.bp
index 4d16129..9866065 100644
--- a/tests/app/Android.bp
+++ b/tests/app/Android.bp
@@ -82,6 +82,20 @@
     per_testcase_directory: true,
 }
 
+android_ravenwood_test {
+    name: "CtsAppTestCasesRavenwood",
+    static_libs: [
+        "androidx.annotation_annotation",
+        "androidx.test.rules",
+        "compatibility-device-util-axt",
+    ],
+    srcs: [
+        "src/android/app/cts/ActivityOptionsTest.java",
+        "src/android/app/cts/BroadcastOptionsTest.java",
+    ],
+    auto_gen_config: true,
+}
+
 android_test {
     name: "CtsDownloadManagerApi28",
     defaults: ["cts_defaults"],
diff --git a/tests/app/src/android/app/cts/ActivityOptionsTest.java b/tests/app/src/android/app/cts/ActivityOptionsTest.java
index f0b12f7..04231c3 100644
--- a/tests/app/src/android/app/cts/ActivityOptionsTest.java
+++ b/tests/app/src/android/app/cts/ActivityOptionsTest.java
@@ -18,12 +18,20 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.junit.Assert.assertNotNull;
+
 import android.app.ActivityOptions;
 import android.os.Bundle;
-import android.test.AndroidTestCase;
 
-public class ActivityOptionsTest extends AndroidTestCase {
+import androidx.test.ext.junit.runners.AndroidJUnit4;
 
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class ActivityOptionsTest {
+
+    @Test
     public void testActivityOptionsBundle_makeBasic() throws Throwable {
         ActivityOptions options = ActivityOptions.makeBasic();
         Bundle bundle = options.toBundle();
@@ -31,6 +39,7 @@
         assertNotNull(bundle);
     }
 
+    @Test
     public void testGetPendingIntentBackgroundActivityLaunchAllowedDefault() {
         ActivityOptions options = ActivityOptions.makeBasic();
 
@@ -39,6 +48,7 @@
                 ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED);
     }
 
+    @Test
     public void testGetSetPendingIntentBackgroundActivityLaunchAllowedTrue() {
         ActivityOptions options = ActivityOptions.makeBasic();
         options.setPendingIntentBackgroundActivityLaunchAllowed(true);
@@ -47,6 +57,7 @@
                 ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
     }
 
+    @Test
     public void testGetSetPendingIntentBackgroundActivityLaunchAllowedFalse() {
         ActivityOptions options = ActivityOptions.makeBasic();
         options.setPendingIntentBackgroundActivityLaunchAllowed(false);
@@ -55,6 +66,7 @@
                 ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_DENIED);
     }
 
+    @Test
     public void testGetSetPendingIntentBackgroundActivityStartModeAllowed() {
         ActivityOptions options = ActivityOptions.makeBasic()
                 .setPendingIntentBackgroundActivityStartMode(
@@ -64,6 +76,7 @@
                 ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
     }
 
+    @Test
     public void testGetSetPendingIntentBackgroundActivityStartModeDenied() {
         ActivityOptions options = ActivityOptions.makeBasic()
                 .setPendingIntentBackgroundActivityStartMode(
@@ -89,6 +102,7 @@
         }
     }
 
+    @Test
     public void testGetPendingIntentCreatorBackgroundActivityLaunchAllowedDefault() {
         ActivityOptions options = ActivityOptions.makeBasic();
 
@@ -97,6 +111,7 @@
                 ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED);
     }
 
+    @Test
     public void testGetPendingIntentCreatorBackgroundActivityStartModeAllowed() {
         ActivityOptions options = ActivityOptions.makeBasic()
                 .setPendingIntentCreatorBackgroundActivityStartMode(
@@ -106,6 +121,7 @@
                 ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
     }
 
+    @Test
     public void testGetPendingIntentCreatorBackgroundActivityStartModeDenied() {
         ActivityOptions options = ActivityOptions.makeBasic()
                 .setPendingIntentCreatorBackgroundActivityStartMode(
diff --git a/tests/app/src/android/app/cts/BroadcastOptionsIntegrationTest.java b/tests/app/src/android/app/cts/BroadcastOptionsIntegrationTest.java
new file mode 100644
index 0000000..57828bb
--- /dev/null
+++ b/tests/app/src/android/app/cts/BroadcastOptionsIntegrationTest.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.app.cts;
+
+import static android.app.cts.ActivityManagerFgsBgStartTest.PACKAGE_NAME_APP1;
+import static android.app.cts.ActivityManagerFgsBgStartTest.PACKAGE_NAME_APP2;
+import static android.app.cts.ActivityManagerFgsBgStartTest.WAITFOR_MSEC;
+import static android.app.cts.BroadcastOptionsTest.cloneViaBundle;
+import static android.app.stubs.LocalForegroundService.ACTION_START_FGS_RESULT;
+
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import static org.junit.Assert.assertThrows;
+
+import android.app.BroadcastOptions;
+import android.app.Instrumentation;
+import android.app.cts.android.app.cts.tools.WaitForBroadcast;
+import android.app.stubs.CommandReceiver;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import com.android.compatibility.common.util.SystemUtil;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class BroadcastOptionsIntegrationTest {
+    private void assertBroadcastSuccess(BroadcastOptions options) {
+        final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+        final WaitForBroadcast waiter = new WaitForBroadcast(instrumentation.getTargetContext());
+        waiter.prepare(ACTION_START_FGS_RESULT);
+        CommandReceiver.sendCommandWithBroadcastOptions(instrumentation.getContext(),
+                CommandReceiver.COMMAND_START_FOREGROUND_SERVICE,
+                PACKAGE_NAME_APP1, PACKAGE_NAME_APP2, 0, null,
+                options.toBundle());
+        waiter.doWait(WAITFOR_MSEC);
+    }
+
+    private void assertBroadcastFailure(BroadcastOptions options) {
+        final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+        final WaitForBroadcast waiter = new WaitForBroadcast(instrumentation.getTargetContext());
+        waiter.prepare(ACTION_START_FGS_RESULT);
+        CommandReceiver.sendCommandWithBroadcastOptions(instrumentation.getContext(),
+                CommandReceiver.COMMAND_START_FOREGROUND_SERVICE,
+                PACKAGE_NAME_APP1, PACKAGE_NAME_APP2, 0, null,
+                options.toBundle());
+        assertThrows(Exception.class, () -> waiter.doWait(WAITFOR_MSEC));
+    }
+
+    @Test
+    public void testRequireCompatChange_simple() {
+        SystemUtil.runWithShellPermissionIdentity(() -> {
+            final int uid = android.os.Process.myUid();
+            final BroadcastOptions options = BroadcastOptions.makeBasic();
+
+            // Default passes
+            assertTrue(options.testRequireCompatChange(uid));
+            assertTrue(cloneViaBundle(options).testRequireCompatChange(uid));
+
+            // Verify both enabled and disabled
+            options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_ENABLED, true);
+            assertTrue(options.testRequireCompatChange(uid));
+            assertTrue(cloneViaBundle(options).testRequireCompatChange(uid));
+            options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_ENABLED, false);
+            assertFalse(options.testRequireCompatChange(uid));
+            assertFalse(cloneViaBundle(options).testRequireCompatChange(uid));
+
+            // And back to default passes
+            options.clearRequireCompatChange();
+            assertTrue(options.testRequireCompatChange(uid));
+            assertTrue(cloneViaBundle(options).testRequireCompatChange(uid));
+        });
+    }
+
+    @Test
+    public void testRequireCompatChange_enabled_success() {
+        final BroadcastOptions options = BroadcastOptions.makeBasic();
+        options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_ENABLED, true);
+        assertBroadcastSuccess(options);
+    }
+
+    @Test
+    public void testRequireCompatChange_enabled_failure() {
+        final BroadcastOptions options = BroadcastOptions.makeBasic();
+        options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_DISABLED, true);
+        assertBroadcastFailure(options);
+    }
+
+    @Test
+    public void testRequireCompatChange_disabled_success() {
+        final BroadcastOptions options = BroadcastOptions.makeBasic();
+        options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_DISABLED, false);
+        assertBroadcastSuccess(options);
+    }
+
+    @Test
+    public void testRequireCompatChange_disabled_failure() {
+        final BroadcastOptions options = BroadcastOptions.makeBasic();
+        options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_ENABLED, false);
+        assertBroadcastFailure(options);
+    }
+}
diff --git a/tests/app/src/android/app/cts/BroadcastOptionsTest.java b/tests/app/src/android/app/cts/BroadcastOptionsTest.java
index 5a3d602..0b52c30 100644
--- a/tests/app/src/android/app/cts/BroadcastOptionsTest.java
+++ b/tests/app/src/android/app/cts/BroadcastOptionsTest.java
@@ -16,11 +16,6 @@
 
 package android.app.cts;
 
-import static android.app.cts.ActivityManagerFgsBgStartTest.PACKAGE_NAME_APP1;
-import static android.app.cts.ActivityManagerFgsBgStartTest.PACKAGE_NAME_APP2;
-import static android.app.cts.ActivityManagerFgsBgStartTest.WAITFOR_MSEC;
-import static android.app.stubs.LocalForegroundService.ACTION_START_FGS_RESULT;
-
 import static com.google.common.truth.Truth.assertThat;
 
 import static junit.framework.Assert.assertEquals;
@@ -28,19 +23,11 @@
 import static junit.framework.Assert.assertTrue;
 
 import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThrows;
 
 import android.app.BroadcastOptions;
-import android.app.Instrumentation;
-import android.app.cts.android.app.cts.tools.WaitForBroadcast;
-import android.app.stubs.CommandReceiver;
-import android.content.IntentFilter;
 import android.os.Build;
-import android.os.Bundle;
-import android.os.PersistableBundle;
 import android.os.PowerExemptionManager;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.ext.junit.runners.AndroidJUnit4;
 
 import com.android.compatibility.common.util.SystemUtil;
@@ -50,11 +37,10 @@
 
 @RunWith(AndroidJUnit4.class)
 public class BroadcastOptionsTest {
-
     /**
      * Creates a clone of BroadcastOptions, using toBundle().
      */
-    private BroadcastOptions cloneViaBundle(BroadcastOptions bo) {
+    static BroadcastOptions cloneViaBundle(BroadcastOptions bo) {
         return BroadcastOptions.fromBundle(bo.toBundle());
     }
 
@@ -222,81 +208,6 @@
                 BroadcastOptions.MODE_BACKGROUND_ACTIVITY_START_DENIED);
     }
 
-    private void assertBroadcastSuccess(BroadcastOptions options) {
-        final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
-        final WaitForBroadcast waiter = new WaitForBroadcast(instrumentation.getTargetContext());
-        waiter.prepare(ACTION_START_FGS_RESULT);
-        CommandReceiver.sendCommandWithBroadcastOptions(instrumentation.getContext(),
-                CommandReceiver.COMMAND_START_FOREGROUND_SERVICE,
-                PACKAGE_NAME_APP1, PACKAGE_NAME_APP2, 0, null,
-                options.toBundle());
-        waiter.doWait(WAITFOR_MSEC);
-    }
-
-    private void assertBroadcastFailure(BroadcastOptions options) {
-        final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
-        final WaitForBroadcast waiter = new WaitForBroadcast(instrumentation.getTargetContext());
-        waiter.prepare(ACTION_START_FGS_RESULT);
-        CommandReceiver.sendCommandWithBroadcastOptions(instrumentation.getContext(),
-                CommandReceiver.COMMAND_START_FOREGROUND_SERVICE,
-                PACKAGE_NAME_APP1, PACKAGE_NAME_APP2, 0, null,
-                options.toBundle());
-        assertThrows(Exception.class, () -> waiter.doWait(WAITFOR_MSEC));
-    }
-
-    @Test
-    public void testRequireCompatChange_simple() {
-        SystemUtil.runWithShellPermissionIdentity(() -> {
-            final int uid = android.os.Process.myUid();
-            final BroadcastOptions options = BroadcastOptions.makeBasic();
-
-            // Default passes
-            assertTrue(options.testRequireCompatChange(uid));
-            assertTrue(cloneViaBundle(options).testRequireCompatChange(uid));
-
-            // Verify both enabled and disabled
-            options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_ENABLED, true);
-            assertTrue(options.testRequireCompatChange(uid));
-            assertTrue(cloneViaBundle(options).testRequireCompatChange(uid));
-            options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_ENABLED, false);
-            assertFalse(options.testRequireCompatChange(uid));
-            assertFalse(cloneViaBundle(options).testRequireCompatChange(uid));
-
-            // And back to default passes
-            options.clearRequireCompatChange();
-            assertTrue(options.testRequireCompatChange(uid));
-            assertTrue(cloneViaBundle(options).testRequireCompatChange(uid));
-        });
-    }
-
-    @Test
-    public void testRequireCompatChange_enabled_success() {
-        final BroadcastOptions options = BroadcastOptions.makeBasic();
-        options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_ENABLED, true);
-        assertBroadcastSuccess(options);
-    }
-
-    @Test
-    public void testRequireCompatChange_enabled_failure() {
-        final BroadcastOptions options = BroadcastOptions.makeBasic();
-        options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_DISABLED, true);
-        assertBroadcastFailure(options);
-    }
-
-    @Test
-    public void testRequireCompatChange_disabled_success() {
-        final BroadcastOptions options = BroadcastOptions.makeBasic();
-        options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_DISABLED, false);
-        assertBroadcastSuccess(options);
-    }
-
-    @Test
-    public void testRequireCompatChange_disabled_failure() {
-        final BroadcastOptions options = BroadcastOptions.makeBasic();
-        options.setRequireCompatChange(BroadcastOptions.CHANGE_ALWAYS_ENABLED, false);
-        assertBroadcastFailure(options);
-    }
-
     @Test
     public void testSetGetDeferralPolicy() {
         final BroadcastOptions options = BroadcastOptions.makeBasic();
diff --git a/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java b/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
index f479efa..562e28b 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
@@ -2884,8 +2884,6 @@
                                 " Preview size is " + previewSize + ", repeating is " + repeating);
                     }
                     requestBuilder.set(CaptureRequest.SCALER_CROP_REGION, cropRegions[i]);
-                    requestBuilder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE,
-                            CameraMetadata.CONTROL_VIDEO_STABILIZATION_MODE_OFF);
                     requests[i] = requestBuilder.build();
                     if (VERBOSE) {
                         Log.v(TAG, "submit crop region " + cropRegions[i]);
@@ -2934,32 +2932,36 @@
                                      previousCrop.height() > currentCrop.height()));
                     }
 
-                    if (mStaticInfo.isHardwareLevelAtLeastLimited()) {
-                        mCollector.expectRectsAreSimilar(
-                                "Request and result crop region should be similar",
-                                cropRegions[i], cropRegion, CROP_REGION_ERROR_PERCENT_DELTA);
-                    }
+                    if (CameraTestUtils.isStabilizationOff(requests[i])) {
+                        if (mStaticInfo.isHardwareLevelAtLeastLimited()) {
+                            mCollector.expectRectsAreSimilar(
+                                    "Request and result crop region should be similar",
+                                    cropRegions[i], cropRegion, CROP_REGION_ERROR_PERCENT_DELTA);
+                        }
 
-                    if (croppingType == SCALER_CROPPING_TYPE_CENTER_ONLY) {
-                        mCollector.expectRectCentered(
-                                "Result crop region should be centered inside the active array",
-                                new Size(activeArraySize.width(), activeArraySize.height()),
-                                cropRegion, CROP_REGION_ERROR_PERCENT_CENTERED);
-                    }
+                        if (croppingType == SCALER_CROPPING_TYPE_CENTER_ONLY) {
+                            mCollector.expectRectCentered(
+                                    "Result crop region should be centered inside the active array",
+                                    new Size(activeArraySize.width(), activeArraySize.height()),
+                                    cropRegion, CROP_REGION_ERROR_PERCENT_CENTERED);
+                        }
 
-                    /*
-                     * Validate resulting metering regions
-                     */
+                        /*
+                         * Validate resulting metering regions
+                         */
 
-                    // Use the actual reported crop region to calculate the resulting metering region
-                    expectRegions[i] = getExpectedOutputRegion(
-                            /*requestRegion*/meteringRect,
-                            /*cropRect*/     cropRegion);
+                        // Use the actual reported crop region to calculate the resulting
+                        // metering region
+                        expectRegions[i] = getExpectedOutputRegion(
+                                /*requestRegion*/meteringRect,
+                                /*cropRect*/     cropRegion);
 
-                    // Verify Output 3A region is intersection of input 3A region and crop region
-                    for (int algo = 0; algo < NUM_ALGORITHMS; algo++) {
-                        validate3aRegion(result, partialResults, algo, expectRegions[i],
-                                false/*scaleByZoomRatio*/, mStaticInfo);
+                        // Verify Output 3A region is intersection of input 3A region and
+                        // crop region
+                        for (int algo = 0; algo < NUM_ALGORITHMS; algo++) {
+                            validate3aRegion(result, partialResults, algo, expectRegions[i],
+                                    false/*scaleByZoomRatio*/, mStaticInfo);
+                        }
                     }
 
                     previousCrop = cropRegion;
@@ -3032,8 +3034,6 @@
             }
             requestBuilder.set(CaptureRequest.CONTROL_ZOOM_RATIO, zoomFactor);
             requestBuilder.set(CaptureRequest.SCALER_CROP_REGION, defaultCropRegion);
-            requestBuilder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE,
-                    CameraMetadata.CONTROL_VIDEO_STABILIZATION_MODE_OFF);
             CaptureRequest request = requestBuilder.build();
             for (int j = 0; j < captureSubmitRepeat; ++j) {
                 mSession.capture(request, listener, mHandler);
@@ -3074,40 +3074,42 @@
                     Math.abs(previousRatio - resultZoomRatio) < ZOOM_ERROR_MARGIN ||
                         (previousRatio < resultZoomRatio));
 
-            mCollector.expectTrue(String.format(
-                    "Request and result zoom ratio should be similar " +
-                    "(requested = %f, result = %f", zoomFactor, resultZoomRatio),
-                    Math.abs(zoomFactor - resultZoomRatio)/zoomFactor <= ZOOM_ERROR_MARGIN);
+            if (CameraTestUtils.isStabilizationOff(request)) {
+                mCollector.expectTrue(String.format(
+                        "Request and result zoom ratio should be similar "
+                        + "(requested = %f, result = %f", zoomFactor, resultZoomRatio),
+                        Math.abs(zoomFactor - resultZoomRatio) / zoomFactor <= ZOOM_ERROR_MARGIN);
 
-            //In case zoom ratio is converted to crop region at HAL, due to error magnification
-            //when converting to post-zoom crop region, scale the error threshold for crop region
-            //check.
-            float errorMultiplier = Math.max(1.0f, zoomFactor);
-            if (mStaticInfo.isHardwareLevelAtLeastLimited()) {
-                mCollector.expectRectsAreSimilar(
-                        "Request and result crop region should be similar",
-                        defaultCropRegion, cropRegion,
-                        CROP_REGION_ERROR_PERCENT_DELTA * errorMultiplier);
-            }
+                //In case zoom ratio is converted to crop region at HAL, due to error magnification
+                //when converting to post-zoom crop region, scale the error threshold for crop
+                //region check.
+                float errorMultiplier = Math.max(1.0f, zoomFactor);
+                if (mStaticInfo.isHardwareLevelAtLeastLimited()) {
+                    mCollector.expectRectsAreSimilar(
+                            "Request and result crop region should be similar",
+                            defaultCropRegion, cropRegion,
+                            CROP_REGION_ERROR_PERCENT_DELTA * errorMultiplier);
+                }
 
-            mCollector.expectRectCentered(
-                    "Result crop region should be centered inside the active array",
-                    new Size(activeArraySize.width(), activeArraySize.height()),
-                    cropRegion, CROP_REGION_ERROR_PERCENT_CENTERED * errorMultiplier);
+                mCollector.expectRectCentered(
+                        "Result crop region should be centered inside the active array",
+                        new Size(activeArraySize.width(), activeArraySize.height()),
+                        cropRegion, CROP_REGION_ERROR_PERCENT_CENTERED * errorMultiplier);
 
-            /*
-             * Validate resulting metering regions
-             */
-            // Use the actual reported crop region to calculate the resulting metering region
-            expectRegions[i] = getExpectedOutputRegion(
-                    /*requestRegion*/defaultMeteringRect,
-                    /*cropRect*/     cropRegion);
+                /*
+                 * Validate resulting metering regions
+                 */
+                // Use the actual reported crop region to calculate the resulting metering region
+                expectRegions[i] = getExpectedOutputRegion(
+                        /*requestRegion*/defaultMeteringRect,
+                        /*cropRect*/     cropRegion);
 
-            // Verify Output 3A region is intersection of input 3A region and crop region
-            boolean scaleByZoomRatio = zoomFactor > 1.0f;
-            for (int algo = 0; algo < NUM_ALGORITHMS; algo++) {
-                validate3aRegion(result, partialResults, algo, expectRegions[i], scaleByZoomRatio,
-                        mStaticInfo);
+                // Verify Output 3A region is intersection of input 3A region and crop region
+                boolean scaleByZoomRatio = zoomFactor > 1.0f;
+                for (int algo = 0; algo < NUM_ALGORITHMS; algo++) {
+                    validate3aRegion(result, partialResults, algo, expectRegions[i],
+                            scaleByZoomRatio, mStaticInfo);
+                }
             }
 
             previousRatio = resultZoomRatio;
@@ -3277,8 +3279,6 @@
         Size maxPreviewSize = mOrderedPreviewSizes.get(0);
         CaptureRequest.Builder requestBuilder =
                 mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
-        requestBuilder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE,
-                CameraMetadata.CONTROL_VIDEO_STABILIZATION_MODE_OFF);
 
         for (Capability cap : extendedSceneModeCaps) {
             int mode = cap.getMode();
@@ -3301,8 +3301,10 @@
                 verifyCaptureResultForKey(CaptureResult.CONTROL_EXTENDED_SCENE_MODE,
                         mode, listener, NUM_FRAMES_VERIFIED);
                 float zoomRatioDelta = ZOOM_RATIO_ERROR_PERCENT_DELTA * ratio;
-                verifyCaptureResultForKey(CaptureResult.CONTROL_ZOOM_RATIO,
-                        ratio, listener, NUM_FRAMES_VERIFIED, zoomRatioDelta);
+                if (CameraTestUtils.isStabilizationOff(requestBuilder.build())) {
+                    verifyCaptureResultForKey(CaptureResult.CONTROL_ZOOM_RATIO,
+                            ratio, listener, NUM_FRAMES_VERIFIED, zoomRatioDelta);
+                }
             }
         }
     }
diff --git a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
index 8ef8404..e5ac608 100644
--- a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
@@ -28,41 +28,41 @@
 import android.hardware.camera2.CaptureRequest;
 import android.hardware.camera2.CaptureResult;
 import android.hardware.camera2.DngCreator;
-import android.hardware.camera2.params.DynamicRangeProfiles;
-import android.hardware.camera2.params.OutputConfiguration;
-import android.location.Location;
-import android.location.LocationManager;
-import android.media.ImageReader;
-import android.util.Pair;
-import android.util.Size;
 import android.hardware.camera2.cts.CameraTestUtils.SimpleCaptureCallback;
 import android.hardware.camera2.cts.CameraTestUtils.SimpleImageReaderListener;
 import android.hardware.camera2.cts.helpers.Camera2Focuser;
 import android.hardware.camera2.cts.helpers.StaticMetadata;
 import android.hardware.camera2.cts.testcases.Camera2SurfaceViewTestCase;
+import android.hardware.camera2.params.DynamicRangeProfiles;
 import android.hardware.camera2.params.MeteringRectangle;
+import android.hardware.camera2.params.OutputConfiguration;
+import android.location.Location;
+import android.location.LocationManager;
 import android.media.Image;
+import android.media.ImageReader;
 import android.os.ConditionVariable;
 import android.util.Log;
+import android.util.Pair;
 import android.util.Range;
 import android.util.Rational;
+import android.util.Size;
 import android.view.Surface;
 
 import com.android.ex.camera2.blocking.BlockingSessionCallback;
 import com.android.ex.camera2.exceptions.TimeoutRuntimeException;
 
+import junit.framework.Assert;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
 import java.io.ByteArrayOutputStream;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Set;
 
-import junit.framework.Assert;
-
-import org.junit.runners.Parameterized;
-import org.junit.runner.RunWith;
-import org.junit.Test;
-
 @RunWith(Parameterized.class)
 public class StillCaptureTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "StillCaptureTest";
@@ -980,7 +980,7 @@
         mCollector.expectEquals("AWB mode in result and request should be same",
                 previewRequest.get(CaptureRequest.CONTROL_AWB_MODE),
                 result.get(CaptureResult.CONTROL_AWB_MODE));
-        if (canSetAwbRegion) {
+        if (canSetAwbRegion && CameraTestUtils.isStabilizationOff(previewRequest.build())) {
             MeteringRectangle[] resultAwbRegions =
                     getValueNotNull(result, CaptureResult.CONTROL_AWB_REGIONS);
             mCollector.expectEquals("AWB regions in result and request should be same",
@@ -1024,7 +1024,7 @@
         mCollector.expectEquals("AE mode in result and request should be same",
                 previewRequest.get(CaptureRequest.CONTROL_AE_MODE),
                 result.get(CaptureResult.CONTROL_AE_MODE));
-        if (canSetAeRegion) {
+        if (canSetAeRegion && CameraTestUtils.isStabilizationOff(previewRequest.build())) {
             MeteringRectangle[] resultAeRegions =
                     getValueNotNull(result, CaptureResult.CONTROL_AE_REGIONS);
 
@@ -1046,7 +1046,7 @@
         mCollector.expectEquals("AF mode in result and request should be same",
                 stillRequest.get(CaptureRequest.CONTROL_AF_MODE),
                 result.get(CaptureResult.CONTROL_AF_MODE));
-        if (canSetAfRegion) {
+        if (canSetAfRegion && CameraTestUtils.isStabilizationOff(stillRequest.build())) {
             MeteringRectangle[] resultAfRegions =
                     getValueNotNull(result, CaptureResult.CONTROL_AF_REGIONS);
             mCollector.expectMeteringRegionsAreSimilar(
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
index 66619fd..e938373 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
@@ -5203,4 +5203,19 @@
                     externalCameraConnected);
         }
     }
+
+    /**
+     * Check if the camera device keeps stabilization off
+     *
+     * @param result The capture request builder
+     * @return true if stabilization is OFF
+     */
+    public static boolean isStabilizationOff(CaptureRequest request) {
+        Integer stabilizationMode = request.get(
+                CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE);
+        assertNotNull("Value of Key CONTROL_VIDEO_STABILIZATION_MODE shouldn't be null",
+                stabilizationMode);
+
+        return (stabilizationMode == CameraMetadata.CONTROL_VIDEO_STABILIZATION_MODE_OFF);
+    }
 }
diff --git a/tests/devicepolicy/src/android/devicepolicy/cts/ProvisioningTest.kt b/tests/devicepolicy/src/android/devicepolicy/cts/ProvisioningTest.kt
index 975d655..c5328b5 100644
--- a/tests/devicepolicy/src/android/devicepolicy/cts/ProvisioningTest.kt
+++ b/tests/devicepolicy/src/android/devicepolicy/cts/ProvisioningTest.kt
@@ -1392,6 +1392,16 @@
         ).isFalse()
     }
 
+    @Postsubmit(reason = "new test")
+    @ApiTest(apis = ["android.app.admin.DevicePolicyManager#isProvisioningAllowed"])
+    @Test
+    @EnsureHasDeviceOwner
+    fun isProvisioningAllowed_hasDeviceOwner_returnsFalse() {
+    assertThat(
+      localDevicePolicyManager.isProvisioningAllowed(
+        DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE
+    )).isFalse()
+    }
     @Throws(IOException::class)
     private fun createNfcIntentFromMap(input: Map<String, String>): Intent {
         return createNfcIntent(
diff --git a/tests/inputmethod/src/android/view/inputmethod/cts/InputMethodStatsTest.java b/tests/inputmethod/src/android/view/inputmethod/cts/InputMethodStatsTest.java
index 2e31057..5844194 100644
--- a/tests/inputmethod/src/android/view/inputmethod/cts/InputMethodStatsTest.java
+++ b/tests/inputmethod/src/android/view/inputmethod/cts/InputMethodStatsTest.java
@@ -29,9 +29,12 @@
 import android.app.Activity;
 import android.app.Instrumentation;
 import android.platform.test.annotations.AppModeSdkSandbox;
+import android.support.test.uiautomator.UiDevice;
+import android.view.MotionEvent;
 import android.view.WindowInsets;
 import android.view.WindowInsetsController.OnControllableInsetsChangedListener;
 import android.view.WindowManager;
+import android.view.inputmethod.InputMethodManager;
 import android.view.inputmethod.cts.util.EndToEndImeTestBase;
 import android.view.inputmethod.cts.util.MetricsRecorder;
 import android.view.inputmethod.cts.util.TestActivity;
@@ -39,6 +42,7 @@
 import android.view.inputmethod.nano.ImeProtoEnums;
 import android.widget.EditText;
 import android.widget.LinearLayout;
+import android.widget.TextView;
 
 import androidx.annotation.NonNull;
 import androidx.test.ext.junit.runners.AndroidJUnit4;
@@ -66,6 +70,9 @@
 
     private static final String TAG = "InputMethodStatsTest";
 
+    private static final int EDIT_TEXT_ID = 1;
+    private static final int TEXT_VIEW_ID = 2;
+
     private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(20);
 
     private Instrumentation mInstrumentation;
@@ -117,8 +124,15 @@
         layout.setOrientation(LinearLayout.VERTICAL);
 
         final var editText = new EditText(activity);
+        editText.setId(EDIT_TEXT_ID);
         editText.setText("Editable");
+
+        final var textView = new TextView(activity);
+        textView.setId(TEXT_VIEW_ID);
+        textView.setText("Not Editable");
+
         layout.addView(editText);
+        layout.addView(textView);
         editText.requestFocus();
         activity.getWindow().setSoftInputMode(mode);
         return layout;
@@ -171,7 +185,7 @@
     @Test
     public void testClientShowImeRequestFinished() throws Throwable {
         verifyLogging(true /* show */, ImeProtoEnums.ORIGIN_CLIENT_SHOW_SOFT_INPUT,
-                (imeSession, activity) -> {
+                false /* fromUser */, (imeSession, activity) -> {
                     awaitControl(WindowInsets.Type.ime(), activity);
                     expectImeInvisible(TIMEOUT);
 
@@ -190,7 +204,7 @@
     @Test
     public void testClientHideImeRequestFinished() throws Exception {
         verifyLogging(false /* show */, ImeProtoEnums.ORIGIN_CLIENT_HIDE_SOFT_INPUT,
-                (imeSession, activity) -> {
+                false /* fromUser */, (imeSession, activity) -> {
                     TestUtils.runOnMainSync(() -> activity.getWindow()
                             .getDecorView()
                             .getWindowInsetsController()
@@ -206,7 +220,7 @@
     @Test
     public void testServerShowImeRequestFinished() throws Exception {
         verifyLogging(true /* show */, ImeProtoEnums.ORIGIN_SERVER_START_INPUT,
-                (imeSession, activity) -> {
+                false /* fromUser */, (imeSession, activity) -> {
                     createTestActivity(SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                     expectImeVisible(TIMEOUT);
                 });
@@ -218,7 +232,7 @@
     @Test
     public void testServerHideImeRequestFinished() throws Exception {
         verifyLogging(false /* show */, ImeProtoEnums.ORIGIN_SERVER_HIDE_INPUT,
-                (imeSession, activity) -> {
+                false /* fromUser */, (imeSession, activity) -> {
                     // TODO: this is not actually an IME hide request from the server,
                     //  but in the current configuration it is tracked like one.
                     //  Will likely change in the future.
@@ -229,14 +243,130 @@
     }
 
     /**
+     * Test the logging for a user interaction show IME request using InputMethodManager.
+     */
+    @Test
+    public void testFromUser_withImm_showImeRequestFinished() throws Exception {
+        verifyLogging(true /* show */, ImeProtoEnums.ORIGIN_CLIENT_SHOW_SOFT_INPUT,
+                true /* fromUser */, (imeSession, activity) -> {
+                    final EditText editText = activity.requireViewById(EDIT_TEXT_ID);
+                    editText.setShowSoftInputOnFocus(false);
+                    // onClickListener is run later, so ViewRootImpl#isHandlingPointeEvent will
+                    // be false. onTouchListener runs immediately, so the value will be true.
+                    editText.setOnTouchListener((v, ev) -> {
+                        // Three motion events are sent, only react to one of them.
+                        if (ev.getAction() != MotionEvent.ACTION_DOWN) {
+                            return false;
+                        }
+                        editText.getContext().getSystemService(InputMethodManager.class)
+                                .showSoftInput(editText, 0 /* flags */);
+                        return true;
+                    });
+                    mCtsTouchUtils.emulateTapOnViewCenter(mInstrumentation, null, editText);
+
+                    expectImeVisible(TIMEOUT);
+                });
+    }
+
+    /**
+     * Test the logging for a user interaction hide IME request using InputMethodManager.
+     */
+    @Test
+    public void testFromUser_withImm_hideImeRequestFinished() throws Exception {
+        verifyLogging(false /* show */, ImeProtoEnums.ORIGIN_CLIENT_HIDE_SOFT_INPUT,
+                true /* formUser */, (imeSession, activity) -> {
+                    final TextView textView = activity.requireViewById(TEXT_VIEW_ID);
+                    // onClickListener is run later, so ViewRootImpl#isHandlingPointeEvent will
+                    // be false. onTouchListener runs immediately, so the value will be true.
+                    textView.setOnTouchListener((v, ev) -> {
+                        // Three motion events are sent, only react to one of them.
+                        if (ev.getActionMasked() != MotionEvent.ACTION_DOWN) {
+                            return false;
+                        }
+                        textView.getContext().getSystemService(InputMethodManager.class)
+                                .hideSoftInputFromWindow(textView.getWindowToken(), 0 /* flags */);
+                        return true;
+                    });
+                    mCtsTouchUtils.emulateTapOnViewCenter(mInstrumentation, null, textView);
+
+                    expectImeInvisible(TIMEOUT);
+                });
+    }
+
+    /**
+     * Test the logging for a user interaction show IME request using WindowInsetsController.
+     */
+    @Test
+    public void testFromUser_withWic_showImeRequestFinished() throws Exception {
+        verifyLogging(true /* show */, ImeProtoEnums.ORIGIN_CLIENT_SHOW_SOFT_INPUT,
+                true /* fromUser */, (imeSession, activity) -> {
+                    final EditText editText = activity.requireViewById(EDIT_TEXT_ID);
+                    editText.setShowSoftInputOnFocus(false);
+                    // onClickListener is run later, so ViewRootImpl#isHandlingPointeEvent will
+                    // be false. onTouchListener runs immediately, so the value will be true.
+                    editText.setOnTouchListener((v, ev) -> {
+                        // Three motion events are sent, only react to one of them.
+                        if (ev.getActionMasked() != MotionEvent.ACTION_DOWN) {
+                            return false;
+                        }
+                        activity.getWindow().getInsetsController().show(WindowInsets.Type.ime());
+                        return true;
+                    });
+                    mCtsTouchUtils.emulateTapOnViewCenter(mInstrumentation, null, editText);
+
+                    expectImeVisible(TIMEOUT);
+                });
+    }
+
+    /**
+     * Test the logging for a user interaction hide IME request using WindowInsetsController.
+     */
+    @Test
+    public void testFromUser_withWic_hideImeRequestFinished() throws Exception {
+        verifyLogging(false /* show */, ImeProtoEnums.ORIGIN_CLIENT_HIDE_SOFT_INPUT,
+                true /* fromUser */, (imeSession, activity) -> {
+                    final TextView textView = activity.requireViewById(TEXT_VIEW_ID);
+                    // onClickListener is run later, so ViewRootImpl#isHandlingPointeEvent will
+                    // be false. onTouchListener runs immediately, so the value will be true.
+                    textView.setOnTouchListener((v, ev) -> {
+                        // Three motion events are sent, only react to one of them.
+                        if (ev.getActionMasked() != MotionEvent.ACTION_DOWN) {
+                            return false;
+                        }
+                        activity.getWindow().getInsetsController().hide(WindowInsets.Type.ime());
+                        return true;
+                    });
+                    mCtsTouchUtils.emulateTapOnViewCenter(mInstrumentation, null, textView);
+
+                    expectImeInvisible(TIMEOUT);
+                });
+    }
+
+    /**
+     * Test the logging for a user interaction hide IME request using back button press.
+     */
+    @Test
+    public void testFromUser_withBackPress_hideImeRequestFinished() throws Exception {
+        verifyLogging(false /* show */, ImeProtoEnums.ORIGIN_SERVER_HIDE_INPUT,
+                true /* fromUser */, (imeSession, activity) -> {
+                    UiDevice.getInstance(mInstrumentation)
+                            .pressBack();
+
+                    expectImeInvisible(TIMEOUT);
+                });
+    }
+
+    /**
      * Verifies the logged atom events for the given test runnable and expected values.
      *
      * @param show     whether this is testing a show request (starts with IME hidden),
      *                 or hide request (starts with IME shown).
      * @param origin   the expected IME request origin.
+     * @param fromUser whether this request is expected to be created from user interaction.
      * @param runnable the runnable with the test code to execute.
      */
-    private void verifyLogging(boolean show, int origin, TestRunnable runnable) throws Exception {
+    private void verifyLogging(boolean show, int origin, boolean fromUser,
+            TestRunnable runnable) throws Exception {
         // Create mockImeSession to decouple from real IMEs,
         // and enable calling expectImeVisible and expectImeInvisible.
         try (var imeSession = MockImeSession.create(
@@ -305,6 +435,12 @@
                     assertWithMessage("Ime Request origin")
                             .that(imeRequestFinished.origin)
                             .isEqualTo(origin);
+                    if (fromUser) {
+                        // Assert only when fromUser was expected to be true.
+                        assertWithMessage("Ime Request fromUser")
+                                .that(imeRequestFinished.fromUser)
+                                .isEqualTo(true);
+                    }
                 }
 
                 // Must have at least one successful request received.
diff --git a/tests/location/location_none/src/android/location/cts/none/AltitudeConverterTest.java b/tests/location/location_none/src/android/location/cts/none/AltitudeConverterTest.java
index e5a3954..78618e0 100644
--- a/tests/location/location_none/src/android/location/cts/none/AltitudeConverterTest.java
+++ b/tests/location/location_none/src/android/location/cts/none/AltitudeConverterTest.java
@@ -56,7 +56,7 @@
         location.setAltitude(-1);
         location.setVerticalAccuracyMeters(1);
         // Requires data to be loaded from raw assets.
-        assertThat(mAltitudeConverter.addMslAltitudeToLocation(location)).isFalse();
+        assertThat(mAltitudeConverter.tryAddMslAltitudeToLocation(location)).isFalse();
         assertThat(location.hasMslAltitude()).isFalse();
         assertThat(location.hasMslAltitudeAccuracy()).isFalse();
         // Loads data from raw assets.
@@ -73,7 +73,7 @@
         location.setAltitude(-1);
         location.setVerticalAccuracyMeters(-1); // Invalid vertical accuracy
         // Requires no data to be loaded from raw assets.
-        assertThat(mAltitudeConverter.addMslAltitudeToLocation(location)).isTrue();
+        assertThat(mAltitudeConverter.tryAddMslAltitudeToLocation(location)).isTrue();
         assertThat(location.getMslAltitudeMeters()).isWithin(2).of(5.0622);
         assertThat(location.hasMslAltitudeAccuracy()).isFalse();
         // Results in same outcome.
@@ -88,7 +88,7 @@
         location.setAltitude(-1);
         location.setVerticalAccuracyMeters(1);
         // Requires data to be loaded from raw assets.
-        assertThat(mAltitudeConverter.addMslAltitudeToLocation(location)).isFalse();
+        assertThat(mAltitudeConverter.tryAddMslAltitudeToLocation(location)).isFalse();
         assertThat(location.hasMslAltitude()).isFalse();
         assertThat(location.hasMslAltitudeAccuracy()).isFalse();
         // Loads data from raw assets.
diff --git a/tests/smartspace/Android.bp b/tests/smartspace/Android.bp
index 1135137..068b6b9 100644
--- a/tests/smartspace/Android.bp
+++ b/tests/smartspace/Android.bp
@@ -20,6 +20,7 @@
     name: "CtsSmartspaceServiceTestCases",
     defaults: ["cts_defaults"],
     static_libs: [
+        "android.app.smartspace.flags-aconfig-java",
         "androidx.annotation_annotation",
         "compatibility-device-util-axt",
         "ctstestrunner-axt",
diff --git a/tests/smartspace/src/android/smartspace/cts/SmartspaceTargetTest.java b/tests/smartspace/src/android/smartspace/cts/SmartspaceTargetTest.java
index 7d9101f..2b0e707 100644
--- a/tests/smartspace/src/android/smartspace/cts/SmartspaceTargetTest.java
+++ b/tests/smartspace/src/android/smartspace/cts/SmartspaceTargetTest.java
@@ -23,6 +23,7 @@
 
 import android.app.smartspace.SmartspaceAction;
 import android.app.smartspace.SmartspaceTarget;
+import android.app.smartspace.flags.Flags;
 import android.app.smartspace.uitemplatedata.BaseTemplateData;
 import android.app.smartspace.uitemplatedata.BaseTemplateData.SubItemInfo;
 import android.app.smartspace.uitemplatedata.BaseTemplateData.SubItemLoggingInfo;
@@ -32,6 +33,7 @@
 import android.net.Uri;
 import android.os.Parcel;
 import android.os.Process;
+import android.platform.test.annotations.RequiresFlagsEnabled;
 import android.widget.RemoteViews;
 
 import androidx.test.runner.AndroidJUnit4;
@@ -117,6 +119,7 @@
         assertThat(testTarget.getWidget().provider).isEqualTo(testComponentName);
     }
 
+    @RequiresFlagsEnabled(Flags.FLAG_REMOTE_VIEWS)
     @Test
     public void testCreateSmartspaceTargetFromRemoteViews() {
         ComponentName testComponentName = new ComponentName("package_name", "class_name");
@@ -130,6 +133,7 @@
         assertThat(testTarget.getRemoteViews()).isEqualTo(remoteViews);
     }
 
+    @RequiresFlagsEnabled(Flags.FLAG_REMOTE_VIEWS)
     @Test
     public void testCreateSmartspaceTargetFromWidgetAndRemoteViewsAtSameTime() {
         ComponentName testComponentName = new ComponentName("package_name", "class_name");
@@ -152,6 +156,7 @@
                 "Widget providers and RemoteViews cannot be used at the same time.");
     }
 
+    @RequiresFlagsEnabled(Flags.FLAG_REMOTE_VIEWS)
     @Test
     public void testCreateSmartspaceTargetFromRemoteViewsAndWidgetAtSameTime() {
         ComponentName testComponentName = new ComponentName("package_name", "class_name");
diff --git a/tests/tests/assist/common/src/android/assist/common/Utils.java b/tests/tests/assist/common/src/android/assist/common/Utils.java
index bc33ffc..5cee36d 100755
--- a/tests/tests/assist/common/src/android/assist/common/Utils.java
+++ b/tests/tests/assist/common/src/android/assist/common/Utils.java
@@ -54,6 +54,7 @@
     public static final String ASSIST_SCREENSHOT_KEY = "assist_screenshot";
     public static final String SCREENSHOT_COLOR_KEY = "set_screenshot_color";
     public static final String COMPARE_SCREENSHOT_KEY = "compare_screenshot";
+    public static final String ON_SHOW_ARGS_KEY = "on_show_args";
     public static final String DISPLAY_WIDTH_KEY = "display_width";
     public static final String DISPLAY_HEIGHT_KEY = "dislay_height";
     public static final String DISPLAY_AREA_BOUNDS_KEY = "display_area_bounds";
diff --git a/tests/tests/assist/service/src/android/assist/service/MainInteractionSession.java b/tests/tests/assist/service/src/android/assist/service/MainInteractionSession.java
index caea09a..dbd1dc0 100644
--- a/tests/tests/assist/service/src/android/assist/service/MainInteractionSession.java
+++ b/tests/tests/assist/service/src/android/assist/service/MainInteractionSession.java
@@ -61,6 +61,7 @@
     private String mTestName;
     private View mContentView;
     private RemoteCallback mRemoteCallback;
+    private Bundle mOnShowArgs;
 
     MainInteractionSession(Context context) {
         super(context);
@@ -119,6 +120,7 @@
             Log.e(TAG, "onshow() received null args");
             return;
         }
+        mOnShowArgs = args;
         mScreenshotNeeded = (showFlags & SHOW_WITH_SCREENSHOT) != 0;
         mTestName = args.getString(Utils.TESTCASE_TYPE, "");
         mCurColor = args.getInt(Utils.SCREENSHOT_COLOR_KEY);
@@ -300,6 +302,7 @@
         } else {
             Bundle bundle = new Bundle();
             bundle.putString(Utils.EXTRA_REMOTE_CALLBACK_ACTION, Utils.BROADCAST_ASSIST_DATA_INTENT);
+            bundle.putBundle(Utils.ON_SHOW_ARGS_KEY, mOnShowArgs);
             bundle.putAll(mAssistData);
             mRemoteCallback.sendResult(bundle);
 
diff --git a/tests/tests/assist/src/android/assist/cts/AssistTestBase.java b/tests/tests/assist/src/android/assist/cts/AssistTestBase.java
index 99c9aed..86cf9cd 100644
--- a/tests/tests/assist/src/android/assist/cts/AssistTestBase.java
+++ b/tests/tests/assist/src/android/assist/cts/AssistTestBase.java
@@ -124,6 +124,7 @@
     protected AssistStructure mAssistStructure;
     protected boolean mScreenshot;
     protected Bundle mAssistBundle;
+    protected Bundle mOnShowArgs;
     protected Context mContext;
     private AutoResetLatch mReadyLatch = new AutoResetLatch(1);
     private AutoResetLatch mHas3pResumedLatch = new AutoResetLatch(1);
@@ -690,6 +691,7 @@
         mScreenshot = assistData.getBoolean(Utils.ASSIST_SCREENSHOT_KEY, false);
 
         mScreenshotMatches = assistData.getBoolean(Utils.COMPARE_SCREENSHOT_KEY, false);
+        mOnShowArgs = assistData.getBundle(Utils.ON_SHOW_ARGS_KEY);
     }
 
     protected void eventuallyWithSessionClose(@NonNull ThrowingRunnable runnable) throws Throwable {
diff --git a/tests/tests/assist/src/android/assist/cts/DisableContextTest.java b/tests/tests/assist/src/android/assist/cts/DisableContextTest.java
index 99cb8e4..148e9e2 100644
--- a/tests/tests/assist/src/android/assist/cts/DisableContextTest.java
+++ b/tests/tests/assist/src/android/assist/cts/DisableContextTest.java
@@ -16,6 +16,10 @@
 
 package android.assist.cts;
 
+import static android.service.voice.VoiceInteractionSession.KEY_FOREGROUND_ACTIVITIES;
+
+import static com.google.common.truth.Truth.assertThat;
+
 import android.assist.common.Utils;
 import android.content.pm.PackageManager;
 import android.util.Log;
@@ -56,10 +60,11 @@
 
         logContextAndScreenshotSetting();
         verifyAssistDataNullness(true, true, true, true);
+        assertThat(mOnShowArgs.containsKey(KEY_FOREGROUND_ACTIVITIES)).isFalse();
     }
 
     @Test
-    public void testContextOff() throws Exception {
+    public void testScreenshotOff() throws Exception {
         if (!isSupportedDevice()) {
             return;
         }
@@ -75,10 +80,11 @@
 
         logContextAndScreenshotSetting();
         verifyAssistDataNullness(false, false, false, true);
+        assertThat(mOnShowArgs.containsKey(KEY_FOREGROUND_ACTIVITIES)).isTrue();
     }
 
     @Test
-    public void testScreenshotOff() throws Exception {
+    public void testScreenContextOff() throws Exception {
         if (!isSupportedDevice()) {
             return;
         }
@@ -94,6 +100,7 @@
 
         logContextAndScreenshotSetting();
         verifyAssistDataNullness(true, true, true, true);
+        assertThat(mOnShowArgs.containsKey(KEY_FOREGROUND_ACTIVITIES)).isFalse();
     }
 
     private boolean isSupportedDevice() {
diff --git a/tests/tests/assist/src/android/assist/cts/ExtraAssistDataTest.java b/tests/tests/assist/src/android/assist/cts/ExtraAssistDataTest.java
index 8db12e3..a38ff65 100644
--- a/tests/tests/assist/src/android/assist/cts/ExtraAssistDataTest.java
+++ b/tests/tests/assist/src/android/assist/cts/ExtraAssistDataTest.java
@@ -16,19 +16,24 @@
 package android.assist.cts;
 
 import static android.assist.common.Utils.SHOW_SESSION_FLAGS_TO_SET;
+import static android.service.voice.VoiceInteractionSession.KEY_FOREGROUND_ACTIVITIES;
 
+import static com.google.common.truth.Truth.assertThat;
 import static com.google.common.truth.Truth.assertWithMessage;
 
 import static org.junit.Assume.assumeFalse;
 
 import android.assist.common.AutoResetLatch;
 import android.assist.common.Utils;
+import android.content.ComponentName;
 import android.content.Intent;
 import android.os.Bundle;
 import android.util.Log;
 
 import org.junit.Test;
 
+import java.util.ArrayList;
+
 public class ExtraAssistDataTest extends AssistTestBase {
     private static final String TAG = "ExtraAssistDataTest";
     private static final String TEST_CASE_TYPE = Utils.EXTRA_ASSIST;
@@ -68,6 +73,14 @@
         int actualUid = mAssistBundle.getInt(Intent.EXTRA_ASSIST_UID);
         assertWithMessage("Wrong value for EXTRA_ASSIST_UID").that(actualUid)
                 .isEqualTo(expectedUid);
+
+        // Verify KEY_FOREGROUND_ACTIVITIES was correctly provided in onShow args
+        assertThat(mOnShowArgs.containsKey(KEY_FOREGROUND_ACTIVITIES)).isTrue();
+        ArrayList<ComponentName> foregroundApps =
+                mOnShowArgs.getParcelableArrayList(KEY_FOREGROUND_ACTIVITIES);
+        Log.i(TAG, "ForegroundActivityComponent:  " + foregroundApps);
+        assertThat(foregroundApps.size()).isEqualTo(1);
+        assertThat(foregroundApps.get(0).getPackageName()).isEqualTo("android.assist.testapp");
     }
 
     @Test
@@ -89,6 +102,7 @@
 
         verifyActivityIdNullness(/* isActivityIdNull = */ false);
         verifyAssistDataNullness(true, true, true, true);
+        assertThat(mOnShowArgs.containsKey(KEY_FOREGROUND_ACTIVITIES)).isFalse();
     }
 
     private void assumeIsNotAutomotive() {
diff --git a/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothAdapterTest.java b/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothAdapterTest.java
index de67768..774d4d4 100644
--- a/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothAdapterTest.java
+++ b/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothAdapterTest.java
@@ -46,16 +46,21 @@
 import android.os.Build;
 import android.os.Bundle;
 import android.os.SystemProperties;
+import android.platform.test.annotations.RequiresFlagsEnabled;
+import android.platform.test.flag.junit.CheckFlagsRule;
+import android.platform.test.flag.junit.DeviceFlagsValueProvider;
 import android.util.Log;
 
 import androidx.test.ext.junit.runners.AndroidJUnit4;
 import androidx.test.filters.MediumTest;
 import androidx.test.platform.app.InstrumentationRegistry;
 
+import com.android.bluetooth.flags.Flags;
 import com.android.compatibility.common.util.ApiLevelUtil;
 
 import org.junit.After;
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -80,6 +85,10 @@
     private static final String ENABLE_DUAL_MODE_AUDIO =
             "persist.bluetooth.enable_dual_mode_audio";
 
+    @Rule
+    public final CheckFlagsRule mCheckFlagsRule =
+            DeviceFlagsValueProvider.createCheckFlagsRule();
+
     private Context mContext;
     private boolean mHasBluetooth;
     private ReentrantLock mAdapterNameChangedlock;
@@ -634,6 +643,27 @@
     }
 
     @Test
+    @RequiresFlagsEnabled(Flags.FLAG_AUTO_ON_FEATURE)
+    public void autoOnApi() {
+        assumeTrue(mHasBluetooth);
+
+        assertThrows(SecurityException.class, () -> mAdapter.isAutoOnSupported());
+        assertThrows(SecurityException.class, () -> mAdapter.isAutoOnEnabled());
+        assertThrows(SecurityException.class, () -> mAdapter.setAutoOnEnabled(false));
+
+        TestUtils.adoptPermissionAsShellUid(BLUETOOTH_PRIVILEGED);
+
+        // Not all devices support the auto on feature
+        assumeTrue(mAdapter.isAutoOnSupported());
+
+        mAdapter.setAutoOnEnabled(false);
+        assertEquals(false, mAdapter.isAutoOnEnabled());
+
+        mAdapter.setAutoOnEnabled(true);
+        assertEquals(true, mAdapter.isAutoOnEnabled());
+    }
+
+    @Test
     public void getSetBluetoothHciSnoopLoggingMode() {
         assumeTrue(mHasBluetooth);
 
diff --git a/tests/tests/car/src/android/car/app/cts/CarTaskViewControllerTest.java b/tests/tests/car/src/android/car/app/cts/CarTaskViewControllerTest.java
index 1050ec7..01c1b80 100644
--- a/tests/tests/car/src/android/car/app/cts/CarTaskViewControllerTest.java
+++ b/tests/tests/car/src/android/car/app/cts/CarTaskViewControllerTest.java
@@ -50,6 +50,7 @@
 import androidx.annotation.Nullable;
 import androidx.test.filters.FlakyTest;
 import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.uiautomator.UiDevice;
 
 import com.android.compatibility.common.util.ApiTest;
 import com.android.compatibility.common.util.NonApiTest;
@@ -79,6 +80,7 @@
     private final ComponentName mTestActivity =
             new ComponentName(mTargetContext, TestActivity.class);
     private final UiAutomation mUiAutomation = mInstrumentation.getUiAutomation();
+    private final UiDevice mUiDevice = UiDevice.getInstance(mInstrumentation);
 
     private TestCarTaskViewControllerCallback mCallback;
     private TestActivity mHostActivity;
@@ -99,6 +101,8 @@
         assertThat(mCarActivityManager).isNotNull();
 
         assumeTrue(mCarActivityManager.isCarSystemUIProxyRegistered());
+        mUiDevice.pressHome();
+
         Intent startIntent = Intent.makeMainActivity(mTestActivity)
                 .addFlags(FLAG_ACTIVITY_NEW_TASK);
         mHostActivity = (TestActivity) mInstrumentation.startActivitySync(
@@ -362,6 +366,7 @@
         PollingCheck.waitFor(() -> EmbeddedTestActivity1.sInstance != null
                         && EmbeddedTestActivity1.sInstance.mIsResumed,
                 "EmbeddedTestActivity1 is not running.");
+        mUiDevice.waitForIdle(QUIET_TIME_TO_BE_CONSIDERED_IDLE_STATE);
 
         // EmbeddedTestActivity is on the upper part of the screen.
         Point p = getTaskViewCenterOnScreen(carTaskViewHolder.mTaskView);
diff --git a/tests/tests/car/src/android/car/cts/CarAudioManagerTest.java b/tests/tests/car/src/android/car/cts/CarAudioManagerTest.java
index 353c5d2..7ed7172 100644
--- a/tests/tests/car/src/android/car/cts/CarAudioManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarAudioManagerTest.java
@@ -350,7 +350,8 @@
     @Test
     @EnsureHasPermission(Car.PERMISSION_CAR_CONTROL_AUDIO_VOLUME)
     @ApiTest(apis = {"android.car.media.CarAudioManager#getVolumeGroupInfo"})
-    public void getVolumeGroupInfo() {
+    @RequiresFlagsDisabled(Flags.FLAG_CAR_AUDIO_MIN_MAX_ACTIVATION_VOLUME)
+    public void getVolumeGroupInfo_withMinMaxActivationVolumeFlagDisabled() {
         assumeDynamicRoutingIsEnabled();
         int groupCount = mCarAudioManager.getVolumeGroupCount(PRIMARY_AUDIO_ZONE);
 
@@ -372,6 +373,42 @@
 
     @Test
     @EnsureHasPermission(Car.PERMISSION_CAR_CONTROL_AUDIO_VOLUME)
+    @ApiTest(apis = {"android.car.media.CarAudioManager#getVolumeGroupInfo",
+            "android.car.media.CarVolumeGroupInfo#getMaxActivationVolumeGainIndex",
+            "android.car.media.CarVolumeGroupInfo#getMinActivationVolumeGainIndex"})
+    @RequiresFlagsEnabled(Flags.FLAG_CAR_AUDIO_MIN_MAX_ACTIVATION_VOLUME)
+    public void getVolumeGroupInfo_withMinMaxActivationVolumeFlagEnabled() {
+        assumeDynamicRoutingIsEnabled();
+        int groupCount = mCarAudioManager.getVolumeGroupCount(PRIMARY_AUDIO_ZONE);
+
+        for (int index = 0; index < groupCount; index++) {
+            int minIndex = mCarAudioManager.getGroupMinVolume(PRIMARY_AUDIO_ZONE, index);
+            int maxIndex = mCarAudioManager.getGroupMaxVolume(PRIMARY_AUDIO_ZONE, index);
+            CarVolumeGroupInfo info =
+                    mCarAudioManager.getVolumeGroupInfo(PRIMARY_AUDIO_ZONE, index);
+            int minActivationIndex = info.getMinActivationVolumeGainIndex();
+            int maxActivationIndex = info.getMaxActivationVolumeGainIndex();
+
+            expectWithMessage("Car volume group id for info %s and group %s", info, index)
+                    .that(info.getId()).isEqualTo(index);
+            expectWithMessage("Car volume group info zone for info %s and group %s",
+                    info, index).that(info.getZoneId()).isEqualTo(PRIMARY_AUDIO_ZONE);
+            expectWithMessage("Car volume group info max index for info %s and group %s",
+                    info, index).that(info.getMaxVolumeGainIndex()).isEqualTo(maxIndex);
+            expectWithMessage("Car volume group info min index for info %s and group %s",
+                    info, index).that(info.getMinVolumeGainIndex()).isEqualTo(minIndex);
+            expectWithMessage("Car volume group info min activation volume for info %s and"
+                    + " group %s", info, index).that(minActivationIndex).isAtLeast(minIndex);
+            expectWithMessage("Car volume group info max activation volume for info %s and"
+                    + " group %s", info, index).that(maxActivationIndex).isAtMost(maxIndex);
+            expectWithMessage("Max activation volume and min activation volume for info %s"
+                    + " and group %s", info, index).that(maxActivationIndex)
+                    .isGreaterThan(minActivationIndex);
+        }
+    }
+
+    @Test
+    @EnsureHasPermission(Car.PERMISSION_CAR_CONTROL_AUDIO_VOLUME)
     @ApiTest(apis = {"android.car.media.CarAudioManager#getVolumeGroupInfosForZone"})
     public void getVolumeGroupInfosForZone() {
         assumeDynamicRoutingIsEnabled();
@@ -1767,6 +1804,53 @@
             .that(mEventCallback.receivedVolumeGroupEvents()).isFalse();
     }
 
+    @Test
+    @EnsureHasPermission(Car.PERMISSION_CAR_CONTROL_AUDIO_VOLUME)
+    @ApiTest(apis = {"android.car.media.CarAudioManager#isVolumeGroupMuted",
+            "android.car.media.CarVolumeGroupInfo#isMuted"})
+    public void isVolumeGroupMuted() {
+        assumeDynamicRoutingIsEnabled();
+        readFirstZoneAndVolumeGroup();
+        CarVolumeGroupInfo volumeGroupInfo = mCarAudioManager.getVolumeGroupInfo(mZoneId,
+                mVolumeGroupId);
+
+        boolean isMuted = mCarAudioManager.isVolumeGroupMuted(mZoneId, mVolumeGroupId);
+
+        assertWithMessage("Mute state for zone %s group %s", mZoneId, mVolumeGroupId)
+                .that(isMuted).isEqualTo(volumeGroupInfo.isMuted());
+    }
+
+    @Test
+    @EnsureHasPermission(Car.PERMISSION_CAR_CONTROL_AUDIO_VOLUME)
+    @ApiTest(apis = {"android.car.media.CarAudioManager#setVolumeGroupMute",
+            "android.car.media.CarAudioManager#isVolumeGroupMuted",
+            "android.car.media.CarVolumeGroupInfo#isMutedBySystem"})
+    @RequiresFlagsEnabled(Flags.FLAG_CAR_AUDIO_MUTE_AMBIGUITY)
+    public void setVolumeGroupMute_withMuteAmbiguityFlagEnabled() {
+        assumeDynamicRoutingIsEnabled();
+        readFirstZoneAndVolumeGroup();
+        boolean isMuted = mCarAudioManager.isVolumeGroupMuted(mZoneId, mVolumeGroupId);
+        boolean isMutedBySystem = mCarAudioManager.getVolumeGroupInfo(mZoneId,
+                mVolumeGroupId).isMutedBySystem();
+        String muteOperationStr = isMuted ? "unmuting" : "muting";
+
+        try {
+            mCarAudioManager.setVolumeGroupMute(mZoneId, mVolumeGroupId, !isMuted, /* flags= */ 0);
+
+            assertWithMessage("Mute state for zone %s group %s after %s", mZoneId, mVolumeGroupId,
+                    muteOperationStr)
+                    .that(mCarAudioManager.isVolumeGroupMuted(mZoneId, mVolumeGroupId))
+                    .isEqualTo(mCarAudioManager.getVolumeGroupInfo(mZoneId, mVolumeGroupId)
+                            .isMuted());
+            assertWithMessage("Mute by system state for zone %s group %s after %s", mZoneId,
+                    mVolumeGroupId, muteOperationStr)
+                    .that(mCarAudioManager.getVolumeGroupInfo(mZoneId, mVolumeGroupId)
+                            .isMutedBySystem()).isEqualTo(isMutedBySystem);
+        } finally {
+            mCarAudioManager.setVolumeGroupMute(mZoneId, mVolumeGroupId, isMuted, /* flags= */ 0);
+        }
+    }
+
     private int getNumberOfPrimaryZoneAudioMediaCallbacks() {
         if (Flags.carDumpToProto()) {
             return mCarAudioServiceProtoDump.getMediaRequestHandler().hasMediaRequestCallbackCount()
diff --git a/tests/tests/contactkeysprovider/src/android/provider/cts/contactkeys/ContactKeysManagerTest.java b/tests/tests/contactkeysprovider/src/android/provider/cts/contactkeys/ContactKeysManagerTest.java
index fa792ba..6f64793 100644
--- a/tests/tests/contactkeysprovider/src/android/provider/cts/contactkeys/ContactKeysManagerTest.java
+++ b/tests/tests/contactkeysprovider/src/android/provider/cts/contactkeys/ContactKeysManagerTest.java
@@ -69,6 +69,7 @@
     private static final String HELPER_APP_LOOKUP_KEY = "0r1-423A2E4644502A2E50";
     private static final String HELPER_APP_DEVICE_ID = "someDeviceId";
     private static final String HELPER_APP_ACCOUNT_ID = "someAccountId";
+    private static final String OWNER_PACKAGE_NAME = "android.provider.cts.contactkeys";
 
     private ContactKeysManager mContactKeysManager;
     private Context mContext;
@@ -105,6 +106,8 @@
                 .isEqualTo(ContactKeysManager.UNVERIFIED);
         assertThat(contactKey.getRemoteVerificationState())
                 .isEqualTo(ContactKeysManager.UNVERIFIED);
+        assertThat(contactKey.getOwnerPackageName()).isEqualTo(OWNER_PACKAGE_NAME);
+        assertThat(contactKey.getEmailAddress()).isEqualTo(null);
     }
 
     @Test
diff --git a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
index e0f03e9..00cf717 100644
--- a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
+++ b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
@@ -35,6 +35,7 @@
 import android.os.BatteryManager;
 import android.os.storage.StorageManager;
 import android.platform.test.annotations.AppModeFull;
+import android.platform.test.annotations.RequiresFlagsEnabled;
 import android.provider.AlarmClock;
 import android.provider.MediaStore;
 import android.provider.Settings;
@@ -46,6 +47,7 @@
 import com.android.compatibility.common.util.ApiTest;
 import com.android.compatibility.common.util.CddTest;
 import com.android.compatibility.common.util.FeatureUtil;
+import com.android.media.flags.Flags;
 
 import java.util.List;
 
@@ -463,6 +465,14 @@
         assertCanBeHandled(new Intent(Settings.ACTION_REQUEST_MANAGE_MEDIA));
     }
 
+    @RequiresFlagsEnabled(Flags.FLAG_ENABLE_PRIVILEGED_ROUTING_FOR_MEDIA_ROUTING_CONTROL)
+    public void testMediaRoutingControlSettings() {
+        if (FeatureUtil.isWatch()) {
+            return;
+        }
+        assertCanBeHandled(new Intent(Settings.ACTION_REQUEST_MEDIA_ROUTING_CONTROL));
+    }
+
     public void testInteractAcrossProfilesSettings() {
         PackageManager packageManager = mContext.getPackageManager();
         if (packageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_PROFILES)) {
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
index dc3b6d4..f27b445 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
@@ -1044,6 +1044,10 @@
         if (!TestUtils.isAttestationSupported()) {
             return;
         }
+        assumeTrue("Curve25519 Key attestation supported from KeyMint v2 and above.",
+                getContext().getPackageManager()
+                        .hasSystemFeature(PackageManager.FEATURE_HARDWARE_KEYSTORE,
+                                Attestation.KM_VERSION_KEYMINT_2));
 
         if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC)) {
             return;
diff --git a/tests/tests/os/Android.bp b/tests/tests/os/Android.bp
index f85ea76..6eade87 100644
--- a/tests/tests/os/Android.bp
+++ b/tests/tests/os/Android.bp
@@ -101,6 +101,9 @@
         "src/android/os/cts/LooperTest.java",
         "src/android/os/cts/MessageQueueTest.java",
         "src/android/os/cts/MessageTest.java",
+        "src/android/os/cts/ParcelFileDescriptorTest.java",
+        "src/android/os/cts/ParcelFileDescriptor_AutoCloseInputStreamTest.java",
+        "src/android/os/cts/ParcelFileDescriptor_AutoCloseOutputStreamTest.java",
         "src/android/os/cts/ParcelFormatExceptionTest.java",
         "src/android/os/cts/ParcelTest.java",
         "src/android/os/cts/ParcelUuidTest.java",
diff --git a/tests/tests/os/src/android/os/cts/MessageTest.java b/tests/tests/os/src/android/os/cts/MessageTest.java
index 006fbdf..9e72fd6 100644
--- a/tests/tests/os/src/android/os/cts/MessageTest.java
+++ b/tests/tests/os/src/android/os/cts/MessageTest.java
@@ -39,13 +39,16 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
 @RunWith(AndroidJUnit4.class)
 public class MessageTest {
     @Rule
     public final RavenwoodRule mRavenwood = new RavenwoodRule.Builder()
             .setProvideMainThread(true).build();
 
-    public static final int SLEEP_TIME = 300;
     public static final int WHAT = 1;
     public static final int ARG1 = 1;
     public static final int ARG2 = 2;
@@ -53,7 +56,7 @@
     public static final int VALUE = 3;
 
     private Message mMessage;
-    private boolean mMessageHandlerCalled;
+    private CountDownLatch mMessageHandlerCalled;
 
     private Handler mHandler;
 
@@ -67,9 +70,10 @@
     @Before
     public void setUp() throws Exception {
         mMessage = new Message();
+        mMessageHandlerCalled = new CountDownLatch(1);
         mHandler = new Handler(Looper.getMainLooper()) {
             public void handleMessage(Message msg) {
-                mMessageHandlerCalled = true;
+                mMessageHandlerCalled.countDown();
             }
         };
     }
@@ -244,7 +248,7 @@
     }
 
     @Test
-    public void testSendToTarget() {
+    public void testSendToTarget() throws Exception {
         try {
             mMessage.sendToTarget();
             fail("should throw exception");
@@ -253,10 +257,9 @@
         }
 
         Message message = Message.obtain(mHandler);
-        assertFalse(mMessageHandlerCalled);
+        assertFalse(mMessageHandlerCalled.getCount() == 0);
         message.sendToTarget();
-        sleep(SLEEP_TIME);
-        assertTrue(mMessageHandlerCalled);
+        assertTrue(mMessageHandlerCalled.await(1, TimeUnit.SECONDS));
     }
 
     @Test
@@ -298,52 +301,36 @@
     }
 
     @Test
-    public void testRecycleThrowsIfMessageIsBeingDelivered() {
-        final Exception[] caught = new Exception[1];
+    public void testRecycleThrowsIfMessageIsBeingDelivered() throws Exception {
+        final CompletableFuture<IllegalStateException> res = new CompletableFuture<>();
         Handler handler = new Handler(mHandler.getLooper()) {
             @Override
             public void handleMessage(Message msg) {
                 try {
                     msg.recycle();
                 } catch (IllegalStateException ex) {
-                    caught[0] = ex; // expected
+                    res.complete(ex);
                 }
             }
         };
         handler.sendEmptyMessage(WHAT);
-        sleep(SLEEP_TIME);
-
-        if (caught[0] == null) {
-            fail("should throw IllegalStateException");
-        }
+        assertNotNull("should throw IllegalStateException", res.get(1, TimeUnit.SECONDS));
     }
 
     @Test
-    public void testSendMessageThrowsIfMessageIsBeingDelivered() {
-        final Exception[] caught = new Exception[1];
+    public void testSendMessageThrowsIfMessageIsBeingDelivered() throws Exception {
+        final CompletableFuture<IllegalStateException> res = new CompletableFuture<>();
         Handler handler = new Handler(mHandler.getLooper()) {
             @Override
             public void handleMessage(Message msg) {
                 try {
                     mHandler.sendMessage(msg);
                 } catch (IllegalStateException ex) {
-                    caught[0] = ex; // expected
+                    res.complete(ex);
                 }
             }
         };
         handler.sendEmptyMessage(WHAT);
-        sleep(SLEEP_TIME);
-
-        if (caught[0] == null) {
-            fail("should throw IllegalStateException");
-        }
-    }
-
-    private void sleep(long time) {
-        try {
-            Thread.sleep(time);
-        } catch (InterruptedException e) {
-            fail(e.getMessage());
-        }
+        assertNotNull("should throw IllegalStateException", res.get(1, TimeUnit.SECONDS));
     }
 }
diff --git a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorPeer.java b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorPeer.java
index 4417179..8786bea 100644
--- a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorPeer.java
+++ b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorPeer.java
@@ -23,20 +23,14 @@
 import android.os.Looper;
 import android.os.ParcelFileDescriptor;
 import android.os.Process;
-import android.os.ParcelFileDescriptor.OnCloseListener;
-import android.os.ParcelFileDescriptor.FileDescriptorDetachedException;
 import android.os.RemoteException;
 import android.os.SystemClock;
 
-import com.google.common.util.concurrent.AbstractFuture;
-
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
 
 /**
  * Sits around in a remote process doing whatever the CTS test says.
@@ -47,7 +41,7 @@
     private ParcelFileDescriptor mLocal;
     private ParcelFileDescriptor mRemote;
 
-    private FutureCloseListener mListener;
+    private ParcelFileDescriptorTest.FutureCloseListener mListener;
 
     @Override
     public void setPeer(IParcelFileDescriptorPeer peer) throws RemoteException {
@@ -90,7 +84,7 @@
     @Override
     public void setupFile() throws RemoteException {
         final Handler handler = new Handler(Looper.getMainLooper());
-        mListener = new FutureCloseListener();
+        mListener = new ParcelFileDescriptorTest.FutureCloseListener();
         try {
             mLocal = null;
             mRemote = ParcelFileDescriptor.open(File.createTempFile("pfd", "tmp"),
@@ -200,27 +194,6 @@
         }
     }
 
-    public static class FutureCloseListener extends AbstractFuture<IOException>
-            implements OnCloseListener {
-        @Override
-        public void onClose(IOException e) {
-            if (e instanceof FileDescriptorDetachedException) {
-                set(new IOException("DETACHED"));
-            } else {
-                set(e);
-            }
-        }
-
-        @Override
-        public IOException get() throws InterruptedException, ExecutionException {
-            try {
-                return get(5, TimeUnit.SECONDS);
-            } catch (TimeoutException e) {
-                throw new RuntimeException(e);
-            }
-        }
-    }
-
     public static class Red extends Service {
         @Override
         public IBinder onBind(Intent intent) {
diff --git a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
index 69f9a40..5005e71 100644
--- a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
@@ -16,34 +16,36 @@
 
 package android.os.cts;
 
+import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
-import android.content.Context;
 import android.os.Handler;
 import android.os.Looper;
+import android.os.MessageQueue;
 import android.os.Parcel;
 import android.os.ParcelFileDescriptor;
 import android.os.ParcelFileDescriptor.AutoCloseInputStream;
 import android.os.Parcelable;
-import android.os.cts.ParcelFileDescriptorPeer.FutureCloseListener;
 import android.platform.test.annotations.AppModeFull;
+import android.platform.test.annotations.IgnoreUnderRavenwood;
+import android.platform.test.ravenwood.RavenwoodRule;
 import android.system.ErrnoException;
 import android.system.Os;
 import android.system.OsConstants;
-import android.test.MoreAsserts;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.runner.AndroidJUnit4;
 
 import com.google.common.util.concurrent.AbstractFuture;
 
 import junit.framework.ComparisonFailure;
 
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -57,19 +59,22 @@
 import java.net.InetAddress;
 import java.net.ServerSocket;
 import java.net.Socket;
+import java.nio.file.Files;
+import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 
 @RunWith(AndroidJUnit4.class)
 public class ParcelFileDescriptorTest {
-    private static final long DURATION = 100l;
+    @Rule
+    public final RavenwoodRule mRavenwood = new RavenwoodRule.Builder()
+            .setProvideMainThread(true).build();
 
-    private Context getContext() {
-        return InstrumentationRegistry.getContext();
-    }
+    private static final long DURATION = 100l;
 
     @Test
     public void testConstructorAndOpen() throws Exception {
-        ParcelFileDescriptor tempFile = makeParcelFileDescriptor(getContext());
+        ParcelFileDescriptor tempFile = makeParcelFileDescriptor();
 
         ParcelFileDescriptor pfd = new ParcelFileDescriptor(tempFile);
         AutoCloseInputStream in = new AutoCloseInputStream(pfd);
@@ -84,6 +89,81 @@
         }
     }
 
+    @Test
+    public void testDetachAdopt() throws Exception {
+        ParcelFileDescriptor tempFile = makeParcelFileDescriptor();
+
+        ParcelFileDescriptor before = new ParcelFileDescriptor(tempFile);
+        ParcelFileDescriptor after = ParcelFileDescriptor.adoptFd(before.detachFd());
+
+        // Verify reading from post-adopted FD works
+        try (AutoCloseInputStream in = new AutoCloseInputStream(after)) {
+            assertEquals(0, in.read());
+            assertEquals(1, in.read());
+            assertEquals(2, in.read());
+            assertEquals(3, in.read());
+        }
+
+        // Verify trying to detach a second time fails
+        assertThrows(IllegalStateException.class, () -> {
+            before.detachFd();
+        });
+    }
+
+    @Test
+    public void testReadOnly() throws Exception {
+        final File file = File.createTempFile("testReadOnly", "bin");
+        file.createNewFile();
+        try (ParcelFileDescriptor pfd = ParcelFileDescriptor.open(file,
+                ParcelFileDescriptor.MODE_READ_ONLY);
+             ParcelFileDescriptor.AutoCloseOutputStream out =
+                     new ParcelFileDescriptor.AutoCloseOutputStream(pfd)) {
+            assertThrows(IOException.class, () -> {
+                out.write(42);
+            });
+        }
+    }
+
+    @Test
+    public void testNormal() throws Exception {
+        final File file = File.createTempFile("testNormal", "bin");
+        doMultiWrite(file, ParcelFileDescriptor.MODE_READ_WRITE
+                | ParcelFileDescriptor.MODE_CREATE);
+        assertArrayEquals(new byte[]{21, 42}, Files.readAllBytes(file.toPath()));
+    }
+
+    @Test
+    public void testAppend() throws Exception {
+        final File file = File.createTempFile("testAppend", "bin");
+        doMultiWrite(file, ParcelFileDescriptor.MODE_READ_WRITE
+                | ParcelFileDescriptor.MODE_CREATE
+                | ParcelFileDescriptor.MODE_APPEND);
+        assertArrayEquals(new byte[]{42, 42, 21}, Files.readAllBytes(file.toPath()));
+    }
+
+    @Test
+    public void testTruncate() throws Exception {
+        final File file = File.createTempFile("testTruncate", "bin");
+        doMultiWrite(file, ParcelFileDescriptor.MODE_READ_WRITE
+                | ParcelFileDescriptor.MODE_CREATE
+                | ParcelFileDescriptor.MODE_TRUNCATE);
+        assertArrayEquals(new byte[]{21}, Files.readAllBytes(file.toPath()));
+    }
+
+    private void doMultiWrite(File file, int flags) throws Exception {
+        try (ParcelFileDescriptor pfd = ParcelFileDescriptor.open(file, flags);
+             ParcelFileDescriptor.AutoCloseOutputStream out =
+                     new ParcelFileDescriptor.AutoCloseOutputStream(pfd)) {
+            out.write(42);
+            out.write(42);
+        }
+        try (ParcelFileDescriptor pfd = ParcelFileDescriptor.open(file, flags);
+             ParcelFileDescriptor.AutoCloseOutputStream out =
+                     new ParcelFileDescriptor.AutoCloseOutputStream(pfd)) {
+            out.write(21);
+        }
+    }
+
     private static class DoneSignal extends AbstractFuture<Void> {
         public boolean set() {
             return super.set(null);
@@ -97,6 +177,7 @@
 
     @Test
     @AppModeFull // opening a listening socket not permitted for instant apps
+    @IgnoreUnderRavenwood(blockedBy = ParcelFileDescriptor.class)
     public void testFromSocket() throws Throwable {
         final int PORT = 12222;
         final int DATA = 1;
@@ -147,7 +228,7 @@
             int count = is.read(observed);
             assertEquals(expected.length, count);
             assertEquals(-1, is.read());
-            MoreAsserts.assertEquals(expected, observed);
+            assertArrayEquals(expected, observed);
         } finally {
             is.close();
         }
@@ -155,13 +236,14 @@
 
     @Test
     public void testToString() throws Exception {
-        ParcelFileDescriptor pfd = makeParcelFileDescriptor(getContext());
+        ParcelFileDescriptor pfd = makeParcelFileDescriptor();
         assertNotNull(pfd.toString());
     }
 
     @Test
+    @IgnoreUnderRavenwood(blockedBy = Parcel.class)
     public void testWriteToParcel() throws Exception {
-        ParcelFileDescriptor pf = makeParcelFileDescriptor(getContext());
+        ParcelFileDescriptor pf = makeParcelFileDescriptor();
 
         Parcel pl = Parcel.obtain();
         pf.writeToParcel(pl, ParcelFileDescriptor.PARCELABLE_WRITE_RETURN_VALUE);
@@ -181,7 +263,7 @@
 
     @Test
     public void testClose() throws Exception {
-        ParcelFileDescriptor pf = makeParcelFileDescriptor(getContext());
+        ParcelFileDescriptor pf = makeParcelFileDescriptor();
         AutoCloseInputStream in1 = new AutoCloseInputStream(pf);
         try {
             assertEquals(0, in1.read());
@@ -203,14 +285,15 @@
     }
 
     @Test
+    @IgnoreUnderRavenwood(blockedBy = ParcelFileDescriptor.class)
     public void testGetStatSize() throws Exception {
-        ParcelFileDescriptor pf = makeParcelFileDescriptor(getContext());
+        ParcelFileDescriptor pf = makeParcelFileDescriptor();
         assertTrue(pf.getStatSize() >= 0);
     }
 
     @Test
     public void testGetFileDescriptor() throws Exception {
-        ParcelFileDescriptor pfd = makeParcelFileDescriptor(getContext());
+        ParcelFileDescriptor pfd = makeParcelFileDescriptor();
         assertNotNull(pfd.getFileDescriptor());
 
         ParcelFileDescriptor p = new ParcelFileDescriptor(pfd);
@@ -219,7 +302,7 @@
 
     @Test
     public void testDescribeContents() throws Exception{
-        ParcelFileDescriptor pfd = makeParcelFileDescriptor(getContext());
+        ParcelFileDescriptor pfd = makeParcelFileDescriptor();
         assertTrue((Parcelable.CONTENTS_FILE_DESCRIPTOR & pfd.describeContents()) != 0);
     }
 
@@ -243,6 +326,7 @@
     }
 
     @Test
+    @IgnoreUnderRavenwood(blockedBy = ParcelFileDescriptor.class)
     public void testPipeNormal() throws Exception {
         final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
         final ParcelFileDescriptor red = pipe[0];
@@ -259,6 +343,7 @@
     // Reading should be done via AutoCloseInputStream if possible, rather than
     // recreating a FileInputStream from a raw FD, what's done in read(PFD).
     @Test
+    @IgnoreUnderRavenwood(blockedBy = ParcelFileDescriptor.class)
     public void testPipeError_Discouraged() throws Exception {
         final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
         final ParcelFileDescriptor red = pipe[0];
@@ -279,6 +364,7 @@
     }
 
     @Test
+    @IgnoreUnderRavenwood(blockedBy = ParcelFileDescriptor.class)
     public void testPipeError() throws Exception {
         final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
         final ParcelFileDescriptor red = pipe[0];
@@ -297,6 +383,7 @@
     }
 
     @Test
+    @IgnoreUnderRavenwood(blockedBy = MessageQueue.class)
     public void testFileNormal() throws Exception {
         final Handler handler = new Handler(Looper.getMainLooper());
         final FutureCloseListener listener = new FutureCloseListener();
@@ -312,6 +399,7 @@
     }
 
     @Test
+    @IgnoreUnderRavenwood(blockedBy = MessageQueue.class)
     public void testFileError() throws Exception {
         final Handler handler = new Handler(Looper.getMainLooper());
         final FutureCloseListener listener = new FutureCloseListener();
@@ -327,6 +415,7 @@
     }
 
     @Test
+    @IgnoreUnderRavenwood(blockedBy = MessageQueue.class)
     public void testFileDetach() throws Exception {
         final Handler handler = new Handler(Looper.getMainLooper());
         final FutureCloseListener listener = new FutureCloseListener();
@@ -341,6 +430,7 @@
     }
 
     @Test
+    @IgnoreUnderRavenwood(blockedBy = MessageQueue.class)
     public void testFileWrapped() throws Exception {
         final Handler handler1 = new Handler(Looper.getMainLooper());
         final Handler handler2 = new Handler(Looper.getMainLooper());
@@ -359,6 +449,7 @@
     }
 
     @Test
+    @IgnoreUnderRavenwood(blockedBy = ParcelFileDescriptor.class)
     public void testSocketErrorAfterClose() throws Exception {
         final ParcelFileDescriptor[] pair = ParcelFileDescriptor.createReliableSocketPair();
         final ParcelFileDescriptor red = pair[0];
@@ -382,6 +473,7 @@
     }
 
     @Test
+    @IgnoreUnderRavenwood(blockedBy = ParcelFileDescriptor.class)
     public void testSocketMultipleCheck() throws Exception {
         final ParcelFileDescriptor[] pair = ParcelFileDescriptor.createReliableSocketPair();
         final ParcelFileDescriptor red = pair[0];
@@ -413,9 +505,10 @@
     }
 
     @Test
+    @IgnoreUnderRavenwood(blockedBy = Os.class)
     public void testCheckFinalizerBehavior() throws Exception {
         final Runtime runtime = Runtime.getRuntime();
-        ParcelFileDescriptor pfd = makeParcelFileDescriptor(getContext());
+        ParcelFileDescriptor pfd = makeParcelFileDescriptor();
         assertTrue(checkIsValid(pfd.getFileDescriptor()));
 
         ParcelFileDescriptor wrappedPfd = new ParcelFileDescriptor(pfd);
@@ -463,25 +556,35 @@
         }
     }
 
-    static ParcelFileDescriptor makeParcelFileDescriptor(Context con) throws Exception {
-        final String fileName = "testParcelFileDescriptor";
-
-        FileOutputStream fout = null;
-
-        fout = con.openFileOutput(fileName, Context.MODE_PRIVATE);
-
-        try {
+    static ParcelFileDescriptor makeParcelFileDescriptor() throws Exception {
+        File file = File.createTempFile("testParcelFileDescriptor", "bin");
+        try (FileOutputStream fout = new FileOutputStream(file)) {
             fout.write(new byte[] { 0x0, 0x1, 0x2, 0x3 });
-        } finally {
-            fout.close();
         }
 
-        File dir = con.getFilesDir();
-        File file = new File(dir, fileName);
         ParcelFileDescriptor pf = null;
-
         pf = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE);
-
         return pf;
     }
+
+    public static class FutureCloseListener extends AbstractFuture<IOException>
+            implements ParcelFileDescriptor.OnCloseListener {
+        @Override
+        public void onClose(IOException e) {
+            if (e instanceof ParcelFileDescriptor.FileDescriptorDetachedException) {
+                set(new IOException("DETACHED"));
+            } else {
+                set(e);
+            }
+        }
+
+        @Override
+        public IOException get() throws InterruptedException, ExecutionException {
+            try {
+                return get(5, TimeUnit.SECONDS);
+            } catch (TimeoutException e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
 }
diff --git a/tests/tests/os/src/android/os/cts/ParcelFileDescriptor_AutoCloseInputStreamTest.java b/tests/tests/os/src/android/os/cts/ParcelFileDescriptor_AutoCloseInputStreamTest.java
index 040588a..0884b8f 100644
--- a/tests/tests/os/src/android/os/cts/ParcelFileDescriptor_AutoCloseInputStreamTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelFileDescriptor_AutoCloseInputStreamTest.java
@@ -16,15 +16,24 @@
 
 package android.os.cts;
 
-import java.io.IOException;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
 
 import android.os.ParcelFileDescriptor;
 import android.os.ParcelFileDescriptor.AutoCloseInputStream;
-import android.test.AndroidTestCase;
 
-public class ParcelFileDescriptor_AutoCloseInputStreamTest extends AndroidTestCase {
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+
+@RunWith(AndroidJUnit4.class)
+public class ParcelFileDescriptor_AutoCloseInputStreamTest {
+    @Test
     public void testAutoCloseInputStream() throws Exception {
-        ParcelFileDescriptor pf = ParcelFileDescriptorTest.makeParcelFileDescriptor(getContext());
+        ParcelFileDescriptor pf = ParcelFileDescriptorTest.makeParcelFileDescriptor();
 
         AutoCloseInputStream in = new AutoCloseInputStream(pf);
         assertEquals(0, in.read());
diff --git a/tests/tests/os/src/android/os/cts/ParcelFileDescriptor_AutoCloseOutputStreamTest.java b/tests/tests/os/src/android/os/cts/ParcelFileDescriptor_AutoCloseOutputStreamTest.java
index 12494e5..8a820c0 100644
--- a/tests/tests/os/src/android/os/cts/ParcelFileDescriptor_AutoCloseOutputStreamTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelFileDescriptor_AutoCloseOutputStreamTest.java
@@ -16,18 +16,26 @@
 
 package android.os.cts;
 
+import static org.junit.Assert.fail;
+
+import android.os.ParcelFileDescriptor;
+import android.os.ParcelFileDescriptor.AutoCloseOutputStream;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.lang.ref.Reference;
 import java.nio.channels.FileLock;
 
-import android.os.ParcelFileDescriptor;
-import android.os.ParcelFileDescriptor.AutoCloseOutputStream;
-import android.test.AndroidTestCase;
-
-public class ParcelFileDescriptor_AutoCloseOutputStreamTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+public class ParcelFileDescriptor_AutoCloseOutputStreamTest {
+    @Test
     public void testAutoCloseOutputStream() throws Exception {
-        ParcelFileDescriptor pf = ParcelFileDescriptorTest.makeParcelFileDescriptor(getContext());
+        ParcelFileDescriptor pf = ParcelFileDescriptorTest.makeParcelFileDescriptor();
 
         AutoCloseOutputStream out = new AutoCloseOutputStream(pf);
 
@@ -43,9 +51,10 @@
         }
     }
 
+    @Test
     public void testCloseOrdering() throws Exception {
         // b/118316956: Make sure that we close the OutputStream before we close the PFD.
-        ParcelFileDescriptor pfd = ParcelFileDescriptorTest.makeParcelFileDescriptor(getContext());
+        ParcelFileDescriptor pfd = ParcelFileDescriptorTest.makeParcelFileDescriptor();
         FileLock l = null;
         try (FileOutputStream out = new AutoCloseOutputStream(pfd)) {
             l = out.getChannel().lock();
diff --git a/tests/tests/os/src/android/os/storage/cts/StorageManagerCrossProfileSDCardTest.java b/tests/tests/os/src/android/os/storage/cts/StorageManagerCrossProfileSDCardTest.java
index d116302..e823b1c 100644
--- a/tests/tests/os/src/android/os/storage/cts/StorageManagerCrossProfileSDCardTest.java
+++ b/tests/tests/os/src/android/os/storage/cts/StorageManagerCrossProfileSDCardTest.java
@@ -26,7 +26,6 @@
 import android.os.storage.StorageVolume;
 import android.platform.test.annotations.AppModeFull;
 
-import androidx.test.filters.LargeTest;
 import androidx.test.platform.app.InstrumentationRegistry;
 
 import com.android.bedstead.harrier.BedsteadJUnit4;
@@ -71,7 +70,6 @@
 
 
     @Test
-    @LargeTest
     @RequireRunOnWorkProfile
     @AppModeFull(reason = "Instant apps cannot access external storage")
     public void testGetStorageVolumeSDCardWorkProfile() throws Exception {
diff --git a/tests/tests/packageinstaller/install/AndroidManifest.xml b/tests/tests/packageinstaller/install/AndroidManifest.xml
index 8be004e..c811374b 100644
--- a/tests/tests/packageinstaller/install/AndroidManifest.xml
+++ b/tests/tests/packageinstaller/install/AndroidManifest.xml
@@ -33,18 +33,6 @@
                 android:name="android.support.FILE_PROVIDER_PATHS"
                 android:resource="@xml/file_paths" />
         </provider>
-
-        <activity
-            android:name="android.packageinstaller.install.cts.FakeInstantAppInstallerActivity"
-            android:enabled="true"
-            android:exported="true">
-            <intent-filter>
-                <action android:name="android.intent.action.INSTALL_INSTANT_APP_PACKAGE_TEST" />
-                <category android:name="android.intent.category.DEFAULT"/>
-                <data android:scheme="file"/>
-                <data android:mimeType="application/vnd.android.package-archive"/>
-            </intent-filter>
-        </activity>
     </application>
 
     <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/FakeInstantAppInstallerActivity.kt b/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/FakeInstantAppInstallerActivity.kt
deleted file mode 100644
index 9e67488..0000000
--- a/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/FakeInstantAppInstallerActivity.kt
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright 2024 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.packageinstaller.install.cts
-
-import android.app.Activity
-import android.os.Bundle
-
-class FakeInstantAppInstallerActivity : Activity() {
-    override fun onCreate(savedInstanceState: Bundle?) {
-        super.onCreate(savedInstanceState)
-    }
-}
diff --git a/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/InstallPreVerifiedDomainsTest.kt b/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/InstallPreVerifiedDomainsTest.kt
index 4126212..cf62abb 100644
--- a/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/InstallPreVerifiedDomainsTest.kt
+++ b/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/InstallPreVerifiedDomainsTest.kt
@@ -17,6 +17,7 @@
 package android.packageinstaller.install.cts
 
 import android.app.UiAutomation
+import android.content.ComponentName
 import android.content.pm.Flags
 import android.platform.test.annotations.AppModeFull
 import android.platform.test.annotations.RequiresFlagsEnabled
@@ -63,15 +64,27 @@
     @RequiresFlagsEnabled(Flags.FLAG_SET_PRE_VERIFIED_DOMAINS)
     @Test
     fun testSetPreVerifiedDomainsNotInstantAppInstaller() {
+        val defaultInstantAppInstaller: ComponentName? = pm.getInstantAppInstallerComponent()
         uiAutomation.adoptShellPermissionIdentity(android.Manifest.permission.ACCESS_INSTANT_APPS)
         try {
-            assertThrows(
-                    "Only the instant app installer can call this API.",
-                    SecurityException::class.java,
-                    ThrowingRunnable {
-                        createSessionWithPreVerifiedDomains(testDomains)
-                    }
-            )
+            if (defaultInstantAppInstaller != null) {
+                assertThrows(
+                        "Only the instant app installer can call this API.",
+                        SecurityException::class.java,
+                        ThrowingRunnable {
+                            createSessionWithPreVerifiedDomains(testDomains)
+                        }
+                )
+            } else {
+                assertThrows(
+                        "Instant app installer is not available. " +
+                                "Only the instant app installer can call this API.",
+                        IllegalStateException::class.java,
+                        ThrowingRunnable {
+                            createSessionWithPreVerifiedDomains(testDomains)
+                        }
+                )
+            }
         } finally {
             uiAutomation.dropShellPermissionIdentity()
         }
diff --git a/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java
index 1e58f1e..e748fc9 100644
--- a/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java
@@ -1599,6 +1599,11 @@
         verifyIsInSelfManagedCallCrossUsers(TEST_SELF_MANAGED_HANDLE_1,
                 TEST_SELF_MANAGED_HANDLE_1.getUserHandle(), false);
 
+        // Deliberately pass in different UserHandle different from the calling user to ensure that
+        // the API indicates that there aren't any ongoing calls.
+        verifyIsInSelfManagedCallCrossUsers(TEST_SELF_MANAGED_HANDLE_1,
+                UserHandle.of(UserHandle.MIN_SECONDARY_USER_ID), false);
+
         // Deliberately pass in different UserHandle to ensure that cross users functionality
         // works as intended.
         verifyIsInSelfManagedCallCrossUsers(TEST_SELF_MANAGED_HANDLE_1,
@@ -1611,10 +1616,16 @@
             UserHandle userHandle, boolean hasCrossUsers) throws Exception {
         SelfManagedConnection connection = null;
 
+        boolean assertIsInSelfManagedCall = true;
+        if (!handle.getUserHandle().equals(userHandle) && !hasCrossUsers) {
+            assertIsInSelfManagedCall = false;
+        }
+
         try {
             connection = placeSelfManagedCallAndGetConnection(handle, TEST_ADDRESS_1);
-            assertTrue(mTelecomManager.isInSelfManagedCall(
-                    handle.getComponentName().getPackageName(), userHandle, hasCrossUsers));
+            boolean isInSelfManagedCall = mTelecomManager.isInSelfManagedCall(
+                    handle.getComponentName().getPackageName(), userHandle, hasCrossUsers);
+            assertEquals(assertIsInSelfManagedCall, isInSelfManagedCall);
         } finally {
             if (connection != null) {
                 // Disconnect the call
diff --git a/tests/tests/text/src/android/text/style/cts/LineBreakConfigSpanTest.kt b/tests/tests/text/src/android/text/style/cts/LineBreakConfigSpanTest.kt
index 04d89a3..dfac64c 100644
--- a/tests/tests/text/src/android/text/style/cts/LineBreakConfigSpanTest.kt
+++ b/tests/tests/text/src/android/text/style/cts/LineBreakConfigSpanTest.kt
@@ -26,6 +26,9 @@
 import android.graphics.text.LineBreakConfig.LINE_BREAK_WORD_STYLE_UNSPECIFIED
 import android.graphics.text.MeasuredText
 import android.os.Parcel
+import android.platform.test.annotations.RequiresFlagsEnabled
+import android.platform.test.flag.junit.CheckFlagsRule
+import android.platform.test.flag.junit.DeviceFlagsValueProvider
 import android.text.MeasuredParagraph
 import android.text.SpannableString
 import android.text.Spanned
@@ -38,9 +41,11 @@
 import androidx.test.ext.junit.runners.AndroidJUnit4
 import androidx.test.filters.SmallTest
 import androidx.test.platform.app.InstrumentationRegistry
+import com.android.text.flags.Flags
 import com.google.common.truth.Truth.assertThat
 import java.util.Locale
 import junit.framework.Assert.assertEquals
+import org.junit.Rule
 import org.junit.Test
 import org.junit.runner.RunWith
 
@@ -50,6 +55,10 @@
 @RunWith(AndroidJUnit4::class)
 class LineBreakConfigSpanTest {
 
+    @JvmField
+    @Rule
+    val mCheckFlagsRule: CheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule()
+
     private data class Run(val length: Int, val lineBreakConfig: LineBreakConfig?, val paint: Paint)
 
     private val paint = TextPaint().apply {
@@ -85,6 +94,7 @@
     }
 
     @Test
+    @RequiresFlagsEnabled(Flags.FLAG_NO_BREAK_NO_HYPHENATION_SPAN)
     fun testLineBreakConfigSpan() {
         val config = LineBreakConfig.Builder()
                 .setLineBreakStyle(LineBreakConfig.LINE_BREAK_STYLE_LOOSE)
@@ -105,6 +115,19 @@
     }
 
     @Test
+    @RequiresFlagsEnabled(Flags.FLAG_NO_BREAK_NO_HYPHENATION_SPAN)
+    fun testLineBreakConfigSpan_getSpanTypeId() {
+        val config = LineBreakConfig.Builder()
+                .setLineBreakStyle(LineBreakConfig.LINE_BREAK_STYLE_LOOSE)
+                .build()
+        val span = LineBreakConfigSpan(config)
+        // The span type id is an opaque hidden ID, so only verifies that there should not crash by
+        // calling function.
+        span.getSpanTypeId()
+    }
+
+    @Test
+    @RequiresFlagsEnabled(Flags.FLAG_NO_BREAK_NO_HYPHENATION_SPAN)
     fun testLineBreakConfigSpan_override() {
         // Span overview of this test case
         // |------------------------------------------------|: Test String
@@ -150,6 +173,7 @@
     }
 
     @Test
+    @RequiresFlagsEnabled(Flags.FLAG_NO_BREAK_NO_HYPHENATION_SPAN)
     fun testLineBreakConfigSpan_partialOverride() {
         // |------------------------------------------------|: Test String
         //
@@ -197,6 +221,7 @@
     }
 
     @Test
+    @RequiresFlagsEnabled(Flags.FLAG_NO_BREAK_NO_HYPHENATION_SPAN)
     fun testLineBreakConfigSpan_partialOverride2() {
         // |--------------------------------------------------------|: Test String
         //
@@ -247,6 +272,7 @@
     }
 
     @Test
+    @RequiresFlagsEnabled(Flags.FLAG_NO_BREAK_NO_HYPHENATION_SPAN)
     fun testLineBreakConfigSpan_partialOverride3() {
         // |--------------------------------------------------------|: Test String
         //
@@ -299,6 +325,7 @@
     }
 
     @Test
+    @RequiresFlagsEnabled(Flags.FLAG_NO_BREAK_NO_HYPHENATION_SPAN)
     fun testLineBreakConfigSpan_MetricAffectingSpanMixture() {
         // |--------------------------------------------------------|: Test String
         //
@@ -348,6 +375,7 @@
     }
 
     @Test
+    @RequiresFlagsEnabled(Flags.FLAG_NO_BREAK_NO_HYPHENATION_SPAN)
     fun testLineBreakConfigSpan_MetricAffectingSpanMixture2() {
         // |--------------------------------------------------------|: Test String
         //
@@ -428,6 +456,7 @@
     }
 
     @Test
+    @RequiresFlagsEnabled(Flags.FLAG_NO_BREAK_NO_HYPHENATION_SPAN)
     fun testLineBreakConfigSpan_parcelable() {
         val strictConfig = LineBreakConfig.Builder()
                 .setLineBreakStyle(LINE_BREAK_STYLE_STRICT)
@@ -466,6 +495,7 @@
     }
 
     @Test
+    @RequiresFlagsEnabled(Flags.FLAG_NO_BREAK_NO_HYPHENATION_SPAN)
     fun testLineBreakConfigSpan_resource() {
         val context = InstrumentationRegistry.getInstrumentation().getTargetContext()
 
diff --git a/tests/tests/view/src/android/view/cts/GLSurfaceViewCtsActivity.java b/tests/tests/view/src/android/view/cts/GLSurfaceViewCtsActivity.java
index bb4dce7..f7efce2 100644
--- a/tests/tests/view/src/android/view/cts/GLSurfaceViewCtsActivity.java
+++ b/tests/tests/view/src/android/view/cts/GLSurfaceViewCtsActivity.java
@@ -16,22 +16,52 @@
 
 package android.view.cts;
 
+import static junit.framework.Assert.assertTrue;
+import static junit.framework.Assert.fail;
+
 import android.app.Activity;
+import android.content.Context;
 import android.opengl.GLSurfaceView;
 import android.os.Bundle;
 import android.view.Window;
 
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
 /**
  * A minimal activity for testing {@link android.opengl.GLSurfaceView}.
  * Also accepts non-blank renderers to allow its use for more complex tests.
  */
 public abstract class GLSurfaceViewCtsActivity extends Activity {
-    protected GLSurfaceView mView;
+
+    private boolean mIsStarted = false;
+    private boolean mEnterAnimationComplete = false;
+
+    public static class TestableGLSurfaceView extends GLSurfaceView {
+
+        public TestableGLSurfaceView(Context context) {
+            super(context);
+        }
+
+        void requestRenderAndWait() {
+            CountDownLatch fence = new CountDownLatch(1);
+
+            surfaceRedrawNeededAsync(getHolder(), fence::countDown);
+
+            try {
+                assertTrue(fence.await(5, TimeUnit.SECONDS));
+            } catch (InterruptedException ex) {
+                throw new AssertionError("Interrupted", ex);
+            }
+        }
+    }
+
+    protected TestableGLSurfaceView mView;
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        mView = new GLSurfaceView(this);
+        mView = new TestableGLSurfaceView(this);
         configureGLSurfaceView();
 
         requestWindowFeature(Window.FEATURE_NO_TITLE);
@@ -40,19 +70,53 @@
 
     protected abstract void configureGLSurfaceView();
 
-    public GLSurfaceView getView() {
+    public TestableGLSurfaceView getView() {
         return mView;
     }
 
-    @Override
-    protected void onResume() {
-        super.onResume();
-        mView.onResume();
+    public void waitForReady() {
+        long startMs = System.currentTimeMillis();
+        synchronized (this) {
+            while (!(mIsStarted && mEnterAnimationComplete)) {
+                if ((System.currentTimeMillis() - startMs) > 5000) {
+                    fail("Timeout");
+                }
+                try {
+                    wait(100);
+                } catch (InterruptedException ex) {
+                    throw new AssertionError("Interrupted", ex);
+                }
+            }
+        }
+        mView.requestRenderAndWait();
     }
 
     @Override
-    protected void onPause() {
-        super.onPause();
+    protected void onStart() {
+        super.onStart();
+        mView.onResume();
+        synchronized (this) {
+            mIsStarted = true;
+            notifyAll();
+        }
+    }
+
+    @Override
+    public void onEnterAnimationComplete() {
+        super.onEnterAnimationComplete();
+        synchronized (this) {
+            mEnterAnimationComplete = true;
+            notifyAll();
+        }
+    }
+
+    @Override
+    protected void onStop() {
+        super.onStop();
         mView.onPause();
+        synchronized (this) {
+            mIsStarted = false;
+            mEnterAnimationComplete = false;
+        }
     }
 }
diff --git a/tests/tests/view/src/android/view/cts/PixelCopyGLProducerCtsActivity.java b/tests/tests/view/src/android/view/cts/PixelCopyGLProducerCtsActivity.java
index b7518a5..04ff804 100644
--- a/tests/tests/view/src/android/view/cts/PixelCopyGLProducerCtsActivity.java
+++ b/tests/tests/view/src/android/view/cts/PixelCopyGLProducerCtsActivity.java
@@ -20,6 +20,7 @@
 import static android.opengl.GLES20.GL_SCISSOR_TEST;
 import static android.opengl.GLES20.glClear;
 import static android.opengl.GLES20.glClearColor;
+import static android.opengl.GLES20.glDisable;
 import static android.opengl.GLES20.glEnable;
 import static android.opengl.GLES20.glScissor;
 
@@ -65,6 +66,9 @@
             int cx = mWidth / 2;
             int cy = mHeight / 2;
 
+            glDisable(GL_SCISSOR_TEST);
+            clearColor(Color.MAGENTA);
+
             glEnable(GL_SCISSOR_TEST);
 
             glScissor(0, cy, cx, mHeight - cy);
@@ -78,10 +82,6 @@
 
             glScissor(cx, 0, mWidth - cx, cy);
             clearColor(mBottomRightColor);
-
-            if (mFence != null) {
-                mFence.countDown();
-            }
         }
 
         private void clearColor(int color) {
@@ -104,8 +104,4 @@
         mView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
         mView.getHolder().setFixedSize(100, 100);
     }
-
-    public void setSwapFence(CountDownLatch swapFence) {
-        mRenderer.mFence = swapFence;
-    }
 }
diff --git a/tests/tests/view/src/android/view/cts/PixelCopyTest.java b/tests/tests/view/src/android/view/cts/PixelCopyTest.java
index e98e8d7..854c370 100644
--- a/tests/tests/view/src/android/view/cts/PixelCopyTest.java
+++ b/tests/tests/view/src/android/view/cts/PixelCopyTest.java
@@ -228,19 +228,9 @@
     }
 
     private PixelCopyGLProducerCtsActivity waitForGlProducerActivity() {
-        CountDownLatch swapFence = new CountDownLatch(2);
-
         PixelCopyGLProducerCtsActivity activity =
                 mGLSurfaceViewActivityRule.launchActivity(null);
-        activity.setSwapFence(swapFence);
-
-        try {
-            while (!swapFence.await(5, TimeUnit.MILLISECONDS)) {
-                activity.getView().requestRender();
-            }
-        } catch (InterruptedException ex) {
-            Assert.fail("Interrupted, error=" + ex.getMessage());
-        }
+        activity.waitForReady();
         return activity;
     }
 
@@ -333,14 +323,17 @@
         PixelCopyGLProducerCtsActivity activity = waitForGlProducerActivity();
         Bitmap bitmap = Bitmap.createBitmap(20, 20, Config.ARGB_8888);
         int result = mCopyHelper.request(activity.getView(), bitmap);
+        assertEquals(result, PixelCopy.SUCCESS);
         // Make sure nothing messed with the bitmap
         assertEquals(20, bitmap.getWidth());
         assertEquals(20, bitmap.getHeight());
         assertEquals(Config.ARGB_8888, bitmap.getConfig());
         assertBitmapQuadColor(bitmap,
                 Color.RED, Color.GREEN, Color.BLUE, Color.BLACK);
+        bitmap.eraseColor(Color.MAGENTA);
         int generationId = bitmap.getGenerationId();
         result = mCopyHelper.request(activity.getView(), bitmap);
+        assertEquals(result, PixelCopy.SUCCESS);
         // Make sure nothing messed with the bitmap
         assertEquals(20, bitmap.getWidth());
         assertEquals(20, bitmap.getHeight());
@@ -826,34 +819,23 @@
     @Test
     @LargeTest
     public void testNotLeaking() {
-        try {
-            CountDownLatch swapFence = new CountDownLatch(2);
+        PixelCopyGLProducerCtsActivity activity =
+                mGLSurfaceViewActivityRule.launchActivity(null);
+        activity.waitForReady();
 
-            PixelCopyGLProducerCtsActivity activity =
-                    mGLSurfaceViewActivityRule.launchActivity(null);
-            activity.setSwapFence(swapFence);
+        // Test a fullsize copy
+        Bitmap bitmap = Bitmap.createBitmap(100, 100, Config.ARGB_8888);
 
-            while (!swapFence.await(5, TimeUnit.MILLISECONDS)) {
-                activity.getView().requestRender();
-            }
-
-            // Test a fullsize copy
-            Bitmap bitmap = Bitmap.createBitmap(100, 100, Config.ARGB_8888);
-
-            runNotLeakingTest(() -> {
-                int result = mCopyHelper.request(activity.getView(), bitmap);
-                assertEquals("Copy request failed", PixelCopy.SUCCESS, result);
-                // Make sure nothing messed with the bitmap
-                assertEquals(100, bitmap.getWidth());
-                assertEquals(100, bitmap.getHeight());
-                assertEquals(Config.ARGB_8888, bitmap.getConfig());
-                assertBitmapQuadColor(bitmap,
-                        Color.RED, Color.GREEN, Color.BLUE, Color.BLACK);
-            });
-
-        } catch (InterruptedException e) {
-            Assert.fail("Interrupted, error=" + e.getMessage());
-        }
+        runNotLeakingTest(() -> {
+            int result = mCopyHelper.request(activity.getView(), bitmap);
+            assertEquals("Copy request failed", PixelCopy.SUCCESS, result);
+            // Make sure nothing messed with the bitmap
+            assertEquals(100, bitmap.getWidth());
+            assertEquals(100, bitmap.getHeight());
+            assertEquals(Config.ARGB_8888, bitmap.getConfig());
+            assertBitmapQuadColor(bitmap,
+                    Color.RED, Color.GREEN, Color.BLUE, Color.BLACK);
+        });
     }
 
     @Test
diff --git a/tests/tests/voiceinteraction/service/src/android/voiceinteraction/service/MainInteractionSession.java b/tests/tests/voiceinteraction/service/src/android/voiceinteraction/service/MainInteractionSession.java
index 078e47f..196257b 100644
--- a/tests/tests/voiceinteraction/service/src/android/voiceinteraction/service/MainInteractionSession.java
+++ b/tests/tests/voiceinteraction/service/src/android/voiceinteraction/service/MainInteractionSession.java
@@ -38,6 +38,7 @@
     public static final String ACTION_SESSION_STARTED = "session_started";
     public static final String ACTION_SCREENSHOT_RECEIVED = "screenshot_received";
     public static final String ACTION_ASSIST_DATA_RECEIVED = "assist_data_received";
+    public static final String ACTION_ON_SHOW_RECEIVED = "on_show_received";
     public static final String EXTRA_RECEIVED = "received";
 
     Intent mStartIntent;
@@ -74,6 +75,7 @@
             return;
         }
         mStartIntent = args.getParcelable("intent");
+        notifyTestReceiver(ACTION_ON_SHOW_RECEIVED, args);
         if (mStartIntent != null) {
             startVoiceActivity(mStartIntent);
         } else if ((showFlags & SHOW_SOURCE_ACTIVITY) == SHOW_SOURCE_ACTIVITY) {
diff --git a/tests/tests/voiceinteraction/service/src/android/voiceinteraction/service/MainVisualQueryDetectionService.java b/tests/tests/voiceinteraction/service/src/android/voiceinteraction/service/MainVisualQueryDetectionService.java
index 36c3058..cbcdc81 100644
--- a/tests/tests/voiceinteraction/service/src/android/voiceinteraction/service/MainVisualQueryDetectionService.java
+++ b/tests/tests/voiceinteraction/service/src/android/voiceinteraction/service/MainVisualQueryDetectionService.java
@@ -34,6 +34,7 @@
 import android.os.PersistableBundle;
 import android.os.Process;
 import android.os.SharedMemory;
+import android.service.voice.VisualQueryDetectedResult;
 import android.service.voice.VisualQueryDetectionService;
 import android.system.ErrnoException;
 import android.util.Log;
@@ -76,6 +77,7 @@
     public static final int SCENARIO_QUERY_NO_ATTENTION = 5;
     public static final int SCENARIO_QUERY_NO_QUERY_FINISH = 6;
     public static final int SCENARIO_MULTIPLE_QUERIES_FINISHED = 7;
+    public static final int SCENARIO_COMPLEX_RESULT_STREAM_QUERY_ONLY = 8;
     public static final int SCENARIO_READ_FILE_MMAP_READ_ONLY = 100;
     public static final int SCENARIO_READ_FILE_MMAP_WRITE = 101;
     public static final int SCENARIO_READ_FILE_MMAP_MULTIPLE = 102;
@@ -266,6 +268,18 @@
                 }
                 lostAttention();
             };
+        } else if (scenario == SCENARIO_COMPLEX_RESULT_STREAM_QUERY_ONLY) {
+            detectionJob = () -> {
+                gainedAttention();
+                streamQuery(
+                        new VisualQueryDetectedResult.Builder().setPartialQuery(FAKE_QUERY_FIRST)
+                                .build());
+                streamQuery(
+                        new VisualQueryDetectedResult.Builder().setPartialQuery(FAKE_QUERY_SECOND)
+                                .build());
+                finishQuery();
+                lostAttention();
+            };
         } else if (scenario == SCENARIO_READ_FILE_MMAP_READ_ONLY
                 || scenario == SCENARIO_READ_FILE_MMAP_WRITE
                 || scenario == SCENARIO_READ_FILE_FILE_NOT_EXIST) {
diff --git a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VisualQueryDetectionServiceBasicTest.java b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VisualQueryDetectionServiceBasicTest.java
index 3bbcacc..95cda73 100644
--- a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VisualQueryDetectionServiceBasicTest.java
+++ b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VisualQueryDetectionServiceBasicTest.java
@@ -415,6 +415,41 @@
 
     @Test
     @RequiresDevice
+    public void testVisualQueryDetectionService_startRecogintion_complexResultsQueryOnlySuccess()
+            throws Throwable {
+        // Create VisualQueryDetector
+        VisualQueryDetector visualQueryDetector = createVisualQueryDetector();
+        runWithShellPermissionIdentity(() -> {
+            PersistableBundle options = Helper.createFakePersistableBundleData();
+            options.putInt(MainVisualQueryDetectionService.KEY_VQDS_TEST_SCENARIO,
+                    MainVisualQueryDetectionService.SCENARIO_COMPLEX_RESULT_STREAM_QUERY_ONLY);
+            visualQueryDetector.updateState(options, Helper.createFakeSharedMemoryData());
+        });
+        try {
+            adoptShellPermissionIdentityForVisualQueryDetection();
+
+            mService.initQueryFinishRejectLatch(1);
+            visualQueryDetector.startRecognition();
+
+            // wait onStartDetection() called and verify the result
+            mService.waitOnQueryFinishedRejectCalled();
+
+            // verify results
+            ArrayList<String> streamedQueries = mService.getStreamedQueriesResult();
+            assertThat(streamedQueries.get(0)).isEqualTo(
+                    MainVisualQueryDetectionService.FAKE_QUERY_FIRST
+                            + MainVisualQueryDetectionService.FAKE_QUERY_SECOND);
+            assertThat(streamedQueries.size()).isEqualTo(1);
+        } finally {
+            visualQueryDetector.destroy();
+            // Drop identity adopted.
+            InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                    .dropShellPermissionIdentity();
+        }
+    }
+
+    @Test
+    @RequiresDevice
     public void testVisualQueryDetectionService_startRecogintion_noAttention()
             throws Throwable {
         // Create VisualQueryDetector
diff --git a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionServiceTest.java b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionServiceTest.java
index b5abfbc..21ca887 100644
--- a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionServiceTest.java
+++ b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionServiceTest.java
@@ -19,6 +19,7 @@
 import static android.Manifest.permission.CAPTURE_AUDIO_HOTWORD;
 import static android.Manifest.permission.MANAGE_HOTWORD_DETECTION;
 import static android.Manifest.permission.RECORD_AUDIO;
+import static android.service.voice.VoiceInteractionSession.KEY_FOREGROUND_ACTIVITIES;
 import static android.service.voice.VoiceInteractionSession.KEY_SHOW_SESSION_ID;
 import static android.voiceinteraction.cts.testcore.Helper.CTS_SERVICE_PACKAGE;
 
@@ -187,6 +188,29 @@
         assertThat(obtainedAssistData).isFalse();
     }
 
+    @ApiTest(apis = {"android.service.voice.VoiceInteractionSession#onShow"})
+    @Test
+    public void onShow_hasForegroundActivities() throws Exception {
+        startActivityAndShowSession(sDeviceState.initialUser());
+        Bundle onShowArgs = VoiceInteractionTestReceiver.waitOnShowReceived(5,
+                TimeUnit.SECONDS);
+
+        assertThat(onShowArgs).isNotNull();
+        assertThat(onShowArgs.containsKey(KEY_FOREGROUND_ACTIVITIES)).isTrue();
+    }
+
+    @ApiTest(apis = {"android.service.voice.VoiceInteractionSession#onShow"})
+    @Test
+    @EnsureHasPrivateProfile
+    public void onShow_privateProfile_noForegroundActivities() throws Exception {
+        startActivityAndShowSession(sDeviceState.privateProfile());
+        Bundle onShowArgs = VoiceInteractionTestReceiver.waitOnShowReceived(5,
+                TimeUnit.SECONDS);
+
+        assertThat(onShowArgs).isNotNull();
+        assertThat(onShowArgs.containsKey(KEY_FOREGROUND_ACTIVITIES)).isFalse();
+    }
+
     private void startActivityAndShowSession(UserReference userToStartActivity) {
         sScreenshotEnabledManager.set("1");
 
diff --git a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionTestReceiver.java b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionTestReceiver.java
index 59a3a10..1a937fd 100644
--- a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionTestReceiver.java
+++ b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionTestReceiver.java
@@ -21,6 +21,7 @@
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
+import android.os.Bundle;
 import android.util.Log;
 import android.voiceinteraction.service.MainInteractionSession;
 
@@ -34,8 +35,8 @@
     private static CountDownLatch sServiceStartedLatch = new CountDownLatch(1);
     private static Intent sReceivedIntent;
     private static CountDownLatch sScreenshotReceivedLatch = new CountDownLatch(1);
-
     private static CountDownLatch sAssistDataReceivedLatch = new CountDownLatch(1);
+    private static CountDownLatch sOnShowReceivedLatch = new CountDownLatch(1);
 
     public static void waitSessionStarted(long timeout, TimeUnit unit) throws InterruptedException {
         if (!sServiceStartedLatch.await(timeout, unit)) {
@@ -73,6 +74,16 @@
         return sReceivedIntent.getBooleanExtra(MainInteractionSession.EXTRA_RECEIVED, false);
     }
 
+    /** Waits for onShow being called. */
+    public static Bundle waitOnShowReceived(long timeout, TimeUnit unit)
+            throws InterruptedException {
+        if (!sOnShowReceivedLatch.await(timeout, unit)) {
+            // Timeout. Assume this means no assist data is sent to VoiceInteractionService.
+            return null;
+        }
+        return sReceivedIntent.getExtras();
+    }
+
     @Override
     public void onReceive(Context context, Intent intent) {
         Log.i(TAG, "Got broadcast that MainInteractionService started");
@@ -83,6 +94,8 @@
                     sScreenshotReceivedLatch.countDown();
             case MainInteractionSession.ACTION_ASSIST_DATA_RECEIVED ->
                     sAssistDataReceivedLatch.countDown();
+            case MainInteractionSession.ACTION_ON_SHOW_RECEIVED ->
+                    sOnShowReceivedLatch.countDown();
         }
     }
 
@@ -92,5 +105,6 @@
         sServiceStartedLatch = new CountDownLatch(1);
         sScreenshotReceivedLatch = new CountDownLatch(1);
         sAssistDataReceivedLatch = new CountDownLatch(1);
+        sOnShowReceivedLatch = new CountDownLatch(1);
     }
 }
\ No newline at end of file
diff --git a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/services/BaseVoiceInteractionService.java b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/services/BaseVoiceInteractionService.java
index 6851518..8095b72 100644
--- a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/services/BaseVoiceInteractionService.java
+++ b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/services/BaseVoiceInteractionService.java
@@ -28,6 +28,7 @@
 import android.service.voice.AlwaysOnHotwordDetector;
 import android.service.voice.HotwordDetector;
 import android.service.voice.HotwordRejectedResult;
+import android.service.voice.VisualQueryDetectedResult;
 import android.service.voice.VisualQueryDetectionServiceFailure;
 import android.service.voice.VisualQueryDetector;
 import android.service.voice.VoiceInteractionService;
@@ -180,6 +181,11 @@
                 }
 
                 @Override
+                public void onQueryDetected(@NonNull VisualQueryDetectedResult partialResult) {
+                    //No-op
+                }
+
+                @Override
                 public void onQueryRejected() {
                     //No-op
                 }
diff --git a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/services/CtsBasicVoiceInteractionService.java b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/services/CtsBasicVoiceInteractionService.java
index c197a9b..2ea4a47 100644
--- a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/services/CtsBasicVoiceInteractionService.java
+++ b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/services/CtsBasicVoiceInteractionService.java
@@ -42,6 +42,7 @@
 import android.service.voice.HotwordTrainingData;
 import android.service.voice.SandboxedDetectionInitializer;
 import android.service.voice.SoundTriggerFailure;
+import android.service.voice.VisualQueryDetectedResult;
 import android.service.voice.VisualQueryDetectionService;
 import android.service.voice.VisualQueryDetectionServiceFailure;
 import android.service.voice.VisualQueryDetector;
@@ -742,6 +743,12 @@
                 }
 
                 @Override
+                public void onQueryDetected(@NonNull VisualQueryDetectedResult partialResult) {
+                    Log.i(TAG, "onQueryDetected with VisualQueryDetectedResult");
+                    mCurrentQuery += partialResult.getPartialQuery();
+                }
+
+                @Override
                 public void onQueryRejected() {
                     Log.i(TAG, "onQueryRejected");
                     // mStreamedQueries are used to store previously streamed queries for testing
diff --git a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/unittests/HotwordDetectedResultTest.java b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/unittests/HotwordDetectedResultTest.java
index 9e33cf7..07137c0 100644
--- a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/unittests/HotwordDetectedResultTest.java
+++ b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/unittests/HotwordDetectedResultTest.java
@@ -183,6 +183,15 @@
     }
 
     @Test
+    public void testHotwordDetectedResult_setInvalidSpeakerId() throws Exception {
+        assertThrows(IllegalArgumentException.class,
+                () -> new HotwordDetectedResult.Builder().setSpeakerId(-1).build());
+        assertThrows(IllegalArgumentException.class,
+                () -> new HotwordDetectedResult.Builder().setSpeakerId(
+                        HotwordDetectedResult.getMaxSpeakerId() + 1).build());
+    }
+
+    @Test
     public void testHotwordDetectedResultBuilder() throws Exception {
         final ParcelFileDescriptor[] fakeAudioStreamPipe = createFakeAudioStreamPipe(
                 FAKE_HOTWORD_AUDIO_STREAM_DATA);
@@ -205,7 +214,8 @@
                             /* hotwordPhraseId= */ 1,
                             audioStreams,
                             new PersistableBundle(),
-                            /* backgroundAudioPower= */ 100);
+                            /* backgroundAudioPower= */ 100,
+                            /* speakerId= */ 1);
 
             assertHotwordDetectedResult(hotwordDetectedResult);
             HotwordAudioStream result = hotwordDetectedResult.getAudioStreams().get(0);
@@ -239,7 +249,8 @@
                             /* hotwordPhraseId= */ 1,
                             audioStreams,
                             new PersistableBundle(),
-                            /* backgroundAudioPower= */ 100);
+                            /* backgroundAudioPower= */ 100,
+                            /* speakerId= */ 1);
 
             final Parcel p = Parcel.obtain();
             hotwordDetectedResult.writeToParcel(p, 0);
@@ -270,7 +281,8 @@
             int hotwordPhraseId,
             List<HotwordAudioStream> audioStreams,
             PersistableBundle extras,
-            int backgroundAudioPower) {
+            int backgroundAudioPower,
+            int speakerId) {
         return new HotwordDetectedResult.Builder()
                 .setConfidenceLevel(confidenceLevel)
                 .setMediaSyncEvent(mediaSyncEvent)
@@ -284,6 +296,7 @@
                 .setAudioStreams(audioStreams)
                 .setExtras(extras)
                 .setBackgroundAudioPower(backgroundAudioPower)
+                .setSpeakerId(speakerId)
                 .build();
     }
 
@@ -301,6 +314,7 @@
         assertThat(hotwordDetectedResult.getAudioStreams()).isNotNull();
         assertThat(hotwordDetectedResult.getExtras()).isNotNull();
         assertThat(hotwordDetectedResult.getBackgroundAudioPower()).isEqualTo(100);
+        assertThat(hotwordDetectedResult.getSpeakerId()).isEqualTo(1);
     }
 
     private static void assertHotwordAudioStream(HotwordAudioStream hotwordAudioStream,
diff --git a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/unittests/VisualQueryDetectedResultTest.java b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/unittests/VisualQueryDetectedResultTest.java
new file mode 100644
index 0000000..3e98c66
--- /dev/null
+++ b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/unittests/VisualQueryDetectedResultTest.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.voiceinteraction.cts.unittests;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertThrows;
+
+import android.os.Parcel;
+import android.service.voice.VisualQueryDetectedResult;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class VisualQueryDetectedResultTest {
+
+    private static final String TEST_QUERY = "What time is it?";
+
+    @Test
+    public void testVisualQueryDetectedResult_setInvalidSpeakerId() throws Exception {
+        assertThrows(IllegalArgumentException.class,
+                () -> new VisualQueryDetectedResult.Builder().setSpeakerId(-1).build());
+        assertThrows(IllegalArgumentException.class,
+                () -> new VisualQueryDetectedResult.Builder().setSpeakerId(
+                        VisualQueryDetectedResult.getMaxSpeakerId() + 1).build());
+    }
+
+    @Test
+    public void testVisualQueryDetectedResultBuilder() throws Exception {
+        final VisualQueryDetectedResult visualQueryDetectedResult =
+                buildVisualQueryDetectedResult(
+                        /* partialQuery= */ TEST_QUERY,
+                        /* speakerId= */ 1);
+        assertVisualQueryDetectedResult(visualQueryDetectedResult);
+
+    }
+
+    @Test
+    public void testHotwordDetectedResultParcelizeDeparcelize() throws Exception {
+        final VisualQueryDetectedResult visualQueryDetectedResult =
+                buildVisualQueryDetectedResult(
+                        /* partialQuery= */ TEST_QUERY,
+                        /* speakerId= */ 1);
+        final Parcel p = Parcel.obtain();
+        visualQueryDetectedResult.writeToParcel(p, 0);
+        p.setDataPosition(0);
+
+        final VisualQueryDetectedResult targetVisualQueryDetectedResult =
+                VisualQueryDetectedResult.CREATOR.createFromParcel(p);
+        p.recycle();
+        assertVisualQueryDetectedResult(targetVisualQueryDetectedResult);
+    }
+
+    private VisualQueryDetectedResult buildVisualQueryDetectedResult(
+            String partialQuery,
+            int speakerId) {
+        return new VisualQueryDetectedResult.Builder()
+                .setPartialQuery(TEST_QUERY)
+                .setSpeakerId(speakerId)
+                .build();
+    }
+
+    private void assertVisualQueryDetectedResult(
+            VisualQueryDetectedResult visualQueryDetectedResult) {
+        assertThat(visualQueryDetectedResult.getPartialQuery()).isEqualTo(TEST_QUERY);
+        assertThat(visualQueryDetectedResult.getSpeakerId()).isEqualTo(1);
+    }
+}
diff --git a/tests/tests/widget/src/android/widget/cts/TextViewMinimumFontMetrics.kt b/tests/tests/widget/src/android/widget/cts/TextViewMinimumFontMetrics.kt
index c5f0f7d..c0e11b4 100644
--- a/tests/tests/widget/src/android/widget/cts/TextViewMinimumFontMetrics.kt
+++ b/tests/tests/widget/src/android/widget/cts/TextViewMinimumFontMetrics.kt
@@ -17,6 +17,8 @@
 
 import android.graphics.Paint
 import android.platform.test.annotations.RequiresFlagsEnabled
+import android.platform.test.flag.junit.CheckFlagsRule
+import android.platform.test.flag.junit.DeviceFlagsValueProvider
 import android.view.View.MeasureSpec
 import android.widget.TextView
 import androidx.test.InstrumentationRegistry
@@ -24,6 +26,7 @@
 import androidx.test.runner.AndroidJUnit4
 import com.android.text.flags.Flags.FLAG_USE_BOUNDS_FOR_WIDTH
 import com.google.common.truth.Truth.assertThat
+import org.junit.Rule
 import org.junit.Test
 import org.junit.runner.RunWith
 
@@ -36,6 +39,10 @@
 
     private val context = InstrumentationRegistry.getInstrumentation().getTargetContext()
 
+    @JvmField
+    @Rule
+    val mCheckFlagsRule: CheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule()
+
     @Test
     @RequiresFlagsEnabled(FLAG_USE_BOUNDS_FOR_WIDTH)
     fun testMinimumFontHeight_NullByDefault() {