Merge "Use revised constant ProvisioningManager Name" into rvc-dev
diff --git a/apps/CameraITS/tests/scene6/test_zoom.py b/apps/CameraITS/tests/scene6/test_zoom.py
index 4671550..eef7144 100644
--- a/apps/CameraITS/tests/scene6/test_zoom.py
+++ b/apps/CameraITS/tests/scene6/test_zoom.py
@@ -24,19 +24,21 @@
 
 import numpy as np
 
+CIRCLE_COLOR = 0  # [0: black, 255: white]
 CIRCLE_TOL = 0.05  # contour area vs ideal circle area pi*((w+h)/4)**2
-COLOR = 0  # [0: black, 255: white]
+LINE_COLOR = (255, 0, 0)  # red
+LINE_THICKNESS = 5
+MIN_AREA_RATIO = 0.00015  # based on 2000/(4000x3000) pixels
+MIN_CIRCLE_PTS = 25
 NAME = os.path.basename(__file__).split('.')[0]
 NUM_STEPS = 10
-MIN_AREA_RATIO = 0.00015  # Based on 2000/(4000x3000) pixels
-MIN_CIRCLE_PTS = 25
 OFFSET_RTOL = 0.10
 RADIUS_RTOL = 0.10
 ZOOM_MAX_THRESH = 10.0
 ZOOM_MIN_THRESH = 2.0
 
 
-def distance(x, y):
+def distance((x, y)):
     return math.sqrt(x**2 + y**2)
 
 
@@ -116,13 +118,19 @@
         print 'circles [x, y, r, pi*r**2/area, area]:', circles
 
     # find circle closest to center
-    circles.sort(key=lambda x: distance(x[0]-img_ctr[0], x[1]-img_ctr[1]))
+    circles.sort(key=lambda x: distance((x[0]-img_ctr[0], x[1]-img_ctr[1])))
     circle = circles[0]
 
+    # mark image center
+    size = gray.shape
+    cv2.drawMarker(img, (size[1]/2, size[0]/2), LINE_COLOR,
+                   markerType=cv2.MARKER_CROSS, markerSize=LINE_THICKNESS*10,
+                   thickness=LINE_THICKNESS)
+
     # add circle to saved image
     center_i = (int(round(circle[0], 0)), int(round(circle[1], 0)))
     radius_i = int(round(circle[2], 0))
-    cv2.circle(img, center_i, radius_i, (255, 0, 0), 5)
+    cv2.circle(img, center_i, radius_i, LINE_COLOR, LINE_THICKNESS)
     its.image.write_image(img/255.0, name)
 
     if not circles:
@@ -137,7 +145,8 @@
     """Test the camera zoom behavior."""
 
     z_test_list = []
-    circle = {}
+    fls = []
+    circles = []
     with its.device.ItsSession() as cam:
         props = cam.get_camera_properties()
         its.caps.skip_unless(its.caps.zoom_ratio_range(props))
@@ -166,13 +175,15 @@
             img = img.astype(np.uint8)
 
             # Find the circles in img
-            circle[i] = find_center_circle(
-                    img, '%s_%s.jpg' % (NAME, round(z, 2)), COLOR,
+            circle = find_center_circle(
+                    img, '%s_%s.jpg' % (NAME, round(z, 2)), CIRCLE_COLOR,
                     min_area=MIN_AREA_RATIO*size[0]*size[1]*z*z, debug=debug)
-            if circle_cropped(circle[i], size):
+            if circle_cropped(circle, size):
                 print 'zoom %.2f is too large! Skip further captures' % z
                 break
+            circles.append(circle)
             z_test_list.append(z)
+            fls.append(cap['metadata']['android.lens.focalLength'])
 
     # assert some range is tested before circles get too big
     zoom_max_thresh = ZOOM_MAX_THRESH
@@ -182,27 +193,37 @@
             z_test_list[-1], zoom_max_thresh)
     assert z_test_list[-1] >= zoom_max_thresh, msg
 
-    # print 'circles:', circle
-    radius_init = float(circle[0][2])
-    offset_init = [circle[0][0]-size[0]/2,
-                   circle[0][1]-size[1]/2]
-    z_init = float(z_test_list[0])
+    # initialize relative size w/ zoom[0] for diff zoom ratio checks
+    radius_0 = float(circles[0][2])
+    z_0 = float(z_test_list[0])
+
     for i, z in enumerate(z_test_list):
-        print '\nZoom: %.2f' % z
-        offset_x_abs = (circle[i][0] - size[0] / 2)
-        offset_y_abs = (circle[i][1] - size[1] / 2)
+        print '\nZoom: %.2f, fl: %.2f' % (z, fls[i])
+        offset_abs = ((circles[i][0] - size[0]/2), (circles[i][1] - size[1]/2))
         print 'Circle r: %.1f, center offset x, y: %d, %d' % (
-                circle[i][2], offset_x_abs, offset_y_abs)
-        z_ratio = z/z_init
-        radius_ratio = circle[i][2]/radius_init
+                circles[i][2], offset_abs[0], offset_abs[1])
+        z_ratio = z / z_0
+
+        # check relative size against zoom[0]
+        radius_ratio = circles[i][2]/radius_0
+        print 'radius_ratio: %.3f' % radius_ratio
         msg = 'zoom: %.2f, radius ratio: %.2f, RTOL: %.2f' % (
                 z_ratio, radius_ratio, RADIUS_RTOL)
         assert np.isclose(z_ratio, radius_ratio, rtol=RADIUS_RTOL), msg
-        offset_rel = (distance(offset_x_abs, offset_y_abs) / radius_ratio /
-                      distance(offset_init[0], offset_init[1]))
-        msg = 'zoom: %.2f, offset(rel): %.2f, RTOL: %.2f' % (
-                z, offset_rel, OFFSET_RTOL)
-        assert np.isclose(offset_rel, 1.0, rtol=OFFSET_RTOL), msg
+
+        # check relative offset against init vals w/ no focal length change
+        if i == 0 or fls[i-1] != fls[i]:  # set init values
+            z_init = float(z_test_list[i])
+            offset_init = (circles[i][0] - size[0] / 2,
+                           circles[i][1] - size[1] / 2)
+        else:  # check
+            z_ratio = z / z_init
+            offset_rel = (distance(offset_abs) / z_ratio /
+                          distance(offset_init))
+            print 'offset_rel: %.3f' % offset_rel
+            msg = 'zoom: %.2f, offset(rel): %.2f, RTOL: %.2f' % (
+                    z, offset_rel, OFFSET_RTOL)
+            assert np.isclose(offset_rel, 1.0, rtol=OFFSET_RTOL), msg
 
 
 if __name__ == '__main__':
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index fdea362..36c2284 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -2427,6 +2427,10 @@
                   android:label="@string/wifi_test_network_suggestion_connection_failure"
                   android:configChanges="keyboardHidden|orientation|screenSize" />
 
+        <activity android:name=".wifi.NetworkSuggestionModificationInPlaceTestActivity"
+                  android:label="@string/wifi_test_network_suggestion_modification_in_place"
+                  android:configChanges="keyboardHidden|orientation|screenSize" />
+
         <activity android:name=".p2p.GoNegRequesterTestListActivity"
                 android:label="@string/p2p_go_neg_requester"
                 android:configChanges="keyboardHidden|orientation|screenSize" />
diff --git a/apps/CtsVerifier/res/layout/biometric_test_credential_enrolled_tests.xml b/apps/CtsVerifier/res/layout/biometric_test_credential_enrolled_tests.xml
index 722e478..a6539ba 100644
--- a/apps/CtsVerifier/res/layout/biometric_test_credential_enrolled_tests.xml
+++ b/apps/CtsVerifier/res/layout/biometric_test_credential_enrolled_tests.xml
@@ -26,10 +26,18 @@
         android:text="@string/biometric_test_credential_enrolled_instructions" />
 
     <Button
+        android:id="@+id/enroll_credential_button"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_centerInParent="true"
+        android:text="@string/biometric_test_credential_enroll_button"/>
+
+    <Button
         android:id="@+id/bm_button"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_centerInParent="true"
+        android:enabled="false"
         android:text="@string/biometric_test_credential_enrolled_bm_button"/>
 
     <Button
@@ -37,6 +45,7 @@
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_centerInParent="true"
+        android:enabled="false"
         android:text="@string/biometric_test_credential_enrolled_bp_setAllowedAuthenticators_button"/>
 
     <Button
@@ -44,6 +53,7 @@
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerInParent="true"
+        android:enabled="false"
         android:text="@string/biometric_test_credential_enrolled_bp_setDeviceCredentialAllowed_button"/>
 
     <Space
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 0ff0798..0f708d7 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -242,9 +242,9 @@
     <string name="biometric_test_credential_not_enrolled_bp_setDeviceCredentialAllowed_button">Check BiometricPrompt setDeviceCredentialAllowed(true)</string>
 
     <string name="biometric_test_credential_enrolled_label">2) Credential Enrolled Tests</string>
-    <string name="biometric_test_credential_enrolled_instructions">This test checks that the BiometricManager/BiometricPrompt
-        APIs return results consistent with credential (PIN/Pattern/Password) state. Before starting this test, please ensure that you DO
-        have a credential set up.</string>
+    <string name="biometric_test_credential_enrolled_instructions">This test checks that apps are able to request credential enrollment, and that the BiometricManager/BiometricPrompt
+        APIs return results consistent with credential (PIN/Pattern/Password) state.</string>
+    <string name="biometric_test_credential_enroll_button">Enroll credential</string>
     <string name="biometric_test_credential_enrolled_bm_button">Check BiometricManager</string>
     <string name="biometric_test_credential_enrolled_bp_setAllowedAuthenticators_button">Check BiometricPrompt setAllowedAuthenticators(DEVICE_CREDENTIAL)</string>
     <string name="biometric_test_credential_enrolled_bp_setDeviceCredentialAllowed_button">Check BiometricPrompt setDeviceCredentialAllowed(true)</string>
@@ -278,7 +278,7 @@
 
     <string name="biometric_test_strong_label">4) Strong Biometrics + Crypto</string>
     <string name="biometric_test_strong_instructions">This test checks that the Settings.ACTION_BIOMETRIC_ENROLL and its corresponding
-        EXTRA_BIOMETRIC_MINIMUM_STRENGTH_REQUIRED APIs enroll only a STRONG biometric. Please ensure that the device
+        EXTRA_BIOMETRIC_AUTHENTICATOR_REQUIREMENTS APIs enroll only a STRONG biometric. Please ensure that the device
         does NOT have ANY biometrics enrolled before starting this test. After passing the first part of the test, it will check various use cases
         when authentication is invoked with the STRONG biometric.</string>
     <string name="biometric_test_strong_check_and_enroll_button">Start enrollment</string>
@@ -292,7 +292,7 @@
 
     <string name="biometric_test_weak_label">5) Weak Biometrics</string>
     <string name="biometric_test_weak_instructions">This test checks that the Settings.ACTION_BIOMETRIC_ENROLL and its corresponding
-        EXTRA_BIOMETRIC_MINIMUM_STRENGTH_REQUIRED APIs enroll a biometric that meets or exceeds WEAK. Please ensure that the device
+        EXTRA_BIOMETRIC_AUTHENTICATOR_REQUIREMENTS APIs enroll a biometric that meets or exceeds WEAK. Please ensure that the device
         does NOT have ANY biometrics enrolled before starting this test. After passing the first part of the test, it will check various use cases
         when authentication is invoked.</string>
     <string name="biometric_test_weak_enroll">Start enrollment</string>
@@ -1684,6 +1684,10 @@
     <string name="wifi_status_suggestion_connection_status">Received connection status.</string>
     <string name="wifi_status_suggestion_connection_status_failure">Failed to receive connection status.</string>
     <string name="wifi_status_suggestion_wait_for_disconnect">Ensuring device does disconnect from the network after removing suggestions.</string>
+    <string name="wifi_status_suggestion_metered_change">Marking the network metered.</string>
+    <string name="wifi_status_suggestion_metered_check_failed">Network meteredness check failed.</string>
+    <string name="wifi_status_suggestion_metered_changed">Network marked metered successfully.</string>
+    <string name="wifi_status_suggestion_capabilities_not_changed">Network capabilities did not change.</string>
     <string name="wifi_status_suggestion_not_disconnected">Did not disconnect from the network.</string>
     <string name="wifi_status_suggestion_disconnected">Disconnected from the network.</string>
 
@@ -1709,6 +1713,8 @@
     <string name="wifi_test_network_suggestion_ssid_post_connect_info">Tests whether the API can be used to suggest a network with SSID to the device and the device connects to it and sends the post connect broadcast back to the app.</string>
     <string name="wifi_test_network_suggestion_connection_failure">Network suggestion connection failure.</string>
     <string name="wifi_test_network_suggestion_connection_failure_info">Tests whether the SuggestionConnectionStatusListener API can be used to listen to connection failures for suggested networks.</string>
+    <string name="wifi_test_network_suggestion_modification_in_place">Network suggestion modification in place.</string>
+    <string name="wifi_test_network_suggestion_modification_in_place_info">Tests whether the suggested network params can be modified in place when connected to it.</string>
 
     <!-- Strings for P2pTestActivity -->
     <string name="p2p_test">Wi-Fi Direct Test</string>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/AbstractBaseTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/AbstractBaseTest.java
index d1a300e..a79d82a 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/AbstractBaseTest.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/AbstractBaseTest.java
@@ -42,7 +42,8 @@
  */
 public abstract class AbstractBaseTest extends PassFailButtons.Activity {
 
-    private static final int REQUEST_ENROLL = 1;
+    private static final int REQUEST_ENROLL_WHEN_NONE_ENROLLED = 1;
+    private static final int REQUEST_ENROLL_WHEN_ENROLLED = 2;
 
     abstract protected String getTag();
     abstract protected boolean isOnPauseAllowed();
@@ -52,6 +53,10 @@
 
     protected boolean mCurrentlyEnrolling;
 
+    // Not great to keep this here, but we use it to check that requesting enrollment of a
+    // combination that was just enrolled results in RESULT_CANCELED.
+    private int mRequestedStrength;
+
     BiometricManager mBiometricManager;
 
     @Override
@@ -77,9 +82,22 @@
 
     @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
-        if (requestCode == REQUEST_ENROLL) {
-            mCurrentlyEnrolling = false;
-            onBiometricEnrollFinished();
+        mCurrentlyEnrolling = false;
+
+        if (requestCode == REQUEST_ENROLL_WHEN_NONE_ENROLLED) {
+            if (resultCode == RESULT_OK) {
+                startBiometricEnroll(REQUEST_ENROLL_WHEN_ENROLLED, mRequestedStrength);
+            } else {
+                showToastAndLog("Unexpected result when requesting enrollment when not enrolled"
+                        + " yet: " + resultCode);
+            }
+        } else if (requestCode == REQUEST_ENROLL_WHEN_ENROLLED) {
+            if (resultCode == RESULT_CANCELED) {
+                onBiometricEnrollFinished();
+            } else {
+                showToastAndLog("Unexpected result when requesting enrollment when already"
+                        + " enrolled: " + resultCode);
+            }
         }
     }
 
@@ -93,8 +111,10 @@
 
     void checkAndEnroll(Button enrollButton, int requestedStrength,
             int[] acceptableConfigStrengths) {
+        mRequestedStrength = requestedStrength;
+
         // Check that no biometrics (of any strength) are enrolled
-        int result = mBiometricManager.canAuthenticate(requestedStrength);
+        int result = mBiometricManager.canAuthenticate(Authenticators.BIOMETRIC_WEAK);
         if (result == BiometricManager.BIOMETRIC_SUCCESS) {
             showToastAndLog("Please ensure that all biometrics are removed before starting"
                     + " this test");
@@ -124,18 +144,22 @@
                 getPassButton().setEnabled(true);
             }
         } else if (result == BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED) {
-            mCurrentlyEnrolling = true;
-            final Intent enrollIntent = new Intent(Settings.ACTION_BIOMETRIC_ENROLL);
-            enrollIntent.putExtra(Settings.EXTRA_BIOMETRIC_MINIMUM_STRENGTH_REQUIRED,
-                    requestedStrength);
-
-            startActivityForResult(enrollIntent, REQUEST_ENROLL);
+            startBiometricEnroll(REQUEST_ENROLL_WHEN_NONE_ENROLLED, requestedStrength);
         } else {
             showToastAndLog("Unexpected result: " + result + ". Please ensure you have removed"
                     + "all biometric enrollments.");
         }
     }
 
+    private void startBiometricEnroll(int requestCode, int requestedStrength) {
+        mCurrentlyEnrolling = true;
+        final Intent enrollIntent = new Intent(Settings.ACTION_BIOMETRIC_ENROLL);
+        enrollIntent.putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
+                requestedStrength);
+
+        startActivityForResult(enrollIntent, requestCode);
+    }
+
     void testBiometricUI(Utils.VerifyRandomContents contents, int allowedAuthenticators) {
         Utils.showInstructionDialog(this,
                 R.string.biometric_test_ui_instruction_dialog_title,
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/BiometricStrongTests.java b/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/BiometricStrongTests.java
index 367d76d..079c56f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/BiometricStrongTests.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/BiometricStrongTests.java
@@ -48,7 +48,7 @@
  * Ensure that this result is consistent with the configuration in core/res/res/values/config.xml
  *
  * Ensure that invoking {@link Settings.ACTION_BIOMETRIC_ENROLL} with its corresponding
- * {@link Settings.EXTRA_BIOMETRIC_MINIMUM_STRENGTH_REQUIRED} enrolls a
+ * {@link Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED} enrolls a
  * {@link BiometricManager.Authenticators.BIOMETRIC_STRONG} authenticator. This can be done by
  * authenticating a {@link BiometricPrompt.CryptoObject}.
  *
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/BiometricWeakTests.java b/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/BiometricWeakTests.java
index f6fad5c..3ce9ccb 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/BiometricWeakTests.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/BiometricWeakTests.java
@@ -40,7 +40,7 @@
  * Ensure that this result is consistent with the configuration in core/res/res/values/config.xml
  *
  * Ensure that invoking {@link Settings.ACTION_BIOMETRIC_ENROLL} with its corresponding
- * {@link Settings.EXTRA_BIOMETRIC_MINIMUM_STRENGTH_REQUIRED} enrolls a biometric that meets or
+ * {@link Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED} enrolls a biometric that meets or
  * exceeds {@link BiometricManager.Authenticators.BIOMETRIC_WEAK}.
  *
  * Ensure that the BiometricPrompt UI displays all fields in the public API surface.
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/CredentialEnrolledTests.java b/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/CredentialEnrolledTests.java
index 1fc950e..0186ecb 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/CredentialEnrolledTests.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/CredentialEnrolledTests.java
@@ -16,6 +16,7 @@
 
 package com.android.cts.verifier.biometrics;
 
+import android.content.Intent;
 import android.hardware.biometrics.BiometricManager;
 import android.hardware.biometrics.BiometricManager.Authenticators;
 import android.hardware.biometrics.BiometricPrompt;
@@ -23,6 +24,7 @@
 import android.os.CancellationSignal;
 import android.os.Handler;
 import android.os.Looper;
+import android.provider.Settings;
 import android.util.Log;
 import android.widget.Button;
 import android.widget.Toast;
@@ -39,6 +41,15 @@
 public class CredentialEnrolledTests extends AbstractBaseTest {
     private static final String TAG = "CredentialEnrolledTests";
 
+    private static final int REQUEST_ENROLL_WHEN_NONE_ENROLLED = 1;
+    private static final int REQUEST_ENROLL_WHEN_ENROLLED = 2;
+
+    private Button mEnrollButton;
+    private Button mBiometricManagerButton;
+    private Button mBPSetAllowedAuthenticatorsButton;
+    private Button mBPSetDeviceCredentialAllowedButton;
+
+    private boolean mEnrollPass;
     private boolean mBiometricManagerPass;
     private boolean mBiometricPromptSetAllowedAuthenticatorsPass;
     private boolean mBiometricPromptSetDeviceCredentialAllowedPass;
@@ -58,10 +69,23 @@
         setPassFailButtonClickListeners();
         getPassButton().setEnabled(false);
 
+        final BiometricManager bm = getSystemService(BiometricManager.class);
+
+        mEnrollButton = findViewById(R.id.enroll_credential_button);
+        mEnrollButton.setOnClickListener((view) -> {
+            final int biometricResult = bm.canAuthenticate(Authenticators.DEVICE_CREDENTIAL);
+            if (biometricResult != BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED) {
+                showToastAndLog("Please ensure you do not have a PIN/Pattern/Password set");
+                return;
+            }
+
+            requestCredentialEnrollment(REQUEST_ENROLL_WHEN_NONE_ENROLLED);
+        });
+
         // Test BiometricManager#canAuthenticate(DEVICE_CREDENTIAL)
-        final Button bmButton = findViewById(R.id.bm_button);
-        bmButton.setOnClickListener((view) -> {
-            final BiometricManager bm = getSystemService(BiometricManager.class);
+        mBiometricManagerButton = findViewById(R.id.bm_button);
+        mBiometricManagerButton.setOnClickListener((view) -> {
+
 
             final int biometricResult = bm.canAuthenticate(Authenticators.BIOMETRIC_WEAK);
             switch (biometricResult) {
@@ -80,7 +104,7 @@
 
             final int credentialResult = bm.canAuthenticate(Authenticators.DEVICE_CREDENTIAL);
             if (credentialResult == BiometricManager.BIOMETRIC_SUCCESS) {
-                bmButton.setEnabled(false);
+                mBiometricManagerButton.setEnabled(false);
                 mBiometricManagerPass = true;
                 updatePassButton();
             } else {
@@ -91,9 +115,8 @@
         });
 
         // Test setAllowedAuthenticators(DEVICE_CREDENTIAL)
-        final Button bpSetAllowedAuthenticatorsButton =
-                findViewById(R.id.setAllowedAuthenticators_button);
-        bpSetAllowedAuthenticatorsButton.setOnClickListener((view) -> {
+        mBPSetAllowedAuthenticatorsButton = findViewById(R.id.setAllowedAuthenticators_button);
+        mBPSetAllowedAuthenticatorsButton.setOnClickListener((view) -> {
             BiometricPrompt.Builder builder = new BiometricPrompt.Builder(this);
             builder.setTitle("Title");
             builder.setSubtitle("Subtitle");
@@ -108,7 +131,7 @@
                             final int authenticator = result.getAuthenticationType();
                             if (authenticator ==
                                     BiometricPrompt.AUTHENTICATION_RESULT_TYPE_DEVICE_CREDENTIAL) {
-                                bpSetAllowedAuthenticatorsButton.setEnabled(false);
+                                mBPSetAllowedAuthenticatorsButton.setEnabled(false);
                                 mBiometricPromptSetAllowedAuthenticatorsPass = true;
                                 updatePassButton();
                             } else {
@@ -124,9 +147,8 @@
         });
 
         // Test setDeviceCredentialAllowed(true)
-        final Button bpSetDeviceCredentialAllowedButton =
-                findViewById(R.id.setDeviceCredentialAllowed_button);
-        bpSetDeviceCredentialAllowedButton.setOnClickListener((view) -> {
+        mBPSetDeviceCredentialAllowedButton = findViewById(R.id.setDeviceCredentialAllowed_button);
+        mBPSetDeviceCredentialAllowedButton.setOnClickListener((view) -> {
             BiometricPrompt.Builder builder = new BiometricPrompt.Builder(this);
             builder.setTitle("Title");
             builder.setSubtitle("Subtitle");
@@ -141,7 +163,7 @@
                             final int authenticator = result.getAuthenticationType();
                             if (authenticator ==
                                     BiometricPrompt.AUTHENTICATION_RESULT_TYPE_DEVICE_CREDENTIAL) {
-                                bpSetDeviceCredentialAllowedButton.setEnabled(false);
+                                mBPSetDeviceCredentialAllowedButton.setEnabled(false);
                                 mBiometricPromptSetDeviceCredentialAllowedPass = true;
                                 updatePassButton();
                             } else {
@@ -165,8 +187,47 @@
         return !mBiometricManagerPass;
     }
 
+    @Override
+    public void onActivityResult(int requestCode, int resultCode, Intent data) {
+        if (requestCode == REQUEST_ENROLL_WHEN_NONE_ENROLLED) {
+            if (resultCode == RESULT_OK) {
+                final BiometricManager bm = getSystemService(BiometricManager.class);
+                final int result = bm.canAuthenticate(Authenticators.DEVICE_CREDENTIAL);
+                if (result == BiometricManager.BIOMETRIC_SUCCESS) {
+                    // Request enrollment one more time. Ensure that we receive RESULT_CANCELED
+                    requestCredentialEnrollment(REQUEST_ENROLL_WHEN_ENROLLED);
+                } else {
+                    showToastAndLog("Unexpected result: " + result + ". Please ensure that tapping"
+                            + " the button sends you to credential enrollment, and that you have"
+                            + " enrolled a credential.");
+                }
+            } else {
+                showToastAndLog("Unexpected result after enroll: " + resultCode);
+            }
+        } else if (requestCode == REQUEST_ENROLL_WHEN_ENROLLED) {
+            if (resultCode == RESULT_CANCELED) {
+                mEnrollPass = true;
+                mEnrollButton.setEnabled(false);
+                mBiometricManagerButton.setEnabled(true);
+                mBPSetAllowedAuthenticatorsButton.setEnabled(true);
+                mBPSetDeviceCredentialAllowedButton.setEnabled(true);
+            } else {
+                showToastAndLog("Unexpected result when requesting enrolling with"
+                        + " pre-existing credential: " + resultCode);
+            }
+        }
+    }
+
+    private void requestCredentialEnrollment(int requestCode) {
+        final Intent enrollIntent = new Intent(Settings.ACTION_BIOMETRIC_ENROLL);
+        enrollIntent.putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
+                Authenticators.DEVICE_CREDENTIAL);
+
+        startActivityForResult(enrollIntent, requestCode);
+    }
+
     private void updatePassButton() {
-        if (mBiometricManagerPass && mBiometricPromptSetAllowedAuthenticatorsPass
+        if (mEnrollPass && mBiometricManagerPass && mBiometricPromptSetAllowedAuthenticatorsPass
                 && mBiometricPromptSetDeviceCredentialAllowedPass) {
             showToastAndLog("All tests passed");
             getPassButton().setEnabled(true);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/security/IdentityCredentialAuthentication.java b/apps/CtsVerifier/src/com/android/cts/verifier/security/IdentityCredentialAuthentication.java
index 0493aa7..0e7af05 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/security/IdentityCredentialAuthentication.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/security/IdentityCredentialAuthentication.java
@@ -168,7 +168,7 @@
         idsProfile0.add(new AccessControlProfileId(0));
         PersonalizationData pd = new PersonalizationData.Builder()
                                  .addAccessControlProfile(acp)
-                                 .setEntry("org.iso.18013-5.2019", "Foo", idsProfile0, barCbor)
+                                 .putEntry("org.iso.18013-5.2019", "Foo", idsProfile0, barCbor)
                                  .build();
         byte[] proofOfProvisioningSignature = wc.personalize(pd);
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/CallbackUtils.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/CallbackUtils.java
index facf101..38c2f11 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/CallbackUtils.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/CallbackUtils.java
@@ -17,7 +17,9 @@
 package com.android.cts.verifier.wifi;
 
 import android.net.ConnectivityManager;
+import android.net.LinkProperties;
 import android.net.Network;
+import android.net.NetworkCapabilities;
 import android.util.Log;
 import android.util.Pair;
 
@@ -42,7 +44,11 @@
         private CountDownLatch mOnAvailableBlocker = new CountDownLatch(1);
         private CountDownLatch mOnUnAvailableBlocker = new CountDownLatch(1);
         private CountDownLatch mOnLostBlocker = new CountDownLatch(1);
+        // This is invoked multiple times, so initialize only when waitForCapabilitiesChanged() is
+        // invoked.
+        private CountDownLatch mOnCapabilitiesChangedBlocker = null;
         private Network mNetwork;
+        private NetworkCapabilities mNetworkCapabilities;
 
         public NetworkCallback() {
             mCallbackTimeoutInMs = DEFAULT_CALLBACK_TIMEOUT_MS;
@@ -53,13 +59,23 @@
         }
 
         @Override
-        public void onAvailable(Network network) {
+        public void onAvailable(Network network, NetworkCapabilities networkCapabilities,
+                LinkProperties linkProperties, boolean isBlocked) {
             if (DBG) Log.v(TAG, "onAvailable");
             mNetwork = network;
+            mNetworkCapabilities = networkCapabilities;
             mOnAvailableBlocker.countDown();
         }
 
         @Override
+        public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
+            if (DBG) Log.v(TAG, "onCapabilitiesChanged");
+            mNetwork = network;
+            mNetworkCapabilities = networkCapabilities;
+            if (mOnCapabilitiesChangedBlocker != null) mOnCapabilitiesChangedBlocker.countDown();
+        }
+
+        @Override
         public void onUnavailable() {
             if (DBG) Log.v(TAG, "onUnavailable");
             mOnUnAvailableBlocker.countDown();
@@ -72,6 +88,14 @@
             mOnLostBlocker.countDown();
         }
 
+        public Network getNetwork() {
+            return mNetwork;
+        }
+
+        public NetworkCapabilities getNetworkCapabilities() {
+            return mNetworkCapabilities;
+        }
+
         /**
          * Wait (blocks) for {@link #onAvailable(Network)} or timeout.
          *
@@ -91,10 +115,7 @@
          * @return true whether the callback was invoked.
          */
         public boolean waitForUnavailable() throws InterruptedException {
-            if (mOnUnAvailableBlocker.await(mCallbackTimeoutInMs, TimeUnit.MILLISECONDS)) {
-                return true;
-            }
-            return false;
+            return mOnUnAvailableBlocker.await(mCallbackTimeoutInMs, TimeUnit.MILLISECONDS);
         }
 
         /**
@@ -103,10 +124,18 @@
          * @return true whether the callback was invoked.
          */
         public boolean waitForLost() throws InterruptedException {
-            if (mOnLostBlocker.await(mCallbackTimeoutInMs, TimeUnit.MILLISECONDS)) {
-                return true;
-            }
-            return false;
+            return mOnLostBlocker.await(mCallbackTimeoutInMs, TimeUnit.MILLISECONDS);
+        }
+
+        /**
+         * Wait (blocks) for {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} or
+         * timeout.
+         *
+         * @return true whether the callback was invoked.
+         */
+        public boolean waitForCapabilitiesChanged() throws InterruptedException {
+            mOnCapabilitiesChangedBlocker = new CountDownLatch(1);
+            return mOnCapabilitiesChangedBlocker.await(mCallbackTimeoutInMs, TimeUnit.MILLISECONDS);
         }
     }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/NetworkSuggestionModificationInPlaceTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/NetworkSuggestionModificationInPlaceTestActivity.java
new file mode 100644
index 0000000..8a8a390
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/NetworkSuggestionModificationInPlaceTestActivity.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.verifier.wifi;
+
+import android.content.Context;
+import android.os.Bundle;
+
+import com.android.cts.verifier.R;
+import com.android.cts.verifier.wifi.testcase.NetworkSuggestionTestCase;
+
+/**
+ * Test activity for suggestion which is modified while connected to it.
+ */
+public class NetworkSuggestionModificationInPlaceTestActivity extends BaseTestActivity {
+    @Override
+    protected BaseTestCase getTestCase(Context context) {
+        return new NetworkSuggestionTestCase(
+                context,
+                false, /* setBssid */
+                false, /* setRequiresAppInteraction */
+                false, /* simulateConnectionFailure */
+                true /* setMeteredPostConnection */);
+    }
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setInfoResources(R.string.wifi_test_network_suggestion_modification_in_place,
+                R.string.wifi_test_network_suggestion_modification_in_place_info, 0);
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/TestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/TestListActivity.java
index c88bd1f..852f9af 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/TestListActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/TestListActivity.java
@@ -97,6 +97,10 @@
                 R.string.wifi_test_network_suggestion_connection_failure,
                 NetworkSuggestionConnectionFailureTestActivity.class.getName(),
                 new Intent(this, NetworkSuggestionConnectionFailureTestActivity.class), null));
+        adapter.add(TestListAdapter.TestListItem.newTest(this,
+                R.string.wifi_test_network_suggestion_modification_in_place,
+                NetworkSuggestionModificationInPlaceTestActivity.class.getName(),
+                new Intent(this, NetworkSuggestionModificationInPlaceTestActivity.class), null));
 
         adapter.registerDataSetObserver(new DataSetObserver() {
             @Override
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkSuggestionTestCase.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkSuggestionTestCase.java
index 53bb220..7c7c399 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkSuggestionTestCase.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkSuggestionTestCase.java
@@ -16,6 +16,7 @@
 
 package com.android.cts.verifier.wifi.testcase;
 
+import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
 import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
 import static android.net.wifi.WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS;
 
@@ -28,12 +29,15 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.net.ConnectivityManager;
+import android.net.LinkProperties;
 import android.net.MacAddress;
 import android.net.Network;
+import android.net.NetworkCapabilities;
 import android.net.NetworkRequest;
 import android.net.wifi.ScanResult;
 import android.net.wifi.WifiManager;
 import android.net.wifi.WifiNetworkSuggestion;
+import android.os.SystemClock;
 import android.util.Log;
 import android.util.Pair;
 
@@ -43,6 +47,7 @@
 import com.android.cts.verifier.wifi.TestUtils;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 import java.util.Objects;
 import java.util.concurrent.CountDownLatch;
@@ -60,10 +65,13 @@
 
     private static final int PERIODIC_SCAN_INTERVAL_MS = 10_000;
     private static final int CALLBACK_TIMEOUT_MS = 40_000;
+    private static final int CAPABILITIES_CHANGED_FOR_METERED_TIMEOUT_MS = 80_000;
 
     private final Object mLock = new Object();
     private final ScheduledExecutorService mExecutorService;
     private final List<WifiNetworkSuggestion> mNetworkSuggestions = new ArrayList<>();
+    private final WifiNetworkSuggestion.Builder mNetworkSuggestionBuilder =
+            new WifiNetworkSuggestion.Builder();
 
     private ConnectivityManager mConnectivityManager;
     private NetworkRequest mNetworkRequest;
@@ -74,6 +82,7 @@
     private final boolean mSetBssid;
     private final boolean mSetRequiresAppInteraction;
     private final boolean mSimulateConnectionFailure;
+    private final boolean mSetMeteredPostConnection;
 
     public NetworkSuggestionTestCase(Context context, boolean setBssid,
             boolean setRequiresAppInteraction) {
@@ -82,30 +91,36 @@
 
     public NetworkSuggestionTestCase(Context context, boolean setBssid,
             boolean setRequiresAppInteraction, boolean simulateConnectionFailure) {
+        this(context, setBssid, setRequiresAppInteraction, simulateConnectionFailure, false);
+    }
+
+    public NetworkSuggestionTestCase(Context context, boolean setBssid,
+            boolean setRequiresAppInteraction, boolean simulateConnectionFailure,
+            boolean setMeteredPostConnection) {
         super(context);
         mExecutorService = Executors.newSingleThreadScheduledExecutor();
         mSetBssid = setBssid;
         mSetRequiresAppInteraction = setRequiresAppInteraction;
         mSimulateConnectionFailure = simulateConnectionFailure;
+        mSetMeteredPostConnection = true;
     }
 
     // Create a network specifier based on the test type.
     private WifiNetworkSuggestion createNetworkSuggestion(@NonNull ScanResult scanResult) {
-        WifiNetworkSuggestion.Builder builder = new WifiNetworkSuggestion.Builder();
-        builder.setSsid(scanResult.SSID);
+        mNetworkSuggestionBuilder.setSsid(scanResult.SSID);
         if (mSetBssid) {
-            builder.setBssid(MacAddress.fromString(scanResult.BSSID));
+            mNetworkSuggestionBuilder.setBssid(MacAddress.fromString(scanResult.BSSID));
         }
         if (mSetRequiresAppInteraction) {
-            builder.setIsAppInteractionRequired(true);
+            mNetworkSuggestionBuilder.setIsAppInteractionRequired(true);
         }
         // Use a random password to simulate connection failure.
         if (TestUtils.isScanResultForWpa2Network(scanResult)) {
-            builder.setWpa2Passphrase(mTestUtils.generateRandomPassphrase());
+            mNetworkSuggestionBuilder.setWpa2Passphrase(mTestUtils.generateRandomPassphrase());
         } else if (TestUtils.isScanResultForWpa3Network(scanResult)) {
-            builder.setWpa3Passphrase(mTestUtils.generateRandomPassphrase());
+            mNetworkSuggestionBuilder.setWpa3Passphrase(mTestUtils.generateRandomPassphrase());
         }
-        return builder.build();
+        return mNetworkSuggestionBuilder.build();
     }
 
     private void setFailureReason(String reason) {
@@ -133,6 +148,30 @@
         }
     }
 
+    // TODO(b/150890482): Capabilities changed callback can occur multiple times (for ex: RSSI
+    // change) & the sufficiency checks may result in ths change taking longer to take effect.
+    // This method accounts for both of these situations.
+    private boolean waitForNetworkToBeMetered() throws InterruptedException {
+        long startTimeMillis = SystemClock.elapsedRealtime();
+        while (SystemClock.elapsedRealtime()
+                < startTimeMillis + CAPABILITIES_CHANGED_FOR_METERED_TIMEOUT_MS) {
+            // Wait for the suggestion to be marked metered now.
+            if (!mNetworkCallback.waitForCapabilitiesChanged()) {
+                Log.e(TAG, "Network capabilities did not change");
+                continue;
+            }
+            if (mNetworkCallback.getNetworkCapabilities()
+                    .hasCapability(NET_CAPABILITY_NOT_METERED)) {
+                Log.e(TAG, "Network meteredness check failed "
+                        + mNetworkCallback.getNetworkCapabilities());
+                continue;
+            }
+            // Network marked metered.
+            return true;
+        }
+        return false;
+    }
+
     @Override
     protected boolean executeTest() throws InterruptedException {
         // Step: Scan and find any open network around.
@@ -288,6 +327,37 @@
                     mContext.getString(R.string.wifi_status_suggestion_connection_status));
         }
 
+        if (mSetMeteredPostConnection) {
+            // ensure that the network is not metered before change.
+            if (!mNetworkCallback.getNetworkCapabilities()
+                    .hasCapability(NET_CAPABILITY_NOT_METERED)) {
+                Log.e(TAG, "Network meteredness check failed "
+                        + mNetworkCallback.getNetworkCapabilities());
+                setFailureReason(mContext.getString(
+                        R.string.wifi_status_suggestion_metered_check_failed));
+                return false;
+            }
+            if (DBG) Log.v(TAG, "Mark suggestion metered after connection");
+            mListener.onTestMsgReceived(
+                    mContext.getString(R.string.wifi_status_suggestion_metered_change));
+            WifiNetworkSuggestion modifiedSuggestion = mNetworkSuggestionBuilder
+                    .setIsMetered(true)
+                    .build();
+            if (mWifiManager.addNetworkSuggestions(Arrays.asList(modifiedSuggestion))
+                    != STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
+                setFailureReason(mContext.getString(R.string.wifi_status_suggestion_add_failure));
+                return false;
+            }
+            if (!waitForNetworkToBeMetered()) {
+                Log.e(TAG, "Network was not marked metered");
+                setFailureReason(mContext.getString(
+                        R.string.wifi_status_suggestion_metered_check_failed));
+                return false;
+            }
+            mListener.onTestMsgReceived(
+                    mContext.getString(R.string.wifi_status_suggestion_metered_changed));
+        }
+
         // Step: Remove the suggestions from the app.
         if (DBG) Log.v(TAG, "Removing suggestion");
         mListener.onTestMsgReceived(mContext.getString(R.string.wifi_status_suggestion_remove));
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/DocumentClient/AndroidManifest.xml
index c90a6f6..79eb44d 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/AndroidManifest.xml
@@ -16,7 +16,7 @@
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="com.android.cts.documentclient">
-    <application>
+    <application android:forceQueryable="true">
         <uses-library android:name="android.test.runner" />
         <activity android:name=".MyActivity" />
     </application>
diff --git a/hostsidetests/appsecurity/test-apps/DocumentProvider/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/DocumentProvider/AndroidManifest.xml
index 6e140d7..2b2f1fd 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentProvider/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/DocumentProvider/AndroidManifest.xml
@@ -16,7 +16,7 @@
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="com.android.cts.documentprovider">
-    <application>
+    <application android:forceQueryable="true">
         <uses-library android:name="android.test.runner" />
 
         <provider android:name=".MyDocumentsProvider"
diff --git a/hostsidetests/backup/PreservedSettingsApp/src/android/cts/backup/preservedsettingsapp/PreservedSettingsRestoreTest.java b/hostsidetests/backup/PreservedSettingsApp/src/android/cts/backup/preservedsettingsapp/PreservedSettingsRestoreTest.java
index 52bc651..07d1d24 100644
--- a/hostsidetests/backup/PreservedSettingsApp/src/android/cts/backup/preservedsettingsapp/PreservedSettingsRestoreTest.java
+++ b/hostsidetests/backup/PreservedSettingsApp/src/android/cts/backup/preservedsettingsapp/PreservedSettingsRestoreTest.java
@@ -114,6 +114,11 @@
     @Test
     public void cleanupDevice() throws Exception {
         SystemUtil.runWithShellPermissionIdentity(() -> {
+            // "Touch" the affected settings so that we're the last package that modified them.
+            modifySettings();
+            // Reset all secure settings modified by this package.
+            Settings.Secure.resetToDefaults(mContentResolver, null);
+
             Settings.Secure.putString(mContentResolver, OVERRIDEABLE_SETTING,
                     getOriginalSettingValue(OVERRIDEABLE_SETTING),
                     /* overrideableByRestore */ true);
diff --git a/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/InputMethodServiceLifecycleTest.java b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/InputMethodServiceLifecycleTest.java
index 644ba72..ed4e672 100644
--- a/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/InputMethodServiceLifecycleTest.java
+++ b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/InputMethodServiceLifecycleTest.java
@@ -37,7 +37,6 @@
 import android.platform.test.annotations.AppModeInstant;
 
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 
 import org.junit.After;
 import org.junit.Before;
@@ -51,7 +50,7 @@
  * Test general lifecycle events around InputMethodService.
  */
 @RunWith(DeviceJUnit4ClassRunner.class)
-public class InputMethodServiceLifecycleTest extends BaseHostJUnit4Test {
+public class InputMethodServiceLifecycleTest extends RebootFreeHostTestBase {
 
     private static final long WAIT_TIMEOUT = TimeUnit.SECONDS.toMillis(1);
     private static final long PACKAGE_OP_TIMEOUT = TimeUnit.SECONDS.toMillis(7);
diff --git a/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/MultiUserTest.java b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/MultiUserTest.java
index f1e73a2..8fece56 100644
--- a/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/MultiUserTest.java
+++ b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/MultiUserTest.java
@@ -30,7 +30,6 @@
 import android.platform.test.annotations.AppModeInstant;
 
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 import com.android.tradefed.testtype.junit4.DeviceTestRunOptions;
 import com.android.tradefed.util.CommandResult;
 import com.android.tradefed.util.CommandStatus;
@@ -49,7 +48,7 @@
  * Test IME APIs for multi-user environment.
  */
 @RunWith(DeviceJUnit4ClassRunner.class)
-public class MultiUserTest extends BaseHostJUnit4Test {
+public class MultiUserTest extends RebootFreeHostTestBase {
     private static final long USER_SWITCH_TIMEOUT = TimeUnit.SECONDS.toMillis(60);
     private static final long USER_SWITCH_POLLING_INTERVAL = TimeUnit.MILLISECONDS.toMillis(100);
     private static final long IME_COMMAND_TIMEOUT = TimeUnit.SECONDS.toMillis(7);
diff --git a/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/RebootFreeHostTestBase.java b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/RebootFreeHostTestBase.java
new file mode 100644
index 0000000..e90f1f6
--- /dev/null
+++ b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/RebootFreeHostTestBase.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.inputmethodservice.cts.hostside;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+
+import java.util.Objects;
+import java.util.WeakHashMap;
+
+/**
+ * A utility class that enforces the device under test must never reboot during the test runs.
+ *
+ * <p>For instance, suppose the following test class.</p>
+ * <pre>{@code
+ * @RunWith(DeviceJUnit4ClassRunner.class)
+ * public class MyTestClass extends RebootFreeHostTestBase {
+ *     @Test
+ *     public void test1() throws Exception {
+ *         // do something;
+ *     }
+ *
+ *     @Test
+ *     public void test2() throws Exception {
+ *         // do something;
+ *     }
+ *
+ *     @Test
+ *     public void test3() throws Exception {
+ *         // do something;
+ *     }
+ * }
+ * }</pre>
+ *
+ * <p>If the device (soft-)rebooted between {@code test1()} and {@code test2()}, then this base
+ * class would let {@code test2()} and {@code test3()} immediately fail by throwing
+ * {@link IllegalStateException} with saying that the device reboot is detected and the last
+ * test method before reboot is {@code test1()}</p>
+ *
+ * <p>Note that reboot-free is enforced only within each subclass of {@link RebootFreeHostTestBase}.
+ * Another sub-class such as {@code class MyTestClass2 extends RebootFreeHostTestBase} will not
+ * immediately fail because of device restart detected while running {@code class MyTestClass}.</p>
+ */
+public class RebootFreeHostTestBase extends BaseHostJUnit4Test {
+    private static final String PROP_SYSTEM_SERVER_START_COUNT = "sys.system_server.start_count";
+
+    private static final WeakHashMap<Class<?>, String> sExpectedSystemStartCount =
+            new WeakHashMap<>();
+    private static final WeakHashMap<Class<?>, String> sLastRunningTestName = new WeakHashMap<>();
+
+    /**
+     * A {@link TestName} object to receive the currently running test name.
+     *
+     * <p>Note this field needs to be {@code public} due to a restriction of JUnit4.</p>
+     */
+    @Rule
+    public TestName mTestName = new TestName();
+
+    /**
+     * @return device start count as {@link String}.
+     * @throws DeviceNotAvailableException
+     */
+    private String getSystemStartCountAsString() throws DeviceNotAvailableException  {
+        final String countString = getDevice().getProperty(PROP_SYSTEM_SERVER_START_COUNT);
+        if (countString == null) {
+            throw new IllegalStateException(
+                    String.format("Property %s must not be null", PROP_SYSTEM_SERVER_START_COUNT));
+        }
+        return countString;
+    }
+
+    /**
+     * Ensures there was no unexpected device reboot.
+     *
+     * @throws IllegalStateException when an unexpected device reboot is detected.
+     */
+    @Before
+    public void ensureNoSystemRestart() throws Exception {
+        final Class<?> myClass = getClass();
+        final String currentCount = getSystemStartCountAsString();
+        final String expectedCount = sExpectedSystemStartCount.get(myClass);
+        if (expectedCount == null) {
+            // This is the first time for the given test class to run.
+            // Just remember the current system start count.
+            sExpectedSystemStartCount.put(myClass, currentCount);
+        } else if (!Objects.equals(expectedCount, currentCount)) {
+            final String lastTest = sLastRunningTestName.getOrDefault(myClass, "<unknown>");
+            throw new IllegalStateException(String.format(
+                    "Unexpected device restart detected [%s: %s -> %s]. "
+                            + "lastTestBeforeRestart=%s. Check the device log!",
+                    PROP_SYSTEM_SERVER_START_COUNT, expectedCount, currentCount, lastTest));
+        }
+        sLastRunningTestName.put(myClass, mTestName.getMethodName());
+    }
+}
diff --git a/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/ShellCommandFromAppTest.java b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/ShellCommandFromAppTest.java
index 6c66949..0ab53cd 100644
--- a/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/ShellCommandFromAppTest.java
+++ b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/ShellCommandFromAppTest.java
@@ -25,7 +25,6 @@
 import android.platform.test.annotations.AppModeInstant;
 
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 import com.android.tradefed.testtype.junit4.DeviceTestRunOptions;
 
 import org.junit.After;
@@ -37,7 +36,7 @@
  * Test IInputMethodManager#shellComman verifies callers.
  */
 @RunWith(DeviceJUnit4ClassRunner.class)
-public class ShellCommandFromAppTest extends BaseHostJUnit4Test {
+public class ShellCommandFromAppTest extends RebootFreeHostTestBase {
 
     /**
      * {@code true} if {@link #tearDown()} needs to be fully executed.
diff --git a/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java b/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java
index 7ea47aa..dfee062 100644
--- a/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java
+++ b/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java
@@ -175,8 +175,6 @@
                 .build());
         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                 .detectAll()
-                // TODO(b/149790106): Fix and remove.
-                .permitIncorrectContextUse()
                 .penaltyLog()
                 .penaltyDeath()
                 .build());
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java
index db7192b..59018ea 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java
@@ -30,6 +30,7 @@
 import android.os.Looper;
 import android.os.Message;
 import android.os.UserHandle;
+import android.platform.test.annotations.RequiresDevice;
 import android.util.Log;
 
 import com.android.compatibility.common.util.ShellIdentityUtils;
@@ -46,6 +47,7 @@
  * Similarly, requires that the phone be connected to a wifi hotspot, or else the test will fail.
  */
 @TargetApi(21)
+@RequiresDevice // Emulators don't always have access to wifi/network
 public class ConnectivityConstraintTest extends BaseJobSchedulerTest {
     private static final String TAG = "ConnectivityConstraintTest";
     private static final String RESTRICT_BACKGROUND_GET_CMD =
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
index 0a34398..effabb7 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
@@ -39,6 +39,7 @@
 import android.os.SystemClock;
 import android.os.Temperature;
 import android.os.UserHandle;
+import android.platform.test.annotations.RequiresDevice;
 import android.provider.Settings;
 import android.support.test.uiautomator.UiDevice;
 import android.util.Log;
@@ -50,7 +51,6 @@
 import com.android.compatibility.common.util.AppOpsUtils;
 import com.android.compatibility.common.util.AppStandbyUtils;
 import com.android.compatibility.common.util.BatteryUtils;
-import com.android.compatibility.common.util.SystemUtil;
 import com.android.compatibility.common.util.ThermalUtils;
 
 import org.junit.After;
@@ -237,6 +237,7 @@
                 mTestAppInterface.awaitJobStart(DEFAULT_WAIT_TIMEOUT));
     }
 
+    @RequiresDevice // Emulators don't always have access to wifi/network
     @Test
     public void testBackgroundConnectivityJobsThrottled() throws Exception {
         if (!mHasWifi) {
@@ -315,6 +316,7 @@
                 mTestAppInterface.awaitJobStart(3_000));
     }
 
+    @RequiresDevice // Emulators don't always have access to wifi/network
     @Test
     public void testJobsInRestrictedBucket_WithRequiredNetwork() throws Exception {
         assumeTrue("app standby not enabled", mAppStandbyEnabled);
diff --git a/tests/app/src/android/app/cts/NotificationManagerTest.java b/tests/app/src/android/app/cts/NotificationManagerTest.java
index 0c4d6fe..459e01b 100644
--- a/tests/app/src/android/app/cts/NotificationManagerTest.java
+++ b/tests/app/src/android/app/cts/NotificationManagerTest.java
@@ -825,6 +825,8 @@
             mNotificationManager.setAutomaticZenRuleState(id1, onCondition1);
             mNotificationManager.setAutomaticZenRuleState(id2, onCondition2);
 
+            Thread.sleep(300); // wait for rules to be applied - it's done asynchronously
+
             mRuleIds.add(id1);
             mRuleIds.add(id2);
             assertExpectedDndState(INTERRUPTION_FILTER_PRIORITY);
diff --git a/tests/framework/base/windowmanager/AndroidManifest.xml b/tests/framework/base/windowmanager/AndroidManifest.xml
index bf7b209..c3d5bce 100644
--- a/tests/framework/base/windowmanager/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/AndroidManifest.xml
@@ -165,8 +165,6 @@
         <activity android:name="android.server.wm.lifecycle.ActivityLifecycleClientTestBase$TransitionDestinationActivity"
                   android:theme="@style/window_activity_transitions" />
 
-        <activity android:name="android.server.wm.StartActivityTests$TestActivity2" />
-
         <activity android:name="android.server.wm.MultiDisplaySystemDecorationTests$ImeTestActivity"
                   android:resizeableActivity="true"
                   android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen" />
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayActivityLaunchTests.java b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayActivityLaunchTests.java
index de0372f..f95b12a 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayActivityLaunchTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayActivityLaunchTests.java
@@ -848,7 +848,6 @@
         getPendingIntentActivity(TEST_ACTIVITY).send(mContext, resultCode, null /* intent */,
                 null /* onFinished */, null /* handler */, null /* requiredPermission */,
                 options.toBundle());
-        waitAndAssertActivityState(TOP_ACTIVITY, STATE_STOPPED, "Activity should be stopped");
         waitAndAssertTopResumedActivity(TEST_ACTIVITY, displayContent.mId,
                 "Activity launched on secondary display and on top");
     }
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySystemDecorationTests.java b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySystemDecorationTests.java
index 5121a39..5920334 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySystemDecorationTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySystemDecorationTests.java
@@ -66,13 +66,10 @@
 import android.widget.EditText;
 import android.widget.LinearLayout;
 
-import androidx.test.filters.FlakyTest;
-
 import com.android.compatibility.common.util.ImeAwareEditText;
 import com.android.compatibility.common.util.SystemUtil;
 import com.android.compatibility.common.util.TestUtils;
 import com.android.cts.mockime.ImeCommand;
-import com.android.cts.mockime.ImeEvent;
 import com.android.cts.mockime.ImeEventStream;
 import com.android.cts.mockime.MockImeSession;
 
@@ -296,19 +293,9 @@
     public void testLaunchSingleHomeActivityOnDisplayWithDecorations() {
         createManagedHomeActivitySession(SINGLE_HOME_ACTIVITY);
 
-        // Create new virtual display with system decoration support.
-        final DisplayContent newDisplay = createManagedExternalDisplaySession()
-                .setShowSystemDecorations(true)
-                .createVirtualDisplay();
-
         // If default home doesn't support multi-instance, default secondary home activity
         // should be automatically launched on the new display.
-        waitAndAssertActivityStateOnDisplay(getDefaultSecondaryHomeComponent(), STATE_RESUMED,
-                newDisplay.mId, "Activity launched on secondary display must be resumed");
-
-        tapOnDisplayCenter(newDisplay.mId);
-        assertEquals("Top activity must be home type", ACTIVITY_TYPE_HOME,
-                mWmState.getFrontStackActivityType(newDisplay.mId));
+        assertSecondaryHomeResumedOnNewDisplay(getDefaultSecondaryHomeComponent());
     }
 
     /**
@@ -319,19 +306,9 @@
     public void testLaunchSingleSecondaryHomeActivityOnDisplayWithDecorations() {
         createManagedHomeActivitySession(SINGLE_SECONDARY_HOME_ACTIVITY);
 
-        // Create new virtual display with system decoration support.
-        final DisplayContent newDisplay = createManagedExternalDisplaySession()
-                .setShowSystemDecorations(true)
-                .createVirtualDisplay();
-
         // If provided secondary home doesn't support multi-instance, default secondary home
         // activity should be automatically launched on the new display.
-        waitAndAssertActivityStateOnDisplay(getDefaultSecondaryHomeComponent(), STATE_RESUMED,
-                newDisplay.mId, "Activity launched on secondary display must be resumed");
-
-        tapOnDisplayCenter(newDisplay.mId);
-        assertEquals("Top activity must be home type", ACTIVITY_TYPE_HOME,
-                mWmState.getFrontStackActivityType(newDisplay.mId));
+        assertSecondaryHomeResumedOnNewDisplay(getDefaultSecondaryHomeComponent());
     }
 
     /**
@@ -341,21 +318,10 @@
     @Test
     public void testLaunchHomeActivityOnDisplayWithDecorations() {
         createManagedHomeActivitySession(HOME_ACTIVITY);
-        final VirtualDisplaySession virtualDisplaySession = createManagedVirtualDisplaySession();
-
-        // Create new virtual display with system decoration support.
-        final DisplayContent newDisplay = createManagedExternalDisplaySession()
-                .setShowSystemDecorations(true)
-                .createVirtualDisplay();
 
         // If default home doesn't have SECONDARY_HOME category, default secondary home
         // activity should be automatically launched on the new display.
-        waitAndAssertActivityStateOnDisplay(getDefaultSecondaryHomeComponent(), STATE_RESUMED,
-                newDisplay.mId, "Activity launched on secondary display must be resumed");
-
-        tapOnDisplayCenter(newDisplay.mId);
-        assertEquals("Top activity must be home type", ACTIVITY_TYPE_HOME,
-                mWmState.getFrontStackActivityType(newDisplay.mId));
+        assertSecondaryHomeResumedOnNewDisplay(getDefaultSecondaryHomeComponent());
     }
 
     /**
@@ -365,15 +331,18 @@
     @Test
     public void testLaunchSecondaryHomeActivityOnDisplayWithDecorations() {
         createManagedHomeActivitySession(SECONDARY_HOME_ACTIVITY);
-        final VirtualDisplaySession virtualDisplaySession = createManagedVirtualDisplaySession();
 
+        // Provided secondary home activity should be automatically launched on the new display.
+        assertSecondaryHomeResumedOnNewDisplay(SECONDARY_HOME_ACTIVITY);
+    }
+
+    private void assertSecondaryHomeResumedOnNewDisplay(ComponentName homeComponentName) {
         // Create new virtual display with system decoration support.
         final DisplayContent newDisplay = createManagedExternalDisplaySession()
                 .setShowSystemDecorations(true)
                 .createVirtualDisplay();
 
-        // Provided secondary home activity should be automatically launched on the new display.
-        waitAndAssertActivityStateOnDisplay(SECONDARY_HOME_ACTIVITY, STATE_RESUMED,
+        waitAndAssertActivityStateOnDisplay(homeComponentName, STATE_RESUMED,
                 newDisplay.mId, "Activity launched on secondary display must be resumed");
 
         tapOnDisplayCenter(newDisplay.mId);
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java b/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
index 7f13089..1863487 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
@@ -28,6 +28,8 @@
 import android.graphics.Rect;
 import android.platform.test.annotations.Presubmit;
 
+import org.junit.After;
+import org.junit.Before;
 import org.junit.Test;
 
 /**
@@ -37,6 +39,17 @@
 @Presubmit
 public class SplashscreenTests extends ActivityManagerTestBase {
 
+    @Before
+    public void setUp() throws Exception {
+        super.setUp();
+        mWmState.setSanityCheckWithFocusedWindow(false);
+    }
+
+    @After
+    public void tearDown() {
+        mWmState.setSanityCheckWithFocusedWindow(true);
+    }
+
     @Test
     public void testSplashscreenContent() {
         launchActivityNoWait(SPLASHSCREEN_ACTIVITY);
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/StartActivityTests.java b/tests/framework/base/windowmanager/src/android/server/wm/StartActivityTests.java
index e9c3f63..1057a94 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/StartActivityTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/StartActivityTests.java
@@ -37,6 +37,8 @@
 import static org.junit.Assert.assertNotEquals;
 
 import android.app.Activity;
+import android.app.WindowConfiguration;
+import android.content.ComponentName;
 import android.content.Intent;
 import android.os.Bundle;
 import android.platform.test.annotations.Presubmit;
@@ -44,9 +46,7 @@
 import android.server.wm.app.Components;
 import android.server.wm.intent.Activities;
 
-import androidx.test.rule.ActivityTestRule;
 
-import org.junit.Rule;
 import org.junit.Test;
 
 import java.util.Arrays;
@@ -58,34 +58,50 @@
 @Presubmit
 public class StartActivityTests extends ActivityManagerTestBase {
 
-    @Rule
-    public final ActivityTestRule<TestActivity2> mTestActivity2Rule =
-            new ActivityTestRule<>(TestActivity2.class, false /* initialTouchMode */,
-                    false /* launchActivity */);
+    @Test
+    public void testStartHomeIfNoActivities() {
+        final ComponentName defaultHome = getDefaultHomeComponent();
+        final int[] allActivityTypes = Arrays.copyOf(ALL_ACTIVITY_TYPE_BUT_HOME,
+                ALL_ACTIVITY_TYPE_BUT_HOME.length + 1);
+        allActivityTypes[allActivityTypes.length - 1] = WindowConfiguration.ACTIVITY_TYPE_HOME;
+        removeStacksWithActivityTypes(allActivityTypes);
+
+        waitAndAssertTopResumedActivity(defaultHome, DEFAULT_DISPLAY,
+                "Home activity should be restarted after force-finish");
+
+        stopTestPackage(defaultHome.getPackageName());
+
+        waitAndAssertTopResumedActivity(defaultHome, DEFAULT_DISPLAY,
+                "Home activity should be restarted after force-stop");
+    }
 
     /**
-     * Ensures {@link Activity} can only be launched from an {@link Activity}
-     * {@link android.content.Context}.
+     * Ensures {@link Activity} without {@link Intent#FLAG_ACTIVITY_NEW_TASK} can only be launched
+     * from an {@link Activity} {@link android.content.Context}.
      */
     @Test
     public void testStartActivityContexts() {
-        // Launch Activity from application context.
+        // Note by default LaunchActivityBuilder will use LAUNCHING_ACTIVITY to launch the target.
+
+        // Launch Activity from application context without FLAG_ACTIVITY_NEW_TASK.
         getLaunchActivityBuilder()
                 .setTargetActivity(TEST_ACTIVITY)
                 .setUseApplicationContext(true)
                 .setSuppressExceptions(true)
+                .setWaitForLaunched(false)
                 .execute();
 
-        // Launch second Activity from Activity Context to ensure previous Activity has launched.
-        final Activity testActivity2 = mTestActivity2Rule.launchActivity(null);
+        // Launch another activity from activity to ensure previous one has done.
+        getLaunchActivityBuilder()
+                .setTargetActivity(NO_RELAUNCH_ACTIVITY)
+                .execute();
 
-        mWmState.computeState(testActivity2.getComponentName());
+        mWmState.computeState(NO_RELAUNCH_ACTIVITY);
 
         // Verify Activity was not started.
         assertFalse(mWmState.containsActivity(TEST_ACTIVITY));
         mWmState.assertResumedActivity(
-                "Activity launched from activity context should be present",
-                testActivity2.getComponentName());
+                "Activity launched from activity context should be present", NO_RELAUNCH_ACTIVITY);
     }
 
     /**
@@ -273,7 +289,4 @@
         }
         return taskIds;
     }
-
-    public static class TestActivity2 extends Activity {
-    }
 }
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
index 24033a2..8fbb635 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
@@ -1153,6 +1153,19 @@
         }
     }
 
+    ComponentName getDefaultHomeComponent() {
+        final Intent intent = new Intent(ACTION_MAIN);
+        intent.addCategory(CATEGORY_HOME);
+        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
+        final ResolveInfo resolveInfo =
+                mContext.getPackageManager().resolveActivity(intent, MATCH_DEFAULT_ONLY);
+        if (resolveInfo == null) {
+            throw new AssertionError("Home activity not found");
+        }
+        return new ComponentName(resolveInfo.activityInfo.packageName,
+                resolveInfo.activityInfo.name);
+    }
+
     /**
      * HomeActivitySession is used to replace the default home component, so that you can use
      * your preferred home for testing within the session. The original default home will be
@@ -1166,16 +1179,7 @@
         HomeActivitySession(ComponentName sessionHome) {
             mSessionHome = sessionHome;
             mPackageManager = mContext.getPackageManager();
-
-            final Intent intent = new Intent(ACTION_MAIN);
-            intent.addCategory(CATEGORY_HOME);
-            intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
-            final ResolveInfo resolveInfo =
-                    mPackageManager.resolveActivity(intent, MATCH_DEFAULT_ONLY);
-            if (resolveInfo != null) {
-                mOrigHome = new ComponentName(resolveInfo.activityInfo.packageName,
-                        resolveInfo.activityInfo.name);
-            }
+            mOrigHome = getDefaultHomeComponent();
 
             SystemUtil.runWithShellPermissionIdentity(
                     () -> mPackageManager.setComponentEnabledSetting(mSessionHome,
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java b/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java
index d747155..87688f5 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java
@@ -141,6 +141,7 @@
     private int mRotation;
     private int mLastOrientation;
     private boolean mDisplayFrozen;
+    private boolean mSanityCheckFocusedWindow = true;
 
     static String appStateToString(int appState) {
         switch (appState) {
@@ -237,6 +238,11 @@
         return TYPE_NAVIGATION_BAR == navState.getType();
     }
 
+    /** Enable/disable the mFocusedWindow check during the computeState.*/
+    void setSanityCheckWithFocusedWindow(boolean sanityCheckFocusedWindow) {
+        mSanityCheckFocusedWindow = sanityCheckFocusedWindow;
+    }
+
     public void computeState() {
         // It is possible the system is in the middle of transition to the right state when we get
         // the dump. We try a few times to get the information we need before giving up.
@@ -264,7 +270,7 @@
             }
 
             retry = mRootTasks.isEmpty() || mTopFocusedTaskId == -1 || mWindowStates.isEmpty()
-                    || mFocusedApp == null
+                    || mFocusedApp == null || (mSanityCheckFocusedWindow && mFocusedWindow == null)
                     || (mTopResumedActivityRecord == null || mResumedActivitiesInStacks.isEmpty())
                     && !mKeyguardControllerState.keyguardShowing;
         } while (retry && retriesLeft-- > 0);
diff --git a/tests/inputmethod/AndroidManifest.xml b/tests/inputmethod/AndroidManifest.xml
index 2626d5a..3c754de 100644
--- a/tests/inputmethod/AndroidManifest.xml
+++ b/tests/inputmethod/AndroidManifest.xml
@@ -19,6 +19,7 @@
     package="android.view.inputmethod.cts"
     android:targetSandboxVersion="2">
 
+    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
     <application
         android:label="CtsInputMethodTestCases"
         android:multiArch="true"
@@ -61,6 +62,10 @@
             android:exported="false">
         </service>
 
+        <service android:name="android.view.inputmethod.cts.util.WindowFocusHandleService"
+                 android:exported="false">
+        </service>
+
     </application>
 
     <instrumentation
diff --git a/tests/inputmethod/src/android/view/inputmethod/cts/FocusHandlingTest.java b/tests/inputmethod/src/android/view/inputmethod/cts/FocusHandlingTest.java
index 674463e..ca17cdf 100644
--- a/tests/inputmethod/src/android/view/inputmethod/cts/FocusHandlingTest.java
+++ b/tests/inputmethod/src/android/view/inputmethod/cts/FocusHandlingTest.java
@@ -16,6 +16,7 @@
 
 package android.view.inputmethod.cts;
 
+import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;
 import static android.view.inputmethod.cts.util.TestUtils.runOnMainSync;
 import static android.widget.PopupWindow.INPUT_METHOD_NOT_NEEDED;
@@ -27,26 +28,35 @@
 import static com.android.cts.mockime.ImeEventStreamTestUtils.notExpectEvent;
 
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
 import android.app.Instrumentation;
+import android.content.ComponentName;
 import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
 import android.os.Build;
 import android.os.IBinder;
 import android.os.Process;
 import android.os.SystemClock;
 import android.text.TextUtils;
 import android.view.View;
+import android.view.ViewTreeObserver;
+import android.view.WindowManager;
 import android.view.inputmethod.EditorInfo;
 import android.view.inputmethod.InputMethodManager;
 import android.view.inputmethod.cts.util.EndToEndImeTestBase;
 import android.view.inputmethod.cts.util.TestActivity;
 import android.view.inputmethod.cts.util.TestUtils;
+import android.view.inputmethod.cts.util.WindowFocusHandleService;
 import android.view.inputmethod.cts.util.WindowFocusStealer;
 import android.widget.EditText;
 import android.widget.LinearLayout;
 import android.widget.PopupWindow;
 import android.widget.TextView;
 
+import androidx.annotation.NonNull;
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.FlakyTest;
 import androidx.test.filters.MediumTest;
@@ -63,6 +73,8 @@
 import org.junit.runner.RunWith;
 
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
 
 @MediumTest
@@ -92,6 +104,18 @@
         return editTextRef.get();
     }
 
+    public EditText launchTestActivity(String marker,
+            @NonNull AtomicBoolean outEditHasWindowFocusRef) {
+        final EditText editText = launchTestActivity(marker);
+        editText.post(() -> {
+            final ViewTreeObserver observerForEditText = editText.getViewTreeObserver();
+            observerForEditText.addOnWindowFocusChangeListener((hasFocus) ->
+                outEditHasWindowFocusRef.set(editText.hasWindowFocus()));
+            outEditHasWindowFocusRef.set(editText.hasWindowFocus());
+        });
+        return editText;
+    }
+
     private static String getTestMarker() {
         return TEST_MARKER_PREFIX + "/"  + SystemClock.elapsedRealtimeNanos();
     }
@@ -417,4 +441,96 @@
                     NOT_EXPECT_TIMEOUT);
         }
     }
+
+    @Test
+    public void testMultiWindowFocusHandleOnDifferentUiThread() throws Exception {
+        final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+        try (ServiceSession session = new ServiceSession(instrumentation.getContext());
+             MockImeSession imeSession = MockImeSession.create(
+                     instrumentation.getContext(), instrumentation.getUiAutomation(),
+                     new ImeSettings.Builder())) {
+            final ImeEventStream stream = imeSession.openEventStream();
+            final AtomicBoolean popupTextHasWindowFocus = new AtomicBoolean(false);
+            final AtomicBoolean popupTextHasViewFocus = new AtomicBoolean(false);
+            final AtomicBoolean editTextHasWindowFocus = new AtomicBoolean(false);
+
+            // Start a TestActivity and verify the edit text will receive focus and keyboard shown.
+            final String marker = getTestMarker();
+            final EditText editText = launchTestActivity(marker, editTextHasWindowFocus);
+
+            // Wait until the MockIme gets bound to the TestActivity.
+            expectBindInput(stream, Process.myPid(), TIMEOUT);
+
+            // Emulate tap event
+            CtsTouchUtils.emulateTapOnViewCenter(instrumentation, null, editText);
+            TestUtils.waitOnMainUntil(() -> editTextHasWindowFocus.get(), TIMEOUT);
+
+            expectEvent(stream, editorMatcher("onStartInput", marker), TIMEOUT);
+            expectEvent(stream, event -> "showSoftInput".equals(event.getEventName()), TIMEOUT);
+
+            // Create a popupTextView which from Service with different UI thread.
+            final TextView popupTextView = session.getService().getPopupTextView(
+                    popupTextHasWindowFocus);
+            assertTrue(popupTextView.getHandler().getLooper()
+                    != session.getService().getMainLooper());
+
+            // Verify popupTextView will also receive window focus change and soft keyboard shown
+            // after tapping the view.
+            final String marker1 = getTestMarker();
+            popupTextView.post(() -> {
+                popupTextView.setPrivateImeOptions(marker1);
+                popupTextHasViewFocus.set(popupTextView.requestFocus());
+            });
+            TestUtils.waitOnMainUntil(() -> popupTextHasViewFocus.get(), TIMEOUT);
+
+            CtsTouchUtils.emulateTapOnViewCenter(instrumentation, null, popupTextView);
+            TestUtils.waitOnMainUntil(() -> popupTextHasWindowFocus.get()
+                            && !editTextHasWindowFocus.get(), TIMEOUT);
+            expectEvent(stream, editorMatcher("onStartInput", marker1), TIMEOUT);
+            expectEvent(stream, event -> "showSoftInput".equals(event.getEventName()), TIMEOUT);
+
+            // Emulate tap event for editText again, verify soft keyboard and window focus will
+            // come back.
+            CtsTouchUtils.emulateTapOnViewCenter(instrumentation, null, editText);
+            TestUtils.waitOnMainUntil(() -> editTextHasWindowFocus.get()
+                    && !popupTextHasWindowFocus.get(), TIMEOUT);
+            expectEvent(stream, editorMatcher("onStartInput", marker), TIMEOUT);
+            expectEvent(stream, event -> "showSoftInput".equals(event.getEventName()), TIMEOUT);
+        }
+    }
+
+    private static class ServiceSession implements ServiceConnection, AutoCloseable {
+        private final Context mContext;
+
+        ServiceSession(Context context) {
+            mContext = context;
+            Intent service = new Intent(mContext, WindowFocusHandleService.class);
+            mContext.bindService(service, this, Context.BIND_AUTO_CREATE);
+
+            // Wait for service bound.
+            try {
+                TestUtils.waitOnMainUntil(() -> WindowFocusHandleService.getInstance() != null, 5,
+                        "WindowFocusHandleService should be bound");
+            } catch (TimeoutException e) {
+                fail("WindowFocusHandleService should be bound");
+            }
+        }
+
+        @Override
+        public void close() throws Exception {
+            mContext.unbindService(this);
+        }
+
+        WindowFocusHandleService getService() {
+            return WindowFocusHandleService.getInstance();
+        }
+
+        @Override
+        public void onServiceConnected(ComponentName name, IBinder service) {
+        }
+
+        @Override
+        public void onServiceDisconnected(ComponentName name) {
+        }
+    }
 }
diff --git a/tests/inputmethod/src/android/view/inputmethod/cts/util/WindowFocusHandleService.java b/tests/inputmethod/src/android/view/inputmethod/cts/util/WindowFocusHandleService.java
new file mode 100644
index 0000000..427cf11
--- /dev/null
+++ b/tests/inputmethod/src/android/view/inputmethod/cts/util/WindowFocusHandleService.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view.inputmethod.cts.util;
+
+import static android.view.Display.DEFAULT_DISPLAY;
+import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
+import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
+import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
+import static android.view.WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
+import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Color;
+import android.graphics.PixelFormat;
+import android.graphics.Point;
+import android.graphics.drawable.ColorDrawable;
+import android.hardware.display.DisplayManager;
+import android.os.Binder;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.IBinder;
+import android.util.Log;
+import android.view.Display;
+import android.view.MotionEvent;
+import android.view.ViewTreeObserver;
+import android.view.WindowManager;
+import android.widget.EditText;
+
+import androidx.annotation.AnyThread;
+import androidx.annotation.MainThread;
+import androidx.annotation.Nullable;
+import androidx.annotation.UiThread;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * A Service class to create popup window with edit text by handler thread.
+ * For verifying IME focus handle between windows on different UI thread.
+ */
+public class WindowFocusHandleService extends Service {
+    private @Nullable static WindowFocusHandleService sInstance = null;
+    private static final String TAG = WindowFocusHandleService.class.getSimpleName();
+
+    private EditText mPopupTextView;
+    private Handler mThreadHandler;
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+        // Create a popup text view with different UI thread.
+        final HandlerThread localThread = new HandlerThread("TestThreadHandler");
+        localThread.start();
+        mThreadHandler = new Handler(localThread.getLooper());
+        mThreadHandler.post(() -> mPopupTextView = createPopupTextView(new Point(150, 150)));
+    }
+
+    public @Nullable static WindowFocusHandleService getInstance() {
+        return sInstance;
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        sInstance = this;
+        return new Binder();
+    }
+
+    @Override
+    public boolean onUnbind(Intent intent) {
+        sInstance = null;
+        return true;
+    }
+
+    @UiThread
+    private EditText createPopupTextView(Point pos) {
+        final Context windowContext = createWindowContext(DEFAULT_DISPLAY);
+        final WindowManager wm = windowContext.getSystemService(WindowManager.class);
+        final EditText editText = new EditText(windowContext) {
+            @Override
+            public void onWindowFocusChanged(boolean hasWindowFocus) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG,"onWindowFocusChanged for view=" + this
+                            + ", hasWindowfocus: " + hasWindowFocus);
+                }
+            }
+        };
+        editText.setOnFocusChangeListener((v, hasFocus) -> {
+            if (v == editText) {
+                WindowManager.LayoutParams params =
+                        (WindowManager.LayoutParams) editText.getLayoutParams();
+                if (hasFocus) {
+                    params.flags &= ~FLAG_NOT_FOCUSABLE;
+                    params.flags |= FLAG_LAYOUT_IN_SCREEN
+                                    | FLAG_WATCH_OUTSIDE_TOUCH
+                                    | FLAG_NOT_TOUCH_MODAL;
+                    wm.updateViewLayout(editText, params);
+                }
+            }
+        });
+        editText.setOnTouchListener((v, event) -> {
+            if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
+                WindowManager.LayoutParams params =
+                        (WindowManager.LayoutParams) editText.getLayoutParams();
+                if ((params.flags & FLAG_NOT_FOCUSABLE) == 0) {
+                    params.flags |= FLAG_NOT_FOCUSABLE;
+                    wm.updateViewLayout(editText, params);
+                }
+            }
+            return false;
+        });
+        editText.setText("Popup");
+        editText.setBackground(new ColorDrawable(Color.CYAN));
+
+        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
+                150, 150, pos.x, pos.y,
+                TYPE_APPLICATION_OVERLAY, FLAG_NOT_FOCUSABLE,
+                PixelFormat.OPAQUE);
+        wm.addView(editText, params);
+        return editText;
+    }
+
+    private Context createWindowContext(int displayId) {
+        final Display display = getSystemService(DisplayManager.class).getDisplay(displayId);
+        return createDisplayContext(display).createWindowContext(TYPE_APPLICATION_OVERLAY,
+                null /* options */);
+    }
+
+    @AnyThread
+    public EditText getPopupTextView(@Nullable AtomicBoolean outPopupTextHasWindowFocusRef) {
+        if (outPopupTextHasWindowFocusRef != null) {
+            mPopupTextView.post(() -> {
+                final ViewTreeObserver observerForPopupTextView =
+                        mPopupTextView.getViewTreeObserver();
+                observerForPopupTextView.addOnWindowFocusChangeListener((hasFocus) ->
+                        outPopupTextHasWindowFocusRef.set(hasFocus));
+            });
+        }
+        return mPopupTextView;
+    }
+
+    @MainThread
+    public void handleReset() {
+        if (mPopupTextView != null) {
+            final WindowManager wm = mPopupTextView.getContext().getSystemService(
+                    WindowManager.class);
+            wm.removeView(mPopupTextView);
+            mPopupTextView = null;
+        }
+    }
+
+    @MainThread
+    public void onDestroy() {
+        super.onDestroy();
+        handleReset();
+    }
+}
diff --git a/tests/libcore/okhttp/Android.bp b/tests/libcore/okhttp/Android.bp
index 511e28a..00360f1 100644
--- a/tests/libcore/okhttp/Android.bp
+++ b/tests/libcore/okhttp/Android.bp
@@ -16,6 +16,7 @@
     name: "CtsLibcoreOkHttpTestCases",
     defaults: ["cts_support_defaults"],
     platform_apis: true,
+    min_sdk_version: "29",
     static_libs: [
         "bouncycastle-unbundled",
         "cts-core-test-runner-axt",
diff --git a/tests/libcore/okhttp/AndroidManifest.xml b/tests/libcore/okhttp/AndroidManifest.xml
index 5396d8e..1e6718c 100644
--- a/tests/libcore/okhttp/AndroidManifest.xml
+++ b/tests/libcore/okhttp/AndroidManifest.xml
@@ -17,6 +17,7 @@
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.libcore.cts.okhttp">
     <uses-permission android:name="android.permission.INTERNET" />
+    <uses-sdk android:minSdkVersion="29" android:targetSdkVersion="29" />
     <application android:usesCleartextTraffic="true">
         <uses-library android:name="android.test.runner" />
     </application>
diff --git a/tests/tests/appenumeration/app/source/src/android/appenumeration/cts/query/TestActivity.java b/tests/tests/appenumeration/app/source/src/android/appenumeration/cts/query/TestActivity.java
index 01aef3c..7a680f3 100644
--- a/tests/tests/appenumeration/app/source/src/android/appenumeration/cts/query/TestActivity.java
+++ b/tests/tests/appenumeration/app/source/src/android/appenumeration/cts/query/TestActivity.java
@@ -24,15 +24,18 @@
 import static android.appenumeration.cts.Constants.ACTION_SEND_RESULT;
 import static android.appenumeration.cts.Constants.ACTION_START_DIRECTLY;
 import static android.appenumeration.cts.Constants.ACTION_START_FOR_RESULT;
+import static android.appenumeration.cts.Constants.ACTION_START_SENDER_FOR_RESULT;
 import static android.appenumeration.cts.Constants.EXTRA_ERROR;
 import static android.appenumeration.cts.Constants.EXTRA_FLAGS;
 import static android.appenumeration.cts.Constants.EXTRA_REMOTE_CALLBACK;
 import static android.content.Intent.EXTRA_RETURN_RESULT;
 
 import android.app.Activity;
+import android.app.PendingIntent;
 import android.content.ActivityNotFoundException;
 import android.content.ComponentName;
 import android.content.Intent;
+import android.content.IntentSender;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.os.Bundle;
@@ -92,6 +95,16 @@
                 finish();
             } else if (ACTION_GET_INSTALLED_PACKAGES.equals(action)) {
                 sendGetInstalledPackages(remoteCallback, queryIntent.getIntExtra(EXTRA_FLAGS, 0));
+            } else if (ACTION_START_SENDER_FOR_RESULT.equals(action)) {
+                PendingIntent pendingIntent = intent.getParcelableExtra("pendingIntent");
+                int requestCode = RESULT_FIRST_USER + callbacks.size();
+                callbacks.put(requestCode, remoteCallback);
+                try {
+                    startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null,
+                            0, 0, 0);
+                } catch (IntentSender.SendIntentException e) {
+                    sendError(remoteCallback, e);
+                }
             } else {
                 sendError(remoteCallback, new Exception("unknown action " + action));
             }
diff --git a/tests/tests/appenumeration/lib/src/android/appenumeration/cts/Constants.java b/tests/tests/appenumeration/lib/src/android/appenumeration/cts/Constants.java
index 3c80da6..3a992ac 100644
--- a/tests/tests/appenumeration/lib/src/android/appenumeration/cts/Constants.java
+++ b/tests/tests/appenumeration/lib/src/android/appenumeration/cts/Constants.java
@@ -84,8 +84,11 @@
             PKG_BASE + "cts.action.QUERY_INTENT_PROVIDERS";
     public static final String ACTION_GET_INSTALLED_PACKAGES =
             PKG_BASE + "cts.action.GET_INSTALLED_PACKAGES";
+    public static final String ACTION_START_SENDER_FOR_RESULT =
+            PKG_BASE + "cts.action.START_SENDER_FOR_RESULT";
 
     public static final String EXTRA_REMOTE_CALLBACK = "remoteCallback";
     public static final String EXTRA_ERROR = "error";
     public static final String EXTRA_FLAGS = "flags";
+
 }
diff --git a/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java b/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java
index 9beffff..c172c38 100644
--- a/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java
+++ b/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java
@@ -55,6 +55,7 @@
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.fail;
 
+import android.app.PendingIntent;
 import android.content.ActivityNotFoundException;
 import android.content.ComponentName;
 import android.content.Intent;
@@ -66,6 +67,7 @@
 import android.os.ConditionVariable;
 import android.os.Handler;
 import android.os.HandlerThread;
+import android.os.Parcelable;
 import android.os.RemoteCallback;
 
 import androidx.annotation.Nullable;
@@ -292,6 +294,21 @@
     }
 
     @Test
+    public void whenStartedViaIntentSender_canSeeCaller() throws Exception {
+        // let's first make sure that the target cannot see the caller.
+        assertNotVisible(QUERIES_NOTHING, QUERIES_NOTHING_Q);
+        // now let's start the target via pending intent and make sure that it can see the caller
+        // as part of that call
+        PackageInfo packageInfo = startSenderForResult(QUERIES_NOTHING_Q, QUERIES_NOTHING);
+        assertThat(packageInfo, IsNull.notNullValue());
+        assertThat(packageInfo.packageName, is(QUERIES_NOTHING_Q));
+        // and finally let's re-run the last check to make sure that the target can still see the
+        // caller
+        assertVisible(QUERIES_NOTHING, QUERIES_NOTHING_Q);
+    }
+
+
+    @Test
     public void sharedUserMember_canSeeOtherMember() throws Exception {
         assertVisible(QUERIES_NOTHING_SHARED_USER, TARGET_SHARED_USER);
     }
@@ -335,7 +352,7 @@
         }
     }
 
-    interface ThrowingBiFunction<T,U,R> {
+    interface ThrowingBiFunction<T, U, R> {
         R apply(T arg1, U arg2) throws Exception;
     }
 
@@ -352,6 +369,7 @@
             }
         }
     }
+
     private void assertQueryable(String sourcePackageName, String targetPackageName,
             String intentAction, ThrowingBiFunction<String, Intent, String[]> commandMethod)
             throws Exception {
@@ -381,9 +399,25 @@
         return response.getParcelable(Intent.EXTRA_RETURN_RESULT);
     }
 
+    private PackageInfo startSenderForResult(String sourcePackageName, String targetPackageName)
+            throws Exception {
+        PendingIntent pendingIntent = PendingIntent.getActivity(
+                InstrumentationRegistry.getInstrumentation().getContext(), 100,
+                new Intent("android.appenumeration.cts.action.SEND_RESULT").setComponent(
+                        new ComponentName(targetPackageName,
+                                "android.appenumeration.cts.query.TestActivity")),
+                PendingIntent.FLAG_ONE_SHOT);
+
+        Bundle response = sendCommand(sourcePackageName, targetPackageName,
+                pendingIntent /*queryIntent*/, Constants.ACTION_START_SENDER_FOR_RESULT);
+        return response.getParcelable(Intent.EXTRA_RETURN_RESULT);
+    }
+
+
     private String[] queryIntentActivities(String sourcePackageName, Intent queryIntent)
             throws Exception {
-        Bundle response = sendCommand(sourcePackageName, null, queryIntent, ACTION_QUERY_ACTIVITIES);
+        Bundle response =
+                sendCommand(sourcePackageName, null, queryIntent, ACTION_QUERY_ACTIVITIES);
         return response.getStringArray(Intent.EXTRA_RETURN_RESULT);
     }
 
@@ -418,21 +452,25 @@
     }
 
     private Bundle sendCommand(String sourcePackageName, @Nullable String targetPackageName,
-            @Nullable Intent queryIntent, String action)
+            @Nullable Parcelable intentExtra, String action)
             throws Exception {
         final Intent intent = new Intent(action)
                 .setComponent(new ComponentName(sourcePackageName, ACTIVITY_CLASS_TEST))
                 // data uri unique to each activity start to ensure actual launch and not just
                 // redisplay
                 .setData(Uri.parse("test://" + name.getMethodName()
-                      + (targetPackageName != null
-                      ? targetPackageName : UUID.randomUUID().toString())))
+                        + (targetPackageName != null
+                        ? targetPackageName : UUID.randomUUID().toString())))
                 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
         if (targetPackageName != null) {
             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, targetPackageName);
         }
-        if (queryIntent != null) {
-            intent.putExtra(Intent.EXTRA_INTENT, queryIntent);
+        if (intentExtra != null) {
+            if (intentExtra instanceof Intent) {
+                intent.putExtra(Intent.EXTRA_INTENT, intentExtra);
+            } else if (intentExtra instanceof PendingIntent) {
+                intent.putExtra("pendingIntent", intentExtra);
+            }
         }
 
         final ConditionVariable latch = new ConditionVariable();
diff --git a/tests/tests/content/AndroidManifest.xml b/tests/tests/content/AndroidManifest.xml
index bf7674d..aee27b6 100644
--- a/tests/tests/content/AndroidManifest.xml
+++ b/tests/tests/content/AndroidManifest.xml
@@ -33,6 +33,7 @@
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.content.cts.permission.TEST_GRANTED" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
 
     <!-- Used for ContextTest#testCreatePackageContextAsUser -->
     <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
diff --git a/tests/tests/content/src/android/content/cts/ContentResolverTest.java b/tests/tests/content/src/android/content/cts/ContentResolverTest.java
index 821b69a..de17ee1 100644
--- a/tests/tests/content/src/android/content/cts/ContentResolverTest.java
+++ b/tests/tests/content/src/android/content/cts/ContentResolverTest.java
@@ -45,6 +45,7 @@
 import com.android.compatibility.common.util.PollingCheck;
 import com.android.internal.util.ArrayUtils;
 
+import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
@@ -1465,6 +1466,16 @@
         assertNull(response);
     }
 
+    public void testEncodeDecode() {
+        final Uri expected = Uri.parse("content://com.example/item/23");
+        final File file = ContentResolver.encodeToFile(expected);
+        assertNotNull(file);
+
+        final Uri actual = ContentResolver.decodeFromFile(file);
+        assertNotNull(actual);
+        assertEquals(expected, actual);
+    }
+
     public static class Change {
         public final boolean selfChange;
         public final Iterable<Uri> uris;
diff --git a/tests/tests/identity/src/android/security/identity/cts/AttestationTest.java b/tests/tests/identity/src/android/security/identity/cts/AttestationTest.java
index 34b0cf2..d745da0 100644
--- a/tests/tests/identity/src/android/security/identity/cts/AttestationTest.java
+++ b/tests/tests/identity/src/android/security/identity/cts/AttestationTest.java
@@ -26,7 +26,6 @@
 import androidx.test.InstrumentationRegistry;
 
 import org.junit.Test;
-import org.junit.Ignore;
 
 import com.google.common.primitives.Bytes;
 
@@ -49,7 +48,6 @@
     public static final int KM_TAG_ATTESTATION_APPLICATION_ID = 709;
     public static final int KM_TAG_IDENTITY_CREDENTIAL_KEY = 721;
 
-    @Ignore("Not ready until SW implementation produces correct attestations")
     @Test
     public void attestationTest() throws Exception {
         Context appContext = InstrumentationRegistry.getTargetContext();
diff --git a/tests/tests/identity/src/android/security/identity/cts/ProvisioningTest.java b/tests/tests/identity/src/android/security/identity/cts/ProvisioningTest.java
index 48cc405..6a264ef 100644
--- a/tests/tests/identity/src/android/security/identity/cts/ProvisioningTest.java
+++ b/tests/tests/identity/src/android/security/identity/cts/ProvisioningTest.java
@@ -135,22 +135,22 @@
         PersonalizationData personalizationData =
                 new PersonalizationData.Builder()
                         .addAccessControlProfile(noAuthProfile)
-                        .setEntry(mdlNs, "First name", idsNoAuth, Util.cborEncodeString("Alan"))
-                        .setEntry(mdlNs, "Last name", idsNoAuth, Util.cborEncodeString("Turing"))
-                        .setEntry(mdlNs, "Home address", idsNoAuth,
+                        .putEntry(mdlNs, "First name", idsNoAuth, Util.cborEncodeString("Alan"))
+                        .putEntry(mdlNs, "Last name", idsNoAuth, Util.cborEncodeString("Turing"))
+                        .putEntry(mdlNs, "Home address", idsNoAuth,
                                 Util.cborEncodeString("Maida Vale, London, England"))
-                        .setEntry(mdlNs, "Birth date", idsNoAuth, Util.cborEncodeString("19120623"))
-                        .setEntry(mdlNs, "Cryptanalyst", idsNoAuth, Util.cborEncodeBoolean(true))
-                        .setEntry(mdlNs, "Portrait image", idsNoAuth, Util.cborEncodeBytestring(
+                        .putEntry(mdlNs, "Birth date", idsNoAuth, Util.cborEncodeString("19120623"))
+                        .putEntry(mdlNs, "Cryptanalyst", idsNoAuth, Util.cborEncodeBoolean(true))
+                        .putEntry(mdlNs, "Portrait image", idsNoAuth, Util.cborEncodeBytestring(
                             new byte[]{0x01, 0x02}))
-                        .setEntry(mdlNs, "Height", idsNoAuth, Util.cborEncodeInt(180))
-                        .setEntry(mdlNs, "Neg Item", idsNoAuth, Util.cborEncodeInt(-42))
-                        .setEntry(mdlNs, "Int Two Bytes", idsNoAuth, Util.cborEncodeInt(0x101))
-                        .setEntry(mdlNs, "Int Four Bytes", idsNoAuth, Util.cborEncodeInt(0x10001))
-                        .setEntry(mdlNs, "Int Eight Bytes", idsNoAuth,
+                        .putEntry(mdlNs, "Height", idsNoAuth, Util.cborEncodeInt(180))
+                        .putEntry(mdlNs, "Neg Item", idsNoAuth, Util.cborEncodeInt(-42))
+                        .putEntry(mdlNs, "Int Two Bytes", idsNoAuth, Util.cborEncodeInt(0x101))
+                        .putEntry(mdlNs, "Int Four Bytes", idsNoAuth, Util.cborEncodeInt(0x10001))
+                        .putEntry(mdlNs, "Int Eight Bytes", idsNoAuth,
                                 Util.cborEncodeInt(0x100000001L))
-                        .setEntry(mdlNs, "driving_privileges", idsNoAuth, drivingPrivileges)
-                        .setEntry(mdlNs, "No Access", idsNoAcp,
+                        .putEntry(mdlNs, "driving_privileges", idsNoAuth, drivingPrivileges)
+                        .putEntry(mdlNs, "No Access", idsNoAcp,
                                 Util.cborEncodeString("Cannot be retrieved"))
                         .build();
 
@@ -291,13 +291,13 @@
         PersonalizationData personalizationData =
                 new PersonalizationData.Builder()
                         .addAccessControlProfile(noAuthProfile)
-                        .setEntry("org.example.barfoo", "Bar", idsNoAuth,
+                        .putEntry("org.example.barfoo", "Bar", idsNoAuth,
                                 Util.cborEncodeString("Foo"))
-                        .setEntry("org.example.barfoo", "Foo", idsNoAuth,
+                        .putEntry("org.example.barfoo", "Foo", idsNoAuth,
                                 Util.cborEncodeString("Bar"))
-                        .setEntry("org.example.foobar", "Foo", idsNoAuth,
+                        .putEntry("org.example.foobar", "Foo", idsNoAuth,
                                 Util.cborEncodeString("Bar"))
-                        .setEntry("org.example.foobar", "Bar", idsNoAuth,
+                        .putEntry("org.example.foobar", "Bar", idsNoAuth,
                                 Util.cborEncodeString("Foo"))
                         .build();
 
@@ -480,7 +480,7 @@
                 null,
                 null);
 
-        Collection<String> resultNamespaces = rd.getNamespaceNames();
+        Collection<String> resultNamespaces = rd.getNamespaces();
         assertEquals(resultNamespaces.size(), 1);
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         assertEquals(12, rd.getEntryNames("org.iso.18013-5.2019").size());
@@ -628,7 +628,7 @@
                 null,
                 null);
 
-        Collection<String> resultNamespaces = rd.getNamespaceNames();
+        Collection<String> resultNamespaces = rd.getNamespaces();
         assertEquals(resultNamespaces.size(), 1);
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         assertEquals(6, rd.getEntryNames("org.iso.18013-5.2019").size());
@@ -667,7 +667,7 @@
                 null,
                 null);
 
-        Collection<String> resultNamespaces = rd.getNamespaceNames();
+        Collection<String> resultNamespaces = rd.getNamespaces();
         assertEquals(resultNamespaces.size(), 1);
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         assertEquals(1, rd.getEntryNames("org.iso.18013-5.2019").size());
@@ -724,7 +724,7 @@
                 null,
                 null);
 
-        Collection<String> resultNamespaces = rd.getNamespaceNames();
+        Collection<String> resultNamespaces = rd.getNamespaces();
         assertEquals(resultNamespaces.size(), 1);
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         assertEquals(7, rd.getEntryNames("org.iso.18013-5.2019").size());
@@ -769,7 +769,7 @@
                 null,
                 null);
 
-        Collection<String> resultNamespaces = rd.getNamespaceNames();
+        Collection<String> resultNamespaces = rd.getNamespaces();
         assertEquals(resultNamespaces.size(), 1);
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         assertEquals(3, rd.getEntryNames("org.iso.18013-5.2019").size());
@@ -821,7 +821,7 @@
         // that do not exist in the credential.
         //
         // Additionally, each namespace should have exactly the items requested, in the same order.
-        Collection<String> resultNamespaces = rd.getNamespaceNames();
+        Collection<String> resultNamespaces = rd.getNamespaces();
         assertEquals(resultNamespaces.size(), 3);
 
 
diff --git a/tests/tests/identity/src/android/security/identity/cts/ReaderAuthTest.java b/tests/tests/identity/src/android/security/identity/cts/ReaderAuthTest.java
index 1abc0ae..86c920a 100644
--- a/tests/tests/identity/src/android/security/identity/cts/ReaderAuthTest.java
+++ b/tests/tests/identity/src/android/security/identity/cts/ReaderAuthTest.java
@@ -202,13 +202,13 @@
                         .addAccessControlProfile(readerAProfile)
                         .addAccessControlProfile(readerBProfile)
                         .addAccessControlProfile(readerCProfile)
-                        .setEntry(mdlNs, "Accessible to A", idsReaderAuthA,
+                        .putEntry(mdlNs, "Accessible to A", idsReaderAuthA,
                                 Util.cborEncodeString("foo"))
-                        .setEntry(mdlNs, "Accessible to B", idsReaderAuthB,
+                        .putEntry(mdlNs, "Accessible to B", idsReaderAuthB,
                                 Util.cborEncodeString("bar"))
-                        .setEntry(mdlNs, "Accessible to A or B", idsReaderAuthAorB,
+                        .putEntry(mdlNs, "Accessible to A or B", idsReaderAuthAorB,
                                 Util.cborEncodeString("baz"))
-                        .setEntry(mdlNs, "Accessible to C", idsReaderAuthC,
+                        .putEntry(mdlNs, "Accessible to C", idsReaderAuthC,
                                 Util.cborEncodeString("bat"))
                         .build();
         byte[] proofOfProvisioningSignature = wc.personalize(personalizationData);
@@ -291,7 +291,7 @@
         //
         rd = retrieveForReader(credential, eKeyPair, readerKeyPairA, certChainForA, requestMessage,
                 entriesToRequest);
-        resultNamespaces = rd.getNamespaceNames();
+        resultNamespaces = rd.getNamespaces();
         assertEquals(1, resultNamespaces.size());
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         entryNames = rd.getRetrievedEntryNames("org.iso.18013-5.2019");
@@ -324,7 +324,7 @@
         eKeyPair = credential.createEphemeralKeyPair();
         rd = retrieveForReader(credential, eKeyPair, readerKeyPairA, certChainForA,
                 requestMessage2, entriesToRequest);
-        resultNamespaces = rd.getNamespaceNames();
+        resultNamespaces = rd.getNamespaces();
         assertEquals(1, resultNamespaces.size());
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         entryNames = rd.getRetrievedEntryNames("org.iso.18013-5.2019");
@@ -345,7 +345,7 @@
         eKeyPair = credential.createEphemeralKeyPair();
         rd = retrieveForReader(credential, eKeyPair, readerKeyPairA, certChainForAwithC,
                 requestMessage, entriesToRequest);
-        resultNamespaces = rd.getNamespaceNames();
+        resultNamespaces = rd.getNamespaces();
         assertEquals(1, resultNamespaces.size());
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         entryNames = rd.getRetrievedEntryNames("org.iso.18013-5.2019");
@@ -361,7 +361,7 @@
         eKeyPair = credential.createEphemeralKeyPair();
         rd = retrieveForReader(credential, eKeyPair, readerKeyPairB, certChainForB, requestMessage,
                 entriesToRequest);
-        resultNamespaces = rd.getNamespaceNames();
+        resultNamespaces = rd.getNamespaces();
         assertEquals(1, resultNamespaces.size());
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         entryNames = rd.getRetrievedEntryNames("org.iso.18013-5.2019");
@@ -376,7 +376,7 @@
         eKeyPair = credential.createEphemeralKeyPair();
         rd = retrieveForReader(credential, eKeyPair, readerKeyPairB, certChainForBwithC,
                 requestMessage, entriesToRequest);
-        resultNamespaces = rd.getNamespaceNames();
+        resultNamespaces = rd.getNamespaces();
         assertEquals(1, resultNamespaces.size());
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         entryNames = rd.getRetrievedEntryNames("org.iso.18013-5.2019");
@@ -412,7 +412,7 @@
             entriesToRequest,
             null,
             null);
-        resultNamespaces = rd.getNamespaceNames();
+        resultNamespaces = rd.getNamespaces();
         assertEquals(1, resultNamespaces.size());
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         entryNames = rd.getRetrievedEntryNames("org.iso.18013-5.2019");
diff --git a/tests/tests/identity/src/android/security/identity/cts/UserAuthTest.java b/tests/tests/identity/src/android/security/identity/cts/UserAuthTest.java
index d991938..e63c517 100644
--- a/tests/tests/identity/src/android/security/identity/cts/UserAuthTest.java
+++ b/tests/tests/identity/src/android/security/identity/cts/UserAuthTest.java
@@ -229,9 +229,9 @@
                 new PersonalizationData.Builder()
                         .addAccessControlProfile(authTenSecTimeoutProfile)
                         .addAccessControlProfile(freeForAllProfile)
-                        .setEntry(mdlNs, "Accessible to all (0)", idsProfile0,
+                        .putEntry(mdlNs, "Accessible to all (0)", idsProfile0,
                                 Util.cborEncodeString("foo0"))
-                        .setEntry(mdlNs, "Accessible to auth-with-10-sec-timeout (1)", idsProfile1,
+                        .putEntry(mdlNs, "Accessible to auth-with-10-sec-timeout (1)", idsProfile1,
                                 Util.cborEncodeString("foo1"))
                         .build();
         byte[] proofOfProvisioningSignature = wc.personalize(personalizationData);
@@ -301,7 +301,7 @@
             entriesToRequest,
             null,  // sessionTranscript
             null); // readerSignature
-        resultNamespaces = rd.getNamespaceNames();
+        resultNamespaces = rd.getNamespaces();
         assertEquals(1, resultNamespaces.size());
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         entryNames = rd.getEntryNames("org.iso.18013-5.2019");
@@ -334,7 +334,7 @@
                 entriesToRequest,
                 null,  // sessionTranscript
                 null); // readerSignature
-        resultNamespaces = rd.getNamespaceNames();
+        resultNamespaces = rd.getNamespaces();
         assertEquals(1, resultNamespaces.size());
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         entryNames = rd.getEntryNames("org.iso.18013-5.2019");
@@ -368,7 +368,7 @@
             entriesToRequest,
             null,  // sessionTranscript
             null); // readerSignature
-        resultNamespaces = rd.getNamespaceNames();
+        resultNamespaces = rd.getNamespaces();
         assertEquals(1, resultNamespaces.size());
         assertEquals("org.iso.18013-5.2019", resultNamespaces.iterator().next());
         entryNames = rd.getEntryNames("org.iso.18013-5.2019");
diff --git a/tests/tests/jni_vendor/Android.bp b/tests/tests/jni_vendor/Android.bp
deleted file mode 100644
index 544257b..0000000
--- a/tests/tests/jni_vendor/Android.bp
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (C) 2017 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.
-
-android_test {
-    name: "CtsVendorJniTestCases",
-    defaults: ["cts_defaults"],
-
-    compile_multilib: "both",
-    static_libs: [
-        "androidx.test.rules",
-        "ctstestrunner-axt",
-    ],
-    jni_libs: ["libvendorjnitest"],
-    srcs: ["src/**/*.java"],
-    sdk_version: "current",
-    // TODO(jiyong) make this really a part of CTS
-    // This can't be done right now since VNDK runtime restriction is optional
-    // at least for O-MR1.
-    // Tag this module as a cts test artifact
-    // test_suites: ["cts", "vts", "general-tests"],
-}
diff --git a/tests/tests/jni_vendor/AndroidManifest.xml b/tests/tests/jni_vendor/AndroidManifest.xml
deleted file mode 100644
index 96a1c9e..0000000
--- a/tests/tests/jni_vendor/AndroidManifest.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.jni.vendor.cts">
-
-    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
-    <application>
-        <uses-library android:name="android.test.runner" />
-    </application>
-
-    <!-- This is a self-instrumenting test package. -->
-    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
-                     android:targetPackage="android.jni.vendor.cts"
-                     android:label="CTS tests of calling native code via Vendor's JNI">
-        <meta-data android:name="listener"
-            android:value="com.android.cts.runner.CtsTestRunListener" />
-    </instrumentation>
-
-</manifest>
-
diff --git a/tests/tests/jni_vendor/AndroidTest.xml b/tests/tests/jni_vendor/AndroidTest.xml
deleted file mode 100644
index b606559..0000000
--- a/tests/tests/jni_vendor/AndroidTest.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<configuration description="Config for CTS Vendor's JNI test cases">
-    <option name="test-suite-tag" value="cts" />
-    <option name="config-descriptor:metadata" key="component" value="art" />
-    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
-        <option name="cleanup-apks" value="true" />
-        <option name="test-file-name" value="CtsVendorJniTestCases.apk" />
-    </target_preparer>
-    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
-        <option name="package" value="android.jni.vendor.cts" />
-        <option name="runtime-hint" value="1m" />
-    </test>
-</configuration>
diff --git a/tests/tests/jni_vendor/libvendorjnitest/Android.bp b/tests/tests/jni_vendor/libvendorjnitest/Android.bp
deleted file mode 100644
index 0589010..0000000
--- a/tests/tests/jni_vendor/libvendorjnitest/Android.bp
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright (C) 2017 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.
-
-//
-// This is the shared library included by the JNI test app.
-//
-
-cc_test_library {
-    name: "libvendorjnitest",
-    srcs: ["android_jni_vendor_cts_VendorJniTest.cpp"],
-    shared_libs: [
-        "libdl",
-        "liblog",
-    ],
-    sdk_version: "current",
-    stl: "c++_static",
-    cflags: ["-Wno-unused-parameter"],
-    vendor: true,
-    gtest: false,
-}
diff --git a/tests/tests/jni_vendor/libvendorjnitest/android_jni_vendor_cts_VendorJniTest.cpp b/tests/tests/jni_vendor/libvendorjnitest/android_jni_vendor_cts_VendorJniTest.cpp
deleted file mode 100644
index 42e740e..0000000
--- a/tests/tests/jni_vendor/libvendorjnitest/android_jni_vendor_cts_VendorJniTest.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2017 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.
- */
-
-#include <jni.h>
-#include <dlfcn.h>
-
-extern "C" JNIEXPORT jstring JNICALL
-Java_android_jni_vendor_cts_VendorJniTest_dlopen(JNIEnv* env, jclass clazz, jstring name) {
-    const char* libname = env->GetStringUTFChars(name, nullptr);
-    jstring error_msg;
-    dlerror(); // clear any existing error
-    void* handle = dlopen(libname, RTLD_NOW);
-    env->ReleaseStringUTFChars(name, libname);
-    if (handle == nullptr) {
-        error_msg = env->NewStringUTF(dlerror());
-    } else {
-        error_msg = env->NewStringUTF("");
-    }
-    return error_msg;
-}
diff --git a/tests/tests/jni_vendor/src/android/jni/vendor/cts/VendorJniTest.java b/tests/tests/jni_vendor/src/android/jni/vendor/cts/VendorJniTest.java
deleted file mode 100644
index db970e1..0000000
--- a/tests/tests/jni_vendor/src/android/jni/vendor/cts/VendorJniTest.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2017 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.jni.vendor.cts;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.FileSystems;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import android.os.Process;
-
-public class VendorJniTest extends TestCase {
-    private List<String> llndkLibraries;
-    private List<String> publicLibraries;
-    private List<String> vndkspLibraries;
-    private List<String> vndkLibraries;
-    private List<String> frameworkOnlyLibraries;
-
-    protected void setUp() throws Exception {
-        llndkLibraries = Files.readAllLines(FileSystems.getDefault().getPath(
-                "/system/etc/llndk.libraries.txt"));
-        publicLibraries = Files.readAllLines(FileSystems.getDefault().getPath(
-                "/system/etc/public.libraries.txt"));
-        vndkspLibraries = Files.readAllLines(FileSystems.getDefault().getPath(
-                "/system/etc/vndksp.libraries.txt"));
-
-        String systemLibDir = Process.is64Bit() ? "/system/lib64" : "/system/lib";
-
-        vndkLibraries = new ArrayList<>();
-        for(File f : (new File(systemLibDir + "/vndk")).listFiles()) {
-            if (f.isFile()) {
-                String name = f.getName();
-                if (name.endsWith(".so")) {
-                    vndkLibraries.add(name);
-                }
-            }
-        }
-
-        frameworkOnlyLibraries = new ArrayList<>();
-        for(File f : (new File(systemLibDir)).listFiles()) {
-            if (f.isFile()) {
-                String name = f.getName();
-                if (name.endsWith(".so") && !llndkLibraries.contains(name)
-                        && !vndkspLibraries.contains(name)
-                        && !publicLibraries.contains(name)) {
-                    frameworkOnlyLibraries.add(name);
-                }
-            }
-        }
-
-        System.loadLibrary("vendorjnitest");
-    }
-
-    public static native String dlopen(String name);
-
-    /* test if llndk libraries are all accessible */
-    public void test_llndkLibraries() {
-        for(String lib : llndkLibraries) {
-            assertEquals("", dlopen(lib));
-        }
-    }
-
-    /* test if vndk-sp libs are accessible */
-    public void test_vndkSpLibraries() {
-        for(String lib : vndkspLibraries) {
-            String error = dlopen(lib);
-            if (lib.equals("android.hidl.memory@1.0-impl.so")) {
-                // This won't be accessible to vendor JNI. This lib is only accessible from the
-                // 'sphal' namespace which isn't linked to the vendor-classloader-namespace.
-                if (error.equals("")) {
-                    fail(lib + " must not be accessible to vendor apks, but was accessible.");
-                }
-                continue;
-            }
-            assertEquals("", error);
-        }
-    }
-
-    /* test if vndk libs are not accessible */
-    public void test_vndkLibraries() {
-        for(String lib : vndkLibraries) {
-            String error = dlopen(lib);
-            if (error.equals("")) {
-                fail(lib + " must not be accessible to vendor apks, but was accessible.");
-            }
-        }
-    }
-
-    /* test if framework-only libs are not accessible */
-    public void test_frameworkOnlyLibraries() {
-        for(String lib : frameworkOnlyLibraries) {
-            String error = dlopen(lib);
-            if (error.equals("")) {
-                fail(lib + " must not be accessible to vendor apks, but was accessible.");
-            }
-        }
-    }
-}
diff --git a/tests/tests/media/Android.bp b/tests/tests/media/Android.bp
index b0930a6..83d6aef 100644
--- a/tests/tests/media/Android.bp
+++ b/tests/tests/media/Android.bp
@@ -77,4 +77,5 @@
         "mts",
     ],
     host_required: ["cts-dynamic-config"],
+    min_sdk_version: "29",
 }
diff --git a/tests/tests/media/AndroidManifest.xml b/tests/tests/media/AndroidManifest.xml
index 1bec10d..7a00734 100644
--- a/tests/tests/media/AndroidManifest.xml
+++ b/tests/tests/media/AndroidManifest.xml
@@ -152,6 +152,8 @@
        <receiver android:name="android.media.cts.MediaButtonReceiver" />
     </application>
 
+    <uses-sdk android:minSdkVersion="29"   android:targetSdkVersion="29" />
+
     <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
                      android:targetPackage="android.media.cts"
                      android:label="CTS tests of android.media">
diff --git a/tests/tests/media/src/android/media/cts/MediaRoute2InfoTest.java b/tests/tests/media/src/android/media/cts/MediaRoute2InfoTest.java
index 31974df..d4be2a5 100644
--- a/tests/tests/media/src/android/media/cts/MediaRoute2InfoTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaRoute2InfoTest.java
@@ -49,7 +49,6 @@
     public static final String TEST_NAME = "test_name";
     public static final String TEST_ROUTE_TYPE_0 = "test_route_type_0";
     public static final String TEST_ROUTE_TYPE_1 = "test_route_type_1";
-    public static final int TEST_DEVICE_TYPE = MediaRoute2Info.DEVICE_TYPE_REMOTE_SPEAKER;
     public static final Uri TEST_ICON_URI = Uri.parse("https://developer.android.com");
     public static final String TEST_DESCRIPTION = "test_description";
     public static final int TEST_CONNECTION_STATE = MediaRoute2Info.CONNECTION_STATE_CONNECTING;
@@ -113,7 +112,6 @@
         MediaRoute2Info routeInfo = new MediaRoute2Info.Builder(TEST_ID, TEST_NAME)
                 .addFeature(TEST_ROUTE_TYPE_0)
                 .addFeature(TEST_ROUTE_TYPE_1)
-                .setDeviceType(TEST_DEVICE_TYPE)
                 .setIconUri(TEST_ICON_URI)
                 .setDescription(TEST_DESCRIPTION)
                 .setConnectionState(TEST_CONNECTION_STATE)
@@ -131,7 +129,6 @@
         assertEquals(TEST_ROUTE_TYPE_0, routeInfo.getFeatures().get(0));
         assertEquals(TEST_ROUTE_TYPE_1, routeInfo.getFeatures().get(1));
 
-        assertEquals(TEST_DEVICE_TYPE, routeInfo.getDeviceType());
         assertEquals(TEST_ICON_URI, routeInfo.getIconUri());
         assertEquals(TEST_DESCRIPTION, routeInfo.getDescription());
         assertEquals(TEST_CONNECTION_STATE, routeInfo.getConnectionState());
@@ -184,38 +181,6 @@
     }
 
     @Test
-    public void testhasAnyFeaturesReturnsFalse() {
-        MediaRoute2Info routeInfo = new MediaRoute2Info.Builder(TEST_ID, TEST_NAME)
-                .addFeature(TEST_ROUTE_TYPE_0)
-                .addFeature(TEST_ROUTE_TYPE_1)
-                .build();
-
-        List<String> testRouteTypes = new ArrayList<>();
-        testRouteTypes.add("non_matching_route_type_1");
-        testRouteTypes.add("non_matching_route_type_2");
-        testRouteTypes.add("non_matching_route_type_3");
-        testRouteTypes.add("non_matching_route_type_4");
-
-        assertFalse(routeInfo.hasAnyFeatures(testRouteTypes));
-    }
-
-    @Test
-    public void testhasAnyFeaturesReturnsTrue() {
-        MediaRoute2Info routeInfo = new MediaRoute2Info.Builder(TEST_ID, TEST_NAME)
-                .addFeature(TEST_ROUTE_TYPE_0)
-                .addFeature(TEST_ROUTE_TYPE_1)
-                .build();
-
-        List<String> testRouteTypes = new ArrayList<>();
-        testRouteTypes.add("non_matching_route_type_1");
-        testRouteTypes.add("non_matching_route_type_2");
-        testRouteTypes.add("non_matching_route_type_3");
-        testRouteTypes.add(TEST_ROUTE_TYPE_1);
-
-        assertTrue(routeInfo.hasAnyFeatures(testRouteTypes));
-    }
-
-    @Test
     public void testEqualsCreatedWithSameArguments() {
         Bundle extras = new Bundle();
         extras.putString(TEST_KEY, TEST_VALUE);
@@ -223,7 +188,6 @@
         MediaRoute2Info routeInfo1 = new MediaRoute2Info.Builder(TEST_ID, TEST_NAME)
                 .addFeature(TEST_ROUTE_TYPE_0)
                 .addFeature(TEST_ROUTE_TYPE_1)
-                .setDeviceType(TEST_DEVICE_TYPE)
                 .setIconUri(TEST_ICON_URI)
                 .setDescription(TEST_DESCRIPTION)
                 .setConnectionState(TEST_CONNECTION_STATE)
@@ -237,7 +201,6 @@
         MediaRoute2Info routeInfo2 = new MediaRoute2Info.Builder(TEST_ID, TEST_NAME)
                 .addFeature(TEST_ROUTE_TYPE_0)
                 .addFeature(TEST_ROUTE_TYPE_1)
-                .setDeviceType(TEST_DEVICE_TYPE)
                 .setIconUri(TEST_ICON_URI)
                 .setDescription(TEST_DESCRIPTION)
                 .setConnectionState(TEST_CONNECTION_STATE)
@@ -260,7 +223,6 @@
         MediaRoute2Info routeInfo1 = new MediaRoute2Info.Builder(TEST_ID, TEST_NAME)
                 .addFeature(TEST_ROUTE_TYPE_0)
                 .addFeature(TEST_ROUTE_TYPE_1)
-                .setDeviceType(TEST_DEVICE_TYPE)
                 .setIconUri(TEST_ICON_URI)
                 .setDescription(TEST_DESCRIPTION)
                 .setConnectionState(TEST_CONNECTION_STATE)
@@ -285,7 +247,6 @@
         MediaRoute2Info routeInfo = new MediaRoute2Info.Builder(TEST_ID, TEST_NAME)
                 .addFeature(TEST_ROUTE_TYPE_0)
                 .addFeature(TEST_ROUTE_TYPE_1)
-                .setDeviceType(TEST_DEVICE_TYPE)
                 .setIconUri(TEST_ICON_URI)
                 .setDescription(TEST_DESCRIPTION)
                 .setConnectionState(TEST_CONNECTION_STATE)
@@ -301,9 +262,6 @@
                 .addFeature("randomRouteType")
                 .build());
         assertNotEquals(routeInfo, new MediaRoute2Info.Builder(routeInfo)
-                .setDeviceType(TEST_DEVICE_TYPE + 1)
-                .build());
-        assertNotEquals(routeInfo, new MediaRoute2Info.Builder(routeInfo)
                 .setIconUri(Uri.parse("randomUri"))
                 .build());
         assertNotEquals(routeInfo, new MediaRoute2Info.Builder(routeInfo)
@@ -335,7 +293,6 @@
         MediaRoute2Info routeInfo = new MediaRoute2Info.Builder(TEST_ID, TEST_NAME)
                 .addFeature(TEST_ROUTE_TYPE_0)
                 .addFeature(TEST_ROUTE_TYPE_1)
-                .setDeviceType(TEST_DEVICE_TYPE)
                 .setIconUri(TEST_ICON_URI)
                 .setDescription(TEST_DESCRIPTION)
                 .setConnectionState(TEST_CONNECTION_STATE)
@@ -372,7 +329,6 @@
         MediaRoute2Info routeInfo = new MediaRoute2Info.Builder(TEST_ID, TEST_NAME)
                 .addFeature(TEST_ROUTE_TYPE_0)
                 .addFeature(TEST_ROUTE_TYPE_1)
-                .setDeviceType(TEST_DEVICE_TYPE)
                 .setIconUri(TEST_ICON_URI)
                 .setDescription(TEST_DESCRIPTION)
                 .setConnectionState(TEST_CONNECTION_STATE)
diff --git a/tests/tests/media/src/android/media/cts/MediaRoute2ProviderServiceTest.java b/tests/tests/media/src/android/media/cts/MediaRoute2ProviderServiceTest.java
index 46c6dc4..1ebad5e 100644
--- a/tests/tests/media/src/android/media/cts/MediaRoute2ProviderServiceTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaRoute2ProviderServiceTest.java
@@ -121,7 +121,7 @@
                 SESSION_ID_1, "" /* clientPackageName */)
                 .addSelectedRoute(ROUTE_ID1)
                 .build();
-        mService.notifySessionCreated(sessionInfo1, MediaRoute2ProviderService.REQUEST_ID_NONE);
+        mService.notifySessionCreated(MediaRoute2ProviderService.REQUEST_ID_NONE, sessionInfo1);
         assertEquals(1, mService.getAllSessionInfo().size());
         assertEquals(sessionInfo1, mService.getAllSessionInfo().get(0));
         assertEquals(sessionInfo1, mService.getSessionInfo(SESSION_ID_1));
@@ -132,7 +132,7 @@
                 .addSelectedRoute(ROUTE_ID2)
                 .build();
         mService.notifySessionCreated(
-                sessionInfo2, MediaRoute2ProviderService.REQUEST_ID_NONE);
+                MediaRoute2ProviderService.REQUEST_ID_NONE, sessionInfo2);
         assertEquals(2, mService.getAllSessionInfo().size());
         assertEquals(sessionInfo2, mService.getSessionInfo(SESSION_ID_2));
 
@@ -302,7 +302,7 @@
                         .addSelectableRoute(ROUTE_ID4_TO_SELECT_AND_DESELECT)
                         .addTransferableRoute(ROUTE_ID5_TO_TRANSFER_TO)
                         .build();
-                mService.notifySessionCreated(info, requestId);
+                mService.notifySessionCreated(requestId, info);
                 onCreateSessionLatch.countDown();
             }
 
@@ -467,7 +467,7 @@
                         .addSelectableRoute(ROUTE_ID4_TO_SELECT_AND_DESELECT)
                         .addTransferableRoute(ROUTE_ID5_TO_TRANSFER_TO)
                         .build();
-                mService.notifySessionCreated(info, requestId);
+                mService.notifySessionCreated(requestId, info);
                 onCreateSessionLatch.countDown();
             }
         });
diff --git a/tests/tests/media/src/android/media/cts/StubMediaRoute2ProviderService.java b/tests/tests/media/src/android/media/cts/StubMediaRoute2ProviderService.java
index 0411351..af02d16 100644
--- a/tests/tests/media/src/android/media/cts/StubMediaRoute2ProviderService.java
+++ b/tests/tests/media/src/android/media/cts/StubMediaRoute2ProviderService.java
@@ -16,8 +16,6 @@
 
 package android.media.cts;
 
-import static android.media.MediaRoute2Info.DEVICE_TYPE_REMOTE_SPEAKER;
-import static android.media.MediaRoute2Info.DEVICE_TYPE_REMOTE_TV;
 import static android.media.MediaRoute2Info.FEATURE_LIVE_AUDIO;
 import static android.media.MediaRoute2Info.PLAYBACK_VOLUME_VARIABLE;
 
@@ -94,11 +92,9 @@
     public void initializeRoutes() {
         MediaRoute2Info route1 = new MediaRoute2Info.Builder(ROUTE_ID1, ROUTE_NAME1)
                 .addFeature(FEATURE_SAMPLE)
-                .setDeviceType(DEVICE_TYPE_REMOTE_TV)
                 .build();
         MediaRoute2Info route2 = new MediaRoute2Info.Builder(ROUTE_ID2, ROUTE_NAME2)
                 .addFeature(FEATURE_SAMPLE)
-                .setDeviceType(DEVICE_TYPE_REMOTE_SPEAKER)
                 .build();
         MediaRoute2Info route3 = new MediaRoute2Info.Builder(
                 ROUTE_ID3_SESSION_CREATION_FAILED, ROUTE_NAME3)
@@ -241,7 +237,7 @@
                 // Set control hints with given sessionHints
                 .setControlHints(sessionHints)
                 .build();
-        notifySessionCreated(sessionInfo, requestId);
+        notifySessionCreated(requestId, sessionInfo);
         publishRoutes();
     }
 
diff --git a/tests/tests/mediastress/Android.bp b/tests/tests/mediastress/Android.bp
index e0878b6..8a112df 100644
--- a/tests/tests/mediastress/Android.bp
+++ b/tests/tests/mediastress/Android.bp
@@ -39,4 +39,5 @@
     srcs: ["src/**/*.java"],
     host_required: ["cts-dynamic-config"],
     sdk_version: "test_current",
+    min_sdk_version: "29",
 }
diff --git a/tests/tests/mediastress/AndroidManifest.xml b/tests/tests/mediastress/AndroidManifest.xml
index f6c750f..b847ff5 100644
--- a/tests/tests/mediastress/AndroidManifest.xml
+++ b/tests/tests/mediastress/AndroidManifest.xml
@@ -41,6 +41,9 @@
         <activity android:name="android.mediastress.cts.NativeMediaActivity"
                   android:label="NativeMedia" />
     </application>
+
+    <uses-sdk android:minSdkVersion="29"   android:targetSdkVersion="29" />
+
     <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
             android:targetPackage="android.mediastress.cts"
             android:label="Media stress tests InstrumentationRunner" >
diff --git a/tests/tests/net/assets/OWNERS b/tests/tests/net/assets/OWNERS
new file mode 100644
index 0000000..14edd1d
--- /dev/null
+++ b/tests/tests/net/assets/OWNERS
@@ -0,0 +1,4 @@
+# Bug component: 31808
+etancohen@google.com
+lorenzo@google.com
+satk@google.com
diff --git a/tests/tests/net/assets/ValidPasspointProfile.base64 b/tests/tests/net/assets/ValidPasspointProfile.base64
new file mode 100644
index 0000000..3f60eb8
--- /dev/null
+++ b/tests/tests/net/assets/ValidPasspointProfile.base64
@@ -0,0 +1 @@
+Q29udGVudC1UeXBlOiBtdWx0aXBhcnQvbWl4ZWQ7IGJvdW5kYXJ5PXtib3VuZGFyeX0KQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzogYmFzZTY0CgotLXtib3VuZGFyeX0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi94LXBhc3Nwb2ludC1wcm9maWxlCkNvbnRlbnQtVHJhbnNmZXItRW5jb2Rpbmc6IGJhc2U2NAoKUEUxbmJYUlVjbVZsSUhodGJHNXpQU0p6ZVc1amJXdzZaRzFrWkdZeExqSWlQZ29nSUR4V1pYSkVWRVErTVM0eVBDOVdaWEpFVkVRK0NpQWdQRTV2WkdVK0NpQWdJQ0E4VG05a1pVNWhiV1UrVUdWeVVISnZkbWxrWlhKVGRXSnpZM0pwY0hScGIyNDhMMDV2WkdWT1lXMWxQZ29nSUNBZ1BGSlVVSEp2Y0dWeWRHbGxjejRLSUNBZ0lDQWdQRlI1Y0dVK0NpQWdJQ0FnSUNBZ1BFUkVSazVoYldVK2RYSnVPbmRtWVRwdGJ6cG9iM1J6Y0c5ME1tUnZkREF0Y0dWeWNISnZkbWxrWlhKemRXSnpZM0pwY0hScGIyNDZNUzR3UEM5RVJFWk9ZVzFsUGdvZ0lDQWdJQ0E4TDFSNWNHVStDaUFnSUNBOEwxSlVVSEp2Y0dWeWRHbGxjejRLSUNBZ0lEeE9iMlJsUGdvZ0lDQWdJQ0E4VG05a1pVNWhiV1UrYVRBd01Ud3ZUbTlrWlU1aGJXVStDaUFnSUNBZ0lEeE9iMlJsUGdvZ0lDQWdJQ0FnSUR4T2IyUmxUbUZ0WlQ1SWIyMWxVMUE4TDA1dlpHVk9ZVzFsUGdvZ0lDQWdJQ0FnSUR4T2IyUmxQZ29nSUNBZ0lDQWdJQ0FnUEU1dlpHVk9ZVzFsUGtaeWFXVnVaR3g1VG1GdFpUd3ZUbTlrWlU1aGJXVStDaUFnSUNBZ0lDQWdJQ0E4Vm1Gc2RXVStRVlJVSUZCaGMzTndiMmx1ZER3dlZtRnNkV1UrQ2lBZ0lDQWdJQ0FnUEM5T2IyUmxQZ29nSUNBZ0lDQWdJRHhPYjJSbFBnb2dJQ0FnSUNBZ0lDQWdQRTV2WkdWT1lXMWxQa1pSUkU0OEwwNXZaR1ZPWVcxbFBnb2dJQ0FnSUNBZ0lDQWdQRlpoYkhWbFBtRjBkSGRwWm1rdVkyOXRQQzlXWVd4MVpUNEtJQ0FnSUNBZ0lDQThMMDV2WkdVK0NpQWdJQ0FnSUR3dlRtOWtaVDRLSUNBZ0lDQWdQRTV2WkdVK0NpQWdJQ0FnSUNBZ1BFNXZaR1ZPWVcxbFBrTnlaV1JsYm5ScFlXdzhMMDV2WkdWT1lXMWxQZ29nSUNBZ0lDQWdJRHhPYjJSbFBnb2dJQ0FnSUNBZ0lDQWdQRTV2WkdWT1lXMWxQbEpsWVd4dFBDOU9iMlJsVG1GdFpUNEtJQ0FnSUNBZ0lDQWdJRHhXWVd4MVpUNTNiR0Z1TG0xdVl6UXhNQzV0WTJNek1UQXVNMmR3Y0c1bGRIZHZjbXN1YjNKblBDOVdZV3gxWlQ0S0lDQWdJQ0FnSUNBOEwwNXZaR1UrQ2lBZ0lDQWdJQ0FnUEU1dlpHVStDaUFnSUNBZ0lDQWdJQ0E4VG05a1pVNWhiV1UrVTBsTlBDOU9iMlJsVG1GdFpUNEtJQ0FnSUNBZ0lDQWdJRHhPYjJSbFBnb2dJQ0FnSUNBZ0lDQWdJQ0E4VG05a1pVNWhiV1UrU1UxVFNUd3ZUbTlrWlU1aGJXVStDaUFnSUNBZ0lDQWdJQ0FnSUR4V1lXeDFaVDR6TVRBME1UQXFQQzlXWVd4MVpUNEtJQ0FnSUNBZ0lDQWdJRHd2VG05a1pUNEtJQ0FnSUNBZ0lDQWdJQ0FnUEU1dlpHVStDaUFnSUNBZ0lDQWdJQ0FnSUNBZ1BFNXZaR1ZPWVcxbFBrVkJVRlI1Y0dVOEwwNXZaR1ZPWVcxbFBnb2dJQ0FnSUNBZ0lDQWdJQ0FnSUR4V1lXeDFaVDR5TXp3dlZtRnNkV1UrQ2lBZ0lDQWdJQ0FnSUNBZ0lEd3ZUbTlrWlQ0S0lDQWdJQ0FnSUNBOEwwNXZaR1UrQ2lBZ0lDQWdJRHd2VG05a1pUNEtJQ0FnSUR3dlRtOWtaVDRLSUNBOEwwNXZaR1UrQ2p3dlRXZHRkRlJ5WldVKwotLXtib3VuZGFyeX0tLQo=
diff --git a/tests/tests/net/src/android/net/wifi/cts/WifiManagerTest.java b/tests/tests/net/src/android/net/wifi/cts/WifiManagerTest.java
index 9d36493..5bdd712 100644
--- a/tests/tests/net/src/android/net/wifi/cts/WifiManagerTest.java
+++ b/tests/tests/net/src/android/net/wifi/cts/WifiManagerTest.java
@@ -44,6 +44,9 @@
 import android.net.wifi.WifiConfiguration;
 import android.net.wifi.WifiManager;
 import android.net.wifi.WifiManager.WifiLock;
+import android.net.wifi.WifiNetworkConnectionStatistics;
+import android.net.wifi.hotspot2.ConfigParser;
+import android.net.wifi.hotspot2.PasspointConfiguration;
 import android.os.Process;
 import android.os.SystemClock;
 import android.os.UserHandle;
@@ -62,6 +65,10 @@
 import com.android.compatibility.common.util.ShellIdentityUtils;
 import com.android.compatibility.common.util.SystemUtil;
 
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.URL;
 import java.util.List;
@@ -124,6 +131,9 @@
     private static final String TEST_SSID_UNQUOTED = "testSsid1";
     private static final MacAddress TEST_MAC = MacAddress.fromString("aa:bb:cc:dd:ee:ff");
     private static final String TEST_PASSPHRASE = "passphrase";
+    private static final String PASSPOINT_INSTALLATION_FILE_WITH_CA_CERT =
+            "assets/ValidPasspointProfile.base64";
+    private static final String TYPE_WIFI_CONFIG = "application/x-wifi-config";
 
     private IntentFilter mIntentFilter;
     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@@ -742,6 +752,51 @@
     }
 
     /**
+     * Read the content of the given resource file into a String.
+     *
+     * @param filename String name of the file
+     * @return String
+     * @throws IOException
+     */
+    private String loadResourceFile(String filename) throws IOException {
+        InputStream in = getClass().getClassLoader().getResourceAsStream(filename);
+        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+        StringBuilder builder = new StringBuilder();
+        String line;
+        while ((line = reader.readLine()) != null) {
+            builder.append(line).append("\n");
+        }
+        return builder.toString();
+    }
+
+    /**
+     * Verify that changing the mac randomization setting of a Passpoint configuration.
+     */
+    public void testMacRandomizationSettingPasspoint() throws Exception {
+        String configStr = loadResourceFile(PASSPOINT_INSTALLATION_FILE_WITH_CA_CERT);
+        PasspointConfiguration config =
+                ConfigParser.parsePasspointConfig(TYPE_WIFI_CONFIG, configStr.getBytes());
+        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        try {
+            uiAutomation.adoptShellPermissionIdentity();
+
+            mWifiManager.addOrUpdatePasspointConfiguration(config);
+            List<PasspointConfiguration> passpointConfigs =
+                    mWifiManager.getPasspointConfigurations();
+            PasspointConfiguration passpointConfig = passpointConfigs.get(0);
+            assertEquals(1, passpointConfigs.size());
+            assertTrue("Mac randomization should be enabled for passpoint networks by default.",
+                    passpointConfig.isMacRandomizationEnabled());
+
+            String fqdn = passpointConfig.getHomeSp().getFqdn();
+            mWifiManager.setMacRandomizationSettingPasspointEnabled(fqdn, false);
+            assertFalse("Mac randomization should be disabled by the API call.",
+                    mWifiManager.getPasspointConfigurations().get(0).isMacRandomizationEnabled());
+        } finally {
+            uiAutomation.dropShellPermissionIdentity();
+        }
+    }
+    /**
      * Verify that the {@link android.Manifest.permission#NETWORK_STACK} permission is never held by
      * any package.
      * <p>
@@ -1559,6 +1614,16 @@
     }
 
     /**
+     * Test {@link WifiNetworkConnectionStatistics} does not crash.
+     * TODO(b/150891569): deprecate it in Android S, this API is not used anywhere.
+     */
+    public void testWifiNetworkConnectionStatistics() {
+        new WifiNetworkConnectionStatistics();
+        WifiNetworkConnectionStatistics stats = new WifiNetworkConnectionStatistics(0, 0);
+        new WifiNetworkConnectionStatistics(stats);
+    }
+
+    /**
      * Test that the wifi country code is either null, or a length-2 string.
      */
     public void testGetCountryCode() throws Exception {
diff --git a/tests/tests/notificationlegacy/AndroidTest.xml b/tests/tests/notificationlegacy/AndroidTest.xml
index 690766c..571fe44 100644
--- a/tests/tests/notificationlegacy/AndroidTest.xml
+++ b/tests/tests/notificationlegacy/AndroidTest.xml
@@ -16,6 +16,8 @@
 <configuration description="Config for CTS Notification legacy test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="framework" />
+    <!-- Not testing features backed by native code, so only need to run against one ABI -->
+    <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsLegacyNotificationTestCases.apk" />
diff --git a/tests/tests/os/src/android/os/cts/BinderTest.java b/tests/tests/os/src/android/os/cts/BinderTest.java
index 59b81e2..5bc304a 100644
--- a/tests/tests/os/src/android/os/cts/BinderTest.java
+++ b/tests/tests/os/src/android/os/cts/BinderTest.java
@@ -381,6 +381,22 @@
         Binder.restoreCallingIdentity(token);
     }
 
+    public void testClearCallingWorkSource() {
+        final long token = Binder.clearCallingWorkSource();
+        Binder.restoreCallingWorkSource(token);
+    }
+
+    public void testSetCallingWorkSourceUid() {
+        final int otherUid = android.os.Process.myUid() + 1;
+        assertFalse(Binder.getCallingWorkSourceUid() == otherUid);
+
+        final long token = Binder.setCallingWorkSourceUid(otherUid);
+        assertTrue(Binder.getCallingWorkSourceUid() == otherUid);
+        Binder.restoreCallingWorkSource(token);
+
+        assertFalse(Binder.getCallingWorkSourceUid() == otherUid);
+    }
+
     public void testInterfaceRelatedMethods() {
         assertNull(mBinder.getInterfaceDescriptor());
         mBinder.attachInterface(new MockIInterface(), DESCRIPTOR_GOOGLE);
diff --git a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
index f0f2d36..69f9a40 100644
--- a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
@@ -341,6 +341,24 @@
     }
 
     @Test
+    public void testFileWrapped() throws Exception {
+        final Handler handler1 = new Handler(Looper.getMainLooper());
+        final Handler handler2 = new Handler(Looper.getMainLooper());
+        final FutureCloseListener listener1 = new FutureCloseListener();
+        final FutureCloseListener listener2 = new FutureCloseListener();
+        final ParcelFileDescriptor file1 = ParcelFileDescriptor.open(
+                File.createTempFile("pfd", "bbq"), ParcelFileDescriptor.MODE_READ_WRITE, handler1,
+                listener1);
+        final ParcelFileDescriptor file2 = ParcelFileDescriptor.wrap(file1, handler2, listener2);
+
+        write(file2, 7);
+        file2.close();
+
+        // make sure we were notified
+        assertEquals(null, listener2.get());
+    }
+
+    @Test
     public void testSocketErrorAfterClose() throws Exception {
         final ParcelFileDescriptor[] pair = ParcelFileDescriptor.createReliableSocketPair();
         final ParcelFileDescriptor red = pair[0];
diff --git a/tests/tests/provider/src/android/provider/cts/DocumentsContractTest.java b/tests/tests/provider/src/android/provider/cts/DocumentsContractTest.java
index 66bb43b..8f435f7 100644
--- a/tests/tests/provider/src/android/provider/cts/DocumentsContractTest.java
+++ b/tests/tests/provider/src/android/provider/cts/DocumentsContractTest.java
@@ -260,6 +260,12 @@
     }
 
     @Test
+    public void testManageMode() {
+        assertFalse(DocumentsContract.isManageMode(URI_RED));
+        assertTrue(DocumentsContract.isManageMode(DocumentsContract.setManageMode(URI_RED)));
+    }
+
+    @Test
     public void testCreateDocument() throws Exception {
         doReturn(DOC_RESULT).when(mProvider).createDocument(DOC_RED, MIME_TYPE, DISPLAY_NAME);
         assertEquals(URI_RESULT, createDocument(mResolver, URI_RED, MIME_TYPE, DISPLAY_NAME));
diff --git a/tests/tests/provider/src/android/provider/cts/media/MediaStoreTest.java b/tests/tests/provider/src/android/provider/cts/media/MediaStoreTest.java
index 7b2e562..37ed546 100644
--- a/tests/tests/provider/src/android/provider/cts/media/MediaStoreTest.java
+++ b/tests/tests/provider/src/android/provider/cts/media/MediaStoreTest.java
@@ -148,6 +148,15 @@
     }
 
     @Test
+    public void testGetRecentExternalVolumeNames() {
+        Set<String> volumeNames = MediaStore.getRecentExternalVolumeNames(getContext());
+
+        assertFalse(volumeNames.contains(MediaStore.VOLUME_INTERNAL));
+        assertFalse(volumeNames.contains(MediaStore.VOLUME_EXTERNAL));
+        assertTrue(volumeNames.contains(MediaStore.VOLUME_EXTERNAL_PRIMARY));
+    }
+
+    @Test
     public void testGetStorageVolume() throws Exception {
         Assume.assumeFalse(MediaStore.VOLUME_EXTERNAL.equals(mVolumeName));
 
diff --git a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Audio_AlbumsTest.java b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Audio_AlbumsTest.java
index ca0413c..2621949 100644
--- a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Audio_AlbumsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Audio_AlbumsTest.java
@@ -202,6 +202,7 @@
 
             // Delete item and confirm art is cleaned up
             mContentResolver.delete(mediaUri, null, null);
+            MediaStore.waitForIdle(mContentResolver);
 
             try {
                 mContentResolver.loadThumbnail(mediaUri, new Size(32, 32), null);
diff --git a/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
index 08931eb..28ceed0 100755
--- a/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
@@ -18,6 +18,8 @@
 
 import static android.telecom.cts.TestUtils.*;
 
+import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
+
 import android.content.ComponentName;
 import android.content.Context;
 import android.media.AudioManager;
@@ -27,6 +29,8 @@
 import android.telecom.ConnectionService;
 import android.telecom.PhoneAccountHandle;
 
+import androidx.test.InstrumentationRegistry;
+
 import java.util.Collection;
 
 /**
@@ -59,7 +63,9 @@
         // Add second connection (add existing connection)
         final MockConnection connection = new MockConnection();
         connection.setOnHold();
-        CtsConnectionService.addExistingConnectionToTelecom(TEST_PHONE_ACCOUNT_HANDLE, connection);
+        runWithShellPermissionIdentity(() ->
+                CtsConnectionService.addExistingConnectionToTelecom(TEST_PHONE_ACCOUNT_HANDLE,
+                        connection));
         assertNumCalls(mInCallCallbacks.getService(), 2);
         mInCallCallbacks.lock.drainPermits();
         final Call call = mInCallCallbacks.getService().getLastCall();
@@ -81,8 +87,9 @@
                 "com.android.services.telephony.TelephonyConnectionService");
         // This command will fail and a SecurityException will be thrown by Telecom. The Exception
         // will then be absorbed by the ConnectionServiceAdapter.
-        CtsConnectionService.addExistingConnectionToTelecom(new PhoneAccountHandle(invalidName,
-                "Test"), connection);
+        runWithShellPermissionIdentity(() ->
+                CtsConnectionService.addExistingConnectionToTelecom(
+                        new PhoneAccountHandle(invalidName, "Test"), connection));
         // Make sure that only the original Call exists.
         assertNumCalls(mInCallCallbacks.getService(), 1);
         mInCallCallbacks.lock.drainPermits();
@@ -103,8 +110,9 @@
         connection.setOnHold();
         ComponentName validName = new ComponentName(PACKAGE, COMPONENT);
         // This command will fail because the PhoneAccount is not registered to Telecom currently.
-        CtsConnectionService.addExistingConnectionToTelecom(new PhoneAccountHandle(validName,
-                "Invalid Account Id"), connection);
+        runWithShellPermissionIdentity(() ->
+                CtsConnectionService.addExistingConnectionToTelecom(
+                        new PhoneAccountHandle(validName, "Invalid Account Id"), connection));
         // Make sure that only the original Call exists.
         assertNumCalls(mInCallCallbacks.getService(), 1);
         mInCallCallbacks.lock.drainPermits();
@@ -243,19 +251,28 @@
             return;
         }
 
-        // Need to add a call to ensure ConnectionService is up and bound.
-        placeAndVerifyCall();
-        verifyConnectionForOutgoingCall().setActive();
+        InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                .adoptShellPermissionIdentity("android.permission.MODIFY_PHONE_STATE");
+        try {
+            // Need to add a call to ensure ConnectionService is up and bound.
+            placeAndVerifyCall();
+            verifyConnectionForOutgoingCall().setActive();
 
-        final MockConnection connection = new MockConnection();
-        connection.setActive();
-        connection.setCallDirection(Call.Details.DIRECTION_INCOMING);
-        CtsConnectionService.addExistingConnectionToTelecom(TEST_PHONE_ACCOUNT_HANDLE, connection);
-        assertNumCalls(mInCallCallbacks.getService(), 2);
-        mInCallCallbacks.lock.drainPermits();
-        final Call call = mInCallCallbacks.getService().getLastCall();
-        assertCallState(call, Call.STATE_ACTIVE);
-        assertEquals(Call.Details.DIRECTION_INCOMING, call.getDetails().getCallDirection());
+            final MockConnection connection = new MockConnection();
+            connection.setActive();
+            connection.setCallDirection(Call.Details.DIRECTION_INCOMING);
+            CtsConnectionService.addExistingConnectionToTelecom(TEST_PHONE_ACCOUNT_HANDLE,
+                    connection);
+            assertNumCalls(mInCallCallbacks.getService(), 2);
+            mInCallCallbacks.lock.drainPermits();
+            final Call call = mInCallCallbacks.getService().getLastCall();
+            assertCallState(call, Call.STATE_ACTIVE);
+            assertEquals(Call.Details.DIRECTION_INCOMING, call.getDetails().getCallDirection());
+        } finally {
+            InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                    .dropShellPermissionIdentity();
+        }
+
     }
 
     public void testCallDirectionOutgoing() {
@@ -263,25 +280,33 @@
             return;
         }
 
-        // Ensure CS is up and bound.
-        placeAndVerifyCall();
-        verifyConnectionForOutgoingCall().setActive();
+        InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                .adoptShellPermissionIdentity("android.permission.MODIFY_PHONE_STATE");
+        try {
+            // Ensure CS is up and bound.
+            placeAndVerifyCall();
+            verifyConnectionForOutgoingCall().setActive();
 
-        final MockConnection connection = new MockConnection();
-        connection.setActive();
-        connection.setCallDirection(Call.Details.DIRECTION_OUTGOING);
-        connection.setConnectTimeMillis(1000L);
-        assertEquals(1000L, connection.getConnectTimeMillis());
-        connection.setConnectionStartElapsedRealtimeMillis(100L);
-        assertEquals(100L, connection.getConnectionStartElapsedRealtimeMillis());
+            final MockConnection connection = new MockConnection();
+            connection.setActive();
+            connection.setCallDirection(Call.Details.DIRECTION_OUTGOING);
+            connection.setConnectTimeMillis(1000L);
+            assertEquals(1000L, connection.getConnectTimeMillis());
+            connection.setConnectionStartElapsedRealtimeMillis(100L);
+            assertEquals(100L, connection.getConnectionStartElapsedRealtimeMillis());
 
-        CtsConnectionService.addExistingConnectionToTelecom(TEST_PHONE_ACCOUNT_HANDLE, connection);
-        assertNumCalls(mInCallCallbacks.getService(), 2);
-        mInCallCallbacks.lock.drainPermits();
-        final Call call = mInCallCallbacks.getService().getLastCall();
-        assertCallState(call, Call.STATE_ACTIVE);
-        assertEquals(Call.Details.DIRECTION_OUTGOING, call.getDetails().getCallDirection());
-        assertEquals(1000L, call.getDetails().getConnectTimeMillis());
+            CtsConnectionService.addExistingConnectionToTelecom(TEST_PHONE_ACCOUNT_HANDLE,
+                    connection);
+            assertNumCalls(mInCallCallbacks.getService(), 2);
+            mInCallCallbacks.lock.drainPermits();
+            final Call call = mInCallCallbacks.getService().getLastCall();
+            assertCallState(call, Call.STATE_ACTIVE);
+            assertEquals(Call.Details.DIRECTION_OUTGOING, call.getDetails().getCallDirection());
+            assertEquals(1000L, call.getDetails().getConnectTimeMillis());
+        } finally {
+            InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                    .dropShellPermissionIdentity();
+        }
     }
 
     public void testGetAllConnections() {
@@ -289,33 +314,42 @@
             return;
         }
 
-        // Add first connection (outgoing call)
-        placeAndVerifyCall();
-        final Connection connection1 = verifyConnectionForOutgoingCall();
+        InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                .adoptShellPermissionIdentity("android.permission.MODIFY_PHONE_STATE");
+        try {
+            // Add first connection (outgoing call)
+            placeAndVerifyCall();
+            final Connection connection1 = verifyConnectionForOutgoingCall();
 
-        Collection<Connection> connections = CtsConnectionService.getAllConnectionsFromTelecom();
-        assertEquals(1, connections.size());
-        assertTrue(connections.contains(connection1));
-        // Need to move this to active since we reject the 3rd incoming call below if this is in
-        // dialing state (b/23428950).
-        connection1.setActive();
-        assertCallState(mInCallCallbacks.getService().getLastCall(), Call.STATE_ACTIVE);
+            Collection<Connection> connections =
+                    CtsConnectionService.getAllConnectionsFromTelecom();
+            assertEquals(1, connections.size());
+            assertTrue(connections.contains(connection1));
+            // Need to move this to active since we reject the 3rd incoming call below if this is in
+            // dialing state (b/23428950).
+            connection1.setActive();
+            assertCallState(mInCallCallbacks.getService().getLastCall(), Call.STATE_ACTIVE);
 
-        // Add second connection (add existing connection)
-        final Connection connection2 = new MockConnection();
-        connection2.setActive();
-        CtsConnectionService.addExistingConnectionToTelecom(TEST_PHONE_ACCOUNT_HANDLE, connection2);
-        assertNumCalls(mInCallCallbacks.getService(), 2);
-        mInCallCallbacks.lock.drainPermits();
-        connections = CtsConnectionService.getAllConnectionsFromTelecom();
-        assertEquals(2, connections.size());
-        assertTrue(connections.contains(connection2));
+            // Add second connection (add existing connection)
+            final Connection connection2 = new MockConnection();
+            connection2.setActive();
+            CtsConnectionService.addExistingConnectionToTelecom(TEST_PHONE_ACCOUNT_HANDLE,
+                            connection2);
+            assertNumCalls(mInCallCallbacks.getService(), 2);
+            mInCallCallbacks.lock.drainPermits();
+            connections = CtsConnectionService.getAllConnectionsFromTelecom();
+            assertEquals(2, connections.size());
+            assertTrue(connections.contains(connection2));
 
-        // Add third connection (incoming call)
-        addAndVerifyNewIncomingCall(createTestNumber(), null);
-        final Connection connection3 = verifyConnectionForIncomingCall();
-        connections = CtsConnectionService.getAllConnectionsFromTelecom();
-        assertEquals(3, connections.size());
-        assertTrue(connections.contains(connection3));
+            // Add third connection (incoming call)
+            addAndVerifyNewIncomingCall(createTestNumber(), null);
+            final Connection connection3 = verifyConnectionForIncomingCall();
+            connections = CtsConnectionService.getAllConnectionsFromTelecom();
+            assertEquals(3, connections.size());
+            assertTrue(connections.contains(connection3));
+        } finally {
+            InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                    .dropShellPermissionIdentity();
+        }
     }
 }
diff --git a/tests/tests/util/Android.bp b/tests/tests/util/Android.bp
index 0ea529e..f84238d 100644
--- a/tests/tests/util/Android.bp
+++ b/tests/tests/util/Android.bp
@@ -27,6 +27,7 @@
         "androidx.test.rules",
         "ctstestrunner-axt",
         "cts-install-lib",
+        "core-test-rules", // for libcore.dalvik.system.CloseGuardSupport
     ],
     srcs: ["src/**/*.java"],
     platform_apis: true,
diff --git a/tests/tests/util/src/android/util/cts/CloseGuardTest.java b/tests/tests/util/src/android/util/cts/CloseGuardTest.java
new file mode 100644
index 0000000..5945280
--- /dev/null
+++ b/tests/tests/util/src/android/util/cts/CloseGuardTest.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.util.cts;
+
+import android.util.CloseGuard;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import libcore.dalvik.system.CloseGuardSupport;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.runner.RunWith;
+
+/** CTS tests for {@link CloseGuard} */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class CloseGuardTest {
+
+    @Rule
+    public final TestRule rule = CloseGuardSupport.getRule();
+
+    @Test
+    public void testEnabled_NotOpen() throws Throwable {
+        ResourceOwner owner = new ResourceOwner();
+        assertUnreleasedResources(owner, 0);
+    }
+
+    @Test
+    public void testEnabled_OpenNotClosed() throws Throwable {
+        ResourceOwner owner = new ResourceOwner();
+        owner.open();
+        assertUnreleasedResources(owner, 1);
+    }
+
+    @Test
+    public void testEnabled_OpenThenClosed() throws Throwable {
+        ResourceOwner owner = new ResourceOwner();
+        owner.open();
+        owner.close();
+        assertUnreleasedResources(owner, 0);
+    }
+
+    @Test(expected = NullPointerException.class)
+    public void testOpen_withNullMethodName_throwsNPE() throws Throwable {
+        CloseGuard closeGuard = new CloseGuard();
+        closeGuard.open(null);
+    }
+
+    private void assertUnreleasedResources(ResourceOwner owner, int expectedCount)
+            throws Throwable {
+        try {
+            CloseGuardSupport.getFinalizerChecker().accept(owner, expectedCount);
+        } finally {
+            // Close the resource so that CloseGuard does not generate a warning for real when it
+            // is actually finalized.
+            owner.close();
+        }
+    }
+
+    /**
+     * A test user of {@link CloseGuard}.
+     */
+    private static class ResourceOwner {
+
+        private final CloseGuard mCloseGuard;
+
+        ResourceOwner() {
+            mCloseGuard = new CloseGuard();
+        }
+
+        public void open() {
+            mCloseGuard.open("close");
+        }
+
+        public void close() {
+            mCloseGuard.close();
+        }
+
+        /**
+         * Make finalize public so that it can be tested directly without relying on garbage
+         * collection to trigger it.
+         */
+        @Override
+        public void finalize() throws Throwable {
+            mCloseGuard.warnIfOpen();
+            super.finalize();
+        }
+    }
+}
diff --git a/tests/tests/view/src/android/view/cts/VerifyInputEventTest.java b/tests/tests/view/src/android/view/cts/VerifyInputEventTest.java
index fdda4e3..9262dfc 100644
--- a/tests/tests/view/src/android/view/cts/VerifyInputEventTest.java
+++ b/tests/tests/view/src/android/view/cts/VerifyInputEventTest.java
@@ -163,8 +163,8 @@
         compareMotions(downEvent, verified);
 
         // Send UP event for consistency
-        MotionEvent upEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_UP,
-                point.x, point.y, 0 /*metaState*/);
+        MotionEvent upEvent = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(),
+                MotionEvent.ACTION_UP, point.x, point.y, 0 /*metaState*/);
         mAutomation.injectInputEvent(upEvent, true);
         waitForMotion();
     }
@@ -212,8 +212,67 @@
         assertNull(verified);
 
         // Send UP event for consistency
-        MotionEvent upEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_UP,
-                point.x, point.y, 0 /*metaState*/);
+        MotionEvent upEvent = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(),
+                MotionEvent.ACTION_UP, point.x, point.y, 0 /*metaState*/);
+        mAutomation.injectInputEvent(upEvent, true);
+        waitForMotion();
+    }
+
+    /**
+     * Ensure that injected key events that contain a real device id get injected as virtual
+     * device events, to prevent misrepresentation of actual hardware.
+     * The verified events should contain the virtual device id, which is consistent with what the
+     * app receives.
+     */
+    @Test
+    public void testDeviceIdBecomesVirtualForInjectedKeys() {
+        final long downTime = SystemClock.uptimeMillis();
+        KeyEvent downEvent = new KeyEvent(downTime, downTime, KeyEvent.ACTION_DOWN,
+                KeyEvent.KEYCODE_A, 0 /*repeat*/, 0 /*metaState*/,
+                1/*deviceId*/, 0 /*scanCode*/);
+        mAutomation.injectInputEvent(downEvent, true);
+        KeyEvent received = waitForKey();
+        assertEquals(INJECTED_EVENT_DEVICE_ID, received.getDeviceId());
+
+        // This event can still be verified, however.
+        VerifiedInputEvent verified = mInputManager.verifyInputEvent(received);
+        assertEquals(INJECTED_EVENT_DEVICE_ID, verified.getDeviceId());
+
+        // Send UP event for consistency
+        KeyEvent upEvent = new KeyEvent(downTime, SystemClock.uptimeMillis(), KeyEvent.ACTION_UP,
+                KeyEvent.KEYCODE_A, 0 /*repeat*/, 0 /*metaState*/,
+                1/*deviceId*/, 0 /*scanCode*/);
+        mAutomation.injectInputEvent(upEvent, true);
+        waitForKey();
+    }
+
+    /**
+     * Ensure that injected motion events that contain a real device id get injected as virtual
+     * device events, to prevent misrepresentation of actual hardware.
+     * The verified events should contain the virtual device id, which is consistent with what the
+     * app receives.
+     */
+    @Test
+    public void testDeviceIdBecomesVirtualForInjectedMotions() {
+        final View view = mActivity.getWindow().getDecorView();
+        final Point point = getViewCenterOnScreen(view);
+        final long downTime = SystemClock.uptimeMillis();
+        MotionEvent downEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_DOWN,
+                point.x, point.y, 1 /*pressure*/, 1 /*size*/, 0 /*metaState*/,
+                0 /*xPrecision*/, 0 /*yPrecision*/, 1 /*deviceId*/, 0 /*edgeFlags*/);
+        mAutomation.injectInputEvent(downEvent, true);
+        MotionEvent received = waitForMotion();
+        assertEquals(INJECTED_EVENT_DEVICE_ID, received.getDeviceId());
+
+        // This event can still be verified, however.
+        VerifiedInputEvent verified = mInputManager.verifyInputEvent(received);
+        assertEquals(INJECTED_EVENT_DEVICE_ID, verified.getDeviceId());
+
+        // Send UP event for consistency
+        MotionEvent upEvent = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(),
+                MotionEvent.ACTION_UP, point.x, point.y, 0 /*pressure*/, 1 /*size*/,
+                0 /*metaState*/, 0 /*xPrecision*/, 0 /*yPrecision*/,
+                1 /*deviceId*/, 0 /*edgeFlags*/);
         mAutomation.injectInputEvent(upEvent, true);
         waitForMotion();
     }
diff --git a/tools/cts-media-preparer-app/Android.bp b/tools/cts-media-preparer-app/Android.bp
index 400dac7..5991f8b 100644
--- a/tools/cts-media-preparer-app/Android.bp
+++ b/tools/cts-media-preparer-app/Android.bp
@@ -34,4 +34,5 @@
         "mts",
     ],
     sdk_version: "test_current",
+    min_sdk_version: "29",
 }
diff --git a/tools/cts-media-preparer-app/AndroidManifest.xml b/tools/cts-media-preparer-app/AndroidManifest.xml
index 15afba4..789ea99 100644
--- a/tools/cts-media-preparer-app/AndroidManifest.xml
+++ b/tools/cts-media-preparer-app/AndroidManifest.xml
@@ -22,7 +22,7 @@
     <application>
         <uses-library android:name="android.test.runner" />
     </application>
-
+    <uses-sdk android:minSdkVersion="29"   android:targetSdkVersion="29" />
     <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
             android:targetPackage="android.mediastress.cts.preconditions.app"
             android:label="Device-side CTS mediastress preparation" />