Merge "Disable ActivityKeyboardShortcutsTest on watches." into oc-dev
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java
index bd60ea9..2438bb0 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java
@@ -343,8 +343,7 @@
      */
     @Override
     public void testIgnored(TestIdentifier test) {
-        // Ignored tests are not reported.
-        mCurrentTestNum--;
+        mCurrentResult.skipped();
     }
 
     /**
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/IModuleDef.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/IModuleDef.java
index 69e8393..7a2c44d 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/IModuleDef.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/IModuleDef.java
@@ -24,6 +24,7 @@
 import com.android.tradefed.testtype.IRemoteTest;
 import com.android.tradefed.testtype.IRuntimeHintProvider;
 import com.android.tradefed.testtype.ITestCollector;
+import com.android.tradefed.testtype.suite.ModuleDefinition;
 
 import java.util.List;
 import java.util.Set;
@@ -35,8 +36,10 @@
         IRemoteTest, IRuntimeHintProvider, ITestCollector {
 
     /** key names used for saving module info into {@link IInvocationContext} */
-    public static String MODULE_NAME = "module-name";
-    public static String MODULE_ABI = "module-abi";
+    // This currently references ModuleDefinition so that there's only once source for String
+    // literals and making it easier to converge IModuleDef and ModuleDefinition later
+    public static String MODULE_NAME = ModuleDefinition.MODULE_NAME;
+    public static String MODULE_ABI = ModuleDefinition.MODULE_ABI;
 
     /**
      * @return The name of this module.
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/SecurityLoggingTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/SecurityLoggingTest.java
index ba67fdf..201f382 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/SecurityLoggingTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/SecurityLoggingTest.java
@@ -60,19 +60,9 @@
         // There must be at least some events, e.g. PackageManager logs all process launches.
         assertTrue("Unable to get events", events != null && events.size() > 0);
 
-        // We don't know much about the events, so just call public API methods and do a simple
-        // sanity check of timestamps.
-
-        // Check that timestamps are between system start and current time.
-        long systemStartedNanos = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis())
-                - SystemClock.elapsedRealtimeNanos();
-        long nowNanos = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis() + 1);
-
+        // We don't know much about the events, so just call public API methods.
         for (int i = 0; i < events.size(); i++) {
             SecurityEvent event = events.get(i);
-            long currentTimestampNanos = event.getTimeNanos();
-            assertTrue("Logged event predates boot", currentTimestampNanos >= systemStartedNanos);
-            assertTrue("Last logged event is in future", currentTimestampNanos <= nowNanos);
 
             // Test parcelling: flatten to a parcel.
             Parcel p = Parcel.obtain();
diff --git a/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java b/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
index d68d1dd..a7bd120 100644
--- a/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
+++ b/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
@@ -342,6 +342,7 @@
              *      return-object v0
              *  .end method
             */
+            /* DISABLED Due to b/62237378
             new RedefineError(JvmtiErrors.FAILS_VERIFICATION, Transform2.class,
                     "ZGV4CjAzNQBOhefYdQRcgqmkwhWsSyzb5I3udX0SnJ44AwAAcAAAAHhWNBIAAAAAAAAAAIwCAAAN" +
                     "AAAAcAAAAAYAAACkAAAAAQAAALwAAAAAAAAAAAAAAAMAAADIAAAAAQAAAOAAAAA4AgAAAAEAAAAB" +
@@ -358,6 +359,7 @@
                     "BgAAAKQAAAADAAAAAQAAALwAAAAFAAAAAwAAAMgAAAAGAAAAAQAAAOAAAAACIAAADQAAAAABAAAE" +
                     "IAAAAgAAABgCAAADEAAAAgAAACgCAAAGIAAAAQAAADgCAAADIAAAAgAAAEgCAAABIAAAAgAAAFQC" +
                     "AAAAIAAAAQAAAH4CAAAAEAAAAQAAAIwCAAA="),
+             */
             /**
              * Base64 for this class.
              *
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/VirtualDisplayActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/VirtualDisplayActivity.java
index c04ef90..07edfac 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/VirtualDisplayActivity.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/VirtualDisplayActivity.java
@@ -24,6 +24,7 @@
 import android.hardware.display.DisplayManager;
 import android.hardware.display.VirtualDisplay;
 import android.os.Bundle;
+import android.server.cts.tools.ActivityLauncher;
 import android.util.Log;
 import android.view.Surface;
 import android.view.SurfaceHolder;
@@ -42,6 +43,7 @@
     private static final String KEY_DENSITY_DPI = "density_dpi";
     private static final String KEY_PUBLIC_DISPLAY = "public_display";
     private static final String KEY_RESIZE_DISPLAY = "resize_display";
+    private static final String KEY_LAUNCH_TARGET_ACTIVITY = "launch_target_activity";
     private static final String KEY_COUNT = "count";
 
     private DisplayManager mDisplayManager;
@@ -155,6 +157,7 @@
 
         final int densityDpi = entry.extras.getInt(KEY_DENSITY_DPI, DEFAULT_DENSITY_DPI);
         final boolean resizeDisplay = entry.extras.getBoolean(KEY_RESIZE_DISPLAY);
+        final String launchActivityName = entry.extras.getString(KEY_LAUNCH_TARGET_ACTIVITY);
         final Surface surface = surfaceHolder.getSurface();
 
         // Initially, the surface will not have a set width or height so rely on the parent.
@@ -178,6 +181,12 @@
             mVirtualDisplays.put(surface,
                     new VirtualDisplayEntry(virtualDisplay, entry.surfaceView, densityDpi,
                             resizeDisplay));
+            if (launchActivityName != null) {
+                final int displayId = virtualDisplay.getDisplay().getDisplayId();
+                Log.d(TAG, "Launch activity after display created: activityName="
+                        + launchActivityName + ", displayId=" + displayId);
+                launchActivity(launchActivityName, displayId);
+            }
         } catch (IllegalArgumentException e) {
             final ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
             // This is expected when trying to create show-when-locked public display.
@@ -206,4 +215,12 @@
         vd.display.resize(surfaceHolder.getSurfaceFrame().width() / 2,
                 surfaceHolder.getSurfaceFrame().height() / 2, vd.density);
     }
+
+    private void launchActivity(String activityName, int displayId) {
+        final Bundle extras = new Bundle();
+        extras.putBoolean("launch_activity", true);
+        extras.putString("target_activity", activityName);
+        extras.putInt("display_id", displayId);
+        ActivityLauncher.launchActivityFromExtras(this, extras);
+    }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
index dc37d9b..9ea71d8 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
@@ -56,7 +56,6 @@
     private static final String THIRD_PACKAGE_NAME = "android.server.cts.third";
     private static final int INVALID_DENSITY_DPI = -1;
     private static final int CUSTOM_DENSITY_DPI = 222;
-    private static final int SIZE_VALUE_SHIFT = 50;
     private static final int VR_VIRTUAL_DISPLAY_WIDTH = 70;
     private static final int VR_VIRTUAL_DISPLAY_HEIGHT = 90;
     private static final int VR_VIRTUAL_DISPLAY_DPI = 320;
@@ -1235,6 +1234,16 @@
                 initialSizes, testActivitySizes);
     }
 
+    private void rotateAndCheckSameSizes(String activityName) throws Exception {
+        for (int rotation = 3; rotation >= 0; --rotation) {
+            final String logSeparator = clearLogcat();
+            setDeviceRotation(rotation);
+            final ReportedSizes rotatedSizes = getLastReportedSizesForActivity(activityName,
+                    logSeparator);
+            assertNull("Sizes must not change after rotation", rotatedSizes);
+        }
+    }
+
     /**
      * Tests that task affinity does affect what display an activity is launched on but that
      * matching the task component root does.
@@ -1336,16 +1345,6 @@
                 2, secondFrontStack.getTasks().size());
     }
 
-    private void rotateAndCheckSameSizes(String activityName) throws Exception {
-        for (int rotation = 3; rotation >= 0; --rotation) {
-            final String logSeparator = clearLogcat();
-            setDeviceRotation(rotation);
-            final ReportedSizes rotatedSizes = getLastReportedSizesForActivity(activityName,
-                    logSeparator);
-            assertNull("Sizes must not change after rotation", rotatedSizes);
-        }
-    }
-
     /**
      * Test that display overrides apply correctly and won't be affected by display changes.
      * This sets overrides to display size and density, initiates a display changed event by locking
@@ -1386,6 +1385,28 @@
         // All overrides will be cleared in tearDown.
     }
 
+    /**
+     * Tests than an immediate launch after new display creation is handled correctly.
+     */
+    public void testImmediateLaunchOnNewDisplay() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Create new virtual display and immediately launch an activity on it.
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this)
+                .setLaunchActivity(TEST_ACTIVITY_NAME).build();
+
+        // Check that activity is launched and placed correctly.
+        mAmWmState.waitForActivityState(mDevice, TEST_ACTIVITY_NAME, STATE_RESUMED);
+        mAmWmState.assertResumedActivity("Test activity must be launched on a new display",
+                TEST_ACTIVITY_NAME);
+        final int frontStackId = mAmWmState.getAmState().getFrontStackId(newDisplay.mDisplayId);
+        final ActivityManagerState.ActivityStack firstFrontStack =
+                mAmWmState.getAmState().getStackById(frontStackId);
+        assertEquals("Activity launched on secondary display must be resumed",
+                getActivityComponentName(TEST_ACTIVITY_NAME), firstFrontStack.mResumedActivity);
+        mAmWmState.assertFocusedStack("Focus must be on secondary display", frontStackId);
+    }
+
     /** Get physical and override display metrics from WM. */
     private ReportedDisplayMetrics getDisplayMetrics() throws Exception {
         mDumpLines.clear();
@@ -1525,13 +1546,13 @@
      * @param launchInSplitScreen start {@link VirtualDisplayActivity} to side from
      *                            {@link LaunchingActivity} on primary display.
      * @param publicDisplay make display public.
-     * @param mustBeCreated should assert if the display was or wasn't created.
      * @param resizeDisplay should resize display when surface size changes.
+     * @param launchActivity should launch test activity immediately after display creation.
      * @return {@link DisplayState} of newly created display.
      * @throws Exception
      */
     private List<DisplayState> createVirtualDisplays(int densityDpi, boolean launchInSplitScreen,
-            boolean publicDisplay, boolean mustBeCreated, boolean resizeDisplay, int displayCount)
+            boolean publicDisplay, boolean resizeDisplay, String launchActivity, int displayCount)
             throws Exception {
         // Start an activity that is able to create virtual displays.
         if (launchInSplitScreen) {
@@ -1547,20 +1568,14 @@
 
         // Create virtual display with custom density dpi.
         executeShellCommand(getCreateVirtualDisplayCommand(densityDpi, publicDisplay, resizeDisplay,
-                displayCount));
+                launchActivity, displayCount));
         mVirtualDisplayCreated = true;
 
         // Wait for the virtual display to be created and get configurations.
         final ReportedDisplays ds =
                 getDisplayStateAfterChange(originalDisplayCount + displayCount);
-        if (mustBeCreated) {
-            assertEquals("New virtual display must be created",
-                    originalDisplayCount + displayCount, ds.mDisplayStates.size());
-        } else {
-            assertEquals("New virtual display must not be created",
-                    originalDisplayCount, ds.mDisplayStates.size());
-            return null;
-        }
+        assertEquals("New virtual display must be created",
+                originalDisplayCount + displayCount, ds.mDisplayStates.size());
 
         // Find the newly added display.
         final List<DisplayState> newDisplays = findNewDisplayStates(originalDS, ds);
@@ -1749,8 +1764,8 @@
         private int mDensityDpi = CUSTOM_DENSITY_DPI;
         private boolean mLaunchInSplitScreen = false;
         private boolean mPublicDisplay = false;
-        private boolean mMustBeCreated = true;
         private boolean mResizeDisplay = true;
+        private String mLaunchActivity = null;
 
         public VirtualDisplayBuilder(ActivityManagerDisplayTests tests) {
             mTests = tests;
@@ -1771,15 +1786,16 @@
             return this;
         }
 
-        public VirtualDisplayBuilder setMustBeCreated(boolean mustBeCreated) {
-            mMustBeCreated = mustBeCreated;
-            return this;
-        }
-
         public VirtualDisplayBuilder setResizeDisplay(boolean resizeDisplay) {
             mResizeDisplay = resizeDisplay;
             return this;
         }
+
+        public VirtualDisplayBuilder setLaunchActivity(String launchActivity) {
+            mLaunchActivity = launchActivity;
+            return this;
+        }
+
         public DisplayState build() throws Exception {
             final List<DisplayState> displays = build(1);
             return displays != null && !displays.isEmpty() ? displays.get(0) : null;
@@ -1787,12 +1803,12 @@
 
         public List<DisplayState> build(int count) throws Exception {
             return mTests.createVirtualDisplays(mDensityDpi, mLaunchInSplitScreen, mPublicDisplay,
-                    mMustBeCreated, mResizeDisplay, count);
+                    mResizeDisplay, mLaunchActivity, count);
         }
     }
 
     private static String getCreateVirtualDisplayCommand(int densityDpi, boolean publicDisplay,
-            boolean resizeDisplay, int displayCount) {
+            boolean resizeDisplay, String launchActivity, int displayCount) {
         final StringBuilder commandBuilder
                 = new StringBuilder(getAmStartCmd(VIRTUAL_DISPLAY_ACTIVITY));
         commandBuilder.append(" -f 0x20000000");
@@ -1803,6 +1819,9 @@
         commandBuilder.append(" --ei count ").append(displayCount);
         commandBuilder.append(" --ez public_display ").append(publicDisplay);
         commandBuilder.append(" --ez resize_display ").append(resizeDisplay);
+        if (launchActivity != null) {
+            commandBuilder.append(" --es launch_target_activity ").append(launchActivity);
+        }
         return commandBuilder.toString();
     }
 
diff --git a/tests/signature/DynamicConfig.xml b/tests/signature/DynamicConfig.xml
index e078476..5c61a31 100644
--- a/tests/signature/DynamicConfig.xml
+++ b/tests/signature/DynamicConfig.xml
@@ -17,10 +17,12 @@
     Bug: 33305737 android.intent.action.ACTION_CARRIER_SETUP
     Bug: 36980009 android.intent.action.QUICKBOOT_POWERON
     Bug: 36977779 android.intent.action.MASTER_CLEAR
+    Bug: 38182465 android.intent.action.ACTION_DEFAULT_SMS_SUBSCRIPTION_CHANGED
 -->
 <dynamicConfig>
     <entry key ="intent_whitelist">
       <value>android.intent.action.ACTION_CARRIER_SETUP</value>
       <value>android.intent.action.QUICKBOOT_POWERON</value>
+      <value>android.intent.action.ACTION_DEFAULT_SMS_SUBSCRIPTION_CHANGED</value>
     </entry>
 </dynamicConfig>
diff --git a/tests/tests/assist/service/src/android/voiceinteraction/service/MainInteractionSession.java b/tests/tests/assist/service/src/android/voiceinteraction/service/MainInteractionSession.java
index 0224498..28c8ada 100644
--- a/tests/tests/assist/service/src/android/voiceinteraction/service/MainInteractionSession.java
+++ b/tests/tests/assist/service/src/android/voiceinteraction/service/MainInteractionSession.java
@@ -110,6 +110,7 @@
         mDisplayHeight = args.getInt(Utils.DISPLAY_HEIGHT_KEY);
         mDisplayWidth = args.getInt(Utils.DISPLAY_WIDTH_KEY);
         super.onShow(args, showFlags);
+        if (mContentView == null) return; // Happens when ui is not enabled.
         mContentView.getViewTreeObserver().addOnPreDrawListener(
                 new ViewTreeObserver.OnPreDrawListener() {
                 @Override
@@ -218,6 +219,7 @@
             Log.wtf(TAG, "layout inflater was null");
         }
         mContentView = f.inflate(R.layout.assist_layer,null);
+        Log.i(TAG, "onCreateContentView");
         return mContentView;
     }
 }
diff --git a/tests/tests/nativemedia/aaudio/src/test_aaudio.cpp b/tests/tests/nativemedia/aaudio/src/test_aaudio.cpp
index ccf9074..a7da002 100644
--- a/tests/tests/nativemedia/aaudio/src/test_aaudio.cpp
+++ b/tests/tests/nativemedia/aaudio/src/test_aaudio.cpp
@@ -19,6 +19,8 @@
 
 #include <memory>
 
+#include <unistd.h>
+
 #include <aaudio/AAudio.h>
 #include <android/log.h>
 #include <gtest/gtest.h>
@@ -72,13 +74,13 @@
     if (!mSetupSuccesful) return;
 
     const int32_t framesToRecord = actual().sampleRate;  // 1 second
-    const int64_t timeoutNanos = 100 * NANOS_PER_MILLISECOND;
     EXPECT_EQ(0, AAudioStream_getFramesRead(stream()));
     EXPECT_EQ(0, AAudioStream_getFramesWritten(stream()));
     mHelper->startStream();
     for (int32_t framesLeft = framesToRecord; framesLeft > 0; ) {
         aaudio_result_t result = AAudioStream_read(
-                stream(), &mData[0], std::min(framesToRecord, mFramesPerRead), timeoutNanos);
+                stream(), &mData[0], std::min(framesToRecord, mFramesPerRead),
+                DEFAULT_READ_TIMEOUT);
         ASSERT_GT(result, 0);
         framesLeft -= result;
     }
@@ -87,6 +89,56 @@
     EXPECT_GE(AAudioStream_getFramesWritten(stream()), framesToRecord);
 }
 
+TEST_P(AAudioInputStreamTest, testStartReadStop) {
+    if (!mSetupSuccesful) return;
+
+    // Use 1/8 second as start-stops take a lot more time than just recording.
+    const int32_t framesToRecord = actual().sampleRate / 8;
+    EXPECT_EQ(0, AAudioStream_getFramesRead(stream()));
+    EXPECT_EQ(0, AAudioStream_getFramesWritten(stream()));
+    for (int32_t framesLeft = framesToRecord; framesLeft > 0; ) {
+        mHelper->startStream();
+        aaudio_result_t result = AAudioStream_read(
+                stream(), &mData[0], std::min(framesToRecord, mFramesPerRead),
+                DEFAULT_READ_TIMEOUT);
+        ASSERT_GT(result, 0);
+        framesLeft -= result;
+        mHelper->stopStream();
+    }
+    EXPECT_GE(AAudioStream_getFramesRead(stream()), framesToRecord);
+    EXPECT_GE(AAudioStream_getFramesWritten(stream()), framesToRecord);
+}
+
+TEST_P(AAudioInputStreamTest, testReadCounterFreezeAfterStop) {
+    if (!mSetupSuccesful) return;
+
+    const int32_t framesToRecord = actual().sampleRate / 10;  // 1/10 second
+    EXPECT_EQ(0, AAudioStream_getFramesRead(stream()));
+    EXPECT_EQ(0, AAudioStream_getFramesWritten(stream()));
+    mHelper->startStream();
+    for (int32_t framesLeft = framesToRecord; framesLeft > 0; ) {
+        aaudio_result_t result = AAudioStream_read(
+                stream(), &mData[0], std::min(framesToRecord, mFramesPerRead),
+                DEFAULT_READ_TIMEOUT);
+        ASSERT_GT(result, 0);
+        framesLeft -= result;
+    }
+    mHelper->stopStream();
+    const int32_t framesReadAtStop = AAudioStream_getFramesRead(stream());
+    const int32_t framesWrittenAtStop = AAudioStream_getFramesWritten(stream());
+    ASSERT_EQ(0, TEMP_FAILURE_RETRY(usleep(100 * MICROS_PER_MILLISECOND)));
+    EXPECT_EQ(framesReadAtStop, AAudioStream_getFramesRead(stream()));
+    EXPECT_EQ(framesWrittenAtStop, AAudioStream_getFramesWritten(stream()));
+}
+
+TEST_P(AAudioInputStreamTest, testPauseAndFlushNotSupported) {
+    if (!mSetupSuccesful) return;
+    mHelper->startStream();
+    EXPECT_EQ(AAUDIO_ERROR_UNIMPLEMENTED, AAudioStream_requestPause(stream()));
+    EXPECT_EQ(AAUDIO_ERROR_UNIMPLEMENTED, AAudioStream_requestFlush(stream()));
+    mHelper->stopStream();
+}
+
 INSTANTIATE_TEST_CASE_P(SM, AAudioInputStreamTest,
         ::testing::Values(AAUDIO_SHARING_MODE_SHARED, AAUDIO_SHARING_MODE_EXCLUSIVE),
         &getTestName);
@@ -194,14 +246,9 @@
     // Make sure the read counter is not advancing when we are paused.
     aaudioFramesRead = AAudioStream_getFramesRead(stream());
     ASSERT_GE(aaudioFramesRead, aaudioFramesReadFinal); // monotonic increase
-
-    // Use this to sleep by waiting for a state that won't happen.
-    aaudio_stream_state_t state = AAUDIO_STREAM_STATE_UNINITIALIZED;
-    timeoutNanos = 100 * NANOS_PER_MILLISECOND;
-    AAudioStream_waitForStateChange(
-            stream(), AAUDIO_STREAM_STATE_OPEN, &state, timeoutNanos);
-    aaudioFramesReadFinal = AAudioStream_getFramesRead(stream());
-    EXPECT_EQ(aaudioFramesRead, aaudioFramesReadFinal);
+    // Currently not possible to enforce for AAudio over AudioTrack (b/33354715).
+    // ASSERT_EQ(0, TEMP_FAILURE_RETRY(usleep(100 * MICROS_PER_MILLISECOND)));
+    // EXPECT_EQ(aaudioFramesRead, AAudioStream_getFramesRead(stream()));
 
     // ------------------- TEST FLUSH -----------------
     // Prime the buffer.
diff --git a/tests/tests/nativemedia/aaudio/src/test_aaudio.h b/tests/tests/nativemedia/aaudio/src/test_aaudio.h
index f805fe6..d97ffc0 100644
--- a/tests/tests/nativemedia/aaudio/src/test_aaudio.h
+++ b/tests/tests/nativemedia/aaudio/src/test_aaudio.h
@@ -17,11 +17,13 @@
 #ifndef CTS_MEDIA_TEST_AAUDIO_H
 #define CTS_MEDIA_TEST_AAUDIO_H
 
-#define NANOS_PER_MICROSECOND ((int64_t)1000)
-#define NANOS_PER_MILLISECOND (NANOS_PER_MICROSECOND * 1000)
-#define MILLIS_PER_SECOND     1000
-#define NANOS_PER_SECOND      (NANOS_PER_MILLISECOND * MILLIS_PER_SECOND)
+#define NANOS_PER_MICROSECOND  ((int64_t)1000)
+#define NANOS_PER_MILLISECOND  (NANOS_PER_MICROSECOND * 1000)
+#define MICROS_PER_MILLISECOND 1000
+#define MILLIS_PER_SECOND      1000
+#define NANOS_PER_SECOND       (NANOS_PER_MILLISECOND * MILLIS_PER_SECOND)
 
 #define DEFAULT_STATE_TIMEOUT  (500 * NANOS_PER_MILLISECOND)
+#define DEFAULT_READ_TIMEOUT   (300 * NANOS_PER_MILLISECOND)
 
 #endif //CTS_MEDIA_TEST_AAUDIO_H
diff --git a/tests/tests/permission2/res/raw/android_manifest.xml b/tests/tests/permission2/res/raw/android_manifest.xml
index 8ed76de..4223535 100644
--- a/tests/tests/permission2/res/raw/android_manifest.xml
+++ b/tests/tests/permission2/res/raw/android_manifest.xml
@@ -1901,6 +1901,10 @@
                 android:description="@string/permdesc_useDataInBackground"
                 android:protectionLevel="normal" />
 
+    <!-- @hide Allows an application to set display offsets for the screen.
+         This permission is not available to third party applications. -->
+    <permission android:name="android.permission.SET_DISPLAY_OFFSET"
+                android:protectionLevel="signature|privileged" />
 
     <!-- ================================== -->
     <!-- Permissions affecting the system wallpaper -->
diff --git a/tests/tests/security/res/raw/bug_36215950.mp4 b/tests/tests/security/res/raw/bug_36215950.mp4
deleted file mode 100644
index a58f49e..0000000
--- a/tests/tests/security/res/raw/bug_36215950.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_36816007.mp4 b/tests/tests/security/res/raw/bug_36816007.mp4
deleted file mode 100644
index 70fa650..0000000
--- a/tests/tests/security/res/raw/bug_36816007.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_36895511.mp4 b/tests/tests/security/res/raw/bug_36895511.mp4
deleted file mode 100644
index 298494b..0000000
--- a/tests/tests/security/res/raw/bug_36895511.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/AslrTest.java b/tests/tests/security/src/android/security/cts/AslrTest.java
index 378aa0f..cd92611 100644
--- a/tests/tests/security/src/android/security/cts/AslrTest.java
+++ b/tests/tests/security/src/android/security/cts/AslrTest.java
@@ -49,21 +49,24 @@
         ParcelFileDescriptor pfd = getInstrumentation().getUiAutomation()
                 .executeShellCommand("/system/bin/cat /proc/self/maps");
 
-        BufferedReader reader = new BufferedReader(
-                new InputStreamReader(new FileInputStream(pfd.getFileDescriptor())));
+        String result = null;
+        try (BufferedReader reader = new BufferedReader(
+                new InputStreamReader(new ParcelFileDescriptor.AutoCloseInputStream(pfd)))) {
+            Pattern p = Pattern.compile("^([a-f0-9]+)\\-.+\\[" + mappingName + "\\]$");
+            String line;
 
-        Pattern p = Pattern.compile("^([a-f0-9]+)\\-.+\\[" + mappingName + "\\]$");
-        String line;
+            while ((line = reader.readLine()) != null) {
+                // Even after a match is found, read until the end to clean up the pipe.
+                if (result != null) continue;
 
-        while ((line = reader.readLine()) != null) {
-            Matcher m = p.matcher(line);
+                Matcher m = p.matcher(line);
 
-            if (m.matches()) {
-                return m.group(1);
+                if (m.matches()) {
+                    result = m.group(1);
+                }
             }
         }
-
-        return null;
+        return result;
     }
 
     private int calculateEntropyBits(String mappingName) throws Exception {
diff --git a/tests/tests/security/src/android/security/cts/StagefrightTest.java b/tests/tests/security/src/android/security/cts/StagefrightTest.java
index 1642679..7d3170d 100644
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -45,7 +45,6 @@
 import android.view.Surface;
 import android.webkit.cts.CtsTestServer;
 
-import java.io.FileInputStream;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
@@ -752,152 +751,4 @@
         thr.stopLooper();
         thr.join();
     }
-
-    public void testBug36215950() throws Exception {
-        doStagefrightTestRawBlob(R.raw.bug_36215950, "video/hevc", 320, 240);
-    }
-
-    public void testBug36816007() throws Exception {
-        doStagefrightTestRawBlob(R.raw.bug_36816007, "video/avc", 320, 240);
-    }
-
-    public void testBug36895511() throws Exception {
-        doStagefrightTestRawBlob(R.raw.bug_36895511, "video/hevc", 320, 240);
-    }
-
-    private void runWithTimeout(Runnable runner, int timeout) {
-        Thread t = new Thread(runner);
-        t.start();
-        try {
-            t.join(timeout);
-        } catch (InterruptedException e) {
-            fail("operation was interrupted");
-        }
-        if (t.isAlive()) {
-            fail("operation not completed within timeout of " + timeout + "ms");
-        }
-    }
-
-    private void releaseCodec(final MediaCodec codec) {
-        runWithTimeout(new Runnable() {
-            @Override
-            public void run() {
-                codec.release();
-            }
-        }, 5000);
-    }
-
-    private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight) throws Exception {
-
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
-        final Context context = getInstrumentation().getContext();
-        final Resources resources =  context.getResources();
-
-        LooperThread thr = new LooperThread(new Runnable() {
-            @Override
-            public void run() {
-
-                MediaPlayer mp = new MediaPlayer();
-                mp.setOnErrorListener(mpcl);
-                AssetFileDescriptor fd = null;
-                try {
-                    fd = resources.openRawResourceFd(R.raw.good);
-
-                    // the onErrorListener won't receive MEDIA_ERROR_SERVER_DIED until
-                    // setDataSource has been called
-                    mp.setDataSource(fd.getFileDescriptor(),
-                                     fd.getStartOffset(),
-                                     fd.getLength());
-                    fd.close();
-                } catch (Exception e) {
-                    // this is a known-good file, so no failure should occur
-                    fail("setDataSource of known-good file failed");
-                }
-
-                synchronized(mpcl) {
-                    mpcl.notify();
-                }
-                Looper.loop();
-                mp.release();
-            }
-        });
-        thr.start();
-        // wait until the thread has initialized the MediaPlayer
-        synchronized(mpcl) {
-            mpcl.wait();
-        }
-
-        AssetFileDescriptor fd = resources.openRawResourceFd(rid);
-        byte [] blob = new byte[(int)fd.getLength()];
-        FileInputStream fis = fd.createInputStream();
-        int numRead = fis.read(blob);
-        fis.close();
-        //Log.i("@@@@", "read " + numRead + " bytes");
-
-        // find all the available decoders for this format
-        ArrayList<String> matchingCodecs = new ArrayList<String>();
-        int numCodecs = MediaCodecList.getCodecCount();
-        for (int i = 0; i < numCodecs; i++) {
-            MediaCodecInfo info = MediaCodecList.getCodecInfoAt(i);
-            if (info.isEncoder()) {
-                continue;
-            }
-            try {
-                MediaCodecInfo.CodecCapabilities caps = info.getCapabilitiesForType(mime);
-                if (caps != null) {
-                    matchingCodecs.add(info.getName());
-                }
-            } catch (IllegalArgumentException e) {
-                // type is not supported
-            }
-        }
-
-        if (matchingCodecs.size() == 0) {
-            Log.w(TAG, "no codecs for mime type " + mime);
-        }
-        String rname = resources.getResourceEntryName(rid);
-        // decode this blob once with each matching codec
-        for (String codecName: matchingCodecs) {
-            Log.i(TAG, "Decoding blob " + rname + " using codec " + codecName);
-            MediaCodec codec = MediaCodec.createByCodecName(codecName);
-            MediaFormat format = MediaFormat.createVideoFormat(mime, initWidth, initHeight);
-            codec.configure(format, null, null, 0);
-            codec.start();
-
-            try {
-                MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
-                ByteBuffer [] inputBuffers = codec.getInputBuffers();
-                // enqueue the bad data a number of times, in case
-                // the codec needs multiple buffers to fail.
-                for(int i = 0; i < 64; i++) {
-                    int bufidx = codec.dequeueInputBuffer(5000);
-                    if (bufidx >= 0) {
-                        Log.i(TAG, "got input buffer of size " + inputBuffers[bufidx].capacity());
-                        inputBuffers[bufidx].rewind();
-                        inputBuffers[bufidx].put(blob, 0, numRead);
-                        codec.queueInputBuffer(bufidx, 0, numRead, 0, 0);
-                    } else {
-                        Log.i(TAG, "no input buffer");
-                    }
-                    bufidx = codec.dequeueOutputBuffer(info, 5000);
-                    if (bufidx >= 0) {
-                        Log.i(TAG, "got output buffer");
-                        codec.releaseOutputBuffer(bufidx, false);
-                    } else {
-                        Log.i(TAG, "no output buffer");
-                    }
-                }
-            } catch (Exception e) {
-                // ignore, not a security issue
-            } finally {
-                releaseCodec(codec);
-            }
-        }
-
-        String cve = rname.replace("_", "-").toUpperCase();
-        assertFalse("Device *IS* vulnerable to " + cve,
-                    mpcl.waitForError() == MediaPlayer.MEDIA_ERROR_SERVER_DIED);
-        thr.stopLooper();
-        thr.join();
-    }
 }
diff --git a/tests/tests/widget/src/android/widget/cts/GridViewTest.java b/tests/tests/widget/src/android/widget/cts/GridViewTest.java
index 810e1d9..95e3581 100644
--- a/tests/tests/widget/src/android/widget/cts/GridViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/GridViewTest.java
@@ -193,6 +193,17 @@
         mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_LEFT);
         assertEquals(0, mGridView.getSelectedItemPosition());
 
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_TAB);
+        assertEquals(1, mGridView.getSelectedItemPosition());
+
+        event = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB, 0,
+                KeyEvent.META_SHIFT_LEFT_ON);
+        mInstrumentation.sendKeySync(event);
+        event = new KeyEvent(0, 0, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_TAB, 0,
+                KeyEvent.META_SHIFT_LEFT_ON);
+        mInstrumentation.sendKeySync(event);
+        assertEquals(0, mGridView.getSelectedItemPosition());
+
         mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
         assertEquals(NUM_COLUMNS, mGridView.getSelectedItemPosition());
 
diff --git a/tests/tests/widget/src/android/widget/cts/TextViewTest.java b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
index 1198229..a680b14 100644
--- a/tests/tests/widget/src/android/widget/cts/TextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
@@ -164,6 +164,7 @@
 
 import java.io.IOException;
 import java.lang.annotation.Retention;
+import java.util.Arrays;
 import java.util.Locale;
 
 /**
@@ -6654,6 +6655,56 @@
     }
 
     @Test
+    public void testAutoSizeCallers_setText() throws Throwable {
+        final TextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
+                R.id.textview_autosize_uniform, false);
+
+        // Configure layout params and auto-size both in pixels to dodge flakiness on different
+        // devices.
+        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                500, 500);
+        mActivityRule.runOnUiThread(() -> {
+            autoSizeTextView.setLayoutParams(layoutParams);
+            autoSizeTextView.setAutoSizeTextTypeUniformWithConfiguration(
+                    1, 5000, 1, TypedValue.COMPLEX_UNIT_PX);
+        });
+        mInstrumentation.waitForIdleSync();
+
+        final String initialText = "13characters ";
+        StringBuilder textToSet = new StringBuilder().append(initialText);
+
+        // As we add characters the text size shrinks.
+        for (int i = 0; i < 10; i++) {
+            mActivityRule.runOnUiThread(() ->
+                    autoSizeTextView.setText(textToSet.toString()));
+            mInstrumentation.waitForIdleSync();
+            float expectedLargerSize = autoSizeTextView.getTextSize();
+
+            textToSet.append(initialText);
+            mActivityRule.runOnUiThread(() ->
+                    autoSizeTextView.setText(textToSet.toString()));
+            mInstrumentation.waitForIdleSync();
+
+            assertTrue(expectedLargerSize > autoSizeTextView.getTextSize());
+        }
+
+        // As we remove characters the text size expands.
+        for (int i = 9; i >= 0; i--) {
+            mActivityRule.runOnUiThread(() ->
+                    autoSizeTextView.setText(textToSet.toString()));
+            mInstrumentation.waitForIdleSync();
+            float expectedSmallerSize = autoSizeTextView.getTextSize();
+
+            textToSet.replace((textToSet.length() - initialText.length()), textToSet.length(), "");
+            mActivityRule.runOnUiThread(() ->
+                    autoSizeTextView.setText(textToSet.toString()));
+            mInstrumentation.waitForIdleSync();
+
+            assertTrue(autoSizeTextView.getTextSize() > expectedSmallerSize);
+        }
+    }
+
+    @Test
     public void testAutoSize_setEllipsize() throws Throwable {
         final TextView textView = (TextView) mActivity.findViewById(
                 R.id.textview_autosize_uniform_predef_sizes);
@@ -7247,8 +7298,8 @@
 
         // It does not matter which unit has been used to set the min size, the getter always
         // returns it in pixels.
-        assertEquals((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, newMinSize,
-                mActivity.getResources().getDisplayMetrics()), textView.getAutoSizeMinTextSize());
+        assertEquals(Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, newMinSize,
+                mActivity.getResources().getDisplayMetrics())), textView.getAutoSizeMinTextSize());
     }
 
     @Test(expected = IllegalArgumentException.class)
@@ -7318,24 +7369,29 @@
         assertEquals(-1, presetTextView.getAutoSizeStepGranularity());
 
         // Both TextViews generate exactly the same sizes in pixels to choose from when auto-sizing.
-        assertArrayEquals(
+        assertArrayEquals("Expected the granularity and preset configured auto-sized "
+                + "TextViews to have identical available sizes for auto-sizing."
+                + "\ngranularity sizes: "
+                + Arrays.toString(granularityTextView.getAutoSizeTextAvailableSizes())
+                + "\npreset sizes: "
+                + Arrays.toString(presetTextView.getAutoSizeTextAvailableSizes()),
                 granularityTextView.getAutoSizeTextAvailableSizes(),
                 presetTextView.getAutoSizeTextAvailableSizes());
 
         final String someText = "This is a string";
-        final int widthHeight = 600;
+        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                500, 500);
         // Configure identically and attach to layout.
         mActivityRule.runOnUiThread(() -> {
+            granularityTextView.setLayoutParams(layoutParams);
+            presetTextView.setLayoutParams(layoutParams);
+
             LinearLayout ll = mActivity.findViewById(R.id.layout_textviewtest);
+            ll.removeAllViews();
             ll.addView(granularityTextView);
             ll.addView(presetTextView);
 
-            granularityTextView.setWidth(widthHeight);
-            granularityTextView.setHeight(widthHeight);
             granularityTextView.setText(someText);
-
-            presetTextView.setWidth(widthHeight);
-            presetTextView.setHeight(widthHeight);
             presetTextView.setText(someText);
         });
         mInstrumentation.waitForIdleSync();
@@ -7553,7 +7609,6 @@
 
     private void initializeTextForSmartSelection(CharSequence text) throws Throwable {
         assertTrue(text.length() >= SMARTSELECT_END);
-        initTextViewForTypingOnUiThread();
         TextClassifier mockClassifier = mock(TextClassifier.class);
         when(mockClassifier.suggestSelection(
                 any(CharSequence.class), anyInt(), anyInt(), any(LocaleList.class)))
@@ -7563,8 +7618,9 @@
                 .thenReturn(new TextClassification.Builder().build());
         mActivityRule.runOnUiThread(() -> {
             mTextView.setTextIsSelectable(true);
-            mTextView.setText(text, BufferType.EDITABLE);
+            mTextView.setText(text);
             mTextView.setTextClassifier(mockClassifier);
+            mTextView.requestFocus();
         });
         mInstrumentation.waitForIdleSync();
     }