Merge "Fix autofill FillEventHistoryTest on devices with physical keyboard." into pi-dev
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 71ada3d..a7121ad 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -46,6 +46,7 @@
 
 $(call add-clean-step, rm -rf $(HOST_OUT_INTERMEDIATES)/EXECUTABLES/vm-tests-tf_intermediates)
 $(call add-clean-step, rm -rf $(OUT_DIR)/host/common/obj/JAVA_LIBRARIES/cts-tradefed_intermediates/com/android/compatibility/SuiteInfo.java)
+$(call add-clean-step, rm -rf $(HOST_OUT)/cts/android-cts/testcases/CtsUiHostTestCases*)
 
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
diff --git a/apps/CtsVerifier/res/layout/bt_hid_device.xml b/apps/CtsVerifier/res/layout/bt_hid_device.xml
index 39d9ecd..478fc0e 100644
--- a/apps/CtsVerifier/res/layout/bt_hid_device.xml
+++ b/apps/CtsVerifier/res/layout/bt_hid_device.xml
@@ -14,7 +14,11 @@
      limitations under the License.
 -->
 
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+<LinearLayout
     style="@style/RootLayoutPadding"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
@@ -63,3 +67,5 @@
 
   <include layout="@layout/pass_fail_buttons" />
 </LinearLayout>
+
+</ScrollView>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/widget/WidgetTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/widget/WidgetTestActivity.java
index 25f0a7a..32c4267 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/widget/WidgetTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/widget/WidgetTestActivity.java
@@ -19,6 +19,8 @@
 import com.android.cts.verifier.PassFailButtons;
 import com.android.cts.verifier.R;
 
+import com.android.compatibility.common.util.CddTest;
+
 import android.content.Context;
 import android.hardware.Sensor;
 import android.hardware.SensorEventListener;
@@ -29,6 +31,7 @@
 /**
  * CTS Verifier case for verifying basic widget framework functionality.
  */
+@CddTest(requirement="3.8.2/C-1-2,C-1-3")
 public class WidgetTestActivity extends PassFailButtons.Activity {
 
     @Override
diff --git a/hostsidetests/appsecurity/Android.mk b/hostsidetests/appsecurity/Android.mk
index 6919ae5..59ef75e 100644
--- a/hostsidetests/appsecurity/Android.mk
+++ b/hostsidetests/appsecurity/Android.mk
@@ -34,7 +34,8 @@
 
 LOCAL_REQUIRED_MODULES := \
 	CtsCorruptApkTests_b71360999 \
-	CtsCorruptApkTests_b71361168
+	CtsCorruptApkTests_b71361168 \
+	CtsCorruptApkTests_b79488511
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java
index 564804b..6849d0c 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java
@@ -38,7 +38,8 @@
 @AppModeFull // TODO: Needs porting to instant
 public class CorruptApkTests extends DeviceTestCase implements IBuildReceiver {
     private final String B71360999_PKG = "com.android.appsecurity.b71360999";
-    private final String B71361168_PKG = "com.example.helloworld";
+    private final String B71361168_PKG = "com.android.appsecurity.b71361168";
+    private final String B79488511_PKG = "com.android.appsecurity.b79488511";
 
     private IBuildInfo mBuildInfo;
 
@@ -53,6 +54,7 @@
         super.setUp();
         uninstall(B71360999_PKG);
         uninstall(B71361168_PKG);
+        uninstall(B79488511_PKG);
     }
 
     @After
@@ -61,6 +63,7 @@
         super.tearDown();
         uninstall(B71360999_PKG);
         uninstall(B71361168_PKG);
+        uninstall(B79488511_PKG);
     }
 
     /** Uninstall the apk if the test failed previously. */
@@ -72,11 +75,11 @@
     }
 
     /**
-     * Tests that apks described in b/71360999 do not install successfully nor cause
+     * Tests that apks described in b/71360999 do not install successfully.
      */
     public void testFailToInstallCorruptStringPoolHeader_b71360999() throws Exception {
         final String APK_PATH = "CtsCorruptApkTests_b71360999.apk";
-        assertFailsToInstall(APK_PATH, B71360999_PKG);
+        assertInstallNoFatalError(APK_PATH, B71360999_PKG);
     }
 
     /**
@@ -84,14 +87,22 @@
      */
     public void testFailToInstallCorruptStringPoolHeader_b71361168() throws Exception {
         final String APK_PATH = "CtsCorruptApkTests_b71361168.apk";
-        assertFailsToInstall(APK_PATH, B71361168_PKG);
+        assertInstallNoFatalError(APK_PATH, B71361168_PKG);
     }
 
     /**
-     * Assert that the app fails to install and the reason for failing is not caused by a buffer
-     * overflow nor a out of bounds read.
+     * Tests that apks described in b/79488511 do not install successfully.
+     */
+    public void testFailToInstallCorruptStringPoolHeader_b79488511() throws Exception {
+        final String APK_PATH = "CtsCorruptApkTests_b79488511.apk";
+        assertInstallNoFatalError(APK_PATH, B79488511_PKG);
+    }
+
+    /**
+     * Assert that installing the app does not cause a native error caused by a buffer overflow
+     * or an out-of-bounds read.
      **/
-    private void assertFailsToInstall(String filename, String pkg) throws Exception {
+    private void assertInstallNoFatalError(String filename, String pkg) throws Exception {
         ITestDevice device = getDevice();
         device.clearLogcat();
 
@@ -99,9 +110,12 @@
                 new CompatibilityBuildHelper(mBuildInfo).getTestFile(filename),
                 true /*reinstall*/);
 
-        assertThat(result).isNotNull();
-        assertThat(result).isNotEmpty();
-        assertThat(device.getInstalledPackageNames()).doesNotContain(pkg);
+        // Starting from P, corrupt apks should always fail to install
+        if (device.getApiLevel() >= 28) {
+            assertThat(result).isNotNull();
+            assertThat(result).isNotEmpty();
+            assertThat(device.getInstalledPackageNames()).doesNotContain(pkg);
+        }
 
         // This catches if the device fails to install the app because a segmentation fault
         // or out of bounds read created by the bug occurs
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.mk b/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.mk
index feaaa03..9fd8b98 100644
--- a/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.mk
@@ -28,4 +28,12 @@
 LOCAL_SRC_FILES := b71361168.apk
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_CERTIFICATE := PRESIGNED
+include $(BUILD_PREBUILT)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CtsCorruptApkTests_b79488511
+LOCAL_MODULE_CLASS := APPS
+LOCAL_SRC_FILES := b79488511.apk
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_CERTIFICATE := PRESIGNED
 include $(BUILD_PREBUILT)
\ No newline at end of file
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/b71361168.apk b/hostsidetests/appsecurity/test-apps/CorruptApkTests/b71361168.apk
index ef1e2bf..dc00656 100644
--- a/hostsidetests/appsecurity/test-apps/CorruptApkTests/b71361168.apk
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/b71361168.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/b79488511.apk b/hostsidetests/appsecurity/test-apps/CorruptApkTests/b79488511.apk
new file mode 100644
index 0000000..22af499
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/b79488511.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.mk b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.mk
index dab340b..90b7866 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.mk
@@ -22,8 +22,8 @@
 LOCAL_STATIC_JAVA_LIBRARIES := \
     cts-aia-util \
     android-support-test \
-	ctsdeviceutillegacy \
-	ctstestrunner
+    ctsdeviceutillegacy \
+    ctstestrunner
 
 # tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/AndroidManifest.xml
index c1f903e..2dc1b02 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/AndroidManifest.xml
@@ -36,7 +36,7 @@
         <uses-library android:name="android.test.runner" />
         <activity
             android:name=".EphemeralActivity"
-            android:theme="@android:style/Theme.NoDisplay">
+            android:theme="@android:style/Theme.NoDisplay" >
             <!-- TEST: normal app can start w/o knowing about this activity -->
             <intent-filter>
                 <action android:name="android.intent.action.VIEW" />
@@ -67,6 +67,19 @@
                        android:name="android.app.searchable"
                        android:resource="@xml/searchable" />
         </activity>
+        <activity
+            android:name=".EphemeralResult"
+            android:theme="@android:style/Theme.NoDisplay" >
+            <!-- TEST: allow sending results from other instant apps -->
+            <intent-filter>
+                <action android:name="android.intent.action.VIEW" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <category android:name="android.intent.category.BROWSABLE" />
+                <data android:scheme="https" />
+                <data android:host="cts.google.com" />
+                <data android:path="/result" />
+            </intent-filter>
+        </activity>
         <provider android:name=".SearchSuggestionProvider"
             android:authorities="com.android.cts.ephemeralapp1.Search" />
 
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 363dfb0..9e231a1 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
@@ -21,6 +21,7 @@
 import static android.media.MediaRecorder.AudioSource.MIC;
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.hasItems;
 import static org.hamcrest.CoreMatchers.notNullValue;
 import static org.hamcrest.CoreMatchers.nullValue;
 import static org.junit.Assert.assertSame;
@@ -78,6 +79,7 @@
 import org.junit.runner.RunWith;
 
 import java.io.IOException;
+import java.util.Iterator;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.SynchronousQueue;
@@ -97,6 +99,8 @@
     /** Action to start private ephemeral test activities */
     private static final String ACTION_START_EPHEMERAL_PRIVATE =
             "com.android.cts.ephemeraltest.START_EPHEMERAL_PRIVATE";
+    private static final String ACTION_START_EPHEMERAL_ACTIVITY =
+            "com.android.cts.ephemeraltest.START_OTHER_EPHEMERAL";
     /** Action to query for test activities */
     private static final String ACTION_QUERY =
             "com.android.cts.ephemeraltest.QUERY";
@@ -195,6 +199,52 @@
                     is(false));
         }
 
+        // query own ephemeral application activities with a web URI
+        {
+            final Intent queryIntent = new Intent(Intent.ACTION_VIEW);
+            queryIntent.addCategory(Intent.CATEGORY_BROWSABLE);
+            queryIntent.setData(Uri.parse("https://cts.google.com/ephemeral"));
+            final List<ResolveInfo> resolveInfo = InstrumentationRegistry.getContext()
+                    .getPackageManager().queryIntentActivities(
+                            queryIntent, PackageManager.GET_RESOLVED_FILTER);
+            if (resolveInfo == null || resolveInfo.size() == 0) {
+                fail("didn't resolve any intents");
+            }
+            for (ResolveInfo info: resolveInfo) {
+                assertThat(info.filter, is(notNullValue()));
+                if (handlesAllWebData(info.filter)) {
+                    continue;
+                }
+                assertThat(info.activityInfo.packageName,
+                        is("com.android.cts.ephemeralapp1"));
+                assertThat(info.activityInfo.name,
+                        is("com.android.cts.ephemeralapp1.EphemeralActivity"));
+                assertThat(info.isInstantAppAvailable,
+                        is(true));
+            }
+        }
+
+        // query other ephemeral application activities with a web URI
+        {
+            final Intent queryIntent = new Intent(Intent.ACTION_VIEW);
+            queryIntent.addCategory(Intent.CATEGORY_BROWSABLE);
+            queryIntent.setData(Uri.parse("https://cts.google.com/other"));
+            final List<ResolveInfo> resolveInfo = InstrumentationRegistry.getContext()
+                    .getPackageManager().queryIntentActivities(
+                            queryIntent, PackageManager.GET_RESOLVED_FILTER);
+            if (resolveInfo == null || resolveInfo.size() == 0) {
+                fail("didn't resolve any intents");
+            }
+            for (ResolveInfo info: resolveInfo) {
+                assertThat(info.filter, is(notNullValue()));
+                if (handlesAllWebData(info.filter)) {
+                    continue;
+                }
+                fail("resolution should have only matched browsers");
+            }
+        }
+
+        // query services
         {
             final Intent queryIntent = new Intent(ACTION_QUERY);
             final List<ResolveInfo> resolveInfo = InstrumentationRegistry
@@ -215,6 +265,7 @@
                     is(false));
         }
 
+        // query services; directed package
         {
             final Intent queryIntent = new Intent(ACTION_QUERY);
             queryIntent.setPackage("com.android.cts.ephemeralapp1");
@@ -230,6 +281,7 @@
                     is("com.android.cts.ephemeralapp1.EphemeralService"));
         }
 
+        // query services; directed component
         {
             final Intent queryIntent = new Intent(ACTION_QUERY);
             queryIntent.setComponent(
@@ -790,7 +842,7 @@
                     new ComponentName("com.android.cts.ephemeralapp1",
                             "com.android.cts.ephemeralapp1.EphemeralActivity3"));
             InstrumentationRegistry
-            .getContext().startActivity(startEphemeralIntent, null /*options*/);
+                    .getContext().startActivity(startEphemeralIntent, null /*options*/);
             final TestResult testResult = getResult();
             assertThat(testResult.getPackageName(),
                     is("com.android.cts.ephemeralapp1"));
@@ -802,6 +854,52 @@
                     is(nullValue()));
         }
 
+        // start an ephemeral activity; VIEW / BROWSABLE intent
+        {
+            final Intent startEphemeralIntent = new Intent(Intent.ACTION_VIEW)
+                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            startEphemeralIntent.addCategory(Intent.CATEGORY_BROWSABLE);
+            startEphemeralIntent.setData(Uri.parse("https://cts.google.com/other"));
+            InstrumentationRegistry
+                    .getContext().startActivity(startEphemeralIntent, null /*options*/);
+            final TestResult testResult = getResult();
+            assertThat(testResult.getPackageName(),
+                    is("com.android.cts.ephemeralapp2"));
+            assertThat(testResult.getComponentName(),
+                    is("EphemeralActivity"));
+            assertThat(testResult.getIntent().getAction(),
+                    is(Intent.ACTION_VIEW));
+            assertThat(testResult.getIntent().getCategories(),
+                    hasItems(Intent.CATEGORY_BROWSABLE));
+            assertThat(testResult.getIntent().getData().toString(),
+                    is("https://cts.google.com/other"));
+            assertThat(testResult.getStatus(),
+                    is("PASS"));
+            assertThat(testResult.getException(),
+                    is(nullValue()));
+        }
+
+        // start an ephemeral activity; EXTERNAL flag
+        {
+            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL_ACTIVITY)
+                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MATCH_EXTERNAL);
+            InstrumentationRegistry.getContext().startActivity(
+                    startEphemeralIntent, null /*options*/);
+            final TestResult testResult = getResult();
+            assertThat(testResult.getPackageName(),
+                    is("com.android.cts.ephemeralapp2"));
+            assertThat(testResult.getComponentName(),
+                    is("EphemeralActivity"));
+            assertThat(testResult.getIntent().getAction(),
+                    is(ACTION_START_EPHEMERAL_ACTIVITY));
+            assertThat(testResult.getIntent().getData(),
+                    is(nullValue()));
+            assertThat(testResult.getStatus(),
+                    is("PASS"));
+            assertThat(testResult.getException(),
+                    is(nullValue()));
+        }
+
         // start the ephemeral service; directed package
         {
             final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL);
@@ -1280,6 +1378,32 @@
         }
     }
 
+    /** Returns {@code true} if the given filter handles all web URLs, regardless of host. */
+    private boolean handlesAllWebData(IntentFilter filter) {
+        return filter.hasCategory(Intent.CATEGORY_APP_BROWSER) ||
+                (handlesWebUris(filter) && filter.countDataAuthorities() == 0);
+    }
+
+    /** Returns {@code true} if the given filter handles at least one web URL. */
+    private boolean handlesWebUris(IntentFilter filter) {
+        // Require ACTION_VIEW, CATEGORY_BROWSEABLE, and at least one scheme
+        if (!filter.hasAction(Intent.ACTION_VIEW)
+            || !filter.hasCategory(Intent.CATEGORY_BROWSABLE)
+            || filter.countDataSchemes() == 0) {
+            return false;
+        }
+        // Now allow only the schemes "http" and "https"
+        final Iterator<String> schemesIterator = filter.schemesIterator();
+        while (schemesIterator.hasNext()) {
+            final String scheme = schemesIterator.next();
+            final boolean isWebScheme = "http".equals(scheme) || "https".equals(scheme);
+            if (isWebScheme) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     private TestResult getResult() {
         final TestResult result;
         try {
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/EphemeralResult.java b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/EphemeralResult.java
new file mode 100644
index 0000000..a1fad50
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/EphemeralResult.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.ephemeralapp1;
+
+import android.app.Activity;
+import android.app.SearchManager;
+import android.content.Intent;
+import android.content.pm.PackageInfo;
+import android.content.pm.ResolveInfo;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.net.Uri;
+import android.os.Bundle;
+import android.provider.SearchRecentSuggestions;
+import android.util.Log;
+
+import com.android.cts.util.TestResult;
+
+import java.util.List;
+
+public class EphemeralResult extends Activity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        final Intent intent  = getIntent();
+        if (Intent.ACTION_VIEW.equals(intent.getAction())
+                && intent.hasExtra(TestResult.EXTRA_TEST_RESULT)) {
+            ((TestResult) intent.getParcelableExtra(TestResult.EXTRA_TEST_RESULT)).broadcast(this);
+        }
+        finish();
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.mk b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.mk
index a5bc4b0..78c7970 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.mk
@@ -17,12 +17,18 @@
 LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
 
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs android.test.base.stubs
 LOCAL_MODULE_TAGS := tests
-LOCAL_STATIC_JAVA_LIBRARIES := android-support-test
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    cts-aia-util \
+    android-support-test \
+    ctsdeviceutillegacy \
+    ctstestrunner
 
 # tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
 
 LOCAL_PACKAGE_NAME := CtsEphemeralTestsEphemeralApp2
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/AndroidManifest.xml
index 84549b0..0350cc6 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/AndroidManifest.xml
@@ -43,6 +43,10 @@
                 <action android:name="com.android.cts.ephemeraltest.START_EPHEMERAL" />
                 <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
+            <intent-filter android:priority="0">
+                <action android:name="com.android.cts.ephemeraltest.START_OTHER_EPHEMERAL" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
             <intent-filter>
                 <action android:name="android.intent.action.SEARCH" />
             </intent-filter>
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/src/com/android/cts/ephemeralapp2/EphemeralActivity.java b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/src/com/android/cts/ephemeralapp2/EphemeralActivity.java
new file mode 100644
index 0000000..885bc19
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/src/com/android/cts/ephemeralapp2/EphemeralActivity.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.ephemeralapp2;
+
+import android.app.Activity;
+import android.app.SearchManager;
+import android.content.Intent;
+import android.content.pm.PackageInfo;
+import android.content.pm.ResolveInfo;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.net.Uri;
+import android.os.Bundle;
+import android.provider.SearchRecentSuggestions;
+import android.util.Log;
+
+import com.android.cts.util.TestResult;
+
+import java.util.List;
+
+public class EphemeralActivity extends Activity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        final Intent intent  = getIntent();
+        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
+            final String query = intent.getStringExtra(SearchManager.QUERY);
+            final SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
+                    SearchSuggestionProvider.AUTHORITY, SearchSuggestionProvider.MODE);
+            suggestions.saveRecentQuery(query, null);
+        }
+
+        TestResult.getBuilder()
+                .setPackageName("com.android.cts.ephemeralapp2")
+                .setComponentName("EphemeralActivity")
+                .setIntent(getIntent())
+                .setStatus("PASS")
+                .build()
+                .startActivity(this, Uri.parse("https://cts.google.com/result"));
+        finish();
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/src/com/android/cts/ephemeralapp2/EphemeralProvider.java b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/src/com/android/cts/ephemeralapp2/EphemeralProvider.java
new file mode 100644
index 0000000..a0664fe
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/src/com/android/cts/ephemeralapp2/EphemeralProvider.java
@@ -0,0 +1,73 @@
+/*
+ * 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 com.android.cts.ephemeralapp2;
+
+import android.content.ContentProvider;
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.UriMatcher;
+import android.database.CharArrayBuffer;
+import android.database.ContentObserver;
+import android.database.Cursor;
+import android.database.DataSetObserver;
+import android.database.MatrixCursor;
+import android.net.Uri;
+import android.os.Bundle;
+
+public class EphemeralProvider extends ContentProvider {
+    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
+    static {
+        sUriMatcher.addURI("com.android.cts.ephemeralapp2.provider", "table", 1);
+    }
+    private static final String[] sColumnNames = { "_ID", "name" };
+    private static final MatrixCursor sCursor = new MatrixCursor(sColumnNames, 1);
+    static {
+        sCursor.newRow().add(1).add("InstantAppProvider");
+    }
+
+    @Override
+    public boolean onCreate() {
+        return true;
+    }
+
+    @Override
+    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
+            String sortOrder) {
+        return (sUriMatcher.match(uri) != 1) ? null : sCursor;
+    }
+
+    @Override
+    public String getType(Uri uri) {
+        return null;
+    }
+
+    @Override
+    public Uri insert(Uri uri, ContentValues values) {
+        return null;
+    }
+
+    @Override
+    public int delete(Uri uri, String selection, String[] selectionArgs) {
+        return 0;
+    }
+
+    @Override
+    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+        return 0;
+    }
+
+}
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/util/src/com/android/cts/util/TestResult.java b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/util/src/com/android/cts/util/TestResult.java
index 0f52e80..632ded9 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/util/src/com/android/cts/util/TestResult.java
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/util/src/com/android/cts/util/TestResult.java
@@ -18,6 +18,7 @@
 
 import android.content.Context;
 import android.content.Intent;
+import android.net.Uri;
 import android.os.Parcel;
 import android.os.Parcelable;
 
@@ -75,6 +76,14 @@
         context.sendBroadcast(broadcastIntent);
     }
 
+    public void startActivity(Context context, Uri uri) {
+        final Intent broadcastIntent = new Intent(Intent.ACTION_VIEW);
+        broadcastIntent.addCategory(Intent.CATEGORY_BROWSABLE);
+        broadcastIntent.putExtra(EXTRA_TEST_RESULT, this);
+        broadcastIntent.setData(uri);
+        context.startActivity(broadcastIntent);
+    }
+
     private TestResult(String packageName, String componentName, String methodName,
             String status, String exception, Intent intent,
             boolean ephemeralPackageInfoExposed) {
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
index 212cb01..3cb0bce 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
@@ -185,6 +185,12 @@
           </intent-filter>
         </receiver>
 
+        <receiver android:name=".LockProfileReceiver">
+          <intent-filter>
+            <action android:name="com.android.cts.managedprofile.LOCK_PROFILE" />
+          </intent-filter>
+        </receiver>
+
     </application>
 
     <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/LockNowTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/LockNowTest.java
deleted file mode 100644
index fd5fcd2..0000000
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/LockNowTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.managedprofile;
-
-import android.app.admin.DevicePolicyManager;
-
-/**
- * Test lockNow() for use in a managed profile. If called from a managed profile. lockNow() can be
- * passed a flag to evict the CE key of the profile.
- */
-public class LockNowTest extends BaseManagedProfileTest {
-
-  public void testLockNowWithKeyEviction() throws InterruptedException {
-        mDevicePolicyManager.lockNow(DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY);
-        // The test that the managed profile was locked is done in the host
-    }
-
-}
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/LockProfileReceiver.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/LockProfileReceiver.java
new file mode 100644
index 0000000..59f13e1
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/LockProfileReceiver.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.managedprofile;
+
+import android.app.admin.DevicePolicyManager;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+
+/**
+ * Invoke lockNow() with a flag to evict the CE key of the profile. Used by the hostside test to
+ * lock the profile with key eviction. This is triggered via a broadcast instead of a normal
+ * test case, since the test process will be killed after calling lockNow() which will result in
+ * a test failure if this were run as a test case.
+ */
+public class LockProfileReceiver extends BroadcastReceiver {
+
+    private static final String ACTION_LOCK_PROFILE = "com.android.cts.managedprofile.LOCK_PROFILE";
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        if (ACTION_LOCK_PROFILE.equals(intent.getAction())) {
+            final DevicePolicyManager dpm = context.getSystemService(DevicePolicyManager.class);
+            dpm.lockNow(DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY);
+        }
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ResetPasswordWithTokenTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ResetPasswordWithTokenTest.java
index 6487b50..4ea8f3b 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ResetPasswordWithTokenTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ResetPasswordWithTokenTest.java
@@ -40,12 +40,11 @@
     }
 
     /**
-     * Set a reset password token and work challenge on the work profile, and then lock it
-     * with CE evicted. This is the preparation step for {@link #testResetPasswordBeforeUnlock}
-     * to put the profile in RUNNING_LOCKED state, and will be called by the hostside logic before
-     * {@link #testResetPasswordBeforeUnlock} is exercised.
+     * Set a reset password token and work challenge on the work profile. This is the preparation
+     * step for {@link #testResetPasswordBeforeUnlock} and will be called by the hostside logic
+     * before it is exercised.
      */
-    public void testSetupWorkProfileAndLock() {
+    public void testSetupWorkProfile() {
         testSetResetPasswordToken();
         // Reset password on the work profile will enable separate work challenge for it.
         assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT, PASSWORD0,
@@ -54,8 +53,6 @@
         mDevicePolicyManager.setPasswordQuality(ADMIN_RECEIVER_COMPONENT,
                 DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
         mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, 6);
-
-        testLockWorkProfile();
     }
 
     public void testResetPasswordBeforeUnlock() {
@@ -74,8 +71,4 @@
         assertTrue(mDevicePolicyManager.setResetPasswordToken(ADMIN_RECEIVER_COMPONENT, token));
         assertTrue(mDevicePolicyManager.isResetPasswordTokenActive(ADMIN_RECEIVER_COMPONENT));
     }
-
-    public void testLockWorkProfile() {
-        mDevicePolicyManager.lockNow(DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY);
-    }
 }
\ No newline at end of file
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
index b67ce81..2dd5a2a 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
@@ -199,8 +199,14 @@
             return;
         }
         changeUserCredential("1234", null, mProfileUserId);
-        runDeviceTestsAsUser(MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".LockNowTest",
-                "testLockNowWithKeyEviction", mProfileUserId);
+        lockProfile();
+    }
+
+    private void lockProfile() throws Exception {
+        final String cmd = "am broadcast --receiver-foreground --user " + mProfileUserId
+                + " -a com.android.cts.managedprofile.LOCK_PROFILE"
+                + " com.android.cts.managedprofile/.LockProfileReceiver";
+        getDevice().executeShellCommand(cmd);
         waitUntilProfileLocked();
     }
 
@@ -1152,8 +1158,8 @@
         }
 
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
-                "testSetupWorkProfileAndLock", mProfileUserId);
-        waitUntilProfileLocked();
+                "testSetupWorkProfile", mProfileUserId);
+        lockProfile();
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
                 "testResetPasswordBeforeUnlock", mProfileUserId);
         // Password needs to be in sync with ResetPasswordWithTokenTest.PASSWORD1
@@ -1179,10 +1185,7 @@
             changeUserCredential(devicePassword, null, mParentUserId);
             changeUserCredential(null, devicePassword, mParentUserId);
             changeUserCredential(devicePassword, null, mParentUserId);
-
-            runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
-                    "testLockWorkProfile", mProfileUserId);
-            waitUntilProfileLocked();
+            lockProfile();
             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
                     "testResetPasswordBeforeUnlock", mProfileUserId);
             verifyUserCredential(RESET_PASSWORD_TEST_DEFAULT_PASSWORD, mProfileUserId);
diff --git a/hostsidetests/incident/src/com/android/server/cts/MemInfoIncidentTest.java b/hostsidetests/incident/src/com/android/server/cts/MemInfoIncidentTest.java
index 20a6cab..2747972 100644
--- a/hostsidetests/incident/src/com/android/server/cts/MemInfoIncidentTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/MemInfoIncidentTest.java
@@ -60,7 +60,10 @@
         assertTrue(0 <= dump.getUsedPssKb());
         assertTrue(0 <= dump.getUsedKernelKb());
 
-        assertTrue(0 <= dump.getLostRamKb());
+        // Ideally lost RAM would not be negative, but there's an issue where it's sometimes
+        // calculated to be negative.
+        // TODO: re-enable check once the underlying bug has been fixed.
+        // assertTrue(0 <= dump.getLostRamKb());
 
         assertTrue(0 <= dump.getTotalZramKb());
         assertTrue(0 <= dump.getZramPhysicalUsedInSwapKb());
diff --git a/hostsidetests/inputmethodservice/common/Android.mk b/hostsidetests/inputmethodservice/common/Android.mk
index 8d03e93..94b59c9 100644
--- a/hostsidetests/inputmethodservice/common/Android.mk
+++ b/hostsidetests/inputmethodservice/common/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_MODULE := CtsInputMethodServiceCommon
 
diff --git a/hostsidetests/inputmethodservice/deviceside/devicetest/Android.mk b/hostsidetests/inputmethodservice/deviceside/devicetest/Android.mk
index 6f3a29d..1727ad7 100644
--- a/hostsidetests/inputmethodservice/deviceside/devicetest/Android.mk
+++ b/hostsidetests/inputmethodservice/deviceside/devicetest/Android.mk
@@ -36,7 +36,7 @@
     CtsInputMethodServiceLib
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_PACKAGE_NAME := CtsInputMethodServiceDeviceTests
 
diff --git a/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.mk b/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.mk
index 3461dbb..30fdb08 100644
--- a/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.mk
+++ b/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.mk
@@ -31,7 +31,7 @@
     CtsInputMethodServiceCommon
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_PACKAGE_NAME := EditTextApp
 
diff --git a/hostsidetests/inputmethodservice/deviceside/ime1/Android.mk b/hostsidetests/inputmethodservice/deviceside/ime1/Android.mk
index f6da1c4..850b89f 100644
--- a/hostsidetests/inputmethodservice/deviceside/ime1/Android.mk
+++ b/hostsidetests/inputmethodservice/deviceside/ime1/Android.mk
@@ -32,7 +32,7 @@
     CtsInputMethodServiceLib
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_PACKAGE_NAME := CtsInputMethod1
 
diff --git a/hostsidetests/inputmethodservice/deviceside/ime2/Android.mk b/hostsidetests/inputmethodservice/deviceside/ime2/Android.mk
index e11e28a..fcd146c 100644
--- a/hostsidetests/inputmethodservice/deviceside/ime2/Android.mk
+++ b/hostsidetests/inputmethodservice/deviceside/ime2/Android.mk
@@ -32,7 +32,7 @@
     CtsInputMethodServiceLib
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_PACKAGE_NAME := CtsInputMethod2
 
diff --git a/hostsidetests/inputmethodservice/deviceside/provider/Android.mk b/hostsidetests/inputmethodservice/deviceside/provider/Android.mk
index 91f6ce7..b8f308d 100644
--- a/hostsidetests/inputmethodservice/deviceside/provider/Android.mk
+++ b/hostsidetests/inputmethodservice/deviceside/provider/Android.mk
@@ -31,7 +31,7 @@
     CtsInputMethodServiceLib
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_PACKAGE_NAME := CtsInputMethodServiceEventProvider
 
diff --git a/hostsidetests/inputmethodservice/hostside/Android.mk b/hostsidetests/inputmethodservice/hostside/Android.mk
index 5ff22a2..2cfca0e 100644
--- a/hostsidetests/inputmethodservice/hostside/Android.mk
+++ b/hostsidetests/inputmethodservice/hostside/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_MODULE := CtsInputMethodServiceHostTestCases
 
diff --git a/hostsidetests/media/app/MediaSessionTestHelper/Android.mk b/hostsidetests/media/app/MediaSessionTestHelper/Android.mk
index 871140a..514f86a 100644
--- a/hostsidetests/media/app/MediaSessionTestHelper/Android.mk
+++ b/hostsidetests/media/app/MediaSessionTestHelper/Android.mk
@@ -30,7 +30,7 @@
     $(call all-java-files-under, ../../common)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_PACKAGE_NAME := CtsMediaSessionTestHelper
 
diff --git a/hostsidetests/sample/app/Android.mk b/hostsidetests/sample/app/Android.mk
index b3b6ad1..bc271b6 100644
--- a/hostsidetests/sample/app/Android.mk
+++ b/hostsidetests/sample/app/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_PACKAGE_NAME := CtsSampleDeviceApp
 
diff --git a/hostsidetests/sample/app2/Android.mk b/hostsidetests/sample/app2/Android.mk
index d6fbd2d..cec0078 100644
--- a/hostsidetests/sample/app2/Android.mk
+++ b/hostsidetests/sample/app2/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_PACKAGE_NAME := CtsSampleDeviceApp2
 
diff --git a/hostsidetests/ui/Android.mk b/hostsidetests/ui/Android.mk
index af7e2c9..90fdad2 100644
--- a/hostsidetests/ui/Android.mk
+++ b/hostsidetests/ui/Android.mk
@@ -31,7 +31,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.ui.cts
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := general-tests cts_instant
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/ui/appA/Android.mk b/hostsidetests/ui/appA/Android.mk
index 3abc7a0..cf6df92 100644
--- a/hostsidetests/ui/appA/Android.mk
+++ b/hostsidetests/ui/appA/Android.mk
@@ -32,6 +32,6 @@
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_SDK_VERSION := current
+LOCAL_SDK_VERSION := test_current
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/ui/appA/AndroidManifest.xml b/hostsidetests/ui/appA/AndroidManifest.xml
index dd2a901..155e0af 100644
--- a/hostsidetests/ui/appA/AndroidManifest.xml
+++ b/hostsidetests/ui/appA/AndroidManifest.xml
@@ -1,6 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!--
-     Copyright (C) 2012 The Android Open Source Project
+<!-- Copyright (C) 2012 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.
@@ -16,23 +15,29 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-        package="android.taskswitching.appa">
-
-    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
+        package="android.taskswitching.appa"
+        android:targetSandboxVersion="2">
 
     <application>
         <uses-library android:name="android.test.runner" />
 
         <activity
             android:name=".AppAActivity"
-            android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
             android:screenOrientation="portrait" >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
 
-                <category android:name="android.intent.category.LAUNCHER" />
+            <intent-filter>
+                <action android:name="android.intent.action.VIEW" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <category android:name="android.intent.category.BROWSABLE" />
+                <data android:scheme="https" />
+                <data android:host="foo.com" />
+                <data android:path="/appa" />
             </intent-filter>
+
         </activity>
     </application>
 
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.taskswitching.appa" />
+
 </manifest>
diff --git a/hostsidetests/ui/appA/src/android/taskswitching/appa/AppAActivity.java b/hostsidetests/ui/appA/src/android/taskswitching/appa/AppAActivity.java
index 32ccfc1..2fe49ac 100644
--- a/hostsidetests/ui/appA/src/android/taskswitching/appa/AppAActivity.java
+++ b/hostsidetests/ui/appA/src/android/taskswitching/appa/AppAActivity.java
@@ -17,10 +17,9 @@
 package android.taskswitching.appa;
 
 import android.app.ListActivity;
-import android.content.Intent;
-
 import android.os.Bundle;
 import android.os.Handler;
+import android.os.RemoteCallback;
 import android.view.WindowManager;
 import android.widget.ArrayAdapter;
 import android.widget.ListView;
@@ -30,9 +29,7 @@
  * This is for measuring taskswitching time between two apps.
  */
 public class AppAActivity extends ListActivity {
-    static final String TAG = "AppAActivity";
     private static final int NUMBER_ELEMENTS = 1000;
-    private static final String TASKSWITCHING_INTENT = "android.taskswitching.appa";
     private Handler mHandler;
 
     private String[] mItems = new String[NUMBER_ELEMENTS];
@@ -53,13 +50,8 @@
     @Override
     public void onResume() {
         super.onResume();
-        mHandler.post(new Runnable() {
-
-            @Override
-            public void run() {
-                Intent intent = new Intent(TASKSWITCHING_INTENT);
-                sendBroadcast(intent);
-            }
+        mHandler.post(() -> {
+            getIntent().<RemoteCallback>getParcelableExtra("callback").sendResult(null);
         });
     }
 }
diff --git a/hostsidetests/ui/appB/Android.mk b/hostsidetests/ui/appB/Android.mk
index 4501cf3..6c64244 100644
--- a/hostsidetests/ui/appB/Android.mk
+++ b/hostsidetests/ui/appB/Android.mk
@@ -32,6 +32,6 @@
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_SDK_VERSION := current
+LOCAL_SDK_VERSION := test_current
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/ui/appB/AndroidManifest.xml b/hostsidetests/ui/appB/AndroidManifest.xml
index 9d99377..0cd5092 100644
--- a/hostsidetests/ui/appB/AndroidManifest.xml
+++ b/hostsidetests/ui/appB/AndroidManifest.xml
@@ -15,7 +15,8 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-        package="android.taskswitching.appb">
+        package="android.taskswitching.appb"
+        android:targetSandboxVersion="2">
 
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
 
@@ -28,9 +29,18 @@
             android:screenOrientation="portrait" >
 
             <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER"/>
+                <action android:name="android.intent.action.VIEW" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <category android:name="android.intent.category.BROWSABLE" />
+                <data android:scheme="https" />
+                <data android:host="foo.com" />
+                <data android:path="/appb" />
             </intent-filter>
+
         </activity>
     </application>
+
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.taskswitching.appb" />
+
 </manifest>
diff --git a/hostsidetests/ui/appB/src/android/taskswitching/appb/AppBActivity.java b/hostsidetests/ui/appB/src/android/taskswitching/appb/AppBActivity.java
index ea7f52a..c799d46 100644
--- a/hostsidetests/ui/appB/src/android/taskswitching/appb/AppBActivity.java
+++ b/hostsidetests/ui/appB/src/android/taskswitching/appb/AppBActivity.java
@@ -17,9 +17,9 @@
 package android.taskswitching.appb;
 
 import android.app.ListActivity;
-import android.content.Intent;
 import android.os.Bundle;
 import android.os.Handler;
+import android.os.RemoteCallback;
 import android.view.WindowManager;
 import android.widget.ArrayAdapter;
 import android.widget.ListView;
@@ -29,9 +29,7 @@
  * This is for measuring taskswitching time between two apps.
  */
 public class AppBActivity extends ListActivity {
-    static final String TAG = "AppBActivity";
     private static final int NUMBER_ELEMENTS = 1000;
-    private static final String TASKSWITCHING_INTENT = "android.taskswitching.appb";
     private Handler mHandler;
 
     private String[] mItems = new String[NUMBER_ELEMENTS];
@@ -52,13 +50,8 @@
     @Override
     public void onResume() {
         super.onResume();
-        mHandler.post(new Runnable() {
-
-            @Override
-            public void run() {
-                Intent intent = new Intent(TASKSWITCHING_INTENT);
-                sendBroadcast(intent);
-            }
+        mHandler.post(() -> {
+            getIntent().<RemoteCallback>getParcelableExtra("callback").sendResult(null);
         });
     }
 }
diff --git a/hostsidetests/ui/control/Android.mk b/hostsidetests/ui/control/Android.mk
index 3b4f8da..e35c4f0 100644
--- a/hostsidetests/ui/control/Android.mk
+++ b/hostsidetests/ui/control/Android.mk
@@ -31,6 +31,6 @@
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_SDK_VERSION := current
+LOCAL_SDK_VERSION := test_current
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/ui/control/AndroidManifest.xml b/hostsidetests/ui/control/AndroidManifest.xml
index 8102620..2b6b0dd 100644
--- a/hostsidetests/ui/control/AndroidManifest.xml
+++ b/hostsidetests/ui/control/AndroidManifest.xml
@@ -15,7 +15,8 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-        package="android.taskswitching.control.cts">
+        package="android.taskswitching.control.cts"
+        android:targetSandboxVersion="2">
 
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
diff --git a/hostsidetests/ui/control/src/android/taskswitching/control/cts/TaskSwitchingDeviceTest.java b/hostsidetests/ui/control/src/android/taskswitching/control/cts/TaskSwitchingDeviceTest.java
index 6b99c20..1471550 100644
--- a/hostsidetests/ui/control/src/android/taskswitching/control/cts/TaskSwitchingDeviceTest.java
+++ b/hostsidetests/ui/control/src/android/taskswitching/control/cts/TaskSwitchingDeviceTest.java
@@ -16,17 +16,11 @@
 
 package android.taskswitching.control.cts;
 
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.Context;
 import android.content.Intent;
-import android.content.IntentFilter;
+import android.net.Uri;
+import android.os.RemoteCallback;
 
 import com.android.compatibility.common.util.CtsAndroidTestCase;
-
 import com.android.compatibility.common.util.DeviceReportLog;
 import com.android.compatibility.common.util.MeasureRun;
 import com.android.compatibility.common.util.MeasureTime;
@@ -34,6 +28,11 @@
 import com.android.compatibility.common.util.ResultUnit;
 import com.android.compatibility.common.util.Stat;
 
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
 /**
  * Device test which actually launches two apps sequentially and
  * measure time for switching.
@@ -41,32 +40,15 @@
  */
 public class TaskSwitchingDeviceTest extends CtsAndroidTestCase {
     private static final String REPORT_LOG_NAME = "CtsUiHostTestCases";
-    private static final String PKG_A = "android.taskswitching.appa";
-    private static final String PKG_B = "android.taskswitching.appb";
-    private static final String ACTIVITY_A = "AppAActivity";
-    private static final String ACTIVITY_B = "AppBActivity";
     private static final long TASK_SWITCHING_WAIT_TIME = 5;
-    private final AppBroadcastReceiver mReceiverA = new AppBroadcastReceiver();
-    private final AppBroadcastReceiver mReceiverB = new AppBroadcastReceiver();
+
+    private final Semaphore mSemaphore = new Semaphore(0);
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        getContext().registerReceiver(mReceiverA, new IntentFilter(PKG_A));
-        getContext().registerReceiver(mReceiverB, new IntentFilter(PKG_B));
 
-        startActivity(PKG_A, ACTIVITY_A);
-        assertTrue(mReceiverA.waitForBroadcast(TASK_SWITCHING_WAIT_TIME));
-
-        startActivity(PKG_B, ACTIVITY_B);
-        assertTrue(mReceiverB.waitForBroadcast(TASK_SWITCHING_WAIT_TIME));
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        getContext().unregisterReceiver(mReceiverA);
-        getContext().unregisterReceiver(mReceiverB);
-        super.tearDown();
+        startActivitiesABSequentially();
     }
 
     public void testMeasureTaskSwitching() throws Exception {
@@ -78,10 +60,7 @@
             @Override
             public void run(int i) throws Exception {
                 for (int j = 0; j < SWITCHING_PER_ONE_TRY; j++) {
-                    startActivity(PKG_A, ACTIVITY_A);
-                    assertTrue(mReceiverA.waitForBroadcast(TASK_SWITCHING_WAIT_TIME));
-                    startActivity(PKG_B, ACTIVITY_B);
-                    assertTrue(mReceiverB.waitForBroadcast(TASK_SWITCHING_WAIT_TIME));
+                    startActivitiesABSequentially();
                 }
             }
         });
@@ -94,24 +73,20 @@
         report.submit(getInstrumentation());
     }
 
-    private void startActivity(String packageName, String activityName) {
-        Context context = getContext();
-        Intent intent = new Intent();
-        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-        intent.addCategory(Intent.CATEGORY_LAUNCHER);
-        intent.setComponent(new ComponentName(packageName, packageName + "." + activityName));
-        context.startActivity(intent);
+    private void startActivitiesABSequentially()
+            throws InterruptedException, TimeoutException, ExecutionException {
+        startActivityAndWait('a');
+        startActivityAndWait('b');
     }
 
-    class AppBroadcastReceiver extends BroadcastReceiver {
-        private final Semaphore mSemaphore = new Semaphore(0);
-
-        public boolean waitForBroadcast(long timeoutInSec) throws InterruptedException {
-            return mSemaphore.tryAcquire(timeoutInSec, TimeUnit.SECONDS);
-        }
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            mSemaphore.release();
-        }
+    private void startActivityAndWait(char activityLetter)
+            throws InterruptedException, TimeoutException, ExecutionException {
+        getContext().startActivity(new Intent(Intent.ACTION_VIEW)
+                .setData(Uri.parse("https://foo.com/app" + activityLetter))
+                .addCategory(Intent.CATEGORY_DEFAULT)
+                .addCategory(Intent.CATEGORY_BROWSABLE)
+                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+                .putExtra("callback", new RemoteCallback(b -> mSemaphore.release())));
+        mSemaphore.tryAcquire(TASK_SWITCHING_WAIT_TIME, TimeUnit.SECONDS);
     }
 }
diff --git a/hostsidetests/ui/src/android/ui/cts/InstallTimeTest.java b/hostsidetests/ui/src/android/ui/cts/InstallTimeTest.java
index 03a581d..c45b021 100644
--- a/hostsidetests/ui/src/android/ui/cts/InstallTimeTest.java
+++ b/hostsidetests/ui/src/android/ui/cts/InstallTimeTest.java
@@ -16,6 +16,9 @@
 
 package android.ui.cts;
 
+import android.platform.test.annotations.AppModeFull;
+import android.platform.test.annotations.AppModeInstant;
+
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.compatibility.common.util.MeasureRun;
 import com.android.compatibility.common.util.MeasureTime;
@@ -71,7 +74,17 @@
         super.tearDown();
     }
 
-    public void testInstallTime() throws Exception {
+    @AppModeInstant
+    public void testInstallTimeInstant() throws Exception {
+        testInstallTime(true);
+    }
+
+    @AppModeFull
+    public void testInstallTimeFull() throws Exception {
+        testInstallTime(false);
+    }
+
+    private void testInstallTime(boolean instant) throws Exception {
         String streamName = "test_install_time";
         MetricsReportLog report = new MetricsReportLog(mBuild, mAbi.getName(),
                 String.format("%s#%s", getClass().getName(), "testInstallTime"), REPORT_LOG_NAME,
@@ -87,7 +100,8 @@
             @Override
             public void run(int i) throws Exception {
                 File app = buildHelper.getTestFile(APK);
-                String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+                String[] options =
+                        {AbiUtils.createAbiFlag(mAbi.getName()), instant ? "--instant" : ""};
                 device.installPackage(app, false, options);
             }
         });
diff --git a/hostsidetests/ui/src/android/ui/cts/TaskSwitchingTest.java b/hostsidetests/ui/src/android/ui/cts/TaskSwitchingTest.java
index 814d4e1..9f2bd44 100644
--- a/hostsidetests/ui/src/android/ui/cts/TaskSwitchingTest.java
+++ b/hostsidetests/ui/src/android/ui/cts/TaskSwitchingTest.java
@@ -16,6 +16,9 @@
 
 package android.ui.cts;
 
+import android.platform.test.annotations.AppModeFull;
+import android.platform.test.annotations.AppModeInstant;
+
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.compatibility.common.util.MetricsStore;
 import com.android.compatibility.common.util.ReportLog;
@@ -76,9 +79,13 @@
     protected void setUp() throws Exception {
         super.setUp();
         mDevice = getDevice();
-        String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+    }
+
+    private void installPackages(boolean instant) throws Exception {
         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mBuild);
         for (int i = 0; i < PACKAGES.length; i++) {
+            String[] options = {AbiUtils.createAbiFlag(mAbi.getName()),
+                    instant && !PACKAGES[i].contains("control") ? "--instant" : ""};
             mDevice.uninstallPackage(PACKAGES[i]);
             File app = buildHelper.getTestFile(APKS[i]);
             mDevice.installPackage(app, false, options);
@@ -94,7 +101,19 @@
         super.tearDown();
     }
 
-    public void testTaskSwitching() throws Exception {
+    @AppModeInstant
+    public void testTaskSwitchingInstant() throws Exception {
+        installPackages(true);
+        doTestTaskSwitching();
+    }
+
+    @AppModeFull
+    public void testTaskSwitchingFull() throws Exception {
+        installPackages(false);
+        doTestTaskSwitching();
+    }
+
+    private void doTestTaskSwitching() throws Exception {
         RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(PACKAGES[0], RUNNER,
                 mDevice.getIDevice());
         LocalListener listener = new LocalListener();
diff --git a/hostsidetests/webkit/Android.mk b/hostsidetests/webkit/Android.mk
index 663a079..c3ee4f3 100644
--- a/hostsidetests/webkit/Android.mk
+++ b/hostsidetests/webkit/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.webkit.hostside
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/webkit/app/Android.mk b/hostsidetests/webkit/app/Android.mk
index fd2ee9a..2b0be1c 100644
--- a/hostsidetests/webkit/app/Android.mk
+++ b/hostsidetests/webkit/app/Android.mk
@@ -40,6 +40,6 @@
 LOCAL_DEX_PREOPT := false
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/webkit/app/AndroidManifest.xml b/hostsidetests/webkit/app/AndroidManifest.xml
index 108e837..cfd25d5 100644
--- a/hostsidetests/webkit/app/AndroidManifest.xml
+++ b/hostsidetests/webkit/app/AndroidManifest.xml
@@ -15,7 +15,7 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.webkit">
+    package="com.android.cts.webkit" android:targetSandboxVersion="2">
 
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.INTERNET" />
diff --git a/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java b/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java
index 852e4a2..692310b 100644
--- a/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java
+++ b/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java
@@ -18,6 +18,7 @@
 
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
+import android.net.http.SslError;
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.Looper;
@@ -27,9 +28,11 @@
 import android.util.Log;
 import android.webkit.CookieManager;
 import android.webkit.CookieSyncManager;
+import android.webkit.SslErrorHandler;
 import android.webkit.WebView;
 import android.webkit.cts.CtsTestServer;
 import android.webkit.cts.WebViewOnUiThread;
+import android.webkit.cts.WebViewOnUiThread.WaitForLoadedClient;
 import android.webkit.WebView;
 
 import com.android.compatibility.common.util.NullWebViewUtils;
@@ -67,7 +70,8 @@
 
     @UiThreadTest
     public void testCookieManagerBlockingUiThread() throws Throwable {
-        CtsTestServer server = new CtsTestServer(mActivity, false);
+        // Instant app can only have https connection.
+        CtsTestServer server = new CtsTestServer(mActivity, true);
         final String url = server.getCookieUrl("death.html");
 
         Thread background = new Thread(new Runnable() {
@@ -95,7 +99,15 @@
 
         // Now create WebView and test that setting the cookie beforehand really worked.
         mActivity.createAndAttachWebView();
+        WebView webView = mActivity.getWebView();
         WebViewOnUiThread onUiThread = new WebViewOnUiThread(this, mActivity.getWebView());
+        webView.setWebViewClient(new WaitForLoadedClient(onUiThread) {
+            @Override
+            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
+                // Not intended to verify server certificate, ignore the error.
+                if (error.getPrimaryError() == SslError.SSL_IDMISMATCH) handler.proceed();
+            }
+        });
         onUiThread.loadUrlAndWaitForCompletion(url);
         assertEquals("1|count=41", onUiThread.getTitle()); // outgoing cookie
         CookieManager cookieManager = CookieManager.getInstance();
diff --git a/tests/AlarmManager/app/src/android/alarmmanager/alarmtestapp/cts/TestAlarmReceiver.java b/tests/AlarmManager/app/src/android/alarmmanager/alarmtestapp/cts/TestAlarmReceiver.java
index a083e08..55ea6cf 100644
--- a/tests/AlarmManager/app/src/android/alarmmanager/alarmtestapp/cts/TestAlarmReceiver.java
+++ b/tests/AlarmManager/app/src/android/alarmmanager/alarmtestapp/cts/TestAlarmReceiver.java
@@ -34,6 +34,7 @@
         final Intent reportAlarmIntent = new Intent(ACTION_REPORT_ALARM_EXPIRED);
         reportAlarmIntent.putExtra(EXTRA_ALARM_COUNT, count);
         reportAlarmIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
+        reportAlarmIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
         context.sendBroadcast(reportAlarmIntent);
     }
 }
diff --git a/tests/AlarmManager/src/android/alarmmanager/cts/AppStandbyTests.java b/tests/AlarmManager/src/android/alarmmanager/cts/AppStandbyTests.java
index 7c6fc65..36acd82 100644
--- a/tests/AlarmManager/src/android/alarmmanager/cts/AppStandbyTests.java
+++ b/tests/AlarmManager/src/android/alarmmanager/cts/AppStandbyTests.java
@@ -59,7 +59,7 @@
     private static final String TEST_APP_PACKAGE = "android.alarmmanager.alarmtestapp.cts";
     private static final String TEST_APP_RECEIVER = TEST_APP_PACKAGE + ".TestAlarmScheduler";
 
-    private static final long DEFAULT_WAIT = 1_000;
+    private static final long DEFAULT_WAIT = 4_000;
     private static final long POLL_INTERVAL = 200;
 
     // Tweaked alarm manager constants to facilitate testing
@@ -136,6 +136,7 @@
         setAlarmIntent.putExtra(TestAlarmScheduler.EXTRA_TRIGGER_TIME, triggerMillis);
         setAlarmIntent.putExtra(TestAlarmScheduler.EXTRA_REPEAT_INTERVAL, interval);
         setAlarmIntent.putExtra(TestAlarmScheduler.EXTRA_ALLOW_WHILE_IDLE, allowWhileIdle);
+        setAlarmIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
         mContext.sendBroadcast(setAlarmIntent);
     }
 
diff --git a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityManagerTest.java b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityManagerTest.java
index 8c87d78..0cf2c19 100644
--- a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityManagerTest.java
+++ b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityManagerTest.java
@@ -58,6 +58,8 @@
                 getInstrumentation().getContext().getSystemService(Service.ACCESSIBILITY_SERVICE);
         mTargetContext = getInstrumentation().getTargetContext();
         mHandler = new Handler(mTargetContext.getMainLooper());
+        // In case the test runner started a UiAutomation, destroy it to start with a clean slate.
+        getInstrumentation().getUiAutomation().destroy();
         ServiceControlUtils.turnAccessibilityOff(getInstrumentation());
     }
 
diff --git a/tests/autofillservice/src/android/autofillservice/cts/WebViewActivity.java b/tests/autofillservice/src/android/autofillservice/cts/WebViewActivity.java
index ef54c78..a8da1a3 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/WebViewActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/WebViewActivity.java
@@ -15,6 +15,8 @@
  */
 package android.autofillservice.cts;
 
+import static android.autofillservice.cts.Timeouts.WEBVIEW_TIMEOUT;
+
 import android.content.Context;
 import android.os.Bundle;
 import android.os.SystemClock;
@@ -30,6 +32,8 @@
 import android.widget.LinearLayout;
 
 import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 public class WebViewActivity extends AbstractAutoFillActivity {
 
@@ -70,6 +74,7 @@
     }
 
     public MyWebView loadWebView(UiBot uiBot, boolean usingAppContext) throws Exception {
+        final CountDownLatch latch = new CountDownLatch(1);
         syncRunOnUiThread(() -> {
             final Context context = usingAppContext ? getApplicationContext() : this;
             mWebView = new MyWebView(context);
@@ -98,13 +103,26 @@
                         throw new IllegalArgumentException("Error opening " + rawPath, e);
                     }
                 }
+
+                @Override
+                public void onPageFinished(WebView view, String url) {
+                    Log.v(TAG, "onPageFinished(): " + url);
+                    latch.countDown();
+                }
+
             });
             mWebView.loadUrl(FAKE_URL);
         });
 
         // Wait until it's loaded.
+
+        if (!latch.await(WEBVIEW_TIMEOUT.ms(), TimeUnit.MILLISECONDS)) {
+            throw new RetryableException(WEBVIEW_TIMEOUT, "WebView not loaded");
+        }
+
+        // TODO(b/80317628): re-add check below
         // NOTE: we cannot search by resourceId because WebView does not set them...
-        uiBot.assertShownByText("Login"); // Login button
+        // uiBot.assertShownByText("Login"); // Login button
 
         return mWebView;
     }
diff --git a/tests/framework/base/windowmanager/AndroidTest.xml b/tests/framework/base/windowmanager/AndroidTest.xml
index 624d4e6..337ada0 100644
--- a/tests/framework/base/windowmanager/AndroidTest.xml
+++ b/tests/framework/base/windowmanager/AndroidTest.xml
@@ -22,11 +22,16 @@
         <option name="test-file-name" value="CtsWindowManagerDeviceTestCases.apk"/>
         <option name="test-file-name" value="CtsDragAndDropSourceApp.apk"/>
         <option name="test-file-name" value="CtsDragAndDropTargetApp.apk"/>
-        <option name="test-file-name" value="CtsDragAndDropTargetAppSdk23.apk"/>
         <option name="test-file-name" value="CtsDeviceAlertWindowTestApp.apk"/>
-        <option name="test-file-name" value="CtsDeviceAlertWindowTestAppSdk25.apk"/>
         <option name="test-file-name" value="CtsAlertWindowService.apk"/>
     </target_preparer>
+    <!-- Some older apk cannot be installed as instant, so we force them full mode -->
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true"/>
+        <option name="force-install-mode" value="FULL"/>
+        <option name="test-file-name" value="CtsDragAndDropTargetAppSdk23.apk"/>
+        <option name="test-file-name" value="CtsDeviceAlertWindowTestAppSdk25.apk"/>
+    </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest">
         <option name="package" value="android.server.cts.wm"/>
         <option name="runtime-hint" value="8m"/>
diff --git a/tests/framework/base/windowmanager/alertwindowapp/AndroidManifest.xml b/tests/framework/base/windowmanager/alertwindowapp/AndroidManifest.xml
index 446e2fa..00268da 100755
--- a/tests/framework/base/windowmanager/alertwindowapp/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/alertwindowapp/AndroidManifest.xml
@@ -17,7 +17,8 @@
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
-          package="android.server.wm.alertwindowapp">
+          package="android.server.wm.alertwindowapp"
+          android:targetSandboxVersion="2">
     <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
 
     <application android:label="CtsAlertWindow">
diff --git a/tests/framework/base/windowmanager/alertwindowservice/AndroidManifest.xml b/tests/framework/base/windowmanager/alertwindowservice/AndroidManifest.xml
index 76c30bd..48164b6 100644
--- a/tests/framework/base/windowmanager/alertwindowservice/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/alertwindowservice/AndroidManifest.xml
@@ -15,7 +15,8 @@
   ~ limitations under the License
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-       package="android.server.wm.alertwindowservice">
+       package="android.server.wm.alertwindowservice"
+       android:targetSandboxVersion="2">
     <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
 
     <application>
diff --git a/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml b/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml
index 4c8f0bb..e7b3453 100644
--- a/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml
@@ -15,7 +15,8 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-        package="android.server.wm.dndsourceapp">
+        package="android.server.wm.dndsourceapp"
+        android:targetSandboxVersion="2">
     <application android:label="CtsDnDSource">
         <activity android:name="android.server.wm.dndsourceapp.DragSource">
             <intent-filter>
diff --git a/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml b/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml
index 33c7a0f..09a0bc9 100644
--- a/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml
@@ -15,7 +15,8 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-        package="android.server.wm.dndtargetapp">
+        package="android.server.wm.dndtargetapp"
+        android:targetSandboxVersion="2">
     <application android:label="CtsDnDTarget">
         <activity android:name="android.server.wm.dndtargetapp.DropTarget">
             <intent-filter>
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AlertWindowsImportanceTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AlertWindowsImportanceTests.java
index 2da6bf0..5d087a7 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AlertWindowsImportanceTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AlertWindowsImportanceTests.java
@@ -39,6 +39,7 @@
 import android.os.Message;
 import android.os.Messenger;
 import android.os.SystemClock;
+import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.Presubmit;
 import android.server.wm.alertwindowservice.AlertWindowService;
 import android.support.test.InstrumentationRegistry;
@@ -113,6 +114,7 @@
     }
 
     @Test
+    @AppModeFull(reason = "Uses apps targeting older SDK")
     public void testAlertWindowOomAdj() throws Exception {
         // Alert windows are always hidden when running in VR.
         if (isRunningInVR()) {
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AlertWindowsTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AlertWindowsTests.java
index ae9c5b5..3ab7c19 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AlertWindowsTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AlertWindowsTests.java
@@ -26,6 +26,7 @@
 import static org.junit.Assert.assertTrue;
 
 import android.content.ComponentName;
+import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.Presubmit;
 import android.server.am.ActivityManagerTestBase;
 import android.server.am.WaitForValidActivityState;
@@ -44,6 +45,7 @@
  *     atest CtsWindowManagerDeviceTestCases:AlertWindowsTests
  */
 @Presubmit
+@AppModeFull(reason = "Requires android.permission.MANAGE_ACTIVITY_STACKS")
 public class AlertWindowsTests extends ActivityManagerTestBase {
 
     // From WindowManager.java
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/CrossAppDragAndDropTests.java b/tests/framework/base/windowmanager/src/android/server/wm/CrossAppDragAndDropTests.java
index 0cc2ac8..5d26234 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/CrossAppDragAndDropTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/CrossAppDragAndDropTests.java
@@ -37,6 +37,7 @@
 import android.content.Context;
 import android.graphics.Point;
 import android.os.RemoteException;
+import android.platform.test.annotations.AppModeFull;
 import android.os.SystemClock;
 import android.platform.test.annotations.Presubmit;
 import android.support.test.InstrumentationRegistry;
@@ -54,6 +55,7 @@
  * Run: cts/tests/framework/base/activitymanager/util/run-test CtsWindowManagerDeviceTestCases android.server.wm.CrossAppDragAndDropTests
  */
 @Presubmit
+@AppModeFull(reason = "Requires android.permission.MANAGE_ACTIVITY_STACKS")
 public class CrossAppDragAndDropTests {
     private static final String TAG = "CrossAppDragAndDrop";
 
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/DialogFrameTests.java b/tests/framework/base/windowmanager/src/android/server/wm/DialogFrameTests.java
index 7e08bff..cc8eba0 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/DialogFrameTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/DialogFrameTests.java
@@ -36,6 +36,7 @@
 
 import android.content.ComponentName;
 import android.graphics.Rect;
+import android.platform.test.annotations.AppModeFull;
 import android.server.am.WaitForValidActivityState;
 import android.server.am.WindowManagerState;
 import android.server.am.WindowManagerState.WindowState;
@@ -54,6 +55,7 @@
  *
  * TODO: Consolidate this class with {@link ParentChildTestBase}.
  */
+@AppModeFull(reason = "Requires android.permission.MANAGE_ACTIVITY_STACKS")
 public class DialogFrameTests extends ParentChildTestBase<DialogFrameTestActivity> {
 
     private static final ComponentName DIALOG_FRAME_TEST_ACTIVITY = new ComponentName(
diff --git a/tests/tests/accounts/Android.mk b/tests/tests/accounts/Android.mk
index 18ab37f..d816707 100644
--- a/tests/tests/accounts/Android.mk
+++ b/tests/tests/accounts/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
-    CtsAccountTestsCommon ctstestrunner
+    CtsAccountTestsCommon ctstestrunner platform-test-annotations
 
 LOCAL_JAVA_LIBRARIES := android.test.runner.stubs android.test.base.stubs
 
@@ -37,7 +37,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 include $(BUILD_CTS_PACKAGE)
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/accounts/AndroidManifest.xml b/tests/tests/accounts/AndroidManifest.xml
index 73535bc..ec3d42d 100644
--- a/tests/tests/accounts/AndroidManifest.xml
+++ b/tests/tests/accounts/AndroidManifest.xml
@@ -16,7 +16,8 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.accounts.cts">
+        package="android.accounts.cts"
+        android:targetSandboxVersion="2">
     <uses-sdk android:minSdkVersion="1"
           android:targetSdkVersion="26"/>
 
diff --git a/tests/tests/accounts/AndroidTest.xml b/tests/tests/accounts/AndroidTest.xml
index 77118d7..e0a3ae9 100644
--- a/tests/tests/accounts/AndroidTest.xml
+++ b/tests/tests/accounts/AndroidTest.xml
@@ -16,6 +16,10 @@
 <configuration description="Config for CTS Accounts test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="framework" />
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="cmd account set-bind-instant-service-allowed true" />
+        <option name="teardown-command" value="cmd account set-bind-instant-service-allowed false" />
+    </target_preparer>
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsUnaffiliatedAccountAuthenticators.apk" />
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.mk b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.mk
index 924b378..9428279 100644
--- a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.mk
+++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.mk
@@ -38,7 +38,7 @@
 LOCAL_PACKAGE_NAME := CtsUnaffiliatedAccountAuthenticators
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/AndroidManifest.xml b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/AndroidManifest.xml
index 642b3d8..3a0b025 100644
--- a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/AndroidManifest.xml
+++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/AndroidManifest.xml
@@ -16,7 +16,8 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.accounts.cts.unaffiliated">
+        package="android.accounts.cts.unaffiliated"
+        android:targetSandboxVersion="2">
     <uses-sdk android:minSdkVersion="1"
           android:targetSdkVersion="26"/>
 
diff --git a/tests/tests/accounts/src/android/accounts/cts/AbstractAuthenticatorTests.java b/tests/tests/accounts/src/android/accounts/cts/AbstractAuthenticatorTests.java
index 725e7a5..1b4f873 100644
--- a/tests/tests/accounts/src/android/accounts/cts/AbstractAuthenticatorTests.java
+++ b/tests/tests/accounts/src/android/accounts/cts/AbstractAuthenticatorTests.java
@@ -29,6 +29,7 @@
 import android.content.ContentResolver;
 import android.os.Bundle;
 import android.os.RemoteException;
+import android.platform.test.annotations.AppModeFull;
 import android.test.AndroidTestCase;
 
 import java.io.IOException;
@@ -60,7 +61,10 @@
     }
 
     public void tearDown() throws RemoteException {
-        mProviderClient.release();
+        if (mProviderClient != null) {
+            // mProviderClient is null in case of instant test
+            mProviderClient.release();
+        }
     }
 
     /**
@@ -139,6 +143,7 @@
      * Tests finishSession default implementation with default startAddAccountSession.
      * Only account name and account type should be returned as a bundle.
      */
+    @AppModeFull
     public void testFinishSessionAndStartAddAccountSessionDefaultImpl()
             throws OperationCanceledException, AuthenticatorException, IOException,
             RemoteException {
@@ -208,6 +213,7 @@
      * Tests finishSession default implementation with default startUpdateCredentialsSession.
      * Only account name and account type should be returned as a bundle.
      */
+    @AppModeFull
     public void testFinishSessionAndStartUpdateCredentialsSessionDefaultImpl()
             throws OperationCanceledException, AuthenticatorException, IOException,
             RemoteException {
diff --git a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
index c940c3f..4db2fd6 100644
--- a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
+++ b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
@@ -35,6 +35,7 @@
 import android.os.IBinder;
 import android.os.Looper;
 import android.os.StrictMode;
+import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.Presubmit;
 import android.test.ActivityInstrumentationTestCase2;
 
@@ -568,6 +569,7 @@
     /**
      * Test addAccountExplicitly(), renameAccount() and removeAccount().
      */
+    @AppModeFull(reason = "The methods are for sign-up wizards associated with authenticators.")
     public void testAddAccountExplicitlyAndRemoveAccount() throws IOException,
             AuthenticatorException, OperationCanceledException {
 
@@ -593,6 +595,7 @@
     /**
      * Test addAccountExplicitly(), renameAccount() and removeAccount().
      */
+    @AppModeFull(reason = "The methods are for sign-up wizards associated with authenticators.")
     public void testAddAccountExplicitlyAndRemoveAccountWithNewApi() throws IOException,
             AuthenticatorException, OperationCanceledException {
 
@@ -624,6 +627,7 @@
      * Test addAccountExplicitly(), renameAccount() and removeAccount() calling
      * into default implementations.
      */
+    @AppModeFull(reason = "The methods are for sign-up wizards associated with authenticators.")
     public void testAddAccountExplicitlyAndRemoveAccountWithDefaultImpl() throws IOException,
             AuthenticatorException, OperationCanceledException {
 
@@ -648,6 +652,7 @@
     /**
      * Test addAccountExplicitly(), renameAccount() and removeAccount().
      */
+    @AppModeFull(reason = "The methods are for sign-up wizards associated with authenticators.")
     public void testAddAccountExplicitlyAndRemoveAccountWithDeprecatedApi() throws IOException,
             AuthenticatorException, OperationCanceledException {
 
@@ -672,6 +677,7 @@
     /**
      * Test addAccountExplicitly() and removeAccountExplictly().
      */
+    @AppModeFull(reason = "The methods are for sign-up wizards associated with authenticators.")
     public void testAddAccountExplicitlyAndRemoveAccountExplicitly() {
         final int expectedAccountsCount = getAccountsCount();
 
@@ -694,6 +700,7 @@
     /**
      * Test updates to account visibility.
      */
+    @AppModeFull(reason = "The methods requires the caller to match signature with authenticator.")
     public void testSetAccountVisibility()
             throws IOException, AuthenticatorException, OperationCanceledException {
         am.addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */);
@@ -716,6 +723,7 @@
     /**
      * Test updates to account visibility for authenticator package.
      */
+    @AppModeFull(reason = "The methods requires the caller to match signature with authenticator.")
     public void testSetAccountVisibilityForPrivilegedPackage()
             throws IOException, AuthenticatorException, OperationCanceledException {
         am.addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */);
@@ -739,6 +747,7 @@
     /**
      * Test getPackagesAndVisibilityForAccount() method.
      */
+    @AppModeFull(reason = "The methods requires the caller to match signature with authenticator.")
     public void testGetPackagesAndVisibilityForAccount()
             throws IOException, AuthenticatorException, OperationCanceledException {
         am.addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */);
@@ -760,6 +769,7 @@
      * Test addAccountExplicitly(), setAccountVisibility() , getAccountVisibility(), and
      * removeAccount().
      */
+    @AppModeFull(reason = "The methods are for sign-up wizards associated with authenticators.")
     public void testAddAccountExplicitlyWithVisibility()
             throws IOException, AuthenticatorException, OperationCanceledException {
         Map<String, Integer> visibility = new HashMap<>();
@@ -795,6 +805,7 @@
     /**
      * Test testGetAccountsAndVisibilityForPackage(), getAccountsByTypeForPackage() methods.
      */
+    @AppModeFull(reason = "The methods requires the caller to match signature with authenticator.")
     public void testGetAccountsAndVisibilityForPackage() {
         am.addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */, null);
         am.addAccountExplicitly(ACCOUNT_SAME_TYPE, ACCOUNT_PASSWORD, null /* userData */, null);
@@ -852,6 +863,7 @@
      * Test checks order of accounts returned by getAccounts...().
      * Accounts should be grouped by type.
      */
+    @AppModeFull(reason = "The methods requires the caller to match signature with authenticator.")
     public void testGetAccountsReturnedOrder() {
         Account account_1_1 = new Account("account_z", ACCOUNT_TYPE);
         Account account_1_2 = new Account("account_c", ACCOUNT_TYPE);
@@ -1682,6 +1694,9 @@
     /**
      * Tests the setting of lastAuthenticatedTime on adding account
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testLastAuthenticatedTimeAfterAddAccount() throws IOException,
             AuthenticatorException, OperationCanceledException {
         assertTrue(addAccountAndReturnAccountAddedTime(ACCOUNT, ACCOUNT_PASSWORD) > 0);
@@ -1708,6 +1723,9 @@
      * Tests the setting of lastAuthenticatedTime on confirmCredentials being
      * successful.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testLastAuthenticatedTimeAfterConfirmCredentialsSuccess() throws IOException,
             AuthenticatorException, OperationCanceledException {
 
@@ -1729,6 +1747,9 @@
      * Tests the setting of lastAuthenticatedTime on updateCredentials being
      * successful.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testLastAuthenticatedTimeAfterUpdateCredentialsSuccess() throws IOException,
             AuthenticatorException, OperationCanceledException {
 
@@ -1747,6 +1768,7 @@
     /**
      * LastAuthenticatedTime on setPassword should not be disturbed.
      */
+    @AppModeFull(reason = "setPassword should be called by authenticator.")
     public void testLastAuthenticatedTimeAfterSetPassword() throws IOException,
             AuthenticatorException, OperationCanceledException {
         long accountAddTime = addAccountAndReturnAccountAddedTime(ACCOUNT, ACCOUNT_PASSWORD);
@@ -2428,6 +2450,9 @@
      * and return the final result which contains an encrypted session bundle,
      * account password and status token.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testStartAddAccountSessionIntervene()
             throws IOException, AuthenticatorException, OperationCanceledException {
         final String accountName = Fixtures.PREFIX_NAME_INTERVENE + "@"
@@ -2458,6 +2483,9 @@
      * automatically. When no Activity is provided and authenticator requires
      * additional data from user, KEY_INTENT will be returned by AccountManager.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testStartAddAccountSessionWithReturnIntent()
             throws IOException, AuthenticatorException, OperationCanceledException {
         final String accountName = Fixtures.PREFIX_NAME_INTERVENE + "@"
@@ -2532,6 +2560,9 @@
      * session bundle, account password and status token. Callback should be
      * triggered with the result regardless of a handled is provided or not.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testStartAddAccountSessionWithCallbackAndHandlerWithIntervene()
             throws IOException, AuthenticatorException, OperationCanceledException {
         testStartAddAccountSessionWithCallbackAndHandlerWithIntervene(null /* handler */);
@@ -2545,6 +2576,9 @@
      * additional data from user, KEY_INTENT will be returned by AccountManager
      * in callback regardless of a handler is provided or not.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testStartAddAccountSessionWithCallbackAndHandlerWithReturnIntent()
             throws IOException, AuthenticatorException, OperationCanceledException {
         testStartAddAccountSessionWithCallbackAndHandlerWithReturnIntent(null /* handler */);
@@ -2818,6 +2852,9 @@
      * and return the final result which contains an encrypted session bundle,
      * account password and status token.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testStartUpdateCredentialsSessionIntervene()
             throws IOException, AuthenticatorException, OperationCanceledException {
         String accountName = Fixtures.PREFIX_NAME_INTERVENE + "@" + Fixtures.SUFFIX_NAME_FIXTURE;
@@ -2846,6 +2883,9 @@
      * started automatically. When no Activity is provided and authenticator requires
      * additional data from user, KEY_INTENT will be returned by AccountManager.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testStartUpdateCredentialsSessionWithReturnIntent()
             throws IOException, AuthenticatorException, OperationCanceledException {
         String accountName = Fixtures.PREFIX_NAME_INTERVENE + "@" + Fixtures.SUFFIX_NAME_FIXTURE;
@@ -2918,6 +2958,9 @@
      * session bundle, account password and status token. Callback should be
      * triggered with the result regardless of a handler is provided or not.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testStartUpdateCredentialsSessionWithCallbackAndHandlerWithIntervene()
             throws IOException, AuthenticatorException, OperationCanceledException {
         testStartUpdateCredentialsSessionWithCallbackAndHandlerWithIntervene(null /* handler */);
@@ -2931,6 +2974,9 @@
      * additional data from user, KEY_INTENT will be returned by AccountManager
      * in callback regardless of a handler is provided or not.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testStartUpdateCredentialsSessionWithCallbackAndHandlerWithReturnIntent()
             throws IOException, AuthenticatorException, OperationCanceledException {
         testStartUpdateCredentialsSessionWithCallbackAndHandlerWithReturnIntent(null /* handler */);
@@ -3626,6 +3672,9 @@
      * provided by caller, the resolution intent will be started automatically.
      * A bundle containing account name and type will be returned.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testFinishSessionIntervene()
             throws IOException, AuthenticatorException, OperationCanceledException {
         String accountName = Fixtures.PREFIX_NAME_INTERVENE + "@" + Fixtures.SUFFIX_NAME_FIXTURE;
@@ -3675,6 +3724,9 @@
      * will not be started automatically. A bundle containing KEY_INTENT will be
      * returned instead.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testFinishSessionWithReturnIntent()
             throws IOException, AuthenticatorException, OperationCanceledException {
         String accountName = Fixtures.PREFIX_NAME_INTERVENE + "@" + Fixtures.SUFFIX_NAME_FIXTURE;
@@ -3789,6 +3841,9 @@
      * automatically. A bundle containing account name and type will be returned
      * via the callback regardless of if handler is provided or now.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testFinishSessionWithCallbackAndHandlerWithIntervene()
             throws IOException, AuthenticatorException, OperationCanceledException {
         testFinishSessionWithCallbackAndHandlerWithIntervene(null /* handler */);
@@ -3803,6 +3858,9 @@
      * will not be started automatically. A bundle containing KEY_INTENT will be
      * returned instead via callback regardless of if handler is provided or not.
      */
+    // TODO: Either allow the system to see the activity from instant app,
+    // Or separate the authenticator and test app to allow the instant app mode test.
+    @AppModeFull
     public void testFinishSessionWithCallbackAndHandlerWithReturnIntent()
             throws IOException, AuthenticatorException, OperationCanceledException {
         testFinishSessionWithCallbackAndHandlerWithReturnIntent(null /* handler */);
diff --git a/tests/tests/accounts/src/android/accounts/cts/AccountManagerUnaffiliatedAuthenticatorTests.java b/tests/tests/accounts/src/android/accounts/cts/AccountManagerUnaffiliatedAuthenticatorTests.java
index f9418f0..ebd6a13 100644
--- a/tests/tests/accounts/src/android/accounts/cts/AccountManagerUnaffiliatedAuthenticatorTests.java
+++ b/tests/tests/accounts/src/android/accounts/cts/AccountManagerUnaffiliatedAuthenticatorTests.java
@@ -29,6 +29,7 @@
 import android.content.ContentResolver;
 import android.os.Bundle;
 import android.os.RemoteException;
+import android.platform.test.annotations.AppModeFull;
 import android.test.AndroidTestCase;
 
 import java.io.IOException;
@@ -57,28 +58,11 @@
     private ContentProviderClient mProviderClient;
 
     @Override
-    public void setUp() throws Exception {
+    public void setUp() {
         SESSION_BUNDLE.putString(SESSION_DATA_NAME_1, SESSION_DATA_VALUE_1);
 
         // bind to the diagnostic service and set it up.
         mAccountManager = AccountManager.get(getContext());
-        ContentResolver resolver = getContext().getContentResolver();
-        mProviderClient = resolver.acquireContentProviderClient(
-                AuthenticatorContentProvider.AUTHORITY);
-        /*
-         * This will install a bunch of accounts on the device
-         * (see Fixtures.getFixtureAccountNames()).
-         */
-        mProviderClient.call(AuthenticatorContentProvider.METHOD_SETUP, null, null);
-    }
-
-    @Override
-    public void tearDown() throws RemoteException {
-        try {
-            mProviderClient.call(AuthenticatorContentProvider.METHOD_TEARDOWN, null, null);
-        } finally {
-            mProviderClient.release();
-        }
     }
 
     public void testNotifyAccountAuthenticated() {
@@ -288,8 +272,13 @@
      * authenticator.
      * An encrypted session bundle should always be returned without password.
      */
+    // TODO: Either allow instant app to expose content provider, or move the content provider
+    // out of the test app.
+    @AppModeFull
     public void testStartAddAccountSession() throws
             OperationCanceledException, AuthenticatorException, IOException, RemoteException {
+        setupAccounts();
+
         String accountName = Fixtures.PREFIX_NAME_SUCCESS + "@" + Fixtures.SUFFIX_NAME_FIXTURE;
         Bundle options = createOptionsWithAccountName(accountName);
 
@@ -313,6 +302,7 @@
 
         // Validate returned data
         validateSessionBundleAndPasswordAndStatusTokenResult(result);
+        resetAccounts();
     }
 
     /**
@@ -320,8 +310,13 @@
      * the authenticator.
      * An encrypted session bundle should always be returned without password.
      */
+    // TODO: Either allow instant app to expose content provider, or move the content provider
+    // out of the test app.
+    @AppModeFull
     public void testStartUpdateCredentialsSession() throws
             OperationCanceledException, AuthenticatorException, IOException, RemoteException {
+        setupAccounts();
+
         String accountName = Fixtures.PREFIX_NAME_SUCCESS + "@" + Fixtures.SUFFIX_NAME_FIXTURE;
         Bundle options = createOptionsWithAccountName(accountName);
 
@@ -344,6 +339,7 @@
 
         // Validate returned data
         validateSessionBundleAndPasswordAndStatusTokenResult(result);
+        resetAccounts();
     }
 
     /**
@@ -446,6 +442,25 @@
         }
     }
 
+    private void setupAccounts() throws RemoteException {
+        ContentResolver resolver = getContext().getContentResolver();
+        mProviderClient = resolver.acquireContentProviderClient(
+                AuthenticatorContentProvider.AUTHORITY);
+        /*
+         * This will install a bunch of accounts on the device
+         * (see Fixtures.getFixtureAccountNames()).
+         */
+        mProviderClient.call(AuthenticatorContentProvider.METHOD_SETUP, null, null);
+    }
+
+    private void resetAccounts() throws RemoteException {
+        try {
+            mProviderClient.call(AuthenticatorContentProvider.METHOD_TEARDOWN, null, null);
+        } finally {
+            mProviderClient.release();
+        }
+    }
+
     private void validateStartAddAccountSessionParameters(Bundle inOpt)
             throws RemoteException {
         Bundle params = mProviderClient.call(AuthenticatorContentProvider.METHOD_GET, null, null);
@@ -488,4 +503,3 @@
                 result.getString(AccountManager.KEY_ACCOUNT_STATUS_TOKEN));
     }
 }
-
diff --git a/tests/tests/appwidget/Android.mk b/tests/tests/appwidget/Android.mk
index 4e3a218..ae33c1b 100644
--- a/tests/tests/appwidget/Android.mk
+++ b/tests/tests/appwidget/Android.mk
@@ -29,7 +29,8 @@
 LOCAL_STATIC_JAVA_LIBRARIES := \
     mockito-target-minus-junit4 \
     ctstestrunner \
-    junit
+    junit \
+    compatibility-device-util
 
 LOCAL_JAVA_LIBRARIES := android.test.base.stubs
 
diff --git a/tests/tests/appwidget/src/android/appwidget/cts/RequestPinAppWidgetTest.java b/tests/tests/appwidget/src/android/appwidget/cts/RequestPinAppWidgetTest.java
index f015181..6a54e57 100644
--- a/tests/tests/appwidget/src/android/appwidget/cts/RequestPinAppWidgetTest.java
+++ b/tests/tests/appwidget/src/android/appwidget/cts/RequestPinAppWidgetTest.java
@@ -40,6 +40,8 @@
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
+import com.android.compatibility.common.util.CddTest;
+
 @AppModeFull(reason = "Instant apps cannot provide or host app widgets")
 public class RequestPinAppWidgetTest extends AppWidgetTestCase {
 
@@ -59,6 +61,7 @@
         setLauncher(mDefaultLauncher);
     }
 
+    @CddTest(requirement="3.8.2/C-2-2")
     private void runPinWidgetTest(final String launcherPkg) throws Exception {
         setLauncher(launcherPkg + "/" + LAUNCHER_CLASS);
 
@@ -114,6 +117,7 @@
         runPinWidgetTest("android.appwidget.cts.packages.launcher2");
     }
 
+    @CddTest(requirement="3.8.2/C-2-1")
     public void verifyIsRequestPinAppWidgetSupported(String launcherPkg, boolean expectedSupport)
         throws Exception {
         setLauncher(launcherPkg + "/" + LAUNCHER_CLASS);
diff --git a/tests/tests/background/src/android/app/cts/backgroundrestrictions/BroadcastsTest.java b/tests/tests/background/src/android/app/cts/backgroundrestrictions/BroadcastsTest.java
index 6af3020..0f37723 100644
--- a/tests/tests/background/src/android/app/cts/backgroundrestrictions/BroadcastsTest.java
+++ b/tests/tests/background/src/android/app/cts/backgroundrestrictions/BroadcastsTest.java
@@ -23,6 +23,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.platform.test.annotations.AppModeFull;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.runner.AndroidJUnit4;
 import android.util.Log;
@@ -96,6 +97,7 @@
                 () -> MyReceiver.clearCallback());
     }
 
+    @AppModeFull(reason = "Instant apps don't get to run in the background.")
     private void testNonSupportedBroadcastsNotDelivered(
             BiConsumer<IntentFilter, Consumer<Intent>> receiverInitializer,
             Consumer<Intent> intentInitializer,
@@ -103,7 +105,7 @@
 
         AmUtils.waitForBroadcastIdle();
 
-        // This broadcast should be delivered.
+        // This broadcast should not be delivered.
         final String[] UNSUPPORTED_BROADCASTS = new String[]{
                 "com.android.launcher.action.INSTALL_SHORTCUT",
         };
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
index 2759a54..1dcee00 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
@@ -1640,10 +1640,10 @@
     }
 
     /**
-     * Test that enableWriteAheadLogging is not affected by app's journal mode/synchronous mode
-     * settings
+     * Test that enableWriteAheadLogging is not affected by app's journal mode setting,
+     * but app can still control synchronous mode.
      */
-    public void testEnableWalOverridesJournalModeSynchronousMode() {
+    public void testEnableWalOverridesJournalModeSyncModePreserved() {
         mDatabase.close();
         SQLiteDatabase.OpenParams params = new SQLiteDatabase.OpenParams.Builder()
                 .setJournalMode("DELETE").setSynchronousMode("OFF").build();
@@ -1657,7 +1657,7 @@
         String syncMode = DatabaseUtils
                 .stringForQuery(mDatabase, "PRAGMA synchronous", null);
 
-        assertEquals("1" /* NORMAL */, syncMode);
+        assertEquals("0" /* OFF */, syncMode);
     }
 
     /**
diff --git a/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java b/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
index 1ce3706..371d6b6 100644
--- a/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
@@ -24,6 +24,7 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
+import android.app.ActivityManager;
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.res.AssetManager;
@@ -1723,8 +1724,15 @@
                         }
                     }
                 } else {
-                    // Not decoding to HARDWARE, so we can save RAM in either case.
-                    assertTrue(byteCount < normalByteCount);
+                    // Not decoding to HARDWARE, but |normal| was. Again, if basi6a16
+                    // was decoded to 8888, which we can detect by looking at the color
+                    // space, no savings are possible.
+                    if (resId == R.raw.basi6a16 && !normal.getColorSpace().equals(
+                                ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB))) {
+                        assertEquals(normalByteCount, byteCount);
+                    } else {
+                        assertTrue(byteCount < normalByteCount);
+                    }
                 }
             }
         }
@@ -2209,6 +2217,18 @@
 
     @Test
     public void testWarpedDng() {
+        Context context = InstrumentationRegistry.getTargetContext();
+        ActivityManager activityManager = (ActivityManager) context
+                .getSystemService(Context.ACTIVITY_SERVICE);
+        ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
+        activityManager.getMemoryInfo(info);
+
+        // Decoding this image requires a lot of memory. Only attempt if the
+        // device has a total memory of at least 2 Gigs.
+        if (info.totalMem < 2 * 1024 * 1024 * 1024) {
+            return;
+        }
+
         String name = "b78120086.dng";
         ImageDecoder.Source src = ImageDecoder.createSource(mRes.getAssets(), name);
         try {
diff --git a/tests/tests/location/Android.mk b/tests/tests/location/Android.mk
index 9d5e6aa..8297a75 100644
--- a/tests/tests/location/Android.mk
+++ b/tests/tests/location/Android.mk
@@ -29,7 +29,7 @@
 LOCAL_JAVA_LIBRARIES := telephony-common android.test.base.stubs
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
-    compatibility-device-util ctstestrunner apache-commons-math
+    compatibility-device-util ctstestrunner apache-commons-math platform-test-annotations
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src/android/location/cts) \
    $(call all-proto-files-under, protos)
diff --git a/tests/tests/location/src/android/location/cts/EmergencyCallWifiTest.java b/tests/tests/location/src/android/location/cts/EmergencyCallWifiTest.java
index 7ebb04a..1c6ac6c 100644
--- a/tests/tests/location/src/android/location/cts/EmergencyCallWifiTest.java
+++ b/tests/tests/location/src/android/location/cts/EmergencyCallWifiTest.java
@@ -21,10 +21,8 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.net.wifi.ScanResult;
-import android.net.wifi.WifiInfo;
-import android.telephony.TelephonyManager;
 import android.net.wifi.WifiManager;
-import android.test.AndroidTestCase;
+import android.platform.test.annotations.AppModeFull;
 import android.util.Log;
 
 import java.io.IOException;
@@ -63,6 +61,7 @@
         mWifiScanReceiver = new WifiScanReceiver();
     }
 
+    @AppModeFull(reason = "Requires registering a broadcast receiver")
     public void testWifiScan() throws Exception {
         mContext.registerReceiver(mWifiScanReceiver, new IntentFilter(
                 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
diff --git a/tests/tests/location/src/android/location/cts/GnssMeasurementWhenNoLocationTest.java b/tests/tests/location/src/android/location/cts/GnssMeasurementWhenNoLocationTest.java
index 7a6c152..5edca64 100644
--- a/tests/tests/location/src/android/location/cts/GnssMeasurementWhenNoLocationTest.java
+++ b/tests/tests/location/src/android/location/cts/GnssMeasurementWhenNoLocationTest.java
@@ -19,6 +19,7 @@
 import android.location.GnssMeasurement;
 import android.location.GnssMeasurementsEvent;
 import android.location.GpsStatus;
+import android.platform.test.annotations.AppModeFull;
 import android.util.Log;
 
 import java.util.Arrays;
@@ -90,6 +91,7 @@
     /**
      * Test for GPS measurements before a location fix.
      */
+    @AppModeFull(reason = "Requires use of extra LocationManager commands")
     public void testGnssMeasurementWhenNoLocation() throws Exception {
         // Checks if GPS hardware feature is present, skips test (pass) if not,
         // and hard asserts that Location/GPS (Provider) is turned on if is Cts Verifier.
diff --git a/tests/tests/location/src/android/location/cts/LocationManagerTest.java b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
index 3af213e..d58ebb6 100644
--- a/tests/tests/location/src/android/location/cts/LocationManagerTest.java
+++ b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
@@ -38,6 +38,7 @@
 import android.os.HandlerThread;
 import android.os.Looper;
 import android.os.SystemClock;
+import android.platform.test.annotations.AppModeFull;
 import android.provider.Settings;
 import android.test.UiThreadTest;
 
@@ -1046,6 +1047,7 @@
         mManager.unregisterGnssStatusCallback(callback);
     }
 
+    @AppModeFull(reason = "Requires use of extra LocationManager commands")
     public void testSendExtraCommand() {
         // this test assumes TEST_MOCK_PROVIDER_NAME was created in setUp.
         assertNotNull(mManager.getProvider(TEST_MOCK_PROVIDER_NAME));
diff --git a/tests/tests/media/Android.mk b/tests/tests/media/Android.mk
index 6758a4d..dbec359 100644
--- a/tests/tests/media/Android.mk
+++ b/tests/tests/media/Android.mk
@@ -71,6 +71,7 @@
 # do not compress VP9 video files
 LOCAL_AAPT_FLAGS := -0 .vp9
 LOCAL_AAPT_FLAGS += -0 .ts
+LOCAL_AAPT_FLAGS += -0 .heic
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/media/src/android/media/cts/AudioManagerTest.java b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
index 954c331..fcf4d38 100644
--- a/tests/tests/media/src/android/media/cts/AudioManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
@@ -270,6 +270,9 @@
     }
 
     public void testCheckingZenModeBlockDoesNotRequireNotificationPolicyAccess() throws Exception {
+        if (!mSupportNotificationPolicyAccess) {
+            return;
+        }
         try {
             // set zen mode to priority only, so playSoundEffect will check notification policy
             Utils.toggleNotificationPolicyAccess(mContext.getPackageName(), getInstrumentation(),
diff --git a/tests/tests/media/src/android/media/cts/MediaDrmClearkeyTest.java b/tests/tests/media/src/android/media/cts/MediaDrmClearkeyTest.java
index c5024f4..efb3273 100644
--- a/tests/tests/media/src/android/media/cts/MediaDrmClearkeyTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaDrmClearkeyTest.java
@@ -111,8 +111,7 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        if (false == deviceHasMediaDrm() || isWearDevice()) {
-            Log.i(TAG, "Skip tests on Wear device or before Android 5 (Lollipop).");
+        if (false == deviceHasMediaDrm()) {
             tearDown();
         }
     }
@@ -122,7 +121,7 @@
         super.tearDown();
     }
 
-    private boolean isWearDevice() {
+    private boolean isWatchDevice() {
         return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);
     }
 
@@ -357,6 +356,11 @@
             Uri audioUrl, boolean audioEncrypted,
             Uri videoUrl, boolean videoEncrypted,
             int videoWidth, int videoHeight, boolean scrambled) throws Exception {
+
+        if (isWatchDevice()) {
+            return;
+        }
+
         MediaDrm drm = null;
         mSessionId = null;
         if (!scrambled) {
@@ -447,12 +451,15 @@
     }
 
     public void testQueryKeyStatus() throws Exception {
-        MediaDrm drm = startDrm(new byte[][] { CLEAR_KEY_CENC }, "cenc", COMMON_PSSH_SCHEME_UUID);
-        if (!drm.isCryptoSchemeSupported(COMMON_PSSH_SCHEME_UUID)) {
-            stopDrm(drm);
-            throw new Error(ERR_MSG_CRYPTO_SCHEME_NOT_SUPPORTED);
+        if (isWatchDevice()) {
+            // skip this test on watch because it calls
+            // addTrack that requires codec
+            return;
         }
 
+        MediaDrm drm = startDrm(new byte[][] { CLEAR_KEY_CENC }, "cenc",
+                CLEARKEY_SCHEME_UUID);
+
         mSessionId = openSession(drm);
 
         // Test default key status, should not be defined
@@ -512,7 +519,7 @@
 
     public void testClearKeyPlaybackWebm() throws Exception {
         testClearKeyPlayback(
-            COMMON_PSSH_SCHEME_UUID,
+            CLEARKEY_SCHEME_UUID,
             MIME_VIDEO_VP8, new String[0],
             "webm", new byte[][] { CLEAR_KEY_WEBM },
             WEBM_URL, true /* audioEncrypted */,
@@ -522,7 +529,7 @@
 
     public void testClearKeyPlaybackMpeg2ts() throws Exception {
         testClearKeyPlayback(
-            COMMON_PSSH_SCHEME_UUID,
+            CLEARKEY_SCHEME_UUID,
             MIME_VIDEO_AVC, new String[0],
             "mpeg2ts", null,
             MPEG2TS_SCRAMBLED_URL, false /* audioEncrypted */,
@@ -532,7 +539,7 @@
 
     public void testPlaybackMpeg2ts() throws Exception {
         testClearKeyPlayback(
-            COMMON_PSSH_SCHEME_UUID,
+            CLEARKEY_SCHEME_UUID,
             MIME_VIDEO_AVC, new String[0],
             "mpeg2ts", null,
             MPEG2TS_CLEAR_URL, false /* audioEncrypted */,
@@ -589,8 +596,12 @@
     }
 
     public void testGetProperties() throws Exception {
+        if (watchHasNoClearkeySupport()) {
+            return;
+        }
+
         MediaDrm drm = startDrm(new byte[][] { CLEAR_KEY_CENC },
-                "cenc", COMMON_PSSH_SCHEME_UUID);
+                "cenc", CLEARKEY_SCHEME_UUID);
 
         try {
             // The following tests will not verify the value we are getting
@@ -624,8 +635,12 @@
     }
 
     public void testSetProperties() throws Exception {
+        if (watchHasNoClearkeySupport()) {
+            return;
+        }
+
         MediaDrm drm = startDrm(new byte[][]{CLEAR_KEY_CENC},
-                "cenc", COMMON_PSSH_SCHEME_UUID);
+                "cenc", CLEARKEY_SCHEME_UUID);
 
         try {
             // Test setting predefined string property
@@ -694,8 +709,12 @@
     private final static int CLEARKEY_MAX_SESSIONS = 10;
 
     public void testGetNumberOfSessions() {
+        if (watchHasNoClearkeySupport()) {
+            return;
+        }
+
         MediaDrm drm = startDrm(new byte[][] { CLEAR_KEY_CENC },
-                "cenc", COMMON_PSSH_SCHEME_UUID);
+                "cenc", CLEARKEY_SCHEME_UUID);
 
         try {
             if (getClearkeyVersion(drm).equals("1.0")) {
@@ -726,9 +745,13 @@
     }
 
     public void testHdcpLevels() {
+        if (watchHasNoClearkeySupport()) {
+            return;
+        }
+
         MediaDrm drm = null;
         try {
-            drm = new MediaDrm(COMMON_PSSH_SCHEME_UUID);
+            drm = new MediaDrm(CLEARKEY_SCHEME_UUID);
 
             if (getClearkeyVersion(drm).equals("1.0")) {
                 Log.i(TAG, "Skipping testHdcpLevels: not supported by clearkey 1.0");
@@ -743,7 +766,7 @@
                 throw new Error("expected max hdcp level to be HDCP_NO_DIGITAL_OUTPUT");
             }
         } catch(Exception e) {
-            throw new Error("Unexpected exception", e);
+            throw new Error("Unexpected exception ", e);
         } finally {
             if (drm != null) {
                 drm.close();
@@ -752,10 +775,14 @@
     }
 
     public void testSecurityLevels() {
+        if (watchHasNoClearkeySupport()) {
+            return;
+        }
+
         MediaDrm drm = null;
         byte[] sessionId = null;
         try {
-            drm = new MediaDrm(COMMON_PSSH_SCHEME_UUID);
+            drm = new MediaDrm(CLEARKEY_SCHEME_UUID);
 
             if (getClearkeyVersion(drm).equals("1.0")) {
                 Log.i(TAG, "Skipping testSecurityLevels: not supported by clearkey 1.0");
@@ -790,7 +817,7 @@
                 }
             }
         } catch(Exception e) {
-            throw new Error("Unexpected exception", e);
+            throw new Error("Unexpected exception ", e);
         } finally  {
             if (sessionId != null) {
                 drm.closeSession(sessionId);
@@ -802,7 +829,11 @@
      }
 
     public void testSecureStop() {
-        MediaDrm drm = startDrm(new byte[][] {CLEAR_KEY_CENC}, "cenc", COMMON_PSSH_SCHEME_UUID);
+        if (watchHasNoClearkeySupport()) {
+            return;
+        }
+
+        MediaDrm drm = startDrm(new byte[][] {CLEAR_KEY_CENC}, "cenc", CLEARKEY_SCHEME_UUID);
 
         byte[] sessionId = null;
         try {
@@ -811,10 +842,6 @@
                 return;
             }
 
-            if (!drm.isCryptoSchemeSupported(COMMON_PSSH_SCHEME_UUID)) {
-                throw new Error(ERR_MSG_CRYPTO_SCHEME_NOT_SUPPORTED);
-            }
-
             drm.removeAllSecureStops();
             Log.d(TAG, "Test getSecureStops from an empty list.");
             List<byte[]> secureStops = drm.getSecureStops();
@@ -922,4 +949,15 @@
             return "unavailable";
         }
     }
+
+    private boolean watchHasNoClearkeySupport() {
+        if (!MediaDrm.isCryptoSchemeSupported(CLEARKEY_SCHEME_UUID)) {
+            if (isWatchDevice()) {
+                return true;
+            } else {
+                throw new Error(ERR_MSG_CRYPTO_SCHEME_NOT_SUPPORTED);
+            }
+        }
+        return false;
+    }
 }
diff --git a/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java b/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
index f98e1e4..aa31210 100644
--- a/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
@@ -22,8 +22,13 @@
 import android.content.res.AssetFileDescriptor;
 import android.content.res.Resources;
 import android.media.MediaDataSource;
+import android.media.MediaExtractor;
+import android.media.MediaFormat;
 import android.media.MediaMetadataRetriever;
 import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Color;
+import android.graphics.Rect;
 import android.support.test.filters.SmallTest;
 import android.platform.test.annotations.RequiresDevice;
 import android.test.AndroidTestCase;
@@ -37,6 +42,7 @@
 import static android.media.MediaMetadataRetriever.OPTION_NEXT_SYNC;
 import static android.media.MediaMetadataRetriever.OPTION_PREVIOUS_SYNC;
 
+import java.io.InputStream;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
@@ -52,6 +58,19 @@
     protected MediaMetadataRetriever mRetriever;
     private PackageManager mPackageManager;
 
+    private static int BORDER_WIDTH = 16;
+    private static Color COLOR_BLOCK =
+            Color.valueOf(1.0f, 1.0f, 1.0f);
+    private static Color[] COLOR_BARS = {
+            Color.valueOf(0.0f, 0.0f, 0.0f),
+            Color.valueOf(0.0f, 0.0f, 0.64f),
+            Color.valueOf(0.0f, 0.64f, 0.0f),
+            Color.valueOf(0.0f, 0.64f, 0.64f),
+            Color.valueOf(0.64f, 0.0f, 0.0f),
+            Color.valueOf(0.64f, 0.0f, 0.64f),
+            Color.valueOf(0.64f, 0.64f, 0.0f),
+    };
+
     @Override
     protected void setUp() throws Exception {
         super.setUp();
@@ -577,4 +596,147 @@
             fail("Exception getting bitmap: " + e);
         }
     }
+
+    public void testGetImageAtIndex() throws Exception {
+        if (!MediaUtils.hasDecoder(MediaFormat.MIMETYPE_VIDEO_HEVC)) {
+            MediaUtils.skipTest("no video decoders for resource");
+            return;
+        }
+
+        testGetImage(R.raw.heifwriter_input, 1920, 1080, 0 /*rotation*/,
+                4 /*imageCount*/, 3 /*primary*/, true /*useGrid*/, true /*checkColor*/);
+    }
+
+    /**
+     * Determines if two color values are approximately equal.
+     */
+    private static boolean approxEquals(Color expected, Color actual) {
+        final float MAX_DELTA = 0.025f;
+        return (Math.abs(expected.red() - actual.red()) <= MAX_DELTA)
+            && (Math.abs(expected.green() - actual.green()) <= MAX_DELTA)
+            && (Math.abs(expected.blue() - actual.blue()) <= MAX_DELTA);
+    }
+
+    private static Rect getColorBarRect(int index, int width, int height) {
+        int barWidth = (width - BORDER_WIDTH * 2) / COLOR_BARS.length;
+        return new Rect(BORDER_WIDTH + barWidth * index, BORDER_WIDTH,
+                BORDER_WIDTH + barWidth * (index + 1), height - BORDER_WIDTH);
+    }
+
+    private static Rect getColorBlockRect(int index, int width, int height) {
+        int blockCenterX = (width / 5) * (index % 4 + 1);
+        return new Rect(blockCenterX - width / 10, height / 6,
+                        blockCenterX + width / 10, height / 3);
+    }
+
+    private void testGetImage(
+            int resId, int width, int height, int rotation,
+            int imageCount, int primary, boolean useGrid, boolean checkColor)
+                    throws Exception {
+        MediaMetadataRetriever retriever = null;
+        MediaExtractor extractor = null;
+        AssetFileDescriptor afd = null;
+        InputStream inputStream = null;
+
+        try {
+            retriever = new MediaMetadataRetriever();
+
+            Resources resources = getContext().getResources();
+            afd = resources.openRawResourceFd(resId);
+
+            retriever.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
+
+            // Verify image related meta keys.
+            String hasImage = retriever.extractMetadata(
+                    MediaMetadataRetriever.METADATA_KEY_HAS_IMAGE);
+            assertTrue("No images found in resId " + resId, "yes".equals(hasImage));
+            assertEquals("Wrong width", width,
+                    Integer.parseInt(retriever.extractMetadata(
+                            MediaMetadataRetriever.METADATA_KEY_IMAGE_WIDTH)));
+            assertEquals("Wrong height", height,
+                    Integer.parseInt(retriever.extractMetadata(
+                            MediaMetadataRetriever.METADATA_KEY_IMAGE_HEIGHT)));
+            assertEquals("Wrong rotation", rotation,
+                    Integer.parseInt(retriever.extractMetadata(
+                            MediaMetadataRetriever.METADATA_KEY_IMAGE_ROTATION)));
+            assertEquals("Wrong image count", imageCount,
+                    Integer.parseInt(retriever.extractMetadata(
+                            MediaMetadataRetriever.METADATA_KEY_IMAGE_COUNT)));
+            assertEquals("Wrong primary index", primary,
+                    Integer.parseInt(retriever.extractMetadata(
+                            MediaMetadataRetriever.METADATA_KEY_IMAGE_PRIMARY)));
+
+            if (checkColor) {
+                Bitmap bitmap = null;
+                // For each image in the image collection, check the 7 color bars' color.
+                // Also check the position of the color block, which should move left-to-right
+                // with the index.
+                for (int imageIndex = 0; imageIndex < imageCount; imageIndex++) {
+                    bitmap = retriever.getImageAtIndex(imageIndex);
+
+                    for (int barIndex = 0; barIndex < COLOR_BARS.length; barIndex++) {
+                        Rect r = getColorBarRect(barIndex, width, height);
+                        assertTrue("Color bar " + barIndex +
+                                " for image " + imageIndex + " doesn't match",
+                                approxEquals(COLOR_BARS[barIndex], Color.valueOf(
+                                        bitmap.getPixel(r.centerX(), r.centerY()))));
+                    }
+
+                    Rect r = getColorBlockRect(imageIndex, width, height);
+                    assertTrue("Color block for image " + imageIndex + " doesn't match",
+                            approxEquals(COLOR_BLOCK, Color.valueOf(
+                                    bitmap.getPixel(r.centerX(), height - r.centerY()))));
+                    bitmap.recycle();
+                }
+
+                // Check the color block position on the primary image.
+                Rect r = getColorBlockRect(primary, width, height);
+                bitmap = retriever.getPrimaryImage();
+                assertTrue("Color block for primary image doesn't match",
+                        approxEquals(COLOR_BLOCK, Color.valueOf(
+                                bitmap.getPixel(r.centerX(), height - r.centerY()))));
+                bitmap.recycle();
+
+                // Check the color block position on the bitmap decoded by BitmapFactory.
+                // This should match the primary image as well.
+                inputStream = getContext().getResources().openRawResource(resId);
+                bitmap = BitmapFactory.decodeStream(inputStream);
+                assertTrue("Color block for bitmap decoding doesn't match",
+                        approxEquals(COLOR_BLOCK, Color.valueOf(
+                                bitmap.getPixel(r.centerX(), height - r.centerY()))));
+                bitmap.recycle();
+            }
+
+            // Check the grid configuration related keys.
+            if (useGrid) {
+                extractor = new MediaExtractor();
+                extractor.setDataSource(
+                        afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
+                MediaFormat format = extractor.getTrackFormat(0);
+                int tileWidth = format.getInteger(MediaFormat.KEY_TILE_WIDTH);
+                int tileHeight = format.getInteger(MediaFormat.KEY_TILE_HEIGHT);
+                int gridRows = format.getInteger(MediaFormat.KEY_GRID_ROWS);
+                int gridCols = format.getInteger(MediaFormat.KEY_GRID_COLUMNS);
+                assertTrue("Wrong tile width or grid cols",
+                        ((width + tileWidth - 1) / tileWidth) == gridCols);
+                assertTrue("Wrong tile height or grid rows",
+                        ((height + tileHeight - 1) / tileHeight) == gridRows);
+            }
+        } catch (IOException e) {
+            fail("Unable to open file");
+        } finally {
+            if (retriever != null) {
+                retriever.release();
+            }
+            if (extractor != null) {
+                extractor.release();
+            }
+            if (afd != null) {
+                afd.close();
+            }
+            if (inputStream != null) {
+                inputStream.close();
+            }
+        }
+    }
 }
diff --git a/tests/tests/media/src/android/media/cts/NativeMediaDrmClearkeyTest.java b/tests/tests/media/src/android/media/cts/NativeMediaDrmClearkeyTest.java
index 5c6a135..dfbced9 100644
--- a/tests/tests/media/src/android/media/cts/NativeMediaDrmClearkeyTest.java
+++ b/tests/tests/media/src/android/media/cts/NativeMediaDrmClearkeyTest.java
@@ -16,6 +16,7 @@
 package android.media.cts;
 
 import android.content.pm.PackageManager;
+import android.media.MediaDrm;
 import android.net.Uri;
 import android.util.Log;
 import android.view.Surface;
@@ -85,8 +86,7 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        if (false == deviceHasMediaDrm() || isWearDevice()) {
-            Log.i(TAG, "Skip tests on Wear device or before Android 5 (Lollipop).");
+        if (false == deviceHasMediaDrm()) {
             tearDown();
         }
     }
@@ -96,7 +96,18 @@
         super.tearDown();
     }
 
-    private boolean isWearDevice() {
+    private boolean watchHasNoClearkeySupport() {
+        if (!MediaDrm.isCryptoSchemeSupported(CLEARKEY_SCHEME_UUID)) {
+            if (isWatchDevice()) {
+                return true;
+            } else {
+                throw new Error("Crypto scheme is not supported");
+            }
+        }
+        return false;
+    }
+
+    private boolean isWatchDevice() {
         return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);
     }
 
@@ -116,6 +127,10 @@
     }
 
     public void testIsCryptoSchemeSupported() throws Exception {
+        if (watchHasNoClearkeySupport()) {
+            return;
+        }
+
         assertTrue(isCryptoSchemeSupportedNative(uuidByteArray(COMMON_PSSH_SCHEME_UUID)));
         assertTrue(isCryptoSchemeSupportedNative(uuidByteArray(CLEARKEY_SCHEME_UUID)));
     }
@@ -131,16 +146,28 @@
     }
 
     public void testQueryKeyStatus() throws Exception {
-        assertTrue(testQueryKeyStatusNative(uuidByteArray(COMMON_PSSH_SCHEME_UUID)));
+        if (watchHasNoClearkeySupport()) {
+            return;
+        }
+
+        assertTrue(testQueryKeyStatusNative(uuidByteArray(CLEARKEY_SCHEME_UUID)));
     }
 
     public void testFindSessionId() throws Exception {
-        assertTrue(testFindSessionIdNative(uuidByteArray(COMMON_PSSH_SCHEME_UUID)));
+        if (watchHasNoClearkeySupport()) {
+            return;
+        }
+
+        assertTrue(testFindSessionIdNative(uuidByteArray(CLEARKEY_SCHEME_UUID)));
     }
 
     public void testGetPropertyString() throws Exception {
+        if (watchHasNoClearkeySupport()) {
+            return;
+        }
+
         StringBuffer value = new StringBuffer();
-        testGetPropertyStringNative(uuidByteArray(COMMON_PSSH_SCHEME_UUID), "description", value);
+        testGetPropertyStringNative(uuidByteArray(CLEARKEY_SCHEME_UUID), "description", value);
         assertEquals("ClearKey CDM", value.toString());
 
         value.delete(0, value.length());
@@ -152,7 +179,7 @@
         StringBuffer value = new StringBuffer();
 
         try {
-            testGetPropertyStringNative(uuidByteArray(COMMON_PSSH_SCHEME_UUID),
+            testGetPropertyStringNative(uuidByteArray(CLEARKEY_SCHEME_UUID),
                     "unknown-property", value);
             fail("Should have thrown an exception");
         } catch (RuntimeException e) {
@@ -178,8 +205,8 @@
             UUID drmSchemeUuid, String mimeType, /*String initDataType,*/ Uri audioUrl, Uri videoUrl,
             int videoWidth, int videoHeight) throws Exception {
 
-        if (!isCryptoSchemeSupportedNative(uuidByteArray(drmSchemeUuid))) {
-            throw new Error("Crypto scheme is not supported.");
+        if (isWatchDevice()) {
+            return;
         }
 
         IConnectionStatus connectionStatus = new ConnectionStatus(mContext);
diff --git a/tests/tests/net/src/android/net/cts/DnsTest.java b/tests/tests/net/src/android/net/cts/DnsTest.java
index 8575c33..84231c2 100644
--- a/tests/tests/net/src/android/net/cts/DnsTest.java
+++ b/tests/tests/net/src/android/net/cts/DnsTest.java
@@ -19,6 +19,9 @@
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.net.ConnectivityManager;
+import android.net.ConnectivityManager.NetworkCallback;
+import android.net.LinkProperties;
+import android.net.Network;
 import android.net.NetworkInfo;
 import android.os.SystemClock;
 import android.test.AndroidTestCase;
@@ -29,6 +32,8 @@
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.util.ArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 public class DnsTest extends AndroidTestCase {
 
@@ -40,6 +45,12 @@
     private static final String TAG = "DnsTest";
     private static final String PROXY_NETWORK_TYPE = "PROXY";
 
+    private ConnectivityManager mCm;
+
+    public void setUp() {
+        mCm = getContext().getSystemService(ConnectivityManager.class);
+    }
+
     /**
      * @return true on success
      */
@@ -57,7 +68,9 @@
      * Perf - measure size of first and second tier caches and their effect
      * Assert requires network permission
      */
-    public void testDnsWorks() {
+    public void testDnsWorks() throws Exception {
+        ensureIpv6Connectivity();
+
         InetAddress addrs[] = {};
         try {
             addrs = InetAddress.getAllByName("www.google.com");
@@ -88,11 +101,14 @@
         try {
             addrs = InetAddress.getAllByName("ipv6.google.com");
         } catch (UnknownHostException e) {}
-        assertTrue("[RERUN] DNS could not resolve ipv6.google.com, check the network supports IPv6",
-                addrs.length != 0);
+        String msg =
+            "[RERUN] DNS could not resolve ipv6.google.com, check the network supports IPv6. lp=" +
+            mCm.getActiveLinkProperties();
+        assertTrue(msg, addrs.length != 0);
         for (InetAddress addr : addrs) {
-            assertFalse ("[RERUN] ipv6.google.com returned IPv4 address: " + addr.getHostAddress() +
-                    ", check your network's DNS server", addr instanceof Inet4Address);
+            msg = "[RERUN] ipv6.google.com returned IPv4 address: " + addr.getHostAddress() +
+                    ", check your network's DNS server. lp=" + mCm.getActiveLinkProperties();
+            assertFalse (msg, addr instanceof Inet4Address);
             foundV6 |= (addr instanceof Inet6Address);
             if (DBG) Log.e(TAG, "ipv6.google.com gave " + addr.toString());
         }
@@ -256,13 +272,35 @@
     }
 
     private boolean activeNetworkInfoIsProxy() {
-        ConnectivityManager cm = (ConnectivityManager)
-                getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
-        NetworkInfo info = cm.getActiveNetworkInfo();
+        NetworkInfo info = mCm.getActiveNetworkInfo();
         if (PROXY_NETWORK_TYPE.equals(info.getTypeName())) {
             return true;
         }
 
         return false;
     }
+
+    private void ensureIpv6Connectivity() throws InterruptedException {
+        CountDownLatch latch = new CountDownLatch(1);
+        final int TIMEOUT_MS = 5_000;
+
+        final NetworkCallback callback = new NetworkCallback() {
+            @Override
+            public void onLinkPropertiesChanged(Network network, LinkProperties lp) {
+                if (lp.hasGlobalIPv6Address()) {
+                    latch.countDown();
+                }
+            }
+        };
+        mCm.registerDefaultNetworkCallback(callback);
+
+        String msg = "Default network did not provide IPv6 connectivity after " + TIMEOUT_MS
+                + "ms. Please connect to an IPv6-capable network. lp="
+                + mCm.getActiveLinkProperties();
+        try {
+            assertTrue(msg, latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+        } finally {
+            mCm.unregisterNetworkCallback(callback);
+        }
+    }
 }
diff --git a/tests/tests/permission/src/android/permission/cts/NoKeyPermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoKeyPermissionTest.java
index 8ed9143..5a0b259 100644
--- a/tests/tests/permission/src/android/permission/cts/NoKeyPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoKeyPermissionTest.java
@@ -32,7 +32,9 @@
     protected void setUp() throws Exception {
         super.setUp();
         mKeyManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
-        mKeyLock = mKeyManager.newKeyguardLock("testTag");
+        if (mKeyManager != null) {
+            mKeyLock = mKeyManager.newKeyguardLock("testTag");
+        }
     }
 
     /**
@@ -42,6 +44,10 @@
      */
     @SmallTest
     public void testDisableKeyguard() {
+        // KeyguardManager was not accessible, pass.
+        if (mKeyManager == null) {
+            return;
+        }
         try {
             mKeyLock.disableKeyguard();
             fail("KeyguardManager.KeyguardLock.disableKeyguard did not throw SecurityException as"
@@ -58,6 +64,10 @@
      */
     @SmallTest
     public void testReenableKeyguard() {
+        // KeyguardManager was not accessible, pass.
+        if (mKeyManager == null) {
+            return;
+        }
         try {
             mKeyLock.reenableKeyguard();
             fail("KeyguardManager.KeyguardLock.reenableKeyguard did not throw SecurityException as"
@@ -74,6 +84,10 @@
      */
     @SmallTest
     public void testExitKeyguardSecurely() {
+        // KeyguardManager was not accessible, pass.
+        if (mKeyManager == null) {
+            return;
+        }
         try {
             mKeyManager.exitKeyguardSecurely(null);
             fail("KeyguardManager.exitKeyguardSecurely did not throw SecurityException as"
diff --git a/tests/tests/permission/src/android/permission/cts/NoSystemFunctionPermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoSystemFunctionPermissionTest.java
index 9180c77..0ccebed 100644
--- a/tests/tests/permission/src/android/permission/cts/NoSystemFunctionPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoSystemFunctionPermissionTest.java
@@ -24,6 +24,7 @@
 import android.content.pm.PackageManager;
 import android.graphics.Bitmap;
 import android.os.Vibrator;
+import android.platform.test.annotations.AppModeFull;
 import android.telephony.gsm.SmsManager;
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
@@ -82,6 +83,7 @@
      *   {@link android.Manifest.permission#SET_WALLPAPER}.
      * @throws IOException 
      */
+    @AppModeFull(reason = "Instant apps cannot access the WallpaperManager")
     @SmallTest
     public void testSetWallpaper() throws IOException {
         if (!WallpaperManager.getInstance(mContext).isWallpaperSupported()) {
diff --git a/tests/tests/permission/src/android/permission/cts/NoWakeLockPermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoWakeLockPermissionTest.java
index ec11a0c..fd7e977 100644
--- a/tests/tests/permission/src/android/permission/cts/NoWakeLockPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoWakeLockPermissionTest.java
@@ -22,6 +22,7 @@
 import android.net.wifi.WifiManager;
 import android.net.wifi.WifiManager.WifiLock;
 import android.os.PowerManager;
+import android.platform.test.annotations.AppModeFull;
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
 
@@ -45,6 +46,7 @@
      * <p>Requires Permission:
      *   {@link android.Manifest.permission#WAKE_LOCK}.
      */
+    @AppModeFull(reason = "Instant apps cannot access the WifiManager")
     @SmallTest
     public void testWifiLockAcquire() {
         final WifiManager wifiManager = (WifiManager) mContext.getSystemService(
diff --git a/tests/tests/permission/src/android/permission/cts/NoWallpaperPermissionsTest.java b/tests/tests/permission/src/android/permission/cts/NoWallpaperPermissionsTest.java
index ad32923..df1a42c 100644
--- a/tests/tests/permission/src/android/permission/cts/NoWallpaperPermissionsTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoWallpaperPermissionsTest.java
@@ -24,6 +24,7 @@
 import android.net.wifi.WifiManager;
 import android.net.wifi.WifiManager.WifiLock;
 import android.os.PowerManager;
+import android.platform.test.annotations.AppModeFull;
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
 
@@ -36,6 +37,7 @@
 /**
  * Verify that Wallpaper-related operations enforce the correct permissions.
  */
+@AppModeFull(reason = "instant apps cannot access the WallpaperManager")
 public class NoWallpaperPermissionsTest extends AndroidTestCase {
     private WallpaperManager mWM;
 
diff --git a/tests/tests/permission/src/android/permission/cts/NoWifiStatePermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoWifiStatePermissionTest.java
index 0804ebe..d8acd50 100644
--- a/tests/tests/permission/src/android/permission/cts/NoWifiStatePermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoWifiStatePermissionTest.java
@@ -19,12 +19,14 @@
 import android.content.Context;
 import android.net.wifi.WifiConfiguration;
 import android.net.wifi.WifiManager;
+import android.platform.test.annotations.AppModeFull;
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
 
 /**
  * Verify WifiManager related methods without specific Wifi state permissions.
  */
+@AppModeFull(reason = "Instant apps cannot access the WifiManager")
 @SmallTest
 public class NoWifiStatePermissionTest extends AndroidTestCase {
     private static final int TEST_NET_ID = 1;
diff --git a/tests/tests/permission/src/android/permission/cts/ProviderPermissionTest.java b/tests/tests/permission/src/android/permission/cts/ProviderPermissionTest.java
index 909ac35..ec0de49 100644
--- a/tests/tests/permission/src/android/permission/cts/ProviderPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/ProviderPermissionTest.java
@@ -21,6 +21,8 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
+import android.net.Uri;
+import android.platform.test.annotations.AppModeFull;
 import android.provider.CallLog;
 import android.provider.Contacts;
 import android.provider.Settings;
@@ -55,11 +57,28 @@
                 android.Manifest.permission.WRITE_CONTACTS);
     }
 
+    public void assertWritingContentUriRequiresPermission(Uri uri, String permission,
+            boolean allowIAE) {
+        try {
+            getContext().getContentResolver().insert(uri, new ContentValues());
+            fail("expected SecurityException requiring " + permission);
+        } catch (IllegalArgumentException e) {
+            if (!allowIAE) {
+                fail("expected SecurityException requiring " + permission + " got " + e);
+            }
+        } catch (SecurityException expected) {
+            assertNotNull("security exception's error message.", expected.getMessage());
+            assertTrue("error message should contain " + permission + ".",
+                    expected.getMessage().contains(permission));
+        }
+    }
+
     /**
      * Verify that reading call logs requires permissions.
      * <p>Tests Permission:
      *   {@link android.Manifest.permission#READ_CALL_LOG}
      */
+    @AppModeFull
     public void testReadCallLog() {
         assertReadingContentUriRequiresPermission(CallLog.CONTENT_URI,
                 android.Manifest.permission.READ_CALL_LOG);
@@ -72,7 +91,8 @@
      */
     public void testWriteCallLog() {
         assertWritingContentUriRequiresPermission(CallLog.CONTENT_URI,
-                android.Manifest.permission.WRITE_CALL_LOG);
+                android.Manifest.permission.WRITE_CALL_LOG,
+                getContext().getPackageManager().isInstantApp());
     }
 
     /**
diff --git a/tests/tests/permission/src/android/permission/cts/ServicesInstantAppsCannotAccessTests.java b/tests/tests/permission/src/android/permission/cts/ServicesInstantAppsCannotAccessTests.java
new file mode 100644
index 0000000..736cf2f
--- /dev/null
+++ b/tests/tests/permission/src/android/permission/cts/ServicesInstantAppsCannotAccessTests.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2018 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.permission.cts;
+
+import static android.content.Context.DEVICE_POLICY_SERVICE;
+import static android.content.Context.FINGERPRINT_SERVICE;
+import static android.content.Context.SHORTCUT_SERVICE;
+import static android.content.Context.USB_SERVICE;
+import static android.content.Context.WALLPAPER_SERVICE;
+import static android.content.Context.WIFI_AWARE_SERVICE;
+import static android.content.Context.WIFI_P2P_SERVICE;
+import static android.content.Context.WIFI_SERVICE;
+
+import static org.junit.Assert.assertNull;
+
+import android.content.Context;
+import android.platform.test.annotations.AppModeInstant;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Some services are not available to instant apps, see {@link Context#getSystemService}.
+ */
+@AppModeInstant
+@RunWith(AndroidJUnit4.class)
+public class ServicesInstantAppsCannotAccessTests {
+    @Test
+    public void cannotGetDevicePolicyManager() {
+    assertNull(InstrumentationRegistry.getTargetContext().getSystemService(
+            DEVICE_POLICY_SERVICE));
+    }
+
+    @Test
+    public void cannotGetFingerprintManager() {
+        assertNull(InstrumentationRegistry.getTargetContext().getSystemService(
+                FINGERPRINT_SERVICE));
+    }
+
+    @Test
+    public void cannotGetShortcutManager() {
+        assertNull(InstrumentationRegistry.getTargetContext().getSystemService(
+                SHORTCUT_SERVICE));
+    }
+
+    @Test
+    public void cannotGetUsbManager() {
+        assertNull(InstrumentationRegistry.getTargetContext().getSystemService(
+                USB_SERVICE));
+    }
+
+    @Test
+    public void cannotGetWallpaperManager() {
+        assertNull(InstrumentationRegistry.getTargetContext().getSystemService(
+                WALLPAPER_SERVICE));
+    }
+
+    @Test
+    public void cannotGetWifiP2pManager() {
+        assertNull(InstrumentationRegistry.getTargetContext().getSystemService(
+                WIFI_P2P_SERVICE));
+    }
+
+    @Test
+    public void cannotGetWifiManager() {
+        assertNull(InstrumentationRegistry.getTargetContext().getSystemService(
+                WIFI_SERVICE));
+    }
+
+    @Test
+    public void cannotGetWifiAwareManager() {
+        assertNull(InstrumentationRegistry.getTargetContext().getSystemService(
+                WIFI_AWARE_SERVICE));
+    }
+}
diff --git a/tests/tests/print/printTestUtilLib/src/android/print/test/BasePrintTest.java b/tests/tests/print/printTestUtilLib/src/android/print/test/BasePrintTest.java
old mode 100644
new mode 100755
index dc4ae9d..5c40dfc
--- a/tests/tests/print/printTestUtilLib/src/android/print/test/BasePrintTest.java
+++ b/tests/tests/print/printTestUtilLib/src/android/print/test/BasePrintTest.java
@@ -199,13 +199,6 @@
 
         Instrumentation instrumentation = getInstrumentation();
 
-        // Prevent rotation
-        getUiDevice().freezeRotation();
-        while (!getUiDevice().isNaturalOrientation()) {
-            getUiDevice().setOrientationNatural();
-            getUiDevice().waitForIdle();
-        }
-
         // Make sure we start with a clean slate.
         Log.d(LOG_TAG, "clearPrintSpoolerData()");
         clearPrintSpoolerData();
@@ -270,6 +263,13 @@
         assumeTrue(getInstrumentation().getContext().getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_PRINTING));
 
+        // Prevent rotation
+        getUiDevice().freezeRotation();
+        while (!getUiDevice().isNaturalOrientation()) {
+            getUiDevice().setOrientationNatural();
+            getUiDevice().waitForIdle();
+        }
+
         // Initialize the latches.
         Log.d(LOG_TAG, "init counters");
         mCancelOperationCounter = new CallCounter();
@@ -302,6 +302,9 @@
 
         sIdToTest.remove(mTestId);
 
+        // Allow rotation
+        getUiDevice().unfreezeRotation();
+
         Log.d(LOG_TAG, "tearDown() done");
     }
 
@@ -324,9 +327,6 @@
         SystemUtil.runShellCommand(instrumentation, "settings put secure "
                     + Settings.Secure.DISABLED_PRINT_SERVICES + " null");
 
-        // Allow rotation
-        getUiDevice().unfreezeRotation();
-
         Log.d(LOG_TAG, "tearDownClass() done");
     }
 
diff --git a/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk b/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk
index 684cb10..a064bc7 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk
+++ b/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk
Binary files differ
diff --git a/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk b/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk
index 282805e..71c57e9 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk
+++ b/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk
Binary files differ
diff --git a/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk b/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk
index 2f182e5..647b485 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk
+++ b/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_33298089_avc.mp4 b/tests/tests/security/res/raw/bug_33298089_avc.mp4
new file mode 100644
index 0000000..e36f3ae
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_33298089_avc.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_35472997.mp4 b/tests/tests/security/res/raw/bug_35472997.mp4
new file mode 100644
index 0000000..9cd0c67
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_35472997.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_36492741.mp4 b/tests/tests/security/res/raw/bug_36492741.mp4
new file mode 100644
index 0000000..830724d
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_36492741.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_36993291_avc.mp4 b/tests/tests/security/res/raw/bug_36993291_avc.mp4
new file mode 100644
index 0000000..2b5dbc1
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_36993291_avc.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_69269702.mp4 b/tests/tests/security/res/raw/bug_69269702.mp4
new file mode 100644
index 0000000..ae11796
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_69269702.mp4
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/StagefrightTest.java b/tests/tests/security/src/android/security/cts/StagefrightTest.java
index b81be536..06333a8 100755
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -33,6 +33,8 @@
 import android.media.MediaCodec;
 import android.media.MediaCodecInfo;
 import android.media.MediaCodecList;
+import android.media.MediaDrm;
+import android.media.MediaDrm.MediaDrmStateException;
 import android.media.MediaExtractor;
 import android.media.MediaFormat;
 import android.media.MediaMetadataRetriever;
@@ -60,6 +62,7 @@
 import java.io.File;
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.UUID;
 import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.ReentrantLock;
 
@@ -454,11 +457,22 @@
     }
 
     @SecurityTest
+    public void testBug_33298089() throws Exception {
+        int[] frameSizes = {3247, 430, 221, 2305};
+        doStagefrightTestRawBlob(R.raw.bug_33298089_avc, "video/avc", 32, 64, frameSizes);
+    }
+
+    @SecurityTest
     public void testStagefright_cve_2017_0599() throws Exception {
         doStagefrightTest(R.raw.cve_2017_0599);
     }
 
     @SecurityTest
+    public void testStagefright_bug_36492741() throws Exception {
+        doStagefrightTest(R.raw.bug_36492741);
+    }
+
+    @SecurityTest
     public void testStagefright_bug_38487564() throws Exception {
         doStagefrightTest(R.raw.bug_38487564, (4 * 60 * 1000));
     }
@@ -500,6 +514,11 @@
     }
 
     @SecurityTest
+    public void testBug_36993291() throws Exception {
+        doStagefrightTestRawBlob(R.raw.bug_36993291_avc, "video/avc", 320, 240);
+    }
+
+    @SecurityTest
     public void testStagefright_bug_33818508() throws Exception {
         doStagefrightTest(R.raw.bug_33818508);
     }
@@ -528,6 +547,11 @@
     }
 
     @SecurityTest
+    public void testStagefright_bug_69269702() throws Exception {
+        doStagefrightTest(R.raw.bug_69269702);
+    }
+
+    @SecurityTest
     public void testStagefright_cve_2015_3867() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3867);
     }
@@ -628,11 +652,49 @@
     }
 
     @SecurityTest
+    public void testStagefright_bug_37710346() throws Exception {
+        UUID CLEARKEY_SCHEME_UUID = new UUID(0x1077efecc0b24d02L, 0xace33c1e52e2fb4bL);
+
+        String drmInitString = "0000003470737368" +
+                               "01000000" +
+                               "1077efecc0b24d02" +
+                               "ace33c1e52e2fb4b" +
+                               "10000001" +
+                               "60061e017e477e87" +
+                               "7e57d00d1ed00d1e" +
+                               "00000000";
+        int len = drmInitString.length();
+        byte[] drmInitData = new byte[len / 2];
+        for (int i = 0; i < len; i += 2) {
+            drmInitData[i / 2] = (byte) ((Character.digit(drmInitString.charAt(i), 16) << 4) +
+                Character.digit(drmInitString.charAt(i + 1), 16));
+        }
+
+        try {
+            MediaDrm drm = new MediaDrm(CLEARKEY_SCHEME_UUID);
+            byte[] sessionId;
+            String initDataType = "video/mp4";
+
+            sessionId = drm.openSession();
+            MediaDrm.KeyRequest drmRequest = drm.getKeyRequest(sessionId, drmInitData,
+                initDataType, MediaDrm.KEY_TYPE_STREAMING, null);
+        } catch (Exception e) {
+            if (!(e instanceof MediaDrmStateException))
+                fail("media drm server died");
+        }
+    }
+
+    @SecurityTest
     public void testStagefright_cve_2015_3873_b_23248776() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3873_b_23248776);
     }
 
     @SecurityTest
+    public void testStagefright_bug_35472997() throws Exception {
+        doStagefrightTest(R.raw.bug_35472997);
+    }
+
+    @SecurityTest
     public void testStagefright_cve_2015_3873_b_20718524() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3873_b_20718524);
     }
@@ -852,7 +914,10 @@
 
         Bitmap bitmap = BitmapFactory.decodeResource(
                 getInstrumentation().getContext().getResources(), R.raw.bug_73172046);
-        bitmap.recycle();
+        // OK if the decoding failed, but shouldn't cause crashes
+        if (bitmap != null) {
+            bitmap.recycle();
+        }
     }
 
     @SecurityTest
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java
index 56969bb..904f0cf 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java
@@ -32,6 +32,8 @@
 import android.net.Uri;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import com.android.compatibility.common.util.CddTest;
+
 import junit.framework.AssertionFailedError;
 
 /**
@@ -39,6 +41,7 @@
  *
  * In this test, we tests the main functionalities of those, without throttling.
  */
+@CddTest(requirement="3.8.1/C-4-1")
 @SmallTest
 public class ShortcutManagerClientApiTest extends ShortcutManagerCtsTestsBase {
 
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherApiTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherApiTest.java
index f27a60a..67d99fe 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherApiTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherApiTest.java
@@ -29,6 +29,8 @@
 import android.graphics.drawable.Icon;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import com.android.compatibility.common.util.CddTest;
+
 @SmallTest
 public class ShortcutManagerLauncherApiTest extends ShortcutManagerCtsTestsBase {
     @Override
@@ -350,7 +352,7 @@
         assertIconDimensions(icon5, getIconAsLauncher(
                 mLauncherContext1, mPackageContext1.getPackageName(), "ms21", false));
     }
-
+    @CddTest(requirement="3.8.1/C-1-2")
     public void testGetShortcutIconAdaptive() throws Exception {
         final Icon icon1 = Icon.createWithAdaptiveBitmap(BitmapFactory.decodeResource(
             getTestContext().getResources(), R.drawable.black_16x64));
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherCallbackTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherCallbackTest.java
index 166c9ba..8467f9a 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherCallbackTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherCallbackTest.java
@@ -38,6 +38,9 @@
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.function.Predicate;
 
+import com.android.compatibility.common.util.CddTest;
+
+@CddTest(requirement="3.8.1/C-2-3")
 @SmallTest
 public class ShortcutManagerLauncherCallbackTest extends ShortcutManagerCtsTestsBase {
 
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMaxCountTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMaxCountTest.java
index 8b7ae4e..8b18931 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMaxCountTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMaxCountTest.java
@@ -23,6 +23,9 @@
 
 import android.test.suitebuilder.annotation.SmallTest;
 
+import com.android.compatibility.common.util.CddTest;
+
+@CddTest(requirement="3.8.1/C-4-1")
 @SmallTest
 public class ShortcutManagerMaxCountTest extends ShortcutManagerCtsTestsBase {
     /**
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMiscTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMiscTest.java
index 95defb8..46c8661 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMiscTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMiscTest.java
@@ -20,6 +20,9 @@
 import android.content.pm.ShortcutManager;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import com.android.compatibility.common.util.CddTest;
+
+@CddTest(requirement="3.8.1/C-4-1")
 @SmallTest
 public class ShortcutManagerMiscTest extends ShortcutManagerCtsTestsBase {
     @Override
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMultiLauncherTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMultiLauncherTest.java
index 5ed5d52..5f49e1f 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMultiLauncherTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerMultiLauncherTest.java
@@ -28,6 +28,9 @@
 
 import android.test.suitebuilder.annotation.SmallTest;
 
+import com.android.compatibility.common.util.CddTest;
+
+@CddTest(requirement="3.8.1/C-2-3")
 @SmallTest
 public class ShortcutManagerMultiLauncherTest extends ShortcutManagerCtsTestsBase {
     /**
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerNegativeTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerNegativeTest.java
index bae8b0f..c4e492e 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerNegativeTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerNegativeTest.java
@@ -33,6 +33,9 @@
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 
+import com.android.compatibility.common.util.CddTest;
+
+@CddTest(requirement="3.8.1/C-4-1")
 @SmallTest
 public class ShortcutManagerNegativeTest extends ShortcutManagerCtsTestsBase {
     private static final String TAG = "ShortcutNegativeCTS";
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerRequestPinTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerRequestPinTest.java
index c04c0af..d7b506a 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerRequestPinTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerRequestPinTest.java
@@ -33,15 +33,18 @@
 import android.content.pm.cts.shortcutmanager.common.ReplyUtil;
 import android.os.PersistableBundle;
 import android.util.Log;
+import com.android.compatibility.common.util.CddTest;
 
 import java.util.HashMap;
 import java.util.List;
 
+@CddTest(requirement="3.8.1/C-4-1")
 public class ShortcutManagerRequestPinTest extends ShortcutManagerCtsTestsBase {
     private static final String TAG = "ShortcutMRPT";
 
     private static final String SHORTCUT_ID = "s12345";
 
+    @CddTest(requirement="[3.8.1/C-2-1],[3.8.1/C-3-1]")
     public void testIsRequestPinShortcutSupported() {
 
         // Launcher 1 supports it.
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerStartShortcutTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerStartShortcutTest.java
index a66e8ed..cdb14d1 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerStartShortcutTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerStartShortcutTest.java
@@ -30,6 +30,9 @@
 
 import java.util.List;
 
+import com.android.compatibility.common.util.CddTest;
+
+@CddTest(requirement="3.8.1/C-2-3")
 @SmallTest
 public class ShortcutManagerStartShortcutTest extends ShortcutManagerCtsTestsBase {
     private ComponentName mLaunchedActivity;
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 55afe48..7628c82 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
@@ -33,11 +33,14 @@
 import android.test.suitebuilder.annotation.Suppress;
 import android.view.KeyEvent;
 
+import com.android.compatibility.common.util.CddTest;
+
 /**
  * The actual test is implemented in the CtsShortcutManagerThrottlingTest module.
  * This class uses broadcast receivers to communicate with it, because if we just used an
  * instrumentation test, the target process would never been throttled.
  */
+@CddTest(requirement="3.8.1/C-4-1")
 @SmallTest
 public class ShortcutManagerThrottlingTest extends ShortcutManagerCtsTestsBase {
 
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerUsageTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerUsageTest.java
index 50ce615..a8afaaf 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerUsageTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerUsageTest.java
@@ -27,6 +27,9 @@
 import android.test.suitebuilder.annotation.SmallTest;
 import android.text.format.Time;
 
+import com.android.compatibility.common.util.CddTest;
+
+@CddTest(requirement="3.8.1/C-4-1")
 @SmallTest
 public class ShortcutManagerUsageTest extends ShortcutManagerCtsTestsBase {
     private static final String APPOPS_SET_SHELL_COMMAND = "appops set {0} " +