Merge "Use REGULAR_CODECS instead when creating MediaCodecList." into qt-dev
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 8a6c1d7..31fdb88 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -5066,10 +5066,10 @@
     <string name="bubbles_notification_test_verify_9">Click the button below and verify that a bubble
         appears on screen, auto-expanded.</string>
     <string name="bubbles_notification_test_button_9">Send auto-expanded bubble notification</string>
+    <string name="bubbles_notification_no_bubbles_low_mem">No bubbles on low memory device; no tests to run</string>
     <string name="bubbles_test_summary_title">Test Complete</string>
     <string name="bubbles_test_summary">%1$d out of %2$d tests passed</string>
     <string name="bubble_activity_title">Bubble Activity</string>
-
     <!-- Strings for Instant Apps -->
     <string name="ia_instruction_heading_label">Instructions:</string>
     <string name="ia_instruction_text_photo_label">READ BEFORE STARTING TEST</string>
@@ -5090,9 +5090,16 @@
     1. Click Start Test. \n\n
     2. An alert dialog with install instruction will be shown if the sample Instant App has not been installed, otherwise, the sample Instant App will be opened automatically. \n\n
     3. Drag down the notification bar when the sample Instant App is at foreground. \n\n
+    4. Skip this step in china version. \n\n
+    5. Click Pass button if all checks in step 4 passed, otherwise click Fail button.
+    </string>
+    <string name="ia_notification_instruction_label_no_app_market_version">\n
+    1. Click Start Test. \n\n
+    2. An alert dialog with install instruction will be shown if the sample Instant App has not been installed, otherwise, the sample Instant App will be opened automatically. \n\n
+    3. Drag down the notification bar when the sample Instant App is at foreground. \n\n
     4. Check if Instant App is shown in notification area with the following (Please expand the notification if it is collapsed): \n
     \u0020\u0020\u0020a. It provides information about Instant Apps not requiring installation and an action that provides more information about the Instant App. \n
-    \u0020\u0020\u0020b. It provides an action allowing the user to launch the associated link with web browser. \n\n
+    \u0020\u0020\u0020b. Skip this step in china version.Can not launch the associated link with web browser. \n\n
     5. Click Pass button if all checks in step 4 passed, otherwise click Fail button.
     </string>
     <string name="ia_recents">Instant Apps Recents Test</string>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/instantapps/NotificationTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/instantapps/NotificationTestActivity.java
old mode 100644
new mode 100755
index 6e2052c..77caeb9
--- a/apps/CtsVerifier/src/com/android/cts/verifier/instantapps/NotificationTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/instantapps/NotificationTestActivity.java
@@ -16,6 +16,8 @@
 package com.android.cts.verifier.instantapps;
 
 import android.os.Bundle;
+import android.os.SystemProperties;
+import android.content.pm.PackageManager;
 import android.widget.TextView;
 
 import com.android.cts.verifier.R;
@@ -34,6 +36,18 @@
 
         setInfoResources(R.string.ia_notification, R.string.ia_notification_info, -1);
         TextView extraText = (TextView) findViewById(R.id.instruction_extra_text);
-        extraText.setText(R.string.ia_notification_instruction_label);
+        if (isNoGooglePlayStore()) {
+            extraText.setText(R.string.ia_notification_instruction_label_no_app_market_version);
+        } else {
+            extraText.setText(R.string.ia_notification_instruction_label);
+        }
+    }
+
+    private boolean isNoGooglePlayStore() {
+        boolean isCnGmsVersion =
+                getApplicationContext().getPackageManager().hasSystemFeature("cn.google.services");
+        boolean isNoGmsVersion =
+                (SystemProperties.get("ro.com.google.gmsversion", null) == null);
+        return isCnGmsVersion || isNoGmsVersion;
     }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
index cb24dad..11351ec 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
@@ -200,6 +200,11 @@
         context.getPackageManager().setComponentEnabledSetting(
                 new ComponentName(context, ByodPrimaryHelperActivity.class.getName()),
                 PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
+
+        // Disable the work profile instance of ByodFlowTestActivity
+        context.getPackageManager().setComponentEnabledSetting(
+                new ComponentName(context, ByodFlowTestActivity.class),
+                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
     }
 
     private void wipeIfNecessary(Context context, Intent intent) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/BubblesVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/BubblesVerifierActivity.java
index fd1c457..3dc41e6 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/BubblesVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/BubblesVerifierActivity.java
@@ -20,6 +20,7 @@
 import static android.view.View.VISIBLE;
 
 import android.annotation.NonNull;
+import android.app.ActivityManager;
 import android.app.Notification;
 import android.app.NotificationChannel;
 import android.app.NotificationManager;
@@ -33,6 +34,7 @@
 import android.view.ViewGroup;
 import android.widget.Button;
 import android.widget.TextView;
+import android.widget.Toast;
 
 import com.android.cts.verifier.PassFailButtons;
 import com.android.cts.verifier.R;
@@ -101,16 +103,23 @@
             runNextTestOrShowSummary();
         });
 
-        mTests.add(new EnableBubbleTest());
-        mTests.add(new SendBubbleTest());
-        mTests.add(new SuppressNotifTest());
-        mTests.add(new AddNotifTest());
-        mTests.add(new RemoveMetadataTest());
-        mTests.add(new AddMetadataTest());
-        mTests.add(new ExpandBubbleTest());
-        mTests.add(new DismissBubbleTest());
-        mTests.add(new DismissNotificationTest());
-        mTests.add(new AutoExpandBubbleTest());
+        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
+        if (!am.isLowRamDevice()) {
+            mTests.add(new EnableBubbleTest());
+            mTests.add(new SendBubbleTest());
+            mTests.add(new SuppressNotifTest());
+            mTests.add(new AddNotifTest());
+            mTests.add(new RemoveMetadataTest());
+            mTests.add(new AddMetadataTest());
+            mTests.add(new ExpandBubbleTest());
+            mTests.add(new DismissBubbleTest());
+            mTests.add(new DismissNotificationTest());
+            mTests.add(new AutoExpandBubbleTest());
+        } else {
+            Toast.makeText(getApplicationContext(),
+                    getResources().getString(R.string.bubbles_notification_no_bubbles_low_mem),
+                    Toast.LENGTH_LONG).show();
+        }
 
         setPassFailButtonClickListeners();
 
@@ -453,7 +462,6 @@
         }
     }
 
-
     /** Creates a minimally filled out {@link android.app.Notification.BubbleMetadata.Builder} */
     private Notification.BubbleMetadata.Builder getBasicBubbleBuilder() {
         Context context = getApplicationContext();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java
index 966fc7d..9135c92 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java
@@ -695,6 +695,7 @@
                     logTestSkip(name, summary);
                     break;
                 case PASS:
+                    mShouldRetry = false;
                     logTestPass(name, summary);
                     break;
                 case FAIL:
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaPerfUtils.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaPerfUtils.java
index 469e99a..7e02b85 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaPerfUtils.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaPerfUtils.java
@@ -173,4 +173,41 @@
         return "Expected " + kind + ": " + reported + ".\n"
                 + "Measured frame rate: " + Arrays.toString(measuredFps) + ".\n";
     }
+
+    /** Verifies |requestedFps| does not exceed reported achievable rates.
+     *  Returns null if *ALL* requested rates are claimed to be achievable.
+     *  Otherwise, returns a diagnostic explaining why it's not achievable.
+     *  (one of the rates was too fast, we don't have achievability information, etc).
+     *
+     *  we're looking for 90% confidence, which is documented as being:
+     *  "higher than half of the lower limit at least 90% of the time in tested configurations"
+     *
+     *  NB: we only invoke this for the SW codecs; we use performance point info for the
+     *  hardware codecs.
+     *  */
+    public static String areAchievableFrameRates(
+            String name, String mime, int w, int h, double... requestedFps) {
+        Range<Double> reported =
+            MediaUtils.getVideoCapabilities(name, mime).getAchievableFrameRatesFor(w, h);
+        String kind = "achievable frame rates for " + name + " " + mime + " " + w + "x" + h;
+        if (reported == null) {
+            return "Failed to get " + kind;
+        }
+
+        double confidence90 = reported.getLower() / 2.0;
+
+        Log.d(TAG, name + " " + mime + " " + w + "x" + h +
+                " lower " + reported.getLower() + " 90% confidence " + confidence90 +
+                " requested " + Arrays.toString(requestedFps));
+
+        // if *any* of them are too fast, we say no.
+        for (double requested : requestedFps) {
+            if (requested > confidence90) {
+                return "Expected " + kind + ": " + reported + ", 90% confidence: " + confidence90
+                       + ".\n"
+                       + "Requested frame rate: " + Arrays.toString(requestedFps) + ".\n";
+            }
+        }
+        return null;
+    }
 }
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java
index 772009d..53da03a 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java
@@ -20,6 +20,7 @@
 import android.drm.DrmConvertedStatus;
 import android.drm.DrmManagerClient;
 import android.graphics.ImageFormat;
+import android.graphics.Rect;
 import android.media.Image;
 import android.media.Image.Plane;
 import android.media.MediaCodec;
@@ -299,11 +300,79 @@
     }
 
     public static boolean canDecode(MediaFormat format) {
-        if (sMCL.findDecoderForFormat(format) == null) {
+        return canDecode(format, 0.0);
+    }
+
+    // this is "do we claim to decode"; caller is on the hook to determine
+    // if we actually meet that claim, specifically around speed.
+    public static boolean canDecode(MediaFormat format, double rate ) {
+        String decoder = sMCL.findDecoderForFormat(format);
+
+        if (decoder == null) {
             Log.i(TAG, "no decoder for " + format);
             return false;
         }
-        return true;
+
+	if (rate == 0.0) {
+            return true;
+	}
+
+	// we care about speed of decoding
+        Log.d(TAG, "checking for decoding " + format + " at " +
+                   rate + " fps with " + decoder);
+
+        String mime = format.getString(MediaFormat.KEY_MIME);
+        int width = format.getInteger(MediaFormat.KEY_WIDTH);
+        int height = format.getInteger(MediaFormat.KEY_HEIGHT);
+
+        MediaCodecInfo[] mciList = sMCL.getCodecInfos();
+
+        if (mciList == null) {
+            Log.d(TAG, "did not get list of MediaCodecInfo");
+            return false;
+        }
+
+        MediaCodecInfo mci = null;
+        for (MediaCodecInfo mci2 : mciList) {
+            if (mci2.getName().equals(decoder)) {
+                mci = mci2;
+                break;
+            }
+        }
+        if (mci == null) {
+            return false;
+        }
+        if (!mci.getName().equals(decoder)) {
+            Log.e(TAG, "did not find expected " + decoder);
+            return false;
+        }
+
+        if (mci.isSoftwareOnly()) {
+            String verified = MediaPerfUtils.areAchievableFrameRates(
+                              decoder, mime, width, height, rate);
+            if (verified == null) {
+                Log.d(TAG, "claims to decode content at " + rate + " fps");
+                return true;
+            }
+            Log.d(TAG, "achieveable framerates says: " + verified);
+            return false;
+        } else {
+            MediaCodecInfo.VideoCapabilities caps =
+                            mci.getCapabilitiesForType(mime).getVideoCapabilities();
+            List<MediaCodecInfo.VideoCapabilities.PerformancePoint> pp =
+                            caps.getSupportedPerformancePoints();
+            VideoCapabilities.PerformancePoint target =
+                            new VideoCapabilities.PerformancePoint(width, height, (int) rate);
+            for (MediaCodecInfo.VideoCapabilities.PerformancePoint point : pp) {
+                if (point.covers(target)) {
+                    Log.i(TAG, "target " + target.toString() +
+                               " covered by point " + point.toString());
+                    return true;
+                }
+            }
+            Log.i(TAG, "NOT covered by any hardware performance point");
+            return false;
+        }
     }
 
     public static boolean supports(String codecName, String mime, int w, int h) {
@@ -554,15 +623,27 @@
         return check(hasCodecForMimes(true /* encoder */, mimes), "no encoder found");
     }
 
+    // checks format, does not address actual speed of decoding
     public static boolean canDecodeVideo(String mime, int width, int height, float rate) {
+	return canDecodeVideo(mime, width, height, rate, (float)0.0);
+    }
+
+    // format + decode rate
+    public static boolean canDecodeVideo(String mime, int width, int height, float rate, float decodeRate) {
         MediaFormat format = MediaFormat.createVideoFormat(mime, width, height);
         format.setFloat(MediaFormat.KEY_FRAME_RATE, rate);
-        return canDecode(format);
+        return canDecode(format, decodeRate);
     }
 
     public static boolean canDecodeVideo(
             String mime, int width, int height, float rate,
             Integer profile, Integer level, Integer bitrate) {
+        return canDecodeVideo(mime, width, height, rate, profile, level, bitrate, (float)0.0);
+    }
+
+    public static boolean canDecodeVideo(
+            String mime, int width, int height, float rate,
+            Integer profile, Integer level, Integer bitrate, float decodeRate) {
         MediaFormat format = MediaFormat.createVideoFormat(mime, width, height);
         format.setFloat(MediaFormat.KEY_FRAME_RATE, rate);
         if (profile != null) {
@@ -574,7 +655,7 @@
         if (bitrate != null) {
             format.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);
         }
-        return canDecode(format);
+        return canDecode(format, decodeRate);
     }
 
     public static boolean checkEncoderForFormat(MediaFormat format) {
@@ -1168,36 +1249,46 @@
 
         MessageDigest md = MessageDigest.getInstance("MD5");
 
-        int imageWidth = image.getWidth();
-        int imageHeight = image.getHeight();
+        Rect crop = image.getCropRect();
+        int cropLeft = crop.left;
+        int cropRight = crop.right;
+        int cropTop = crop.top;
+        int cropBottom = crop.bottom;
+
+        int imageWidth = cropRight - cropLeft;
+        int imageHeight = cropBottom - cropTop;
 
         Image.Plane[] planes = image.getPlanes();
         for (int i = 0; i < planes.length; ++i) {
             ByteBuffer buf = planes[i].getBuffer();
 
-            int width, height, rowStride, pixelStride, x, y;
+            int width, height, rowStride, pixelStride, x, y, top, left;
             rowStride = planes[i].getRowStride();
             pixelStride = planes[i].getPixelStride();
             if (i == 0) {
                 width = imageWidth;
                 height = imageHeight;
+                left = cropLeft;
+                top = cropTop;
             } else {
                 width = imageWidth / 2;
                 height = imageHeight /2;
+                left = cropLeft / 2;
+                top = cropTop / 2;
             }
             // local contiguous pixel buffer
             byte[] bb = new byte[width * height];
             if (buf.hasArray()) {
                 byte b[] = buf.array();
-                int offs = buf.arrayOffset();
+                int offs = buf.arrayOffset() + left * pixelStride;
                 if (pixelStride == 1) {
                     for (y = 0; y < height; ++y) {
-                        System.arraycopy(bb, y * width, b, y * rowStride + offs, width);
+                        System.arraycopy(bb, y * width, b, (top + y) * rowStride + offs, width);
                     }
                 } else {
                     // do it pixel-by-pixel
                     for (y = 0; y < height; ++y) {
-                        int lineOffset = offs + y * rowStride;
+                        int lineOffset = offs + (top + y) * rowStride;
                         for (x = 0; x < width; ++x) {
                             bb[y * width + x] = b[lineOffset + x * pixelStride];
                         }
@@ -1207,7 +1298,7 @@
                 int pos = buf.position();
                 if (pixelStride == 1) {
                     for (y = 0; y < height; ++y) {
-                        buf.position(pos + y * rowStride);
+                        buf.position(pos + left + (top + y) * rowStride);
                         buf.get(bb, y * width, width);
                     }
                 } else {
@@ -1215,7 +1306,7 @@
                     byte[] lb = new byte[rowStride];
                     // do it pixel-by-pixel
                     for (y = 0; y < height; ++y) {
-                        buf.position(pos + y * rowStride);
+                        buf.position(pos + left * pixelStride + (top + y) * rowStride);
                         // we're only guaranteed to have pixelStride * (width - 1) + 1 bytes
                         buf.get(lb, 0, pixelStride * (width - 1) + 1);
                         for (x = 0; x < width; ++x) {
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/MediaUtils.java b/common/device-side/util/src/com/android/compatibility/common/util/MediaUtils.java
index be91308..c81f648f6 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/MediaUtils.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/MediaUtils.java
@@ -1161,8 +1161,8 @@
         int cropTop = crop.top;
         int cropBottom = crop.bottom;
 
-        int imageWidth = cropRight - cropLeft + 1;
-        int imageHeight = cropBottom - cropTop + 1;
+        int imageWidth = cropRight - cropLeft;
+        int imageHeight = cropBottom - cropTop;
 
         Image.Plane[] planes = image.getPlanes();
         for (int i = 0; i < planes.length; ++i) {
diff --git a/hostsidetests/cpptools/src/com/android/cts/cpptools/RunasPermissionsTest.java b/hostsidetests/cpptools/src/com/android/cts/cpptools/RunasPermissionsTest.java
index d6140f0..7f69bf3 100644
--- a/hostsidetests/cpptools/src/com/android/cts/cpptools/RunasPermissionsTest.java
+++ b/hostsidetests/cpptools/src/com/android/cts/cpptools/RunasPermissionsTest.java
@@ -31,10 +31,7 @@
     private static final String CONNECTOR_EXE_NAME = "connector";
     private static final String START_TEST_APP_COMMAND = String.format("cmd activity start-activity -S -W %s/%s.%s",
             TEST_APP_PACKAGE, TEST_APP_PACKAGE, TEST_APP_CLASS);
-    private static final String COPY_CONNECTOR_COMMAND = String
-            .format("run-as %s sh -c 'cp -f /data/local/tmp/%s ./code_cache/'", TEST_APP_PACKAGE, CONNECTOR_EXE_NAME);
-    private static final String RUN_CONNECTOR_COMMAND = String.format("run-as %s sh -c './code_cache/%s'",
-            TEST_APP_PACKAGE, CONNECTOR_EXE_NAME);
+
     // Test app ('DomainSocketActivity') would pass string "Connection Succeeded." to the
     // connector, and then the connector would append a newline and print it out.
     private static final String EXPECTED_CONNECTOR_OUTPUT = "Connection Succeeded.\n";
@@ -54,8 +51,13 @@
 
         // Start a run-as process that attempts to connect to the socket opened by the
         // app.
-        getDevice().executeShellCommand(COPY_CONNECTOR_COMMAND);
-        String results = getDevice().executeShellCommand(RUN_CONNECTOR_COMMAND);
+        int currentUser = getDevice().getCurrentUser();
+        getDevice().executeShellCommand(String.format(
+                "run-as %s --user %d sh -c 'cp -f /data/local/tmp/%s ./code_cache/'",
+                        TEST_APP_PACKAGE, currentUser, CONNECTOR_EXE_NAME));
+        String results = getDevice().executeShellCommand(String.format(
+                "run-as %s --user %d sh -c './code_cache/%s'",
+                        TEST_APP_PACKAGE, currentUser, CONNECTOR_EXE_NAME));
         assertEquals(EXPECTED_CONNECTOR_OUTPUT, results);
     }
 
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
index 611f5ac..8950802 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
@@ -42,6 +42,7 @@
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -108,6 +109,12 @@
      */
     private static final int STAY_ON_WHILE_PLUGGED_IN_FLAGS = 7;
 
+    /**
+     * User ID for all users.
+     * The value is from the UserHandle class.
+     */
+    protected static final int USER_ALL = -1;
+
     protected static interface Settings {
         public static final String GLOBAL_NAMESPACE = "global";
         public static interface Global {
@@ -213,10 +220,20 @@
 
     protected void installAppAsUser(String appFileName, boolean grantPermissions, int userId)
             throws FileNotFoundException, DeviceNotAvailableException {
+        installAppAsUser(appFileName, grantPermissions, /* dontKillApp */ false, userId);
+    }
+
+    protected void installAppAsUser(String appFileName, boolean grantPermissions,
+            boolean dontKillApp, int userId)
+                    throws FileNotFoundException, DeviceNotAvailableException {
         CLog.d("Installing app " + appFileName + " for user " + userId);
         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
+        List<String> extraArgs = new LinkedList<>();
+        extraArgs.add("-t");
+        if (dontKillApp) extraArgs.add("--dont-kill");
         String result = getDevice().installPackageForUser(
-                buildHelper.getTestFile(appFileName), true, grantPermissions, userId, "-t");
+                buildHelper.getTestFile(appFileName), true, grantPermissions, userId,
+                extraArgs.toArray(new String[extraArgs.size()]));
         assertNull("Failed to install " + appFileName + " for user " + userId + ": " + result,
                 result);
     }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
index f69787f..2b460ce 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
@@ -77,9 +77,10 @@
 
     /**
      * Copied from {@link android.app.admin.DevicePolicyManager
-     * .InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}
+     * .InstallSystemUpdateCallback#UPDATE_ERROR_UPDATE_FILE_INVALID}
      */
-    private static final int UPDATE_ERROR_BATTERY_LOW = 5;
+    private static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
+
     private static final int TYPE_NONE = 0;
 
     /**
@@ -936,20 +937,19 @@
     }
 
     public void testInstallUpdateLogged() throws Exception {
-        if (!mHasFeature) {
+        if (!mHasFeature || !isDeviceAb()) {
             return;
         }
-        pushUpdateFileToDevice("wrongSize.zip");
+        pushUpdateFileToDevice("wrongHash.zip");
         assertMetricsLogged(getDevice(), () -> {
-                executeDeviceTestMethod(".InstallUpdateTest",
-                        "testInstallUpdate_notCharging_belowThreshold_failsBatteryCheck");
+            executeDeviceTestMethod(".InstallUpdateTest", "testInstallUpdate_failWrongHash");
         }, new DevicePolicyEventWrapper.Builder(EventId.INSTALL_SYSTEM_UPDATE_VALUE)
-               .setAdminPackageName(DEVICE_OWNER_PKG)
-               .setBoolean(isDeviceAb())
-               .build(),
-        new DevicePolicyEventWrapper.Builder(EventId.INSTALL_SYSTEM_UPDATE_ERROR_VALUE)
-               .setInt(UPDATE_ERROR_BATTERY_LOW)
-               .build());
+                    .setAdminPackageName(DEVICE_OWNER_PKG)
+                    .setBoolean(/* isDeviceAb */ true)
+                    .build(),
+            new DevicePolicyEventWrapper.Builder(EventId.INSTALL_SYSTEM_UPDATE_ERROR_VALUE)
+                    .setInt(UPDATE_ERROR_UPDATE_FILE_INVALID)
+                    .build());
     }
 
     private boolean isDeviceAb() throws DeviceNotAvailableException {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DevicePlusProfileOwnerHostSideTransferTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DevicePlusProfileOwnerHostSideTransferTest.java
old mode 100644
new mode 100755
index 960fbb2..d941316
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DevicePlusProfileOwnerHostSideTransferTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DevicePlusProfileOwnerHostSideTransferTest.java
@@ -32,8 +32,7 @@
                     TRANSFER_OWNER_OUTGOING_APK, TRANSFER_OWNER_OUTGOING_TEST_RECEIVER);
                 setSameAffiliationId(profileUserId, TRANSFER_PROFILE_OWNER_OUTGOING_TEST);
 
-                installAppAsUser(TRANSFER_OWNER_INCOMING_APK, mPrimaryUserId);
-                installAppAsUser(TRANSFER_OWNER_INCOMING_APK, profileUserId);
+                installAppAsUser(TRANSFER_OWNER_INCOMING_APK, USER_ALL);
                 mUserId = profileUserId;
             } else {
                 removeAdmin(TRANSFER_OWNER_OUTGOING_TEST_RECEIVER, mUserId);
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java
old mode 100644
new mode 100755
index decab02..6872aad
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java
@@ -56,8 +56,7 @@
             startUser(mProfileUserId);
 
             // Install test APK on primary user and the managed profile.
-            installTestApps(mPrimaryUserId);
-            installTestApps(mProfileUserId);
+            installTestApps(USER_ALL);
         }
     }
 
@@ -166,7 +165,8 @@
         }
         installAppAsUser(SIMPLE_APP_APK, mProfileUserId);
         startCallbackService(mPrimaryUserId);
-        installAppAsUser(SIMPLE_APP_APK, mProfileUserId);
+        installAppAsUser(SIMPLE_APP_APK, /* grantPermissions */ true, /* dontKillApp */ true,
+                mProfileUserId);
         runDeviceTestsAsUser(LAUNCHER_TESTS_PKG,
                 LAUNCHER_TESTS_CLASS,
                 "testPackageChangedCallbackForUser",
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
index 01d64ed..3f7bd9d 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
@@ -118,8 +118,10 @@
             mProfileUserId = createManagedProfile(mParentUserId);
             startUser(mProfileUserId);
 
-            installAppAsUser(MANAGED_PROFILE_APK, mParentUserId);
-            installAppAsUser(MANAGED_PROFILE_APK, mProfileUserId);
+            // Install the APK on both primary and profile user in one single transaction.
+            // If they were installed separately, the second installation would become an app
+            // update and result in the current running test process being killed.
+            installAppAsUser(MANAGED_PROFILE_APK, USER_ALL);
             setProfileOwnerOrFail(MANAGED_PROFILE_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS,
                     mProfileUserId);
             waitForUserUnlock();
@@ -488,10 +490,8 @@
         // intents resolution.
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
                 "testDisableAllBrowsers", mProfileUserId);
-        installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
-        installAppAsUser(INTENT_SENDER_APK, mParentUserId);
-        installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
-        installAppAsUser(INTENT_SENDER_APK, mProfileUserId);
+        installAppAsUser(INTENT_RECEIVER_APK, USER_ALL);
+        installAppAsUser(INTENT_SENDER_APK, USER_ALL);
 
         changeVerificationStatus(mParentUserId, INTENT_RECEIVER_PKG, "ask");
         changeVerificationStatus(mProfileUserId, INTENT_RECEIVER_PKG, "ask");
@@ -526,10 +526,8 @@
         // intents resolution.
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
                 "testDisableAllBrowsers", mProfileUserId);
-        installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
-        installAppAsUser(INTENT_SENDER_APK, mParentUserId);
-        installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
-        installAppAsUser(INTENT_SENDER_APK, mProfileUserId);
+        installAppAsUser(INTENT_RECEIVER_APK, USER_ALL);
+        installAppAsUser(INTENT_SENDER_APK, USER_ALL);
 
         final String APP_HANDLER_COMPONENT = "com.android.cts.intent.receiver/.AppLinkActivity";
 
@@ -589,10 +587,8 @@
 
         // Storage permission shouldn't be granted, we check if missing permissions are respected
         // in ContentTest#testSecurity.
-        installAppAsUser(INTENT_SENDER_APK, false /* grantPermissions */, mParentUserId);
-        installAppAsUser(INTENT_SENDER_APK, false /* grantPermissions */, mProfileUserId);
-        installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
-        installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
+        installAppAsUser(INTENT_SENDER_APK, false /* grantPermissions */, USER_ALL);
+        installAppAsUser(INTENT_RECEIVER_APK, USER_ALL);
 
         // Test from parent to managed
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
@@ -615,8 +611,7 @@
             return;
         }
 
-        installAppAsUser(NOTIFICATION_APK, mProfileUserId);
-        installAppAsUser(NOTIFICATION_APK, mParentUserId);
+        installAppAsUser(NOTIFICATION_APK, USER_ALL);
 
         // Profile owner in the profile sets an empty whitelist
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
@@ -633,8 +628,7 @@
             return;
         }
 
-        installAppAsUser(NOTIFICATION_APK, mProfileUserId);
-        installAppAsUser(NOTIFICATION_APK, mParentUserId);
+        installAppAsUser(NOTIFICATION_APK, USER_ALL);
 
         // Profile owner in the profile sets a null whitelist
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
@@ -651,8 +645,7 @@
             return;
         }
 
-        installAppAsUser(NOTIFICATION_APK, mProfileUserId);
-        installAppAsUser(NOTIFICATION_APK, mParentUserId);
+        installAppAsUser(NOTIFICATION_APK, USER_ALL);
 
         // Profile owner in the profile adds listener to the whitelist
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
@@ -668,8 +661,7 @@
         if (!mHasFeature) {
             return;
         }
-        installAppAsUser(NOTIFICATION_APK, mProfileUserId);
-        installAppAsUser(NOTIFICATION_APK, mParentUserId);
+        installAppAsUser(NOTIFICATION_APK, USER_ALL);
 
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
                 "testSetAndGetPermittedCrossProfileNotificationListeners", mProfileUserId,
@@ -680,10 +672,8 @@
         if (!mHasFeature) {
             return;
         }
-        installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
-        installAppAsUser(INTENT_SENDER_APK, mParentUserId);
-        installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
-        installAppAsUser(INTENT_SENDER_APK, mProfileUserId);
+        installAppAsUser(INTENT_RECEIVER_APK, USER_ALL);
+        installAppAsUser(INTENT_SENDER_APK, USER_ALL);
 
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
                 "testAllowCrossProfileCopyPaste", mProfileUserId);
@@ -1001,8 +991,7 @@
         }
 
         try {
-            installAppAsUser(WIDGET_PROVIDER_APK, mProfileUserId);
-            installAppAsUser(WIDGET_PROVIDER_APK, mParentUserId);
+            installAppAsUser(WIDGET_PROVIDER_APK, USER_ALL);
             getDevice().executeShellCommand("appwidget grantbind --user " + mParentUserId
                     + " --package " + WIDGET_PROVIDER_PKG);
             setIdleWhitelist(WIDGET_PROVIDER_PKG, true);
@@ -1048,8 +1037,7 @@
         }
 
         try {
-            installAppAsUser(WIDGET_PROVIDER_APK, mProfileUserId);
-            installAppAsUser(WIDGET_PROVIDER_APK, mParentUserId);
+            installAppAsUser(WIDGET_PROVIDER_APK, USER_ALL);
             getDevice().executeShellCommand("appwidget grantbind --user " + mParentUserId
                     + " --package " + WIDGET_PROVIDER_PKG);
             setIdleWhitelist(WIDGET_PROVIDER_PKG, true);
@@ -1738,8 +1726,7 @@
                     "testAddTestAccount", mProfileUserId);
 
             // Install directory provider to both primary and managed profile
-            installAppAsUser(DIRECTORY_PROVIDER_APK, mProfileUserId);
-            installAppAsUser(DIRECTORY_PROVIDER_APK, mParentUserId);
+            installAppAsUser(DIRECTORY_PROVIDER_APK, USER_ALL);
             setDirectoryPrefix(PRIMARY_DIRECTORY_PREFIX, mParentUserId);
             setDirectoryPrefix(MANAGED_DIRECTORY_PREFIX, mProfileUserId);
 
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/DisplayTests.java b/tests/framework/base/windowmanager/src/android/server/wm/DisplayTests.java
index 2fc2f1e..f51f0b6 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/DisplayTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/DisplayTests.java
@@ -73,7 +73,6 @@
     }
 
     @Test
-    @FlakyTest(bugId = 129521230)
     public void testNonDefaultDisplayResourcesConfiguration() throws Exception {
         final int smallDisplaySize = 1000;
         final int longDisplaySize = 1920;
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayClientTests.java b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayClientTests.java
old mode 100644
new mode 100755
index fd8deb2..df087db
--- a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayClientTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayClientTests.java
@@ -62,7 +62,7 @@
 @Presubmit
 public class MultiDisplayClientTests extends MultiDisplayTestBase {
 
-    private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(5); // 5 seconds
+    private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(10); // 10 seconds
     private static final String EXTRA_SHOW_IME = "show_ime";
 
     @Before
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayTestBase.java b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayTestBase.java
index 32a20ae8..ef78bc7b 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayTestBase.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayTestBase.java
@@ -74,6 +74,7 @@
 import java.util.Collections;
 import java.util.List;
 import java.util.function.Consumer;
+import java.util.function.Predicate;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -244,6 +245,18 @@
         tapOnDisplay(bounds.centerX(), bounds.centerY(), displayId);
     }
 
+    private void waitForDisplayGone(Predicate<WindowManagerState.Display> displayPredicate) {
+        for (int retry = 1; retry <= 5; retry++) {
+            mAmWmState.computeState(true);
+            if (!mAmWmState.getWmState().getDisplays().stream().anyMatch(displayPredicate::test)) {
+                return;
+            }
+            logAlways("Waiting for hosted displays destruction... retry=" + retry);
+            SystemClock.sleep(500);
+        }
+        fail("Waiting for hosted displays destruction failed.");
+    }
+
     /**
      * This class should only be used when you need to test virtual display created by a
      * non-privileged app.
@@ -360,19 +373,13 @@
          * @return {@link ActivityDisplay} of newly created display.
          */
         private List<ActivityDisplay> simulateDisplay() throws Exception {
-            final List<ActivityDisplay> originalDs = getDisplaysStates();
-
             // Create virtual display with custom density dpi and specified size.
             mOverlayDisplayDeviceSession.set(mSimulationDisplaySize + "/" + mDensityDpi);
-            final List<ActivityDisplay> newDisplays = assertAndGetNewDisplays(1, originalDs);
-
             if (mShowSystemDecorations) {
-                for (ActivityDisplay display : newDisplays) {
-                    mOverlayDisplayDeviceSession.addAndConfigDisplayState(display,
-                            true /* requestShowSysDecors */, true /* requestShowIme */);
-                }
+                mOverlayDisplayDeviceSession.configureDisplays(
+                        true /* requestShowSysDecors */, true /* requestShowIme */);
             }
-            return newDisplays;
+            return mOverlayDisplayDeviceSession.getCreatedDisplays();
         }
 
         /**
@@ -448,55 +455,9 @@
                     + " -f 0x20000000"
                     + " --es " + KEY_COMMAND + " " + COMMAND_DESTROY_DISPLAY;
             executeShellCommand(destroyVirtualDisplayCommand);
-            waitForDisplaysDestroyed();
-        }
-
-        private void waitForDisplaysDestroyed() {
-            for (int retry = 1; retry <= 5; retry++) {
-                if (!isHostedVirtualDisplayPresent()) {
-                    return;
-                }
-                logAlways("Waiting for hosted displays destruction... retry=" + retry);
-                SystemClock.sleep(500);
-            }
-            fail("Waiting for hosted displays destruction failed.");
-        }
-
-        private boolean isHostedVirtualDisplayPresent() {
-            mAmWmState.computeState(true);
-            return mAmWmState.getWmState().getDisplays().stream().anyMatch(
+            waitForDisplayGone(
                     d -> d.getName() != null && d.getName().contains(VIRTUAL_DISPLAY_PREFIX));
         }
-
-        /**
-         * Wait for desired number of displays to be created and get their properties.
-         * @param newDisplayCount expected display count, -1 if display should not be created.
-         * @param originalDS display states before creation of new display(s).
-         * @return list of new displays, empty list if no new display is created.
-         */
-        private List<ActivityDisplay> assertAndGetNewDisplays(int newDisplayCount,
-                List<ActivityDisplay> originalDS) {
-            final int originalDisplayCount = originalDS.size();
-
-            // Wait for the display(s) to be created and get configurations.
-            final List<ActivityDisplay> ds = getDisplayStateAfterChange(
-                    originalDisplayCount + newDisplayCount);
-            if (newDisplayCount != -1) {
-                assertEquals("New virtual display(s) must be created",
-                        originalDisplayCount + newDisplayCount, ds.size());
-            } else {
-                assertEquals("New virtual display must not be created",
-                        originalDisplayCount, ds.size());
-                return Collections.emptyList();
-            }
-
-            // Find the newly added display(s).
-            final List<ActivityDisplay> newDisplays = findNewDisplayStates(originalDS, ds);
-            assertThat("New virtual display must be created",
-                    newDisplays, hasSize(newDisplayCount));
-
-            return newDisplays;
-        }
     }
 
     // TODO(b/112837428): Merge into VirtualDisplaySession when all usages are migrated.
@@ -538,7 +499,10 @@
     }
 
     /** Helper class to save, set, and restore overlay_display_devices preference. */
-    private static class OverlayDisplayDevicesSession extends SettingsSession<String> {
+    private class OverlayDisplayDevicesSession extends SettingsSession<String> {
+        /** The displays which are created by this session. */
+        private final List<ActivityDisplay> mDisplays = new ArrayList<>();
+        /** The configured displays that need to be restored when this session is closed. */
         private final List<OverlayDisplayState> mDisplayStates = new ArrayList<>();
         private final WindowManager mWm;
 
@@ -549,23 +513,38 @@
             mWm = context.getSystemService(WindowManager.class);
         }
 
-        void addAndConfigDisplayState(ActivityDisplay display, boolean requestShowSysDecors,
-                boolean requestShowIme) {
+        List<ActivityDisplay> getCreatedDisplays() {
+            return new ArrayList<>(mDisplays);
+        }
+
+        @Override
+        public void set(String value) {
+            final List<ActivityDisplay> originalDisplays = getDisplaysStates();
+            super.set(value);
+            final int newDisplayCount = 1 + (int) value.chars().filter(ch -> ch == ';').count();
+            mDisplays.addAll(assertAndGetNewDisplays(newDisplayCount, originalDisplays));
+        }
+
+        void configureDisplays(boolean requestShowSysDecors, boolean requestShowIme) {
             SystemUtil.runWithShellPermissionIdentity(() -> {
-                final boolean showSystemDecors = mWm.shouldShowSystemDecors(display.mId);
-                final boolean showIme = mWm.shouldShowIme(display.mId);
-                mDisplayStates.add(new OverlayDisplayState(display.mId, showSystemDecors, showIme));
-                if (requestShowSysDecors != showSystemDecors) {
-                    mWm.setShouldShowSystemDecors(display.mId, requestShowSysDecors);
-                    TestUtils.waitUntil("Waiting for display show system decors",
-                            5 /* timeoutSecond */,
-                            () -> mWm.shouldShowSystemDecors(display.mId) == requestShowSysDecors);
-                }
-                if (requestShowIme != showIme) {
-                    mWm.setShouldShowIme(display.mId, requestShowIme);
-                    TestUtils.waitUntil("Waiting for display show Ime",
-                            5 /* timeoutSecond */,
-                            () -> mWm.shouldShowIme(display.mId) == requestShowIme);
+                for (ActivityDisplay display : mDisplays) {
+                    final boolean showSystemDecors = mWm.shouldShowSystemDecors(display.mId);
+                    final boolean showIme = mWm.shouldShowIme(display.mId);
+                    mDisplayStates.add(new OverlayDisplayState(
+                            display.mId, showSystemDecors, showIme));
+                    if (requestShowSysDecors != showSystemDecors) {
+                        mWm.setShouldShowSystemDecors(display.mId, requestShowSysDecors);
+                        TestUtils.waitUntil("Waiting for display show system decors",
+                                5 /* timeoutSecond */,
+                                () -> mWm.shouldShowSystemDecors(
+                                        display.mId) == requestShowSysDecors);
+                    }
+                    if (requestShowIme != showIme) {
+                        mWm.setShouldShowIme(display.mId, requestShowIme);
+                        TestUtils.waitUntil("Waiting for display show Ime",
+                                5 /* timeoutSecond */,
+                                () -> mWm.shouldShowIme(display.mId) == requestShowIme);
+                    }
                 }
             });
         }
@@ -587,6 +566,8 @@
             // Need to restore display state before display is destroyed.
             restoreDisplayStates();
             super.close();
+            waitForDisplayGone(display -> mDisplays.stream()
+                    .anyMatch(state -> state.mId == display.getDisplayId()));
         }
 
         private class OverlayDisplayState {
@@ -632,6 +613,36 @@
         return true;
     }
 
+    /**
+     * Wait for desired number of displays to be created and get their properties.
+     *
+     * @param newDisplayCount expected display count, -1 if display should not be created.
+     * @param originalDisplays display states before creation of new display(s).
+     * @return list of new displays, empty list if no new display is created.
+     */
+    private List<ActivityDisplay> assertAndGetNewDisplays(int newDisplayCount,
+            List<ActivityDisplay> originalDisplays) {
+        final int originalDisplayCount = originalDisplays.size();
+
+        // Wait for the display(s) to be created and get configurations.
+        final List<ActivityDisplay> ds = getDisplayStateAfterChange(
+                originalDisplayCount + newDisplayCount);
+        if (newDisplayCount != -1) {
+            assertEquals("New virtual display(s) must be created",
+                    originalDisplayCount + newDisplayCount, ds.size());
+        } else {
+            assertEquals("New virtual display must not be created",
+                    originalDisplayCount, ds.size());
+            return Collections.emptyList();
+        }
+
+        // Find the newly added display(s).
+        final List<ActivityDisplay> newDisplays = findNewDisplayStates(originalDisplays, ds);
+        assertThat("New virtual display must be created", newDisplays, hasSize(newDisplayCount));
+
+        return newDisplays;
+    }
+
     /** Checks if the device supports multi-display. */
     protected boolean supportsMultiDisplay() {
         return hasDeviceFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
@@ -714,27 +725,10 @@
                 mExternalDisplayHelper.releaseDisplay();
                 mExternalDisplayHelper = null;
 
-                waitForHostedDisplayDestroyed();
+                waitForDisplayGone(d -> d.getDisplayId() == mDisplayId);
                 mDisplayId = INVALID_DISPLAY;
             }
         }
-
-        private void waitForHostedDisplayDestroyed() {
-            for (int retry = 1; retry <= 5; retry++) {
-                if (!isHostedVirtualDisplayPresent()) {
-                    return;
-                }
-                logAlways("Waiting for hosted displays destruction... retry=" + retry);
-                SystemClock.sleep(500);
-            }
-            fail("Waiting for hosted displays destruction failed.");
-        }
-
-        private boolean isHostedVirtualDisplayPresent() {
-            mAmWmState.computeState(true);
-            return mAmWmState.getWmState().getDisplays().stream().anyMatch(
-                    d -> d.getDisplayId() == mDisplayId);
-        }
     }
 
     public static class PrimaryDisplayStateSession implements AutoCloseable {
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 2f88d31..1f35533 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
@@ -1671,20 +1671,28 @@
     static class ActivityLifecycleCounts {
         final int[] mCounts = new int[ActivityCallback.SIZE];
         final int[] mLastIndexes = new int[ActivityCallback.SIZE];
-        final List<ActivityCallback> mCallbackHistory;
+        private ComponentName mActivityName;
 
         ActivityLifecycleCounts(ComponentName componentName) {
-            this(TestJournalContainer.get(componentName).callbacks);
+            mActivityName = componentName;
+            updateCount(TestJournalContainer.get(componentName).callbacks);
         }
 
         ActivityLifecycleCounts(List<ActivityCallback> callbacks) {
-            mCallbackHistory = callbacks;
-            for (int i = 0; i < callbacks.size(); i++) {
-                final ActivityCallback callback = callbacks.get(i);
-                final int ordinal = callback.ordinal();
-                mCounts[ordinal]++;
-                mLastIndexes[ordinal] = i;
-            }
+            updateCount(callbacks);
+        }
+
+        private void updateCount(List<ActivityCallback> callbacks) {
+            // The callback list could be from the reference of TestJournal. If we are counting for
+            // retrying, there may be new data added to the list from other threads.
+            TestJournalContainer.withThreadSafeAccess(() -> {
+                for (int i = 0; i < callbacks.size(); i++) {
+                    final ActivityCallback callback = callbacks.get(i);
+                    final int ordinal = callback.ordinal();
+                    mCounts[ordinal]++;
+                    mLastIndexes[ordinal] = i;
+                }
+            });
         }
 
         int getCount(ActivityCallback callback) {
@@ -1697,9 +1705,16 @@
 
         @SafeVarargs
         final void assertCountWithRetry(String message, CountSpec<ActivityCallback>... countSpecs) {
+            if (mActivityName == null) {
+                throw new IllegalStateException(
+                        "It is meaningless to retry without specified activity");
+            }
             new RetryValidator() {
                 @Override
                 protected String validate() {
+                    Arrays.fill(mCounts, 0);
+                    Arrays.fill(mLastIndexes, 0);
+                    updateCount(TestJournalContainer.get(mActivityName).callbacks);
                     return validateCount(countSpecs);
                 }
             }.assertValidator(message);
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/TestJournalProvider.java b/tests/framework/base/windowmanager/util/src/android/server/wm/TestJournalProvider.java
index d35289b..b2d92a3 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/TestJournalProvider.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/TestJournalProvider.java
@@ -90,19 +90,19 @@
         switch (method) {
             case METHOD_ADD_CALLBACK:
                 ensureExtras(method, extras);
-                TestJournalContainer.get().addCallback(
+                TestJournalContainer.getInstance().addCallback(
                         extras.getString(EXTRA_KEY_OWNER), extras.getParcelable(method));
                 break;
 
             case METHOD_SET_LAST_CONFIG_INFO:
                 ensureExtras(method, extras);
-                TestJournalContainer.get().setLastConfigInfo(
+                TestJournalContainer.getInstance().setLastConfigInfo(
                         extras.getString(EXTRA_KEY_OWNER), extras.getParcelable(method));
                 break;
 
             case METHOD_PUT_EXTRAS:
                 ensureExtras(method, extras);
-                TestJournalContainer.get().putExtras(
+                TestJournalContainer.getInstance().putExtras(
                         extras.getString(EXTRA_KEY_OWNER), extras);
                 break;
         }
@@ -267,7 +267,17 @@
 
         @NonNull
         public static TestJournal get(String owner) {
-            return get().getTestJournal(owner);
+            return getInstance().getTestJournal(owner);
+        }
+
+        /**
+         * Perform the action which may have thread safety concerns when accessing the fields of
+         * {@link TestJournal}.
+         */
+        public static void withThreadSafeAccess(Runnable aciton) {
+            synchronized (getInstance()) {
+                aciton.run();
+            }
         }
 
         private synchronized TestJournal getTestJournal(String owner) {
@@ -291,7 +301,7 @@
             getTestJournal(owner).extras.putAll(extras);
         }
 
-        private synchronized static TestJournalContainer get() {
+        private synchronized static TestJournalContainer getInstance() {
             if (!TestJournalProvider.sCrossProcessAccessGuard) {
                 throw new IllegalAccessError(TestJournalProvider.class.getSimpleName()
                         + " is not alive in this process");
@@ -308,7 +318,7 @@
          */
         @NonNull
         public static TestJournalContainer start() {
-            final TestJournalContainer instance = get();
+            final TestJournalContainer instance = getInstance();
             synchronized (instance) {
                 instance.mContainer.clear();
             }
diff --git a/tests/providerui/src/android/providerui/cts/MediaStoreUiTest.java b/tests/providerui/src/android/providerui/cts/MediaStoreUiTest.java
index 7746c98..fc7ed48 100644
--- a/tests/providerui/src/android/providerui/cts/MediaStoreUiTest.java
+++ b/tests/providerui/src/android/providerui/cts/MediaStoreUiTest.java
@@ -53,6 +53,7 @@
 import android.os.SystemClock;
 import android.os.storage.StorageManager;
 import android.os.storage.StorageVolume;
+import android.os.UserManager;
 import android.provider.MediaStore;
 import android.providerui.cts.GetResultActivity.Result;
 import android.support.test.uiautomator.By;
@@ -483,10 +484,12 @@
     static File stageFile(int resId, File file) throws IOException {
         // The caller may be trying to stage into a location only available to
         // the shell user, so we need to perform the entire copy as the shell
-        if (FileUtils.contains(Environment.getStorageDirectory(), file)) {
+        final Context context = InstrumentationRegistry.getTargetContext();
+        UserManager userManager = context.getSystemService(UserManager.class);
+        if (userManager.isSystemUser() &&
+                 FileUtils.contains(Environment.getStorageDirectory(), file)) {
             executeShellCommand("mkdir -p " + file.getParent());
 
-            final Context context = InstrumentationRegistry.getTargetContext();
             try (AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId)) {
                 final File source = ParcelFileDescriptor.getFile(afd.getFileDescriptor());
                 final long skip = afd.getStartOffset();
@@ -504,7 +507,6 @@
             if (!dir.exists()) {
                 throw new FileNotFoundException("Failed to create parent for " + file);
             }
-            final Context context = InstrumentationRegistry.getTargetContext();
             try (InputStream source = context.getResources().openRawResource(resId);
                     OutputStream target = new FileOutputStream(file)) {
                 FileUtils.copy(source, target);
diff --git a/tests/signature/api-check/src/java/android/signature/cts/api/HiddenApiTest.java b/tests/signature/api-check/src/java/android/signature/cts/api/HiddenApiTest.java
index 8efa483..b185c50 100644
--- a/tests/signature/api-check/src/java/android/signature/cts/api/HiddenApiTest.java
+++ b/tests/signature/api-check/src/java/android/signature/cts/api/HiddenApiTest.java
@@ -26,7 +26,12 @@
 import android.signature.cts.DexMethod;
 import android.signature.cts.FailureType;
 
+import java.io.BufferedReader;
 import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.text.ParseException;
 import java.util.function.Predicate;
 import java.util.stream.Stream;
 
@@ -136,33 +141,21 @@
                     }
                 }
             };
-            parseDexApiFilesAsStream(hiddenapiFiles)
-                    .filter(memberFilter)
-                    .forEach(dexMember -> {
-                        if (shouldTestMember(dexMember)) {
-                            DexMemberChecker.checkSingleMember(dexMember, reflection, jni,
-                                    observer);
-                        }
-                    });
-        });
-    }
-
-    private Stream<DexMember> parseDexApiFilesAsStream(String[] apiFiles) {
-        DexApiDocumentParser dexApiDocumentParser = new DexApiDocumentParser();
-        // To allow parallelization with a DexMember output type, we need two
-        // pipes.
-        Stream<Stream<DexMember>> inputsAsStreams = Stream.of(apiFiles).parallel()
-                .map(name -> new File(API_FILE_DIRECTORY + "/" + name))
-                .flatMap(file -> readFileOptimized(file))
-                .map(obj -> dexApiDocumentParser.parseAsStream(obj));
-        // The flatMap inherently serializes the pipe. The number of inputs is
-        // still small here, so reduce by concatenating (note the caveats of
-        // concats).
-        return inputsAsStreams.reduce(null, (prev, stream) -> {
-            if (prev == null) {
-                return stream;
+            for (String apiFile : hiddenapiFiles) {
+                BufferedReader reader = new BufferedReader(
+                        new FileReader(API_FILE_DIRECTORY + "/" + apiFile));
+                int lineIndex = 1;
+                String line = reader.readLine();
+                while (line != null) {
+                    DexMember dexMember = DexApiDocumentParser.parseLine(line, lineIndex);
+                    if (memberFilter.test(dexMember) && shouldTestMember(dexMember)) {
+                        DexMemberChecker.checkSingleMember(dexMember, reflection, jni,
+                                observer);
+                    }
+                    line = reader.readLine();
+                    lineIndex++;
+                }
             }
-            return Stream.concat(prev, stream);
         });
     }
 
diff --git a/tests/signature/lib/common/src/android/signature/cts/DexApiDocumentParser.java b/tests/signature/lib/common/src/android/signature/cts/DexApiDocumentParser.java
index 7b71d65..8bb3062 100644
--- a/tests/signature/lib/common/src/android/signature/cts/DexApiDocumentParser.java
+++ b/tests/signature/lib/common/src/android/signature/cts/DexApiDocumentParser.java
@@ -88,7 +88,7 @@
                 lineLengthEstimate, DEX_MEMBER_CONVERTER), true);
     }
 
-    private static DexMember parseLine(String line, int lineNum) throws ParseException {
+    public static DexMember parseLine(String line, int lineNum) throws ParseException {
         // Split the CSV line.
         String[] splitLine = line.split(",");
         String signature = splitLine[0];
diff --git a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
index ddedb84..39ec713 100644
--- a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
+++ b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
@@ -37,6 +37,7 @@
 import android.telecom.TelecomManager;
 import android.test.AndroidTestCase;
 
+import com.android.compatibility.common.util.CddTest;
 import com.android.compatibility.common.util.FeatureUtil;
 
 import java.util.List;
@@ -418,6 +419,7 @@
         }
     }
 
+    @CddTest(requirement = "7.4.2.6/C-1-1")
     public void testEasyConnectIntent() {
         WifiManager manager = mContext.getSystemService(WifiManager.class);
 
diff --git a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
index 8eb1966..8c999db 100644
--- a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
+++ b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
@@ -35,6 +35,8 @@
     }
 #define VK_CALL(a) ASSERT(VK_SUCCESS == (a))
 
+#define TIMEOUT_30_SEC 30000000000
+
 static const float vertexData[] = {
         // L:left, T:top, R:right, B:bottom, C:center
         -1.0f, -1.0f, 0.0f, // LT
@@ -862,7 +864,7 @@
     };
     VK_CALL(vkQueueSubmit(mDeviceInfo->queue(), 1, &submitInfo, mFence))
 
-    VK_CALL(vkWaitForFences(mDeviceInfo->device(), 1, &mFence, VK_TRUE, 100000000));
+    VK_CALL(vkWaitForFences(mDeviceInfo->device(), 1, &mFence, VK_TRUE, TIMEOUT_30_SEC));
 
     const VkSwapchainKHR swapchain = mSwapchainInfo->swapchain();
     const VkPresentInfoKHR presentInfo = {
diff --git a/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java b/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
index b2db009..3e47d15 100644
--- a/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
+++ b/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
@@ -30,6 +30,7 @@
 import android.os.FileUtils;
 import android.os.ParcelFileDescriptor;
 import android.os.UserHandle;
+import android.os.UserManager;
 import android.provider.MediaStore;
 import android.provider.MediaStore.MediaColumns;
 import android.provider.cts.MediaStoreUtils.PendingParams;
@@ -217,10 +218,11 @@
     static File stageFile(int resId, File file) throws IOException {
         // The caller may be trying to stage into a location only available to
         // the shell user, so we need to perform the entire copy as the shell
-        if (FileUtils.contains(Environment.getStorageDirectory(), file)) {
+        final Context context = InstrumentationRegistry.getTargetContext();
+        UserManager userManager = context.getSystemService(UserManager.class);
+        if (userManager.isSystemUser() &&
+                    FileUtils.contains(Environment.getStorageDirectory(), file)) {
             executeShellCommand("mkdir -p " + file.getParent());
-
-            final Context context = InstrumentationRegistry.getTargetContext();
             try (AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId)) {
                 final File source = ParcelFileDescriptor.getFile(afd.getFileDescriptor());
                 final long skip = afd.getStartOffset();
@@ -238,7 +240,6 @@
             if (!dir.exists()) {
                 throw new FileNotFoundException("Failed to create parent for " + file);
             }
-            final Context context = InstrumentationRegistry.getTargetContext();
             try (InputStream source = context.getResources().openRawResource(resId);
                     OutputStream target = new FileOutputStream(file)) {
                 FileUtils.copy(source, target);
diff --git a/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java b/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
index ef8011c..8142efe 100644
--- a/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
+++ b/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
@@ -39,6 +39,8 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.Arrays;
+
 /**
  * Tests related SettingsPanels:
  *
@@ -154,7 +156,8 @@
 
         final UiObject2 titleView = mDevice.findObject(By.res(mSettingsPackage, RESOURCE_TITLE));
 
-        assertThat(titleView.getText()).isEqualTo("Wi\u2011Fi");
+        // title must be "Wi\u2011Fi" or "WLAN"
+        assertThat(titleView.getText()).isIn(Arrays.asList("Wi\u2011Fi", "WLAN"));
     }
 
     @Test
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerThrottlingTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerThrottlingTest.java
index 7628c82..79b6bd1 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerThrottlingTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerThrottlingTest.java
@@ -18,7 +18,7 @@
 
 import static android.content.pm.cts.shortcutmanager.common.Constants.INLINE_REPLY_REMOTE_INPUT_CAPTION;
 
-import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.resetThrottling;
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.resetAllThrottling;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.runCommandForNoOutput;
 
 import android.content.ComponentName;
@@ -64,7 +64,7 @@
     protected void setUp() throws Exception {
         super.setUp();
 
-        resetThrottling(getInstrumentation());
+        resetAllThrottling(getInstrumentation());
 
         UiDevice.getInstance(getInstrumentation()).pressHome();
 
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java
index 3ef4ff2..39a9346 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java
@@ -42,6 +42,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.pm.PackageManager;
 import android.net.ConnectivityManager;
 import android.os.Looper;
 import android.os.PersistableBundle;
@@ -63,6 +64,7 @@
     private static final String CARRIER_NAME_OVERRIDE = "carrier_a";
     private CarrierConfigManager mConfigManager;
     private TelephonyManager mTelephonyManager;
+    private PackageManager mPackageManager;
     private static final int TOLERANCE = 2000;
     private final Object mLock = new Object();
 
@@ -72,6 +74,7 @@
                 getContext().getSystemService(Context.TELEPHONY_SERVICE);
         mConfigManager = (CarrierConfigManager)
                 getContext().getSystemService(Context.CARRIER_CONFIG_SERVICE);
+        mPackageManager = getContext().getPackageManager();
     }
 
     @After
@@ -142,6 +145,9 @@
     @SecurityTest
     @Test
     public void testRevokePermission() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
         PersistableBundle config;
 
         try {
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java
index 52ed059..c81240d 100755
--- a/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java
@@ -169,6 +169,9 @@
 
     @Test
     public void testDivideMessage() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
         ArrayList<String> dividedMessages = divideMessage(LONG_TEXT);
         assertNotNull(dividedMessages);
         if (TelephonyUtils.isSkt(mTelephonyManager)) {
@@ -184,6 +187,9 @@
 
     @Test
     public void testDivideUnicodeMessage() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
         ArrayList<String> dividedMessages = divideMessage(LONG_TEXT_WITH_32BIT_CHARS);
         assertNotNull(dividedMessages);
         assertTrue(isComplete(dividedMessages, 3, LONG_TEXT_WITH_32BIT_CHARS));
@@ -437,6 +443,9 @@
 
     @Test
     public void testContentProviderAccessRestriction() throws Exception {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
         Uri dummySmsUri = null;
         Context context = getInstrumentation().getContext();
         ContentResolver contentResolver = context.getContentResolver();
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
index 3a72a80..807ef0c 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
@@ -1229,6 +1229,10 @@
      */
     @Test
     public void testGetUiccCardsInfo() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "Skipping test that requires FEATURE_TELEPHONY");
+            return;
+        }
         try {
             // Requires READ_PRIVILEGED_PHONE_STATE or carrier privileges
             List<UiccCardInfo> infos = mTelephonyManager.getUiccCardsInfo();
diff --git a/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java b/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
index 27c388a..6314ec5 100644
--- a/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
+++ b/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
@@ -105,7 +105,8 @@
     private static final String WHITE_SPACES = " \r \n \t \f ";
 
     private static final String PARAM_CANONICAL_GENRE = "canonical_genre";
-    private static final String NON_EXISTING_COLUMN_NAME = "non_existing_column";
+    private static final String[] NON_EXISTING_COLUMN_NAMES =
+            {"non_existing_column", "another non-existing column --"};
 
     private String mInputId;
     private ContentResolver mContentResolver;
@@ -336,15 +337,20 @@
     private void verifyNonExistingColumn(Uri channelUri, long channelId) {
         String[] projection = {
                 Channels._ID,
-                NON_EXISTING_COLUMN_NAME
+                NON_EXISTING_COLUMN_NAMES[0],
+                NON_EXISTING_COLUMN_NAMES[1]
         };
         try (Cursor cursor = mContentResolver.query(channelUri, projection, null, null, null)) {
             assertNotNull(cursor);
             assertEquals(cursor.getCount(), 1);
             assertTrue(cursor.moveToNext());
             assertEquals(channelId, cursor.getLong(0));
+            assertEquals(NON_EXISTING_COLUMN_NAMES[0], cursor.getColumnName(1));
             assertNull(cursor.getString(1));
             assertEquals(0, cursor.getInt(1));
+            assertEquals(NON_EXISTING_COLUMN_NAMES[1], cursor.getColumnName(2));
+            assertNull(cursor.getString(2));
+            assertEquals(0, cursor.getInt(2));
         }
     }
 
@@ -533,7 +539,8 @@
             return;
         }
         ContentValues values = createDummyChannelValues(mInputId, false);
-        values.put(NON_EXISTING_COLUMN_NAME, "dummy value");
+        values.put(NON_EXISTING_COLUMN_NAMES[0], "dummy value 0");
+        values.put(NON_EXISTING_COLUMN_NAMES[1], "dummy value 1");
         Uri rowUri = mContentResolver.insert(mChannelsUri, values);
         long channelId = ContentUris.parseId(rowUri);
         Uri channelUri = TvContract.buildChannelUri(channelId);
diff --git a/tests/tests/view/surfacevalidator/src/android/view/cts/surfacevalidator/CapturedActivity.java b/tests/tests/view/surfacevalidator/src/android/view/cts/surfacevalidator/CapturedActivity.java
index 84a7999..9c9217b 100644
--- a/tests/tests/view/surfacevalidator/src/android/view/cts/surfacevalidator/CapturedActivity.java
+++ b/tests/tests/view/surfacevalidator/src/android/view/cts/surfacevalidator/CapturedActivity.java
@@ -46,6 +46,7 @@
 import android.view.Display;
 import android.view.PointerIcon;
 import android.view.View;
+import android.view.WindowManager;
 import android.widget.FrameLayout;
 
 import androidx.test.InstrumentationRegistry;
@@ -104,6 +105,8 @@
         // Set the NULL pointer icon so that it won't obstruct the captured image.
         getWindow().getDecorView().setPointerIcon(
                 PointerIcon.getSystemIcon(this, PointerIcon.TYPE_NULL));
+        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+
 
         mProjectionManager =
                 (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);