Merge "Uses USER_SETUP_COMPLETE constant."
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DynamicConfigPusher.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DynamicConfigPusher.java
index 7ac61c9..d64c210 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DynamicConfigPusher.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DynamicConfigPusher.java
@@ -66,7 +66,7 @@
 
     @Option(name = "version", description = "The version of the configuration to retrieve " +
             "from the server, e.g. \"1.0\". Defaults to suite version string.")
-    private static String mVersion;
+    private String mVersion;
 
 
     private String mFilePushed;
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java
index 32e0ce7..44a797c 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java
@@ -84,10 +84,10 @@
             "com.android.cts.ephemeraltest.EXTRA_ACTIVITY_RESULT";
 
     /**
-     * Intents that we expect the system to expose activities to ephemeral apps to handle.
+     * Contact Intents that we expect the system to expose activities to ephemeral apps to handle
+     * (if the system does not have FEATURE_WATCH).
      */
-    private static final Intent[] EXPECTED_EXPOSED_SYSTEM_INTENTS = new Intent[] {
-        // Contacts
+    private static final Intent[] EXPECTED_EXPOSED_SYSTEM_CONTACT_INTENTS = new Intent[] {
         makeIntent(Intent.ACTION_PICK, null, ContactsContract.Contacts.CONTENT_TYPE, null),
         makeIntent(Intent.ACTION_PICK, null,
                 ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE, null),
@@ -95,7 +95,13 @@
                 ContactsContract.CommonDataKinds.Email.CONTENT_TYPE, null),
         makeIntent(Intent.ACTION_PICK, null,
                 ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_TYPE, null),
-        // File Storage
+    };
+
+    /**
+     * File Storage Intents that we expect the system to expose activities to ephemeral apps to
+     * handle (if the system does not have FEATURE_WATCH).
+     */
+    private static final Intent[] EXPECTED_EXPOSED_SYSTEM_STORAGE_INTENTS = new Intent[] {
         makeIntent(Intent.ACTION_OPEN_DOCUMENT, Intent.CATEGORY_OPENABLE, "*/*", null),
         makeIntent(Intent.ACTION_OPEN_DOCUMENT, null, "*/*", null),
         makeIntent(Intent.ACTION_GET_CONTENT, Intent.CATEGORY_OPENABLE, "*/*", null),
@@ -103,7 +109,13 @@
         makeIntent(Intent.ACTION_OPEN_DOCUMENT_TREE, null, null, null),
         makeIntent(Intent.ACTION_CREATE_DOCUMENT, Intent.CATEGORY_OPENABLE, "text/plain", null),
         makeIntent(Intent.ACTION_CREATE_DOCUMENT, null, "text/plain", null),
-        // Framework
+    };
+
+    /**
+     * Framework Intents that we expect the system to expose activities to ephemeral apps
+     * to handle.
+     */
+    private static final Intent[] EXPECTED_EXPOSED_SYSTEM_FRAMEWORK_INTENTS = new Intent[] {
         makeIntent(Intent.ACTION_CHOOSER, null, null, null),
     };
 
@@ -975,9 +987,23 @@
 
     @Test
     public void testExposedSystemActivities() throws Exception {
-        for (Intent queryIntent : EXPECTED_EXPOSED_SYSTEM_INTENTS) {
+        for (Intent queryIntent : EXPECTED_EXPOSED_SYSTEM_FRAMEWORK_INTENTS) {
             assertIntentHasExposedActivities(queryIntent);
         }
+
+        PackageManager packageManager = InstrumentationRegistry.getContext().getPackageManager();
+        if (!(packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)
+                || packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK))) {
+
+            for (Intent queryIntent : EXPECTED_EXPOSED_SYSTEM_CONTACT_INTENTS) {
+                assertIntentHasExposedActivities(queryIntent);
+            }
+
+            for (Intent queryIntent : EXPECTED_EXPOSED_SYSTEM_STORAGE_INTENTS) {
+                assertIntentHasExposedActivities(queryIntent);
+            }
+        }
+
         if (InstrumentationRegistry.getContext().getPackageManager()
                 .hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
             for (Intent queryIntent : EXPECTED_EXPOSED_CAMERA_INTENTS) {
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/WebViewTest.java b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/WebViewTest.java
index 11d1c60..177583e 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/WebViewTest.java
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/WebViewTest.java
@@ -16,6 +16,7 @@
 
 package com.android.cts.ephemeralapp1;
 
+import android.content.pm.PackageManager;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.UiThreadTest;
 
@@ -34,6 +35,9 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
+        if (!hasWebViewFeature()) {
+            return;
+        }
         final WebViewTestActivity activity = getActivity();
         mWebView = activity.getWebView();
         mOnUiThread = new WebViewOnUiThread(this, mWebView);
@@ -41,12 +45,22 @@
 
     @Override
     protected void tearDown() throws Exception {
-        mOnUiThread.cleanUp();
+        if (mOnUiThread != null) {
+            mOnUiThread.cleanUp();
+        }
         super.tearDown();
     }
 
     @UiThreadTest
     public void testWebViewLoads() throws Exception {
+        // Webview is not supported on Watches
+        if (!hasWebViewFeature()) {
+            return;
+        }
         mOnUiThread.loadUrlAndWaitForCompletion("about:blank");
     }
+
+    private boolean hasWebViewFeature() {
+        return getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_WEBVIEW);
+    }
 }
diff --git a/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java b/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
index 61eaa3c..54f1a92 100644
--- a/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
+++ b/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
@@ -459,7 +459,7 @@
         devicePlatFcFile = File.createTempFile("file_contexts", ".tmp");
         devicePlatFcFile.deleteOnExit();
         if (!mDevice.pullFile("/system/etc/selinux/plat_file_contexts", devicePlatFcFile)) {
-            mDevice.pullFile("/file_contexts.bin", devicePlatFcFile);
+            mDevice.pullFile("/plat_file_contexts", devicePlatFcFile);
         }
 
         /* retrieve the AOSP file_contexts file from jar */
@@ -546,11 +546,12 @@
         deviceNonplatFcFile.deleteOnExit();
         if (mDevice.pullFile("/system/etc/selinux/plat_file_contexts", devicePlatFcFile)) {
             mDevice.pullFile("/vendor/etc/selinux/nonplat_file_contexts", deviceNonplatFcFile);
-            appendTo(devicePlatFcFile.getAbsolutePath(),
-                         deviceNonplatFcFile.getAbsolutePath());
         } else {
-            mDevice.pullFile("/file_contexts.bin", devicePlatFcFile);
+            mDevice.pullFile("/plat_file_contexts", devicePlatFcFile);
+            mDevice.pullFile("/nonplat_file_contexts", deviceNonplatFcFile);
         }
+        appendTo(devicePlatFcFile.getAbsolutePath(),
+                deviceNonplatFcFile.getAbsolutePath());
 
         /* run checkfc sepolicy file_contexts */
         ProcessBuilder pb = new ProcessBuilder(checkFc.getAbsolutePath(),
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayLockedKeyguardTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayLockedKeyguardTests.java
new file mode 100644
index 0000000..d520f2c
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayLockedKeyguardTests.java
@@ -0,0 +1,79 @@
+/*
+ * 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.server.cts;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+
+import static android.server.cts.ActivityManagerState.STATE_RESUMED;
+import static android.server.cts.ActivityManagerState.STATE_STOPPED;
+import static android.server.cts.StateLogger.logE;
+
+/**
+ * Display tests that require a locked keyguard.
+ *
+ * Build: mmma -j32 cts/hostsidetests/services
+ * Run: cts/hostsidetests/services/activityandwindowmanager/util/run-test CtsServicesHostTestCases android.server.cts.ActivityManagerDisplayLockedKeyguardTests
+ */
+public class ActivityManagerDisplayLockedKeyguardTests extends ActivityManagerDisplayTestBase {
+
+    private static final String TEST_ACTIVITY_NAME = "TestActivity";
+    private static final String VIRTUAL_DISPLAY_ACTIVITY = "VirtualDisplayActivity";
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        setLockCredential();
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        try {
+            removeLockCredential();
+            gotoKeyguard();
+        } catch (DeviceNotAvailableException e) {
+            logE(e.getMessage());
+        }
+        super.tearDown();
+    }
+
+    /**
+     * Test that virtual display content is hidden when device is locked.
+     */
+    public void testVirtualDisplayHidesContentWhenLocked() throws Exception {
+        if (!supportsMultiDisplay() || !isHandheld()) { return; }
+
+        // Create new usual virtual display.
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this).build();
+        mAmWmState.assertVisibility(VIRTUAL_DISPLAY_ACTIVITY, true /* visible */);
+
+        // Launch activity on new secondary display.
+        launchActivityOnDisplay(TEST_ACTIVITY_NAME, newDisplay.mDisplayId);
+        mAmWmState.assertVisibility(TEST_ACTIVITY_NAME, true /* visible */);
+
+        // Lock the device.
+        gotoKeyguard();
+        mAmWmState.waitForKeyguardShowingAndNotOccluded(mDevice);
+        mAmWmState.waitForActivityState(mDevice, TEST_ACTIVITY_NAME, STATE_STOPPED);
+        mAmWmState.assertVisibility(TEST_ACTIVITY_NAME, false /* visible */);
+
+        // Unlock and check if visibility is back.
+        unlockDeviceWithCredential();
+        mAmWmState.waitForKeyguardGone(mDevice);
+        mAmWmState.waitForActivityState(mDevice, TEST_ACTIVITY_NAME, STATE_RESUMED);
+        mAmWmState.assertVisibility(TEST_ACTIVITY_NAME, true /* visible */);
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTestBase.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTestBase.java
new file mode 100644
index 0000000..cf44ad7
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTestBase.java
@@ -0,0 +1,371 @@
+/*
+ * 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.server.cts;
+
+import com.android.tradefed.device.CollectingOutputReceiver;
+import com.android.tradefed.device.DeviceNotAvailableException;
+
+import static android.server.cts.ActivityAndWindowManagersState.DEFAULT_DISPLAY_ID;
+import static android.server.cts.StateLogger.log;
+import static android.server.cts.StateLogger.logE;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Base class for ActivityManager display tests.
+ *
+ * @see ActivityManagerDisplayTests
+ * @see ActivityManagerDisplayLockedKeyguardTests
+ */
+public class ActivityManagerDisplayTestBase extends ActivityManagerTestBase {
+
+    static final int CUSTOM_DENSITY_DPI = 222;
+
+    private static final String DUMPSYS_ACTIVITY_PROCESSES = "dumpsys activity processes";
+    private static final String VIRTUAL_DISPLAY_ACTIVITY = "VirtualDisplayActivity";
+    private static final int INVALID_DENSITY_DPI = -1;
+
+    private boolean mVirtualDisplayCreated;
+
+    /** Temp storage used for parsing. */
+    final LinkedList<String> mDumpLines = new LinkedList<>();
+
+    @Override
+    protected void tearDown() throws Exception {
+        try {
+            destroyVirtualDisplays();
+        } catch (DeviceNotAvailableException e) {
+            logE(e.getMessage());
+        }
+        super.tearDown();
+    }
+
+    /** Contains the configurations applied to attached displays. */
+    static final class DisplayState {
+        int mDisplayId;
+        String mOverrideConfig;
+
+        private DisplayState(int displayId, String overrideConfig) {
+            mDisplayId = displayId;
+            mOverrideConfig = overrideConfig;
+        }
+
+        private int getWidth() {
+            final String[] configParts = mOverrideConfig.split(" ");
+            for (String part : configParts) {
+                if (part.endsWith("dp") && part.startsWith("w")) {
+                    final String widthString = part.substring(1, part.length() - 3);
+                    return Integer.parseInt(widthString);
+                }
+            }
+
+            return -1;
+        }
+
+        private int getHeight() {
+            final String[] configParts = mOverrideConfig.split(" ");
+            for (String part : configParts) {
+                if (part.endsWith("dp") && part.startsWith("h")) {
+                    final String heightString = part.substring(1, part.length() - 3);
+                    return Integer.parseInt(heightString);
+                }
+            }
+
+            return -1;
+        }
+
+        int getDpi() {
+            final String[] configParts = mOverrideConfig.split(" ");
+            for (String part : configParts) {
+                if (part.endsWith("dpi")) {
+                    final String densityDpiString = part.substring(0, part.length() - 3);
+                    return Integer.parseInt(densityDpiString);
+                }
+            }
+
+            return -1;
+        }
+    }
+
+    /** Contains the configurations applied to attached displays. */
+    static final class ReportedDisplays {
+        private static final Pattern sGlobalConfigurationPattern =
+                Pattern.compile("mGlobalConfiguration: (\\{.*\\})");
+        private static final Pattern sDisplayOverrideConfigurationsPattern =
+                Pattern.compile("Display override configurations:");
+        private static final Pattern sDisplayConfigPattern =
+                Pattern.compile("(\\d+): (\\{.*\\})");
+
+        String mGlobalConfig;
+        private Map<Integer, DisplayState> mDisplayStates = new HashMap<>();
+
+        static ReportedDisplays create(LinkedList<String> dump) {
+            final ReportedDisplays result = new ReportedDisplays();
+
+            while (!dump.isEmpty()) {
+                final String line = dump.pop().trim();
+
+                Matcher matcher = sDisplayOverrideConfigurationsPattern.matcher(line);
+                if (matcher.matches()) {
+                    log(line);
+                    while (ReportedDisplays.shouldContinueExtracting(dump, sDisplayConfigPattern)) {
+                        final String displayOverrideConfigLine = dump.pop().trim();
+                        log(displayOverrideConfigLine);
+                        matcher = sDisplayConfigPattern.matcher(displayOverrideConfigLine);
+                        matcher.matches();
+                        final Integer displayId = Integer.valueOf(matcher.group(1));
+                        result.mDisplayStates.put(displayId,
+                                new DisplayState(displayId, matcher.group(2)));
+                    }
+                    continue;
+                }
+
+                matcher = sGlobalConfigurationPattern.matcher(line);
+                if (matcher.matches()) {
+                    log(line);
+                    result.mGlobalConfig = matcher.group(1);
+                }
+            }
+
+            return result;
+        }
+
+        /** Check if next line in dump matches the pattern and we should continue extracting. */
+        static boolean shouldContinueExtracting(LinkedList<String> dump, Pattern matchingPattern) {
+            if (dump.isEmpty()) {
+                return false;
+            }
+
+            final String line = dump.peek().trim();
+            return matchingPattern.matcher(line).matches();
+        }
+
+        DisplayState getDisplayState(int displayId) {
+            return mDisplayStates.get(displayId);
+        }
+
+        /** Return the display state with width, height, dpi */
+        DisplayState getDisplayState(int width, int height, int dpi) {
+            for (Map.Entry<Integer, DisplayState> entry : mDisplayStates.entrySet()) {
+                final DisplayState ds = entry.getValue();
+                if (ds.mDisplayId != DEFAULT_DISPLAY_ID && ds.getDpi() == dpi
+                        && ds.getWidth() == width && ds.getHeight() == height) {
+                    return ds;
+                }
+            }
+            return null;
+        }
+
+        /** Check if reported state is valid. */
+        boolean isValidState(int expectedDisplayCount) {
+            if (mDisplayStates.size() != expectedDisplayCount) {
+                return false;
+            }
+
+            for (Map.Entry<Integer, DisplayState> entry : mDisplayStates.entrySet()) {
+                final DisplayState ds = entry.getValue();
+                if (ds.mDisplayId != DEFAULT_DISPLAY_ID && ds.getDpi() == -1) {
+                    return false;
+                }
+            }
+            return true;
+        }
+    }
+
+    ReportedDisplays getDisplaysStates() throws DeviceNotAvailableException {
+        final CollectingOutputReceiver outputReceiver = new CollectingOutputReceiver();
+        mDevice.executeShellCommand(DUMPSYS_ACTIVITY_PROCESSES, outputReceiver);
+        String dump = outputReceiver.getOutput();
+        mDumpLines.clear();
+
+        Collections.addAll(mDumpLines, dump.split("\\n"));
+
+        return ReportedDisplays.create(mDumpLines);
+    }
+
+    /** Find the display that was not originally reported in oldDisplays and added in newDisplays */
+    private List<ActivityManagerDisplayTests.DisplayState> findNewDisplayStates(
+            ReportedDisplays oldDisplays, ReportedDisplays newDisplays) {
+        final ArrayList<DisplayState> displays = new ArrayList();
+
+        for (Integer displayId : newDisplays.mDisplayStates.keySet()) {
+            if (!oldDisplays.mDisplayStates.containsKey(displayId)) {
+                displays.add(newDisplays.getDisplayState(displayId));
+            }
+        }
+
+        return displays;
+    }
+
+    /**
+     * Create new virtual display.
+     * @param densityDpi provide custom density for the display.
+     * @param launchInSplitScreen start {@link VirtualDisplayActivity} to side from
+     *                            {@link LaunchingActivity} on primary display.
+     * @param publicDisplay make display public.
+     * @param resizeDisplay should resize display when surface size changes.
+     * @param launchActivity should launch test activity immediately after display creation.
+     * @return {@link ActivityManagerDisplayTests.DisplayState} of newly created display.
+     * @throws Exception
+     */
+    private List<ActivityManagerDisplayTests.DisplayState> createVirtualDisplays(int densityDpi,
+            boolean launchInSplitScreen, boolean publicDisplay, boolean resizeDisplay,
+            String launchActivity, int displayCount) throws Exception {
+        // Start an activity that is able to create virtual displays.
+        if (launchInSplitScreen) {
+            getLaunchActivityBuilder().setToSide(true)
+                    .setTargetActivityName(VIRTUAL_DISPLAY_ACTIVITY).execute();
+        } else {
+            launchActivity(VIRTUAL_DISPLAY_ACTIVITY);
+        }
+        mAmWmState.computeState(mDevice, new String[] {VIRTUAL_DISPLAY_ACTIVITY},
+                false /* compareTaskAndStackBounds */);
+        final ActivityManagerDisplayTests.ReportedDisplays originalDS = getDisplaysStates();
+        final int originalDisplayCount = originalDS.mDisplayStates.size();
+
+        // Create virtual display with custom density dpi.
+        executeShellCommand(getCreateVirtualDisplayCommand(densityDpi, publicDisplay, resizeDisplay,
+                launchActivity, displayCount));
+        mVirtualDisplayCreated = true;
+
+        // Wait for the virtual display to be created and get configurations.
+        final ActivityManagerDisplayTests.ReportedDisplays ds =
+                getDisplayStateAfterChange(originalDisplayCount + displayCount);
+        assertEquals("New virtual display must be created",
+                originalDisplayCount + displayCount, ds.mDisplayStates.size());
+
+        // Find the newly added display.
+        final List<ActivityManagerDisplayTests.DisplayState> newDisplays
+                = findNewDisplayStates(originalDS, ds);
+        assertTrue("New virtual display must be created", displayCount == newDisplays.size());
+
+        return newDisplays;
+    }
+
+    /**
+     * Destroy existing virtual display.
+     */
+    void destroyVirtualDisplays() throws Exception {
+        if (mVirtualDisplayCreated) {
+            executeShellCommand(getDestroyVirtualDisplayCommand());
+            mVirtualDisplayCreated = false;
+        }
+    }
+
+    static class VirtualDisplayBuilder {
+        private final ActivityManagerDisplayTestBase mTests;
+
+        private int mDensityDpi = CUSTOM_DENSITY_DPI;
+        private boolean mLaunchInSplitScreen = false;
+        private boolean mPublicDisplay = false;
+        private boolean mResizeDisplay = true;
+        private String mLaunchActivity = null;
+
+        public VirtualDisplayBuilder(ActivityManagerDisplayTestBase tests) {
+            mTests = tests;
+        }
+
+        public VirtualDisplayBuilder setDensityDpi(int densityDpi) {
+            mDensityDpi = densityDpi;
+            return this;
+        }
+
+        public VirtualDisplayBuilder setLaunchInSplitScreen(boolean launchInSplitScreen) {
+            mLaunchInSplitScreen = launchInSplitScreen;
+            return this;
+        }
+
+        public VirtualDisplayBuilder setPublicDisplay(boolean publicDisplay) {
+            mPublicDisplay = publicDisplay;
+            return this;
+        }
+
+        public VirtualDisplayBuilder setResizeDisplay(boolean resizeDisplay) {
+            mResizeDisplay = resizeDisplay;
+            return this;
+        }
+
+        public VirtualDisplayBuilder setLaunchActivity(String launchActivity) {
+            mLaunchActivity = launchActivity;
+            return this;
+        }
+
+        public DisplayState build() throws Exception {
+            final List<DisplayState> displays = build(1);
+            return displays != null && !displays.isEmpty() ? displays.get(0) : null;
+        }
+
+        public List<DisplayState> build(int count) throws Exception {
+            return mTests.createVirtualDisplays(mDensityDpi, mLaunchInSplitScreen, mPublicDisplay,
+                    mResizeDisplay, mLaunchActivity, count);
+        }
+    }
+
+    private static String getCreateVirtualDisplayCommand(int densityDpi, boolean publicDisplay,
+            boolean resizeDisplay, String launchActivity, int displayCount) {
+        final StringBuilder commandBuilder
+                = new StringBuilder(getAmStartCmd(VIRTUAL_DISPLAY_ACTIVITY));
+        commandBuilder.append(" -f 0x20000000");
+        commandBuilder.append(" --es command create_display");
+        if (densityDpi != INVALID_DENSITY_DPI) {
+            commandBuilder.append(" --ei density_dpi ").append(densityDpi);
+        }
+        commandBuilder.append(" --ei count ").append(displayCount);
+        commandBuilder.append(" --ez public_display ").append(publicDisplay);
+        commandBuilder.append(" --ez resize_display ").append(resizeDisplay);
+        if (launchActivity != null) {
+            commandBuilder.append(" --es launch_target_activity ").append(launchActivity);
+        }
+        return commandBuilder.toString();
+    }
+
+    private static String getDestroyVirtualDisplayCommand() {
+        return getAmStartCmd(VIRTUAL_DISPLAY_ACTIVITY) + " -f 0x20000000" +
+                " --es command destroy_display";
+    }
+
+    /** Wait for provided number of displays and report their configurations. */
+    ReportedDisplays getDisplayStateAfterChange(int expectedDisplayCount)
+            throws DeviceNotAvailableException {
+        ReportedDisplays ds = getDisplaysStates();
+
+        int retriesLeft = 5;
+        while (!ds.isValidState(expectedDisplayCount) && retriesLeft-- > 0) {
+            log("***Waiting for the correct number of displays...");
+            try {
+                Thread.sleep(1000);
+            } catch (InterruptedException e) {
+                log(e.toString());
+            }
+            ds = getDisplaysStates();
+        }
+
+        return ds;
+    }
+
+    /** Checks if the device supports multi-display. */
+    boolean supportsMultiDisplay() throws Exception {
+        return hasDeviceFeature("android.software.activities_on_secondary_displays");
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
index 9ea71d8..4e07eb4 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
@@ -20,19 +20,14 @@
 import com.android.tradefed.device.CollectingOutputReceiver;
 import com.android.tradefed.device.DeviceNotAvailableException;
 
-import java.awt.Rectangle;
-import java.util.ArrayList;
 import java.util.Collections;
-import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
-import java.util.Map;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 import static android.server.cts.ActivityAndWindowManagersState.DEFAULT_DISPLAY_ID;
 import static android.server.cts.ActivityManagerState.STATE_RESUMED;
-import static android.server.cts.ActivityManagerState.STATE_STOPPED;
 import static android.server.cts.StateLogger.log;
 import static android.server.cts.StateLogger.logE;
 
@@ -40,8 +35,7 @@
  * Build: mmma -j32 cts/hostsidetests/services
  * Run: cts/hostsidetests/services/activityandwindowmanager/util/run-test CtsServicesHostTestCases android.server.cts.ActivityManagerDisplayTests
  */
-public class ActivityManagerDisplayTests extends ActivityManagerTestBase {
-    private static final String DUMPSYS_ACTIVITY_PROCESSES = "dumpsys activity processes";
+public class ActivityManagerDisplayTests extends ActivityManagerDisplayTestBase {
     private static final String WM_SIZE = "wm size";
     private static final String WM_DENSITY = "wm density";
 
@@ -54,17 +48,10 @@
     private static final String VR_TEST_ACTIVITY_NAME = "VrTestActivity";
     private static final String SECOND_PACKAGE_NAME = "android.server.cts.second";
     private static final String THIRD_PACKAGE_NAME = "android.server.cts.third";
-    private static final int INVALID_DENSITY_DPI = -1;
-    private static final int CUSTOM_DENSITY_DPI = 222;
     private static final int VR_VIRTUAL_DISPLAY_WIDTH = 70;
     private static final int VR_VIRTUAL_DISPLAY_HEIGHT = 90;
     private static final int VR_VIRTUAL_DISPLAY_DPI = 320;
 
-    /** Temp storage used for parsing. */
-    private final LinkedList<String> mDumpLines = new LinkedList<>();
-
-    private boolean mVirtualDisplayCreated;
-
     /** Physical display metrics and overrides in the beginning of the test. */
     private ReportedDisplayMetrics mInitialDisplayMetrics;
 
@@ -77,7 +64,6 @@
     @Override
     protected void tearDown() throws Exception {
         try {
-            destroyVirtualDisplays();
             enablePersistentVrMode(false);
             restoreDisplayMetricsOverrides();
         } catch (DeviceNotAvailableException e) {
@@ -131,9 +117,6 @@
         // Find the density of created display.
         final int newDensityDpi = newDisplay.getDpi();
         assertEquals(CUSTOM_DENSITY_DPI, newDensityDpi);
-
-        // Destroy the created display.
-        executeShellCommand(getDestroyVirtualDisplayCommand());
     }
 
     /**
@@ -1001,31 +984,6 @@
     }
 
     /**
-     * Test that virtual display content is hidden when device is locked.
-     */
-    public void testVirtualDisplayHidesContentWhenLocked() throws Exception {
-        if (!supportsMultiDisplay() || !isHandheld()) { return; }
-
-        // Create new usual virtual display.
-        final DisplayState newDisplay = new VirtualDisplayBuilder(this).build();
-        mAmWmState.assertVisibility(VIRTUAL_DISPLAY_ACTIVITY, true /* visible */);
-
-        // Launch activity on new secondary display.
-        launchActivityOnDisplay(TEST_ACTIVITY_NAME, newDisplay.mDisplayId);
-        mAmWmState.assertVisibility(TEST_ACTIVITY_NAME, true /* visible */);
-
-        // Lock the device.
-        sleepDevice();
-        mAmWmState.waitForActivityState(mDevice, TEST_ACTIVITY_NAME, STATE_STOPPED);
-        mAmWmState.assertVisibility(TEST_ACTIVITY_NAME, false /* visible */);
-
-        // Unlock and check if visibility is back.
-        wakeUpAndUnlockDevice();
-        mAmWmState.waitForActivityState(mDevice, TEST_ACTIVITY_NAME, STATE_RESUMED);
-        mAmWmState.assertVisibility(TEST_ACTIVITY_NAME, true /* visible */);
-    }
-
-    /**
      * Test that all activities that were on the private display are destroyed on display removal.
      */
     @Presubmit
@@ -1526,317 +1484,8 @@
         }
     }
 
-    /** Find the display that was not originally reported in oldDisplays and added in newDisplays */
-    private List<DisplayState> findNewDisplayStates(ReportedDisplays oldDisplays,
-            ReportedDisplays newDisplays) {
-        final ArrayList<DisplayState> displays = new ArrayList();
-
-        for (Integer displayId : newDisplays.mDisplayStates.keySet()) {
-            if (!oldDisplays.mDisplayStates.containsKey(displayId)) {
-                displays.add(newDisplays.getDisplayState(displayId));
-            }
-        }
-
-        return displays;
-    }
-
-    /**
-     * Create new virtual display.
-     * @param densityDpi provide custom density for the display.
-     * @param launchInSplitScreen start {@link VirtualDisplayActivity} to side from
-     *                            {@link LaunchingActivity} on primary display.
-     * @param publicDisplay make display public.
-     * @param resizeDisplay should resize display when surface size changes.
-     * @param launchActivity should launch test activity immediately after display creation.
-     * @return {@link DisplayState} of newly created display.
-     * @throws Exception
-     */
-    private List<DisplayState> createVirtualDisplays(int densityDpi, boolean launchInSplitScreen,
-            boolean publicDisplay, boolean resizeDisplay, String launchActivity, int displayCount)
-            throws Exception {
-        // Start an activity that is able to create virtual displays.
-        if (launchInSplitScreen) {
-            getLaunchActivityBuilder().setToSide(true)
-                    .setTargetActivityName(VIRTUAL_DISPLAY_ACTIVITY).execute();
-        } else {
-            launchActivity(VIRTUAL_DISPLAY_ACTIVITY);
-        }
-        mAmWmState.computeState(mDevice, new String[] {VIRTUAL_DISPLAY_ACTIVITY},
-                false /* compareTaskAndStackBounds */);
-        final ReportedDisplays originalDS = getDisplaysStates();
-        final int originalDisplayCount = originalDS.mDisplayStates.size();
-
-        // Create virtual display with custom density dpi.
-        executeShellCommand(getCreateVirtualDisplayCommand(densityDpi, publicDisplay, resizeDisplay,
-                launchActivity, displayCount));
-        mVirtualDisplayCreated = true;
-
-        // Wait for the virtual display to be created and get configurations.
-        final ReportedDisplays ds =
-                getDisplayStateAfterChange(originalDisplayCount + displayCount);
-        assertEquals("New virtual display must be created",
-                originalDisplayCount + displayCount, ds.mDisplayStates.size());
-
-        // Find the newly added display.
-        final List<DisplayState> newDisplays = findNewDisplayStates(originalDS, ds);
-        assertTrue("New virtual display must be created", displayCount == newDisplays.size());
-
-        return newDisplays;
-    }
-
-    /**
-     * Destroy existing virtual display.
-     */
-    private void destroyVirtualDisplays() throws Exception {
-        if (mVirtualDisplayCreated) {
-            executeShellCommand(getDestroyVirtualDisplayCommand());
-            mVirtualDisplayCreated = false;
-        }
-    }
-
-    /** Wait for provided number of displays and report their configurations. */
-    private ReportedDisplays getDisplayStateAfterChange(int expectedDisplayCount)
-            throws DeviceNotAvailableException {
-        ReportedDisplays ds = getDisplaysStates();
-
-        int retriesLeft = 5;
-        while (!ds.isValidState(expectedDisplayCount) && retriesLeft-- > 0) {
-            log("***Waiting for the correct number of displays...");
-            try {
-                Thread.sleep(1000);
-            } catch (InterruptedException e) {
-                log(e.toString());
-            }
-            ds = getDisplaysStates();
-        }
-
-        return ds;
-    }
-
-    private ReportedDisplays getDisplaysStates() throws DeviceNotAvailableException {
-        final CollectingOutputReceiver outputReceiver = new CollectingOutputReceiver();
-        mDevice.executeShellCommand(DUMPSYS_ACTIVITY_PROCESSES, outputReceiver);
-        String dump = outputReceiver.getOutput();
-        mDumpLines.clear();
-
-        Collections.addAll(mDumpLines, dump.split("\\n"));
-
-        return ReportedDisplays.create(mDumpLines);
-    }
-
-    /** Contains the configurations applied to attached displays. */
-    private static final class DisplayState {
-        private int mDisplayId;
-        private String mOverrideConfig;
-
-        private DisplayState(int displayId, String overrideConfig) {
-            mDisplayId = displayId;
-            mOverrideConfig = overrideConfig;
-        }
-
-        private int getWidth() {
-            final String[] configParts = mOverrideConfig.split(" ");
-            for (String part : configParts) {
-                if (part.endsWith("dp") && part.startsWith("w")) {
-                    final String widthString = part.substring(1, part.length() - 3);
-                    return Integer.parseInt(widthString);
-                }
-            }
-
-            return -1;
-        }
-
-        private int getHeight() {
-            final String[] configParts = mOverrideConfig.split(" ");
-            for (String part : configParts) {
-                if (part.endsWith("dp") && part.startsWith("h")) {
-                    final String heightString = part.substring(1, part.length() - 3);
-                    return Integer.parseInt(heightString);
-                }
-            }
-
-            return -1;
-        }
-
-        private int getDpi() {
-            final String[] configParts = mOverrideConfig.split(" ");
-            for (String part : configParts) {
-                if (part.endsWith("dpi")) {
-                    final String densityDpiString = part.substring(0, part.length() - 3);
-                    return Integer.parseInt(densityDpiString);
-                }
-            }
-
-            return -1;
-        }
-    }
-
-
-
-    /** Contains the configurations applied to attached displays. */
-    private static final class ReportedDisplays {
-        private static final Pattern sGlobalConfigurationPattern =
-                Pattern.compile("mGlobalConfiguration: (\\{.*\\})");
-        private static final Pattern sDisplayOverrideConfigurationsPattern =
-                Pattern.compile("Display override configurations:");
-        private static final Pattern sDisplayConfigPattern =
-                Pattern.compile("(\\d+): (\\{.*\\})");
-
-        private String mGlobalConfig;
-        private Map<Integer, DisplayState> mDisplayStates = new HashMap<>();
-
-        static ReportedDisplays create(LinkedList<String> dump) {
-            final ReportedDisplays result = new ReportedDisplays();
-
-            while (!dump.isEmpty()) {
-                final String line = dump.pop().trim();
-
-                Matcher matcher = sDisplayOverrideConfigurationsPattern.matcher(line);
-                if (matcher.matches()) {
-                    log(line);
-                    while (ReportedDisplays.shouldContinueExtracting(dump, sDisplayConfigPattern)) {
-                        final String displayOverrideConfigLine = dump.pop().trim();
-                        log(displayOverrideConfigLine);
-                        matcher = sDisplayConfigPattern.matcher(displayOverrideConfigLine);
-                        matcher.matches();
-                        final Integer displayId = Integer.valueOf(matcher.group(1));
-                        result.mDisplayStates.put(displayId,
-                                new DisplayState(displayId, matcher.group(2)));
-                    }
-                    continue;
-                }
-
-                matcher = sGlobalConfigurationPattern.matcher(line);
-                if (matcher.matches()) {
-                    log(line);
-                    result.mGlobalConfig = matcher.group(1);
-                }
-            }
-
-            return result;
-        }
-
-        /** Check if next line in dump matches the pattern and we should continue extracting. */
-        static boolean shouldContinueExtracting(LinkedList<String> dump, Pattern matchingPattern) {
-            if (dump.isEmpty()) {
-                return false;
-            }
-
-            final String line = dump.peek().trim();
-            return matchingPattern.matcher(line).matches();
-        }
-
-        DisplayState getDisplayState(int displayId) {
-            return mDisplayStates.get(displayId);
-        }
-
-        /** Return the display state with width, height, dpi */
-        DisplayState getDisplayState(int width, int height, int dpi) {
-            for (Map.Entry<Integer, DisplayState> entry : mDisplayStates.entrySet()) {
-                final DisplayState ds = entry.getValue();
-                if (ds.mDisplayId != DEFAULT_DISPLAY_ID && ds.getDpi() == dpi
-                    && ds.getWidth() == width && ds.getHeight() == height) {
-                    return ds;
-                }
-            }
-            return null;
-        }
-
-        /** Check if reported state is valid. */
-        boolean isValidState(int expectedDisplayCount) {
-            if (mDisplayStates.size() != expectedDisplayCount) {
-                return false;
-            }
-
-            for (Map.Entry<Integer, DisplayState> entry : mDisplayStates.entrySet()) {
-                final DisplayState ds = entry.getValue();
-                if (ds.mDisplayId != DEFAULT_DISPLAY_ID && ds.getDpi() == -1) {
-                    return false;
-                }
-            }
-            return true;
-        }
-    }
-
-    private static class VirtualDisplayBuilder {
-        private final ActivityManagerDisplayTests mTests;
-
-        private int mDensityDpi = CUSTOM_DENSITY_DPI;
-        private boolean mLaunchInSplitScreen = false;
-        private boolean mPublicDisplay = false;
-        private boolean mResizeDisplay = true;
-        private String mLaunchActivity = null;
-
-        public VirtualDisplayBuilder(ActivityManagerDisplayTests tests) {
-            mTests = tests;
-        }
-
-        public VirtualDisplayBuilder setDensityDpi(int densityDpi) {
-            mDensityDpi = densityDpi;
-            return this;
-        }
-
-        public VirtualDisplayBuilder setLaunchInSplitScreen(boolean launchInSplitScreen) {
-            mLaunchInSplitScreen = launchInSplitScreen;
-            return this;
-        }
-
-        public VirtualDisplayBuilder setPublicDisplay(boolean publicDisplay) {
-            mPublicDisplay = publicDisplay;
-            return this;
-        }
-
-        public VirtualDisplayBuilder setResizeDisplay(boolean resizeDisplay) {
-            mResizeDisplay = resizeDisplay;
-            return this;
-        }
-
-        public VirtualDisplayBuilder setLaunchActivity(String launchActivity) {
-            mLaunchActivity = launchActivity;
-            return this;
-        }
-
-        public DisplayState build() throws Exception {
-            final List<DisplayState> displays = build(1);
-            return displays != null && !displays.isEmpty() ? displays.get(0) : null;
-        }
-
-        public List<DisplayState> build(int count) throws Exception {
-            return mTests.createVirtualDisplays(mDensityDpi, mLaunchInSplitScreen, mPublicDisplay,
-                    mResizeDisplay, mLaunchActivity, count);
-        }
-    }
-
-    private static String getCreateVirtualDisplayCommand(int densityDpi, boolean publicDisplay,
-            boolean resizeDisplay, String launchActivity, int displayCount) {
-        final StringBuilder commandBuilder
-                = new StringBuilder(getAmStartCmd(VIRTUAL_DISPLAY_ACTIVITY));
-        commandBuilder.append(" -f 0x20000000");
-        commandBuilder.append(" --es command create_display");
-        if (densityDpi != INVALID_DENSITY_DPI) {
-            commandBuilder.append(" --ei density_dpi ").append(densityDpi);
-        }
-        commandBuilder.append(" --ei count ").append(displayCount);
-        commandBuilder.append(" --ez public_display ").append(publicDisplay);
-        commandBuilder.append(" --ez resize_display ").append(resizeDisplay);
-        if (launchActivity != null) {
-            commandBuilder.append(" --es launch_target_activity ").append(launchActivity);
-        }
-        return commandBuilder.toString();
-    }
-
-    private static String getDestroyVirtualDisplayCommand() {
-        return getAmStartCmd(VIRTUAL_DISPLAY_ACTIVITY) + " -f 0x20000000" +
-                " --es command destroy_display";
-    }
-
     private static String getResizeVirtualDisplayCommand() {
         return getAmStartCmd(VIRTUAL_DISPLAY_ACTIVITY) + " -f 0x20000000" +
                 " --es command resize_display";
     }
-
-    /** Checks if the device supports multi-display. */
-    private boolean supportsMultiDisplay() throws Exception {
-        return hasDeviceFeature("android.software.activities_on_secondary_displays");
-    }
 }
diff --git a/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java b/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java
index 756db48..eb18aed 100755
--- a/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java
+++ b/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java
@@ -35,8 +35,7 @@
 public class ComparisonTask implements Callable<Pair<String, File>> {
     private static final String TAG = "ComparisonTask";
 
-    /** Maximum allowed LAB distance between two pixels. */
-    private static final double IMAGE_THRESHOLD = 0.76;
+    private static final int IMAGE_THRESHOLD = 4;
 
     /** Neutral gray for blending colors. */
     private static final int GRAY = 0xFF808080;
@@ -99,7 +98,7 @@
      * @return {@code true} if the images are similar, false otherwise
      */
     private static boolean compare(BufferedImage reference, BufferedImage generated,
-            double threshold) {
+            int threshold) {
         final int w = generated.getWidth();
         final int h = generated.getHeight();
         if (w != reference.getWidth() || h != reference.getHeight()) {
@@ -113,9 +112,15 @@
             for (int j = 0; j < h; j++) {
                 final int p1 = reference.getRGB(i, j);
                 final int p2 = generated.getRGB(i, j);
-                final double dist = computeLabDistance(p1, p2);
-                if (dist > threshold) {
-                    System.err.println("fail " + dist);
+
+                final int dr = getAlphaScaledRed(p1) - getAlphaScaledRed(p2);
+                final int dg = getAlphaScaledGreen(p1) - getAlphaScaledGreen(p2);
+                final int db = getAlphaScaledBlue(p1) - getAlphaScaledBlue(p2);
+
+                if (Math.abs(db) > threshold ||
+                    Math.abs(dg) > threshold ||
+                    Math.abs(dr) > threshold) {
+                    System.err.println("fail dr=" + dr+ " dg=" + dg+ " db=" + db);
 
                     consecutive++;
 
diff --git a/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java b/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java
index 7083875..eca8970 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java
@@ -324,7 +324,7 @@
                 }
                 if (response == null) {
                     dumpStructure("onFillRequest() without response", contexts);
-                    throw new IllegalStateException("No CannedResponse");
+                    throw new RetryableException("No CannedResponse");
                 }
                 if (response == NO_RESPONSE) {
                     Log.d(TAG, "onFillRequest(): replying with null");
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
index 2242ef7..4d2581f 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
@@ -2538,7 +2538,7 @@
         setUserRestrictionForAutofill(true);
         try {
             waitUntilDisconnected();
-            assertNoDanglingSessions();
+            eventually(() -> assertNoDanglingSessions());
             assertThat(afm.isEnabled()).isFalse();
             assertThat(afm.isAutofillSupported()).isFalse();
 
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3
new file mode 100644
index 0000000..af2c7ac
--- /dev/null
+++ b/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3
new file mode 100644
index 0000000..d1c88fe
--- /dev/null
+++ b/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3
new file mode 100644
index 0000000..ddae12f
--- /dev/null
+++ b/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3
new file mode 100644
index 0000000..78bad13
--- /dev/null
+++ b/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3
new file mode 100644
index 0000000..c7d8429
--- /dev/null
+++ b/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3
new file mode 100644
index 0000000..c8d4afa
--- /dev/null
+++ b/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3
Binary files differ
diff --git a/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java b/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java
index 9b5f001..f0b303b 100644
--- a/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java
+++ b/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java
@@ -21,6 +21,7 @@
 import android.graphics.BitmapFactory;
 import android.media.ExifInterface;
 import android.os.Environment;
+import android.os.FileUtils;
 import android.test.AndroidTestCase;
 import android.util.Log;
 import android.system.ErrnoException;
@@ -70,7 +71,7 @@
             ExifInterface.TAG_MAKE,
             ExifInterface.TAG_MODEL,
             ExifInterface.TAG_F_NUMBER,
-            ExifInterface.TAG_DATETIME,
+            ExifInterface.TAG_DATETIME_ORIGINAL,
             ExifInterface.TAG_EXPOSURE_TIME,
             ExifInterface.TAG_FLASH,
             ExifInterface.TAG_FOCAL_LENGTH,
@@ -107,7 +108,7 @@
         public final String make;
         public final String model;
         public final float aperture;
-        public final String datetime;
+        public final String dateTimeOriginal;
         public final float exposureTime;
         public final float flash;
         public final String focalLength;
@@ -153,7 +154,7 @@
             make = getString(typedArray, index++);
             model = getString(typedArray, index++);
             aperture = typedArray.getFloat(index++, 0f);
-            datetime = getString(typedArray, index++);
+            dateTimeOriginal = getString(typedArray, index++);
             exposureTime = typedArray.getFloat(index++, 0f);
             flash = typedArray.getFloat(index++, 0f);
             focalLength = getString(typedArray, index++);
@@ -273,7 +274,8 @@
         assertStringTag(exifInterface, ExifInterface.TAG_MAKE, expectedValue.make);
         assertStringTag(exifInterface, ExifInterface.TAG_MODEL, expectedValue.model);
         assertFloatTag(exifInterface, ExifInterface.TAG_F_NUMBER, expectedValue.aperture);
-        assertStringTag(exifInterface, ExifInterface.TAG_DATETIME, expectedValue.datetime);
+        assertStringTag(exifInterface, ExifInterface.TAG_DATETIME_ORIGINAL,
+                expectedValue.dateTimeOriginal);
         assertFloatTag(exifInterface, ExifInterface.TAG_EXPOSURE_TIME, expectedValue.exposureTime);
         assertFloatTag(exifInterface, ExifInterface.TAG_FLASH, expectedValue.flash);
         assertStringTag(exifInterface, ExifInterface.TAG_FOCAL_LENGTH, expectedValue.focalLength);
@@ -478,4 +480,34 @@
     public void testReadExifDataFromSamsungNX3000Srw() throws Throwable {
         testExifInterfaceForRaw(SAMSUNG_NX3000_SRW, R.array.samsung_nx3000_srw);
     }
+
+    public void testSetDateTime() throws IOException {
+        final String dateTimeValue = "2017:02:02 22:22:22";
+        final String dateTimeOriginalValue = "2017:01:01 11:11:11";
+
+        File srcFile = new File(Environment.getExternalStorageDirectory(),
+                EXTERNAL_BASE_DIRECTORY + EXIF_BYTE_ORDER_II_JPEG);
+        File imageFile = new File(Environment.getExternalStorageDirectory(),
+                EXTERNAL_BASE_DIRECTORY + EXIF_BYTE_ORDER_II_JPEG + "_copied");
+
+        FileUtils.copyFileOrThrow(srcFile, imageFile);
+        ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
+        exif.setAttribute(ExifInterface.TAG_DATETIME, dateTimeValue);
+        exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, dateTimeOriginalValue);
+        exif.saveAttributes();
+
+        // Check that the DATETIME value is not overwritten by DATETIME_ORIGINAL's value.
+        exif = new ExifInterface(imageFile.getAbsolutePath());
+        assertEquals(dateTimeValue, exif.getAttribute(ExifInterface.TAG_DATETIME));
+        assertEquals(dateTimeOriginalValue, exif.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL));
+
+        // Now remove the DATETIME value.
+        exif.setAttribute(ExifInterface.TAG_DATETIME, null);
+        exif.saveAttributes();
+
+        // When the DATETIME has no value, then it should be set to DATETIME_ORIGINAL's value.
+        exif = new ExifInterface(imageFile.getAbsolutePath());
+        assertEquals(dateTimeOriginalValue, exif.getAttribute(ExifInterface.TAG_DATETIME));
+        imageFile.delete();
+    }
 }
diff --git a/tests/tests/media/src/android/media/cts/MediaScannerTest.java b/tests/tests/media/src/android/media/cts/MediaScannerTest.java
index 3a12e3b..137b7cf 100644
--- a/tests/tests/media/src/android/media/cts/MediaScannerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaScannerTest.java
@@ -470,7 +470,20 @@
             new MediaScanEntry(R.raw.iso88591_13,
                     new String[] {"Michael Bublé", "Crazy Love", "Michael Bublé", "Haven't Met You Yet", null}),
             new MediaScanEntry(R.raw.utf16_1,
-                    new String[] {"Shakira", "Latin Mix USA", "Shakira", "Estoy Aquí", null})
+                    new String[] {"Shakira", "Latin Mix USA", "Shakira", "Estoy Aquí", null}),
+            // Tags are encoded in different charsets.
+            new MediaScanEntry(R.raw.iso88591_utf8_mixed_1,
+                    new String[] {"刘昊霖/kidult.", "鱼干铺里", "刘昊霖/kidult.", "Colin Wine's Mailbox", null}),
+            new MediaScanEntry(R.raw.iso88591_utf8_mixed_2,
+                    new String[] {"冰块先生/郭美孜", "hey jude", "冰块先生/郭美孜", "Hey Jude", null}),
+            new MediaScanEntry(R.raw.iso88591_utf8_mixed_3,
+                    new String[] {"Toy王奕/Tizzy T/满舒克", "1993", "Toy王奕/Tizzy T/满舒克", "Me&Ma Bros", null}),
+            new MediaScanEntry(R.raw.gb18030_utf8_mixed_1,
+                    new String[] {"张国荣", "钟情张国荣", null, "左右手", null}),
+            new MediaScanEntry(R.raw.gb18030_utf8_mixed_2,
+                    new String[] {"纵贯线", "Live in Taipei 出发\\/终点站", null, "皇后大道东(Live)", null}),
+            new MediaScanEntry(R.raw.gb18030_utf8_mixed_3,
+                    new String[] {"谭咏麟", "二十年白金畅销金曲全记录", null, "知心当玩偶", null})
     };
 
     public void testEncodingDetection() throws Exception {
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 cbf3e93..b1e9e30 100644
--- a/tests/tests/net/src/android/net/wifi/cts/WifiManagerTest.java
+++ b/tests/tests/net/src/android/net/wifi/cts/WifiManagerTest.java
@@ -385,6 +385,7 @@
 
             wifiConfiguration = new WifiConfiguration();
             wifiConfiguration.SSID = SSID1;
+            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
             int netId = mWifiManager.addNetwork(wifiConfiguration);
             assertTrue(existSSID(SSID1));
 
diff --git a/tests/tests/packageinstaller/adminpackageinstaller/src/android/packageinstaller/admin/cts/BasePackageInstallTest.java b/tests/tests/packageinstaller/adminpackageinstaller/src/android/packageinstaller/admin/cts/BasePackageInstallTest.java
index 3497387..28ec019 100644
--- a/tests/tests/packageinstaller/adminpackageinstaller/src/android/packageinstaller/admin/cts/BasePackageInstallTest.java
+++ b/tests/tests/packageinstaller/adminpackageinstaller/src/android/packageinstaller/admin/cts/BasePackageInstallTest.java
@@ -26,14 +26,18 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageInstaller;
 import android.content.pm.PackageManager;
+import android.os.ParcelFileDescriptor;
 import android.os.Process;
 import android.support.test.uiautomator.UiDevice;
 import android.test.InstrumentationTestCase;
 
+import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.InputStream;
+import java.io.InputStreamReader;
 import java.io.OutputStream;
+import java.util.ArrayList;
 
 /**
  * Base test case for testing PackageInstaller.
@@ -51,7 +55,7 @@
     protected Context mContext;
     protected UiDevice mDevice;
     protected DevicePolicyManager mDevicePolicyManager;
-    private PackageManager mPackageManager;
+    protected PackageManager mPackageManager;
     private PackageInstaller mPackageInstaller;
     private PackageInstaller.Session mSession;
     protected boolean mCallbackReceived;
@@ -95,6 +99,7 @@
         mHasFeature = mPackageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
 
         if (mHasFeature) {
+            forceUninstall();
             // check that app is not already installed
             assertFalse(isPackageInstalled(TEST_APP_PKG));
         }
@@ -207,4 +212,24 @@
     protected int getInstallReason(String packageName) {
         return mPackageManager.getInstallReason(packageName, Process.myUserHandle());
     }
+
+    protected void forceUninstall() throws Exception {
+        runShellCommand("pm uninstall " + TEST_APP_PKG);
+    }
+
+    public ArrayList<String> runShellCommand(String command) throws Exception {
+        ParcelFileDescriptor pfd = getInstrumentation().getUiAutomation()
+                .executeShellCommand(command);
+
+        ArrayList<String> ret = new ArrayList<>();
+        // Read the input stream fully.
+        try (BufferedReader r = new BufferedReader(
+                new InputStreamReader(new ParcelFileDescriptor.AutoCloseInputStream(pfd)))) {
+            String line;
+            while ((line = r.readLine()) != null) {
+                ret.add(line);
+            }
+        }
+        return ret;
+    }
 }
diff --git a/tests/tests/packageinstaller/adminpackageinstaller/src/android/packageinstaller/admin/cts/SessionCommitBroadcastTest.java b/tests/tests/packageinstaller/adminpackageinstaller/src/android/packageinstaller/admin/cts/SessionCommitBroadcastTest.java
index 08c4926..6f1244f 100644
--- a/tests/tests/packageinstaller/adminpackageinstaller/src/android/packageinstaller/admin/cts/SessionCommitBroadcastTest.java
+++ b/tests/tests/packageinstaller/adminpackageinstaller/src/android/packageinstaller/admin/cts/SessionCommitBroadcastTest.java
@@ -22,14 +22,11 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.pm.PackageInstaller;
-import android.os.ParcelFileDescriptor;
+import android.content.pm.ResolveInfo;
 import android.os.Process;
 import android.os.UserHandle;
 import android.text.TextUtils;
 
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
@@ -55,8 +52,22 @@
         if (!mHasFeature) {
             return;
         }
-        assertNotSame(mDefaultLauncher, mThisAppLauncher);
+        if (mDefaultLauncher.equals(mThisAppLauncher)) {
+            // Find a different launcher
+            Intent homeIntent = new Intent(Intent.ACTION_MAIN)
+                    .addCategory(Intent.CATEGORY_HOME)
+                    .addCategory(Intent.CATEGORY_DEFAULT);
+            for (ResolveInfo info : mPackageManager.queryIntentActivities(homeIntent, 0)) {
+                mDefaultLauncher =
+                        new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
+                if (!mDefaultLauncher.equals(mThisAppLauncher)) {
+                    setLauncher(mDefaultLauncher.flattenToString());
+                    break;
+                }
+            }
+        }
 
+        assertFalse("No default launcher found", mDefaultLauncher.equals(mThisAppLauncher));
         SessionCommitReceiver receiver = new SessionCommitReceiver();
         // install the app
         assertInstallPackage();
@@ -126,10 +137,6 @@
         forceUninstall();
     }
 
-    private void forceUninstall() throws Exception {
-        runShellCommand("pm uninstall " + TEST_APP_PKG);
-    }
-
     private String getDefaultLauncher() throws Exception {
         final String PREFIX = "Launcher: ComponentInfo{";
         final String POSTFIX = "}";
@@ -146,22 +153,6 @@
                 + getInstrumentation().getContext().getUserId() + " " + component);
     }
 
-    public ArrayList<String> runShellCommand(String command) throws Exception {
-        ParcelFileDescriptor pfd = getInstrumentation().getUiAutomation()
-                .executeShellCommand(command);
-
-        ArrayList<String> ret = new ArrayList<>();
-        // Read the input stream fully.
-        try (BufferedReader r = new BufferedReader(
-                new InputStreamReader(new ParcelFileDescriptor.AutoCloseInputStream(pfd)))) {
-            String line;
-            while ((line = r.readLine()) != null) {
-                ret.add(line);
-            }
-        }
-        return ret;
-    }
-
     private class SessionCommitReceiver extends BroadcastReceiver {
 
         private final CountDownLatch mLatch = new CountDownLatch(1);
diff --git a/tests/tests/packageinstaller/externalsources/Android.mk b/tests/tests/packageinstaller/externalsources/Android.mk
index ca2fbda..7d2b1e9 100755
--- a/tests/tests/packageinstaller/externalsources/Android.mk
+++ b/tests/tests/packageinstaller/externalsources/Android.mk
@@ -22,8 +22,6 @@
 
 LOCAL_PACKAGE_NAME := CtsExternalSourcesTestCases
 
-LOCAL_RESOURCE_DIR += $(LOCAL_PATH)/res
-
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_STATIC_JAVA_LIBRARIES := ub-uiautomator android-support-test android-support-v4
diff --git a/tests/tests/packageinstaller/externalsources/AndroidManifest.xml b/tests/tests/packageinstaller/externalsources/AndroidManifest.xml
index 33d1d6e..8bcdd04 100755
--- a/tests/tests/packageinstaller/externalsources/AndroidManifest.xml
+++ b/tests/tests/packageinstaller/externalsources/AndroidManifest.xml
@@ -21,13 +21,6 @@
 
     <application android:label="Cts External Sources Test">
         <uses-library android:name="android.test.runner"/>
-        <provider android:authorities="android.packageinstaller.externalsources.cts.fileprovider"
-                  android:name="android.support.v4.content.FileProvider"
-                  android:grantUriPermissions="true">
-            <meta-data
-                android:name="android.support.FILE_PROVIDER_PATHS"
-                android:resource="@xml/file_paths" />
-        </provider>
     </application>
 
     <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/packageinstaller/externalsources/AndroidTest.xml b/tests/tests/packageinstaller/externalsources/AndroidTest.xml
index 39d2d67..2d782d8 100644
--- a/tests/tests/packageinstaller/externalsources/AndroidTest.xml
+++ b/tests/tests/packageinstaller/externalsources/AndroidTest.xml
@@ -17,16 +17,6 @@
 <configuration description="Config for CTS External Sources test cases">
     <option name="config-descriptor:metadata" key="component" value="framework" />
 
-    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
-        <option name="run-command" value="mkdir -p /data/local/tmp/cts/externalsources" />
-        <option name="teardown-command" value="rm -rf /data/local/tmp/cts"/>
-    </target_preparer>
-
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
-        <option name="cleanup" value="true" />
-        <option name="push" value="CtsEmptyTestApp.apk->/data/local/tmp/cts/externalsources/CtsEmptyTestApp.apk" />
-    </target_preparer>
-
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsExternalSourcesTestCases.apk" />
@@ -34,7 +24,7 @@
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.packageinstaller.externalsources.cts" />
-        <option name="runtime-hint" value="1m" />
+        <option name="runtime-hint" value="10s" />
     </test>
 
 </configuration>
diff --git a/tests/tests/packageinstaller/externalsources/res/xml/file_paths.xml b/tests/tests/packageinstaller/externalsources/res/xml/file_paths.xml
deleted file mode 100644
index 173435b..0000000
--- a/tests/tests/packageinstaller/externalsources/res/xml/file_paths.xml
+++ /dev/null
@@ -1,19 +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.
--->
-
-<paths xmlns:android="http://schemas.android.com/apk/res/android">
-    <files-path name="apk" path="/" />
-</paths>
\ No newline at end of file
diff --git a/tests/tests/packageinstaller/externalsources/src/android/packageinstaller/externalsources/cts/ExternalSourcesTest.java b/tests/tests/packageinstaller/externalsources/src/android/packageinstaller/externalsources/cts/ExternalSourcesTest.java
index e10e278..921f5f1 100644
--- a/tests/tests/packageinstaller/externalsources/src/android/packageinstaller/externalsources/cts/ExternalSourcesTest.java
+++ b/tests/tests/packageinstaller/externalsources/src/android/packageinstaller/externalsources/cts/ExternalSourcesTest.java
@@ -15,122 +15,41 @@
  */
 package android.packageinstaller.externalsources.cts;
 
-import android.app.Instrumentation;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.provider.Settings;
 import android.support.test.InstrumentationRegistry;
-import android.support.test.filters.MediumTest;
+import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
-import android.support.test.uiautomator.By;
-import android.support.test.uiautomator.BySelector;
 import android.support.test.uiautomator.UiDevice;
-import android.support.test.uiautomator.UiObject2;
-import android.support.test.uiautomator.Until;
-import android.support.v4.content.FileProvider;
-import android.util.Log;
 
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
 import java.io.IOException;
 
 @RunWith(AndroidJUnit4.class)
-@MediumTest
+@SmallTest
 public class ExternalSourcesTest {
 
-    private static final String TAG = ExternalSourcesTest.class.getSimpleName();
-    private static final String TEST_APK_NAME = "CtsEmptyTestApp.apk";
-    private static final String TEST_APK_EXTERNAL_LOCATION = "/data/local/tmp/cts/externalsources";
-    private static final String CONTENT_AUTHORITY =
-            "android.packageinstaller.externalsources.cts.fileprovider";
-    private static final String PACKAGE_INSTALLER_PACKAGE_NAME = "com.android.packageinstaller";
-    private static final String INSTALL_CONFIRM_TEXT_ID = "install_confirm_question";
-    private static final String WM_DISMISS_KEYGUARD_COMMAND = "wm dismiss-keyguard";
-    private static final String ALERT_DIALOG_TITLE_ID = "android:id/alertTitle";
-
-    private static final long WAIT_FOR_UI_TIMEOUT = 5000;
-
     private Context mContext;
     private PackageManager mPm;
-    private Instrumentation mInstrumentation;
     private String mPackageName;
-    private File mApkFile;
     private UiDevice mUiDevice;
-
-    @BeforeClass
-    public static void setUpOnce() throws IOException {
-        File srcApkFile = new File(TEST_APK_EXTERNAL_LOCATION, TEST_APK_NAME);
-        File destApkFile = new File(InstrumentationRegistry.getTargetContext().getFilesDir(),
-                TEST_APK_NAME);
-        copyFile(srcApkFile, destApkFile);
-    }
+    private boolean mHasFeature;
 
     @Before
     public void setUp() throws Exception {
         mContext = InstrumentationRegistry.getTargetContext();
-        mInstrumentation = InstrumentationRegistry.getInstrumentation();
         mPm = mContext.getPackageManager();
         mPackageName = mContext.getPackageName();
-        mApkFile = new File(mContext.getFilesDir(), TEST_APK_NAME);
-        mUiDevice = UiDevice.getInstance(mInstrumentation);
-        if (!mUiDevice.isScreenOn()) {
-            mUiDevice.wakeUp();
-        }
-        mUiDevice.executeShellCommand(WM_DISMISS_KEYGUARD_COMMAND);
-    }
-
-    private static void copyFile(File srcFile, File destFile) throws IOException {
-        if (destFile.exists()) {
-            destFile.delete();
-        }
-        FileInputStream inputStream = new FileInputStream(srcFile);
-        FileOutputStream out = new FileOutputStream(destFile);
-        try {
-            byte[] buffer = new byte[4096];
-            int bytesRead;
-            while ((bytesRead = inputStream.read(buffer)) >= 0) {
-                out.write(buffer, 0, bytesRead);
-            }
-            Log.d(TAG, "copied file " + srcFile + " to " + destFile);
-        } finally {
-            out.flush();
-            try {
-                out.getFD().sync();
-            } catch (IOException e) {
-            }
-            out.close();
-            inputStream.close();
-        }
-    }
-
-    private void launchPackageInstaller() {
-        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
-        intent.setData(FileProvider.getUriForFile(mContext, CONTENT_AUTHORITY, mApkFile));
-        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
-        Log.d(TAG, "Starting intent with uri " + intent.getDataString());
-        mContext.startActivity(intent);
-    }
-
-    private void assertInstallAllowed(String errorMessage) {
-        BySelector selector = By.res(PACKAGE_INSTALLER_PACKAGE_NAME, INSTALL_CONFIRM_TEXT_ID);
-        UiObject2 uiObject = mUiDevice.wait(Until.findObject(selector), WAIT_FOR_UI_TIMEOUT);
-        Assert.assertNotNull(errorMessage, uiObject);
-        mUiDevice.pressBack();
-    }
-
-    private void assertInstallBlocked(String errorMessage) {
-        BySelector selector = By.res(ALERT_DIALOG_TITLE_ID);
-        UiObject2 settingsButton = mUiDevice.wait(Until.findObject(selector), WAIT_FOR_UI_TIMEOUT);
-        Assert.assertNotNull(errorMessage, settingsButton);
-        mUiDevice.pressBack();
+        mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+        mHasFeature = !mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);
     }
 
     private void setAppOpsMode(String mode) throws IOException {
@@ -144,35 +63,39 @@
     @Test
     public void blockedSourceTest() throws Exception {
         setAppOpsMode("deny");
-        boolean isTrusted = mPm.canRequestPackageInstalls();
+        final boolean isTrusted = mPm.canRequestPackageInstalls();
         Assert.assertFalse("Package " + mPackageName
                 + " allowed to install packages after setting app op to errored", isTrusted);
-        launchPackageInstaller();
-        assertInstallBlocked("Install blocking dialog not shown when app op set to errored");
     }
 
     @Test
     public void allowedSourceTest() throws Exception {
         setAppOpsMode("allow");
-        boolean isTrusted = mPm.canRequestPackageInstalls();
+        final boolean isTrusted = mPm.canRequestPackageInstalls();
         Assert.assertTrue("Package " + mPackageName
                 + " blocked from installing packages after setting app op to allowed", isTrusted);
-        launchPackageInstaller();
-        assertInstallAllowed("Install confirmation not shown when app op set to allowed");
     }
 
     @Test
     public void defaultSourceTest() throws Exception {
-        boolean isTrusted = mPm.canRequestPackageInstalls();
+        setAppOpsMode("default");
+        final boolean isTrusted = mPm.canRequestPackageInstalls();
         Assert.assertFalse("Package " + mPackageName
                 + " with default app ops state allowed to install packages", isTrusted);
-        launchPackageInstaller();
-        assertInstallBlocked("Install blocking dialog not shown when app op set to default");
+    }
+
+    @Test
+    public void testManageUnknownSourcesExists() {
+        if (!mHasFeature) {
+            return;
+        }
+        Intent manageUnknownSources = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
+        ResolveInfo info = mPm.resolveActivity(manageUnknownSources, 0);
+        Assert.assertNotNull("No activity found for " + manageUnknownSources.getAction(), info);
     }
 
     @After
     public void tearDown() throws Exception {
-        mUiDevice.pressHome();
         setAppOpsMode("default");
     }
 }
diff --git a/tests/tests/preference2/src/android/preference2/cts/TestUtils.java b/tests/tests/preference2/src/android/preference2/cts/TestUtils.java
index e02fe78..04e0ed9 100644
--- a/tests/tests/preference2/src/android/preference2/cts/TestUtils.java
+++ b/tests/tests/preference2/src/android/preference2/cts/TestUtils.java
@@ -26,7 +26,6 @@
 import android.support.test.uiautomator.UiDevice;
 import android.support.test.uiautomator.UiObject;
 import android.support.test.uiautomator.UiObjectNotFoundException;
-import android.support.test.uiautomator.UiScrollable;
 import android.support.test.uiautomator.UiSelector;
 
 import com.android.compatibility.common.util.SystemUtil;
@@ -62,37 +61,22 @@
         return bt;
     }
 
-    void tapOnViewWithText(String searchText) {
-        if (searchText == null) {
-            return;
-        }
-
-        UiScrollable textScroll =  new UiScrollable(new UiSelector().scrollable(true));
+    void tapOnViewWithText(String text) {
+        UiObject obj = device.findObject(new UiSelector().textMatches(text));
         try {
-            textScroll.scrollIntoView(new UiSelector().text(searchText));
-            UiObject text = new UiObject(new UiSelector().text(searchText));
-            text.click();
+            obj.click();
         } catch (UiObjectNotFoundException e) {
-            throw new AssertionError("View with text '" + searchText + "' was not found!", e);
+            throw new AssertionError("View with text '" + text + "' was not found!", e);
         }
+        device.waitForIdle();
     }
 
-    boolean isTextShown(String searchText) {
-        if (searchText == null) {
-            return false;
-        }
-
-        UiObject text = new UiObject(new UiSelector().text(searchText));
-        if (text.exists() || text.waitForExists(1000)) {
+    boolean isTextShown(String text) {
+        UiObject obj = device.findObject(new UiSelector().textMatches(text));
+        if (obj.exists()) {
             return true;
         }
-
-        UiScrollable textScroll = new UiScrollable(new UiSelector().scrollable(true));
-        try {
-            return textScroll.scrollIntoView(new UiSelector().text(searchText));
-        } catch (UiObjectNotFoundException e) {
-            return false;
-        }
+        return obj.waitForExists(1000);
     }
 
     boolean isTextHidden(String text) {
diff --git a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
index 9de1db4..7c971b3 100644
--- a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
@@ -238,12 +238,12 @@
             TestRawContact rawContact = mBuilder.newRawContact()
                     .with(RawContacts.ACCOUNT_TYPE, "test_type")
                     .with(RawContacts.ACCOUNT_NAME, "test_name")
-                    .with(RawContacts.TIMES_CONTACTED, 12345) // should be ignored.
+                    .with(RawContacts.TIMES_CONTACTED, 12345)
                     .with(RawContacts.LAST_TIME_CONTACTED, now)
                     .insert();
 
             rawContact.load();
-            assertEquals(0L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
+            assertEquals(12340, rawContact.getLong(RawContacts.TIMES_CONTACTED));
             assertEquals(now / 86400 * 86400, rawContact.getLong(RawContacts.LAST_TIME_CONTACTED));
         }
 
@@ -251,11 +251,11 @@
             TestRawContact rawContact = mBuilder.newRawContact()
                     .with(RawContacts.ACCOUNT_TYPE, "test_type")
                     .with(RawContacts.ACCOUNT_NAME, "test_name")
-                    .with(RawContacts.TIMES_CONTACTED, 12345) // should be ignored.
+                    .with(RawContacts.TIMES_CONTACTED, 5)
                     .insert();
 
             rawContact.load();
-            assertEquals(0L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
+            assertEquals(5L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
             assertEquals(0, rawContact.getLong(RawContacts.LAST_TIME_CONTACTED));
         }
         {
@@ -278,21 +278,20 @@
         TestRawContact rawContact = mBuilder.newRawContact()
                 .with(RawContacts.ACCOUNT_TYPE, "test_type")
                 .with(RawContacts.ACCOUNT_NAME, "test_name")
-                .with(RawContacts.TIMES_CONTACTED, 12345) // should be ignored.
+                .with(RawContacts.TIMES_CONTACTED, 12345)
                 .with(RawContacts.LAST_TIME_CONTACTED, now)
                 .insert();
 
         rawContact.load();
-        assertEquals(0L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
+        assertEquals(12340L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
         assertEquals(now / 86400 * 86400, rawContact.getLong(RawContacts.LAST_TIME_CONTACTED));
 
         values.clear();
         values.put(RawContacts.TIMES_CONTACTED, 99999);
         RawContactUtil.update(mResolver, rawContact.getId(), values);
 
-        // Shouldn't change.
         rawContact.load();
-        assertEquals(0L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
+        assertEquals(99990L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
         assertEquals(now / 86400 * 86400, rawContact.getLong(RawContacts.LAST_TIME_CONTACTED));
 
         values.clear();
@@ -300,7 +299,7 @@
         RawContactUtil.update(mResolver, rawContact.getId(), values);
 
         rawContact.load();
-        assertEquals(0L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
+        assertEquals(99990L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
         assertEquals((now / 86400 * 86400) + 86400,
                 rawContact.getLong(RawContacts.LAST_TIME_CONTACTED));
     }
diff --git a/tests/tests/widget/res/layout/seekbar_layout.xml b/tests/tests/widget/res/layout/seekbar_layout.xml
index 4b4a6b7..2bed18e 100644
--- a/tests/tests/widget/res/layout/seekbar_layout.xml
+++ b/tests/tests/widget/res/layout/seekbar_layout.xml
@@ -15,6 +15,7 @@
 -->
 
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:orientation="vertical"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
 
@@ -29,14 +30,14 @@
         android:id="@+id/thumb_tint"
         android:thumbTint="@android:color/white"
         android:thumbTintMode="src_over"
-        android:layout_width="wrap_content"
+        android:layout_width="match_parent"
         android:layout_height="wrap_content" />
 
     <SeekBar
         android:id="@+id/tick_mark_tint"
         android:tickMarkTint="@android:color/white"
         android:tickMarkTintMode="src_over"
-        android:layout_width="wrap_content"
+        android:layout_width="match_parent"
         android:layout_height="wrap_content" />
 
 </LinearLayout>
diff --git a/tests/tests/widget/src/android/widget/cts/CalendarViewTest.java b/tests/tests/widget/src/android/widget/cts/CalendarViewTest.java
index 670b4f8..d475117 100644
--- a/tests/tests/widget/src/android/widget/cts/CalendarViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/CalendarViewTest.java
@@ -134,12 +134,7 @@
 
     @UiThreadTest
     @Test
-    public void testCalendarViewMinMaxRangeRestrictions() {
-        verifyMinMaxRangeRestrictions(mCalendarViewHolo);
-        verifyMinMaxRangeRestrictions(mCalendarViewMaterial);
-    }
-
-    private void verifyMinMaxRangeRestrictions(CalendarView calendarView) {
+    public void testMinMaxRangeRestrictionsHolo() {
         // Use a range of minus/plus one year as min/max dates.
         final Calendar minCalendar = new GregorianCalendar();
         minCalendar.set(Calendar.YEAR, minCalendar.get(Calendar.YEAR) - 1);
@@ -148,22 +143,53 @@
         final long minDate = minCalendar.getTime().getTime();
         final long maxDate = maxCalendar.getTime().getTime();
 
-        calendarView.setMinDate(minDate);
-        calendarView.setMaxDate(maxDate);
+        mCalendarViewHolo.setMinDate(minDate);
+        mCalendarViewHolo.setMaxDate(maxDate);
 
         try {
-            calendarView.setDate(minDate - 1);
+            mCalendarViewHolo.setDate(minDate - 1);
             fail("Should throw IllegalArgumentException, date is before minDate");
         } catch (IllegalArgumentException e) {
         }
 
         try {
-            calendarView.setDate(maxDate + 1);
+            mCalendarViewHolo.setDate(maxDate + 1);
             fail("Should throw IllegalArgumentException, date is after maxDate");
         } catch (IllegalArgumentException e) {
         }
     }
 
+    @UiThreadTest
+    @Test
+    public void testMinMaxRangeClampingMaterial() {
+        // Use a range of minus/plus one year as min/max dates.
+        final Calendar minCalendar = new GregorianCalendar();
+        minCalendar.set(Calendar.YEAR, minCalendar.get(Calendar.YEAR) - 1);
+        final Calendar maxCalendar = new GregorianCalendar();
+        maxCalendar.set(Calendar.YEAR, maxCalendar.get(Calendar.YEAR) + 1);
+        final long minDate = minCalendar.getTime().getTime();
+        final long maxDate = maxCalendar.getTime().getTime();
+
+        mCalendarViewMaterial.setMinDate(minDate);
+        mCalendarViewMaterial.setMaxDate(maxDate);
+        mCalendarViewMaterial.setDate(minDate + 1);
+
+        assertEquals(minDate, mCalendarViewMaterial.getMinDate());
+        assertEquals(maxDate, mCalendarViewMaterial.getMaxDate());
+        assertEquals(minDate + 1, mCalendarViewMaterial.getDate());
+
+        mCalendarViewMaterial.setMinDate(minDate + 20);
+        assertEquals(minDate + 20, mCalendarViewMaterial.getMinDate());
+        assertEquals(maxDate, mCalendarViewMaterial.getMaxDate());
+        assertEquals(minDate + 20, mCalendarViewMaterial.getDate());
+
+        mCalendarViewMaterial.setMinDate(minDate);
+        mCalendarViewMaterial.setMaxDate(minDate + 10);
+        assertEquals(minDate, mCalendarViewMaterial.getMinDate());
+        assertEquals(minDate + 10, mCalendarViewMaterial.getMaxDate());
+        assertEquals(minDate + 10, mCalendarViewMaterial.getDate());
+    }
+
     private void verifyOnDateChangeListener(CalendarView calendarView,
             boolean onlyAllowOneChangeEvent) throws Throwable {
         final CalendarView.OnDateChangeListener mockDateChangeListener =