Merge "videoperf: avoid potential ArrayIndexOutOfBounds" into mnc-dev
diff --git a/apps/CameraITS/pymodules/its/image.py b/apps/CameraITS/pymodules/its/image.py
index 8e76c6f..4769bb7 100644
--- a/apps/CameraITS/pymodules/its/image.py
+++ b/apps/CameraITS/pymodules/its/image.py
@@ -211,6 +211,9 @@
     if cap["format"] == "raw10":
         assert(props is not None)
         cap = unpack_raw10_capture(cap, props)
+    if cap["format"] == "raw12":
+        assert(props is not None)
+        cap = unpack_raw12_capture(cap, props)
     if cap["format"] == "yuv":
         y = cap["data"][0:w*h]
         u = cap["data"][w*h:w*h*5/4]
@@ -229,6 +232,36 @@
         img = numpy.ndarray(shape=(h*w,), dtype='<u2',
                             buffer=cap["data"][0:w*h*2])
         img = img.astype(numpy.float32).reshape(h,w) / white_level
+        # Crop the raw image to the active array region.
+        if props.has_key("android.sensor.info.activeArraySize") \
+                and props["android.sensor.info.activeArraySize"] is not None \
+                and props.has_key("android.sensor.info.pixelArraySize") \
+                and props["android.sensor.info.pixelArraySize"] is not None:
+            # Note that the Rect class is defined such that the left,top values
+            # are "inside" while the right,bottom values are "outside"; that is,
+            # it's inclusive of the top,left sides only. So, the width is
+            # computed as right-left, rather than right-left+1, etc.
+            wfull = props["android.sensor.info.pixelArraySize"]["width"]
+            hfull = props["android.sensor.info.pixelArraySize"]["height"]
+            xcrop = props["android.sensor.info.activeArraySize"]["left"]
+            ycrop = props["android.sensor.info.activeArraySize"]["top"]
+            wcrop = props["android.sensor.info.activeArraySize"]["right"]-xcrop
+            hcrop = props["android.sensor.info.activeArraySize"]["bottom"]-ycrop
+            assert(wfull >= wcrop >= 0)
+            assert(hfull >= hcrop >= 0)
+            assert(wfull - wcrop >= xcrop >= 0)
+            assert(hfull - hcrop >= ycrop >= 0)
+            if w == wfull and h == hfull:
+                # Crop needed; extract the center region.
+                img = img[ycrop:ycrop+hcrop,xcrop:xcrop+wcrop]
+                w = wcrop
+                h = hcrop
+            elif w == wcrop and h == hcrop:
+                # No crop needed; image is already cropped to the active array.
+                None
+            else:
+                raise its.error.Error('Invalid image size metadata')
+        # Separate the image planes.
         imgs = [img[::2].reshape(w*h/2)[::2].reshape(h/2,w/2,1),
                 img[::2].reshape(w*h/2)[1::2].reshape(h/2,w/2,1),
                 img[1::2].reshape(w*h/2)[::2].reshape(h/2,w/2,1),
diff --git a/apps/CtsVerifier/Android.mk b/apps/CtsVerifier/Android.mk
index 364f13e..dd85a19 100644
--- a/apps/CtsVerifier/Android.mk
+++ b/apps/CtsVerifier/Android.mk
@@ -34,6 +34,7 @@
                                androidplot \
                                ctsverifier-opencv \
                                core-tests \
+                               android-support-v4  \
                                mockito-target \
                                mockwebserver \
                                compatibility-device-util_v2 \
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 5137761..0f4cb6b 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -1200,6 +1200,23 @@
                        android:value="android.hardware.type.television:android.software.leanback" />
         </activity>
 -->
+          <activity
+                android:name="com.android.cts.verifier.sensors.DeviceSuspendTestActivity"
+                android:label="@string/snsr_device_suspend_test"
+                android:screenOrientation="nosensor" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+            <meta-data android:name="test_category" android:value="@string/test_category_sensors" />
+        </activity>
+
+        <receiver android:name="com.android.cts.verifier.sensors.DeviceSuspendTestActivity$AlarmReceiver">
+        </receiver>
+
+        <receiver android:name="com.android.cts.verifier.sensors.SignificantMotionTestActivity$AlarmReceiver">
+        </receiver>
+
         <activity
             android:name="com.android.cts.verifier.sensors.SignificantMotionTestActivity"
             android:label="@string/snsr_significant_motion_test"
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 52cdd10..800deb6 100644
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -649,6 +649,14 @@
     <string name="snsr_step_counter_event">%1$d | Step Counter event. count=%2$d.</string>
     <string name="snsr_step_detector_event">%1$d | Step Detector event.</string>
 
+    <!-- Device suspend tests -->
+    <string name="snsr_device_suspend_test">Device Suspend Tests</string>
+    <string name="snsr_device_did_not_go_into_suspend">Device did not go into suspend mode during test execution </string>
+    <string name="snsr_batch_did_not_arrive_at_expected_time">Batch did not arrive at the expected time estimatedBatchArrivalMs=%1$d
+    firstEventReceivedMs=%2$d diffMs=%3$d toleranceMs=%4$d </string>
+    <string name="snsr_device_suspend_test_instr">One you begin the test, disconnect USB, turn off the display and allow
+    the device to go into suspend mode. The screen will turn on and a sound will be played once all the tests are completed.</string>
+
     <!-- Significant Motion -->
     <string name="snsr_significant_motion_test">Significant Motion Tests</string>
     <string name="snsr_significant_motion_event_arrival">Event expected to trigger. Triggered=%1$s.</string>
@@ -663,6 +671,9 @@
     <string name="snsr_significant_motion_test_deactivation">Once you begin the test, you will need to walk to ensure Significant Motion triggers only once.</string>
     <string name="snsr_significant_motion_registration">Expected to be able to register for TriggerSensor. Found=%1$b.</string>
     <string name="snsr_significant_motion_cancelation">Expected to be able to cancel TriggerSensor. Found=%b.</string>
+    <string name="snsr_significant_motion_ap_suspend">One you begin the test, disconnect USB, turn off the display and allow the device to go into suspend.
+    You will need to walk to ensure that Significant Motion triggers. The screen will turn on and a sound will be played once the test completes.</string>
+    <string name="snsr_device_did_not_wake_up_at_trigger">Device did not wakeup at tigger time. wakeTime=%1$d ms triggerTime=%2$d ms</string>
 
     <!-- Strings for Sensor CTS tests inside CtsVerifier -->
     <string name="snsr_single_sensor_tests">CTS Single Sensor Tests</string>
@@ -1603,6 +1614,28 @@
             Settings &gt; WiFi and see if the CTSVerifier created WiFi configuration can be forgotten.
             The test is successful if the config could be forgotten and is removed from the list of saved configs.
     </string>
+    <string name="device_owner_disable_statusbar_test">Disable status bar</string>
+    <string name="device_owner_disable_statusbar_test_info">
+            Please press the below button to disable the status bar and verify that quick settings, notifications
+            and the assist gesture are no longer available.\n
+            Next, press the button to reenable the status bar and verify that quick settings, notification
+            and the assist gesture are available again.\n
+            Please mark the test accordingly.
+    </string>
+    <string name="device_owner_disable_statusbar_button">Disable status bar</string>
+    <string name="device_owner_reenable_statusbar_button">Reenable status bar</string>
+    <string name="device_owner_disable_keyguard_test">Disable keyguard</string>
+    <string name="device_owner_disable_keyguard_test_info">
+            Note that any device passwords that you might have set will be deleted during this test.\n
+            Please press the below button to disable the keyguard. Press the power button on your device to
+            switch off the screen. Then press the power button to switch the screen back on and verify that
+            no keyguard was shown.\n
+            Next, press the button to reenable the keyguard and repeat the above steps, this time verifying that
+            a keyguard was shown again.\n
+            Please mark the test accordingly.
+    </string>
+    <string name="device_owner_disable_keyguard_button">Disable keyguard</string>
+    <string name="device_owner_reenable_keyguard_button">Reenable keyguard</string>
 
     <!-- Strings for JobScheduler Tests -->
     <string name="js_test_description">This test is mostly automated, but requires some user interaction. You can pass this test once the list items below are checked.</string>
diff --git a/apps/CtsVerifier/res/xml/device_admin_byod.xml b/apps/CtsVerifier/res/xml/device_admin_byod.xml
index 0408ce2..61238aa 100644
--- a/apps/CtsVerifier/res/xml/device_admin_byod.xml
+++ b/apps/CtsVerifier/res/xml/device_admin_byod.xml
@@ -19,6 +19,7 @@
     <uses-policies>
         <encrypted-storage />
         <wipe-data />
+        <reset-password />
     </uses-policies>
 </device-admin>
 <!-- END_INCLUDE(meta_data) -->
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
index e214c92..1a5e73c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
@@ -19,6 +19,7 @@
 import android.app.Activity;
 import android.app.AlertDialog;
 import android.app.admin.DevicePolicyManager;
+import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
@@ -56,13 +57,17 @@
     static final String COMMAND_ADD_USER_RESTRICTION = "add-user-restriction";
     static final String COMMAND_CLEAR_USER_RESTRICTION = "clear-user-restriction";
     static final String EXTRA_RESTRICTION = "extra-restriction";
-    static final String COMMAND_REMOVE_DEVICE_OWNER = "remove-device-owner";
+    static final String COMMAND_TEAR_DOWN = "tear-down";
     static final String COMMAND_CHECK_DEVICE_OWNER = "check-device-owner";
     static final String COMMAND_SET_GLOBAL_SETTING = "set-global-setting";
+    static final String COMMAND_SET_STATUSBAR_DISABLED = "set-statusbar-disabled";
+    static final String COMMAND_SET_KEYGUARD_DISABLED = "set-keyguard-disabled";
     static final String EXTRA_SETTING = "extra-setting";
 
     private static final String CHECK_DEVICE_OWNER_TEST_ID = "CHECK_DEVICE_OWNER";
     private static final String WIFI_LOCKDOWN_TEST_ID = WifiLockdownTestActivity.class.getName();
+    private static final String DISABLE_STATUS_BAR_TEST_ID = "DISABLE_STATUS_BAR";
+    private static final String DISABLE_KEYGUARD_TEST_ID = "DISABLE_KEYGUARD";
     private static final String REMOVE_DEVICE_OWNER_TEST_ID = "REMOVE_DEVICE_OWNER";
 
     @Override
@@ -107,7 +112,7 @@
     public void finish() {
         // Pass and fail buttons are known to call finish() when clicked, and this is when we want
         // to remove the device owner.
-        startActivity(createRemoveDeviceOwnerIntent());
+        startActivity(createTearDownIntent());
         super.finish();
     }
 
@@ -130,12 +135,42 @@
                     R.string.device_owner_wifi_lockdown_test,
                     new Intent(this, WifiLockdownTestActivity.class)));
         }
+
+        // setStatusBarDisabled
+        adapter.add(createInteractiveTestItem(this, DISABLE_STATUS_BAR_TEST_ID,
+                R.string.device_owner_disable_statusbar_test,
+                R.string.device_owner_disable_statusbar_test_info,
+                new ButtonInfo[] {
+                        new ButtonInfo(
+                                R.string.device_owner_disable_statusbar_button,
+                                createDeviceOwnerIntentWithBooleanParameter(
+                                        COMMAND_SET_STATUSBAR_DISABLED, true)),
+                        new ButtonInfo(
+                                R.string.device_owner_reenable_statusbar_button,
+                                createDeviceOwnerIntentWithBooleanParameter(
+                                        COMMAND_SET_STATUSBAR_DISABLED, false))}));
+
+        // setKeyguardDisabled
+        adapter.add(createInteractiveTestItem(this, DISABLE_KEYGUARD_TEST_ID,
+                R.string.device_owner_disable_keyguard_test,
+                R.string.device_owner_disable_keyguard_test_info,
+                new ButtonInfo[] {
+                        new ButtonInfo(
+                                R.string.device_owner_disable_keyguard_button,
+                                createDeviceOwnerIntentWithBooleanParameter(
+                                        COMMAND_SET_KEYGUARD_DISABLED, true)),
+                        new ButtonInfo(
+                                R.string.device_owner_reenable_keyguard_button,
+                                createDeviceOwnerIntentWithBooleanParameter(
+                                        COMMAND_SET_KEYGUARD_DISABLED, false))}));
+
+        // removeDeviceOwner
         adapter.add(createInteractiveTestItem(this, REMOVE_DEVICE_OWNER_TEST_ID,
                 R.string.device_owner_remove_device_owner_test,
                 R.string.device_owner_remove_device_owner_test_info,
                 new ButtonInfo(
                         R.string.remove_device_owner_button,
-                        createRemoveDeviceOwnerIntent())));
+                        createTearDownIntent())));
     }
 
     static TestListItem createInteractiveTestItem(Activity activity, String id, int titleRes,
@@ -161,9 +196,15 @@
                 null);
     }
 
-    private Intent createRemoveDeviceOwnerIntent() {
+    private Intent createTearDownIntent() {
         return new Intent(this, CommandReceiver.class)
-                .putExtra(EXTRA_COMMAND, COMMAND_REMOVE_DEVICE_OWNER);
+                .putExtra(EXTRA_COMMAND, COMMAND_TEAR_DOWN);
+    }
+
+    private Intent createDeviceOwnerIntentWithBooleanParameter(String command, boolean value) {
+        return new Intent(this, CommandReceiver.class)
+                .putExtra(EXTRA_COMMAND, command)
+                .putExtra(EXTRA_PARAMETER_1, value);
     }
 
     public static class CommandReceiver extends Activity {
@@ -175,26 +216,32 @@
             try {
                 DevicePolicyManager dpm = (DevicePolicyManager)
                         getSystemService(Context.DEVICE_POLICY_SERVICE);
+                ComponentName admin = DeviceAdminTestReceiver.getReceiverComponentName();
                 Log.i(TAG, "Command: " + command);
 
                 if (COMMAND_ADD_USER_RESTRICTION.equals(command)) {
                     String restrictionKey = intent.getStringExtra(EXTRA_RESTRICTION);
-                    dpm.addUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(),
-                            restrictionKey);
+                    dpm.addUserRestriction(admin, restrictionKey);
                     Log.i(TAG, "Added user restriction " + restrictionKey);
                 } else if (COMMAND_CLEAR_USER_RESTRICTION.equals(command)) {
                     String restrictionKey = intent.getStringExtra(EXTRA_RESTRICTION);
-                    dpm.clearUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(),
-                            restrictionKey);
+                    dpm.clearUserRestriction(admin, restrictionKey);
                     Log.i(TAG, "Cleared user restriction " + restrictionKey);
-                } else if (COMMAND_REMOVE_DEVICE_OWNER.equals(command)) {
-                    dpm.clearDeviceOwnerApp(DeviceAdminTestReceiver.getReceiverComponentName()
-                            .getPackageName());
+                } else if (COMMAND_TEAR_DOWN.equals(command)) {
+                    tearDown(dpm, admin);
                 } else if (COMMAND_SET_GLOBAL_SETTING.equals(command)) {
                     final String setting = intent.getStringExtra(EXTRA_SETTING);
                     final String value = intent.getStringExtra(EXTRA_PARAMETER_1);
-                    dpm.setGlobalSetting(DeviceAdminTestReceiver.getReceiverComponentName(),
-                            setting, value);
+                    dpm.setGlobalSetting(admin, setting, value);
+                } else if (COMMAND_SET_STATUSBAR_DISABLED.equals(command)) {
+                    final boolean value = intent.getBooleanExtra(EXTRA_PARAMETER_1, false);
+                    dpm.setStatusBarDisabled(admin, value);
+                } else if (COMMAND_SET_KEYGUARD_DISABLED.equals(command)) {
+                    final boolean value = intent.getBooleanExtra(EXTRA_PARAMETER_1, false);
+                    if (value) {
+                        dpm.resetPassword(null, 0);
+                    }
+                    dpm.setKeyguardDisabled(admin, value);
                 } else if (COMMAND_CHECK_DEVICE_OWNER.equals(command)) {
                     if (dpm.isDeviceOwnerApp(getPackageName())) {
                         TestResult.setPassedResult(this, intent.getStringExtra(EXTRA_TEST_ID),
@@ -213,6 +260,16 @@
                 finish();
             }
         }
+
+        private void tearDown(DevicePolicyManager dpm, ComponentName admin) {
+            if (dpm == null || !dpm.isDeviceOwnerApp(getPackageName())) {
+                return;
+            }
+
+            dpm.setStatusBarDisabled(admin, false);
+            dpm.setKeyguardDisabled(admin, false);
+            dpm.clearDeviceOwnerApp(getPackageName());
+        }
     }
 }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java
new file mode 100644
index 0000000..d066fce
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java
@@ -0,0 +1,263 @@
+package com.android.cts.verifier.sensors;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import com.android.cts.verifier.R;
+import com.android.cts.verifier.sensors.base.SensorCtsVerifierTestActivity;
+import com.android.cts.verifier.sensors.helpers.SensorTestScreenManipulator;
+
+import android.app.AlarmManager;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.hardware.TriggerEvent;
+import android.hardware.TriggerEventListener;
+import android.hardware.cts.helpers.MovementDetectorHelper;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.SensorTestStateNotSupportedException;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.TestSensorEvent;
+import android.hardware.cts.helpers.TestSensorEventListener;
+import android.hardware.cts.helpers.TestSensorManager;
+import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
+import android.hardware.cts.helpers.SensorNotSupportedException;
+import android.hardware.cts.helpers.sensorverification.BatchArrivalVerification;
+import android.os.PowerManager;
+import android.os.PowerManager.WakeLock;
+import android.os.SystemClock;
+import android.support.v4.content.LocalBroadcastManager;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.view.View;
+
+import junit.framework.Assert;
+
+public class DeviceSuspendTestActivity
+            extends SensorCtsVerifierTestActivity {
+        public DeviceSuspendTestActivity() {
+            super(DeviceSuspendTestActivity.class);
+        }
+
+        private SensorTestScreenManipulator mScreenManipulator;
+        private PowerManager.WakeLock mDeviceSuspendLock;
+        private PendingIntent mPendingIntent;
+        private AlarmManager mAlarmManager;
+        private static String ACTION_ALARM = "DeviceSuspendTestActivity.ACTION_ALARM";
+        private static String TAG = "DeviceSuspendTestActivity";
+        private SensorManager mSensorManager;
+
+        @Override
+        protected void activitySetUp() throws InterruptedException {
+            mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
+            mScreenManipulator = new SensorTestScreenManipulator(this);
+            mScreenManipulator.initialize(this);
+            LocalBroadcastManager.getInstance(this).registerReceiver(myBroadCastReceiver,
+                                            new IntentFilter(ACTION_ALARM));
+
+            Intent intent = new Intent(this, AlarmReceiver.class);
+            mPendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
+
+            mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
+
+            PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
+            mDeviceSuspendLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
+                                                "DeviceSuspendTestActivity");
+            mDeviceSuspendLock.acquire();
+            SensorTestLogger logger = getTestLogger();
+            logger.logInstructions(R.string.snsr_device_suspend_test_instr);
+            waitForUserToBegin();
+        }
+
+        @Override
+        protected void activityCleanUp() {
+            mScreenManipulator.turnScreenOn();
+            try {
+                playSound();
+            } catch(InterruptedException e) {
+              // Ignore.
+            }
+            LocalBroadcastManager.getInstance(this).unregisterReceiver(myBroadCastReceiver);
+        }
+
+        @Override
+        protected void onDestroy() {
+            super.onDestroy();
+            if (mScreenManipulator != null) {
+                mScreenManipulator.releaseScreenOn();
+                mScreenManipulator.close();
+            }
+            if (mDeviceSuspendLock.isHeld()) {
+                mDeviceSuspendLock.release();
+            }
+        }
+
+        public static class AlarmReceiver extends BroadcastReceiver {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                Intent alarm_intent = new Intent(context, DeviceSuspendTestActivity.class);
+                alarm_intent.setAction(DeviceSuspendTestActivity.ACTION_ALARM);
+                LocalBroadcastManager.getInstance(context).sendBroadcastSync(alarm_intent);
+            }
+        }
+
+        public BroadcastReceiver myBroadCastReceiver = new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                if (!mDeviceSuspendLock.isHeld()) {
+                    mDeviceSuspendLock.acquire();
+                }
+            }
+        };
+
+        public String testAPWakeUpWhenReportLatencyExpiresAccel() throws Throwable {
+            Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER, true);
+            if (wakeUpSensor == null) {
+                throw new SensorNotSupportedException(Sensor.TYPE_ACCELEROMETER, true);
+            }
+            return runAPWakeUpWhenReportLatencyExpires(wakeUpSensor);
+        }
+
+        public String testAPWakeUpWhenReportLatencyExpiresGyro() throws Throwable {
+            Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE, true);
+            if (wakeUpSensor == null) {
+                throw new SensorNotSupportedException(Sensor.TYPE_GYROSCOPE, true);
+            }
+            return runAPWakeUpWhenReportLatencyExpires(wakeUpSensor);
+        }
+
+        public String testAPWakeUpWhenReportLatencyExpiresMag() throws Throwable {
+            Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD,true);
+            if (wakeUpSensor == null) {
+                throw new SensorNotSupportedException(Sensor.TYPE_MAGNETIC_FIELD, true);
+            }
+            return runAPWakeUpWhenFIFOFull(wakeUpSensor);
+        }
+
+        public String testAPWakeUpWhenFIFOFullAccel() throws Throwable {
+            Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER, true);
+            if (wakeUpSensor == null) {
+                throw new SensorNotSupportedException(Sensor.TYPE_ACCELEROMETER, true);
+            }
+            return runAPWakeUpWhenFIFOFull(wakeUpSensor);
+        }
+
+        public String testAPWakeUpWhenFIFOFullGyro() throws Throwable {
+            Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE, true);
+            if (wakeUpSensor == null) {
+                throw new SensorNotSupportedException(Sensor.TYPE_GYROSCOPE, true);
+            }
+            return runAPWakeUpWhenFIFOFull(wakeUpSensor);
+        }
+
+        public String testAPWakeUpWhenFIFOFullMag() throws Throwable {
+            Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD,true);
+            if (wakeUpSensor == null) {
+                throw new SensorNotSupportedException(Sensor.TYPE_MAGNETIC_FIELD, true);
+            }
+            return runAPWakeUpWhenFIFOFull(wakeUpSensor);
+        }
+
+        public String runAPWakeUpWhenReportLatencyExpires(Sensor sensor) throws Throwable {
+            int fifoMaxEventCount = sensor.getFifoMaxEventCount();
+            if (fifoMaxEventCount == 0) {
+                throw new SensorTestStateNotSupportedException("Batching not supported.");
+            }
+            int maximumExpectedSamplingPeriodUs = sensor.getMaxDelay();
+            if (maximumExpectedSamplingPeriodUs == 0) {
+                // If maxDelay is not defined, set the value for 5 Hz.
+                maximumExpectedSamplingPeriodUs = 200000;
+            }
+            int fifoBasedReportLatencyUs = fifoMaxEventCount * maximumExpectedSamplingPeriodUs;
+
+            // Ensure that FIFO based report latency is at least 20 seconds, we need at least 10
+            // seconds of time to allow the device to be in suspend state.
+            if (fifoBasedReportLatencyUs < 20000000L) {
+                throw new SensorTestStateNotSupportedException("FIFO too small to test reliably");
+            }
+
+            final int MAX_REPORT_LATENCY_US = 15000000; // 15 seconds
+            TestSensorEnvironment environment = new TestSensorEnvironment(
+                    this,
+                    sensor,
+                    false,
+                    maximumExpectedSamplingPeriodUs,
+                    MAX_REPORT_LATENCY_US,
+                    true /*isDeviceSuspendTest*/);
+
+            int numEventsToWaitFor = MAX_REPORT_LATENCY_US/maximumExpectedSamplingPeriodUs;
+            TestSensorOperation op = TestSensorOperation.createOperation(environment,
+                                                                          numEventsToWaitFor,
+                                                                          mDeviceSuspendLock,
+                                                                          false);
+            final int ALARM_WAKE_UP_DELAY_MS = MAX_REPORT_LATENCY_US/1000 +
+                (int)TimeUnit.SECONDS.toMillis(10);
+            op.addVerification(BatchArrivalVerification.getDefault(environment));
+            mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
+                                    SystemClock.elapsedRealtime() + ALARM_WAKE_UP_DELAY_MS,
+                                    mPendingIntent);
+            try {
+                op.execute(getCurrentTestNode());
+            } finally {
+                mAlarmManager.cancel(mPendingIntent);
+            }
+            return null;
+        }
+
+        public String runAPWakeUpWhenFIFOFull(Sensor sensor) throws Throwable {
+            int fifoMaxEventCount = sensor.getFifoMaxEventCount();
+            if (fifoMaxEventCount == 0) {
+                throw new SensorTestStateNotSupportedException("Batching not supported.");
+            }
+            // Try to fill the FIFO at the fastest rate and check if the time is enough to run
+            // the manual test.
+            int maximumExpectedSamplingPeriodUs = sensor.getMinDelay();
+            int fifoBasedReportLatencyUs = fifoMaxEventCount * maximumExpectedSamplingPeriodUs;
+
+            final int MIN_LATENCY_US = (int)TimeUnit.SECONDS.toMicros(20);
+            // Ensure that FIFO based report latency is at least 20 seconds, we need at least 10
+            // seconds of time to allow the device to be in suspend state.
+            if (fifoBasedReportLatencyUs < MIN_LATENCY_US) {
+                maximumExpectedSamplingPeriodUs = MIN_LATENCY_US/fifoMaxEventCount;
+                fifoBasedReportLatencyUs = MIN_LATENCY_US;
+            }
+
+            final int MAX_REPORT_LATENCY_US = Integer.MAX_VALUE;
+            final int ALARM_WAKE_UP_DELAY_MS = fifoBasedReportLatencyUs/1000 +
+                (int)TimeUnit.SECONDS.toMillis(10);
+            TestSensorEnvironment environment = new TestSensorEnvironment(
+                    this,
+                    sensor,
+                    false,
+                    maximumExpectedSamplingPeriodUs,
+                    MAX_REPORT_LATENCY_US,
+                    true /*isDeviceSuspendTest*/);
+
+           int numEventsToWaitFor = fifoMaxEventCount;
+            TestSensorOperation op = TestSensorOperation.createOperation(environment,
+                                                                          numEventsToWaitFor,
+                                                                          mDeviceSuspendLock,
+                                                                         true);
+            mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
+                                    SystemClock.elapsedRealtime() + ALARM_WAKE_UP_DELAY_MS,
+                                    mPendingIntent);
+            op.addDefaultVerifications();
+            try {
+                op.execute(getCurrentTestNode());
+            } finally {
+                mAlarmManager.cancel(mPendingIntent);
+            }
+            return null;
+        }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java
index faba445..f8f1a9a 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java
@@ -16,22 +16,36 @@
 
 package com.android.cts.verifier.sensors;
 
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
 import com.android.cts.verifier.R;
 import com.android.cts.verifier.sensors.base.SensorCtsVerifierTestActivity;
+import com.android.cts.verifier.sensors.helpers.SensorTestScreenManipulator;
 
-import junit.framework.Assert;
-
+import android.app.AlarmManager;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
 import android.hardware.Sensor;
 import android.hardware.SensorManager;
 import android.hardware.TriggerEvent;
 import android.hardware.TriggerEventListener;
 import android.hardware.cts.helpers.SensorNotSupportedException;
 import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.SuspendStateMonitor;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.PowerManager;
 import android.os.SystemClock;
+import android.support.v4.content.LocalBroadcastManager;
+import android.util.Log;
 
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
+import junit.framework.Assert;
 
 /**
  * Test cases for Significant Motion sensor.
@@ -46,20 +60,30 @@
     private static final long MAX_ACCEPTABLE_EVENT_TIME_DELAY_NANOS =
             TimeUnit.MILLISECONDS.toNanos(500);
 
+    // acceptable time difference between event time and AP wake up time.
+    private static final long MAX_ACCEPTABLE_DELAY_EVENT_AP_WAKE_UP_NS =
+            TimeUnit.MILLISECONDS.toNanos(2000);
+
+    // time to wait for SMD after the device has gone into suspend. Even after
+    // 45 secs if SMD does not trigger, the test will fail.
+    private static final long ALARM_WAKE_TIME_DELAY_MS = TimeUnit.SECONDS.toMillis(45);
+
     // time for the test to wait for a trigger
     private static final int TRIGGER_MAX_DELAY_SECONDS = 30;
     private static final int VIBRATE_DURATION_MILLIS = 10000;
 
     private static final int EVENT_VALUES_LENGTH = 1;
     private static final float EXPECTED_EVENT_VALUE = 1.0f;
+    private static String ACTION_ALARM = "SignificantMotionTestActivity.ACTION_ALARM";
 
     private SensorManager mSensorManager;
     private Sensor mSensorSignificantMotion;
+    private TriggerVerifier mVerifier;
+    private SensorTestScreenManipulator mScreenManipulator;
 
     /**
      * Test cases.
      */
-
     @SuppressWarnings("unused")
     public String testTrigger() throws Throwable {
         return runTest(
@@ -131,6 +155,69 @@
         return result;
     }
 
+    public static class AlarmReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            Intent alarm_intent = new Intent(context, SignificantMotionTestActivity.class);
+            alarm_intent.setAction(SignificantMotionTestActivity.ACTION_ALARM);
+            LocalBroadcastManager.getInstance(context).sendBroadcastSync(alarm_intent);
+        }
+    }
+
+    public BroadcastReceiver myBroadCastReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            mVerifier.releaseLatch();
+            mScreenManipulator.turnScreenOn();
+            try {
+                playSound();
+            } catch (InterruptedException e) {
+                // Ignore ...
+            }
+        }
+    };
+
+    @SuppressWarnings("unused")
+    public String testAPWakeUpOnSMDTrigger() throws Throwable {
+        SensorTestLogger logger = getTestLogger();
+        logger.logInstructions(R.string.snsr_significant_motion_ap_suspend);
+        waitForUserToBegin();
+        mVerifier = new TriggerVerifier();
+        mSensorManager.requestTriggerSensor(mVerifier, mSensorSignificantMotion);
+        long testStartTimeNs = SystemClock.elapsedRealtimeNanos();
+        Handler handler = new Handler(Looper.getMainLooper());
+        SuspendStateMonitor suspendStateMonitor = new SuspendStateMonitor();
+
+        Intent intent = new Intent(this, AlarmReceiver.class);
+        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
+
+        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
+        am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
+                     SystemClock.elapsedRealtime() + ALARM_WAKE_TIME_DELAY_MS, pendingIntent);
+        try {
+            // Wait for the first event to trigger. Device is expected to go into suspend here.
+            mVerifier.verifyEventTriggered();
+            long eventTimeStampNs = mVerifier.getTimeStampForTriggerEvent();
+            long endTimeNs = SystemClock.elapsedRealtimeNanos();
+            long lastWakeupTimeNs = TimeUnit.MILLISECONDS.toNanos(
+                    suspendStateMonitor.getLastWakeUpTime());
+            Assert.assertTrue(getString(R.string.snsr_device_did_not_go_into_suspend),
+                              testStartTimeNs < lastWakeupTimeNs && lastWakeupTimeNs < endTimeNs);
+            long timestampDelta = Math.abs(lastWakeupTimeNs - eventTimeStampNs);
+            Assert.assertTrue(
+                    String.format(getString(R.string.snsr_device_did_not_wake_up_at_trigger),
+                              TimeUnit.NANOSECONDS.toMillis(lastWakeupTimeNs),
+                              TimeUnit.NANOSECONDS.toMillis(eventTimeStampNs)),
+                              timestampDelta < MAX_ACCEPTABLE_DELAY_EVENT_AP_WAKE_UP_NS);
+        } finally {
+            am.cancel(pendingIntent);
+            suspendStateMonitor.cancel();
+            mScreenManipulator.turnScreenOn();
+            playSound();
+        }
+        return null;
+    }
+
     /**
      * @param instructionsResId Instruction to be shown to testers
      * @param isMotionExpected Should the device detect significant motion event
@@ -187,6 +274,27 @@
         if (mSensorSignificantMotion == null) {
             throw new SensorNotSupportedException(Sensor.TYPE_SIGNIFICANT_MOTION);
         }
+
+        mScreenManipulator = new SensorTestScreenManipulator(this);
+        try {
+            mScreenManipulator.initialize(this);
+        } catch (InterruptedException e) {
+        }
+        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
+        LocalBroadcastManager.getInstance(this).registerReceiver(myBroadCastReceiver,
+                                            new IntentFilter(ACTION_ALARM));
+    }
+
+    @Override
+    protected void activityCleanUp() {
+        mScreenManipulator.turnScreenOff();
+        LocalBroadcastManager.getInstance(this).unregisterReceiver(myBroadCastReceiver);
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        mScreenManipulator.close();
     }
 
     /**
@@ -194,7 +302,7 @@
      * It cannot be reused.
      */
     private class TriggerVerifier extends TriggerEventListener {
-        private volatile CountDownLatch mCountDownLatch;
+        private volatile CountDownLatch mCountDownLatch = new CountDownLatch(1);
         private volatile TriggerEventRegistry mEventRegistry;
 
         // TODO: refactor out if needed
@@ -214,6 +322,19 @@
             mCountDownLatch.countDown();
         }
 
+        public void releaseLatch() {
+            if (mCountDownLatch != null) {
+                mCountDownLatch.countDown();
+            }
+        }
+
+        public long getTimeStampForTriggerEvent() {
+            if (mEventRegistry != null && mEventRegistry.triggerEvent != null) {
+                return mEventRegistry.triggerEvent.timestamp;
+            }
+            return 0;
+        }
+
         public String verifyEventTriggered() throws Throwable {
             TriggerEventRegistry registry = awaitForEvent();
 
@@ -267,11 +388,8 @@
         }
 
         private TriggerEventRegistry awaitForEvent() throws InterruptedException {
-            mCountDownLatch = new CountDownLatch(1);
             mCountDownLatch.await(TRIGGER_MAX_DELAY_SECONDS, TimeUnit.SECONDS);
-
             TriggerEventRegistry registry = mEventRegistry;
-            mEventRegistry = null;
 
             playSound();
             return registry != null ? registry : new TriggerEventRegistry(null, 0);
diff --git a/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java b/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java
index 4e70264..cb50f16 100644
--- a/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java
+++ b/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java
@@ -810,6 +810,7 @@
      */
     public void testGfxinfoFramestats() throws Exception {
         final String MARKER = "---PROFILEDATA---";
+        final int TIMESTAMP_COUNT = 14;
 
         String frameinfo = mDevice.executeShellCommand("dumpsys gfxinfo com.android.systemui framestats");
         assertNotNull(frameinfo);
@@ -831,15 +832,15 @@
             assertTrue("First line was not the expected header",
                     line.startsWith("Flags,IntendedVsync,Vsync,OldestInputEvent" +
                             ",NewestInputEvent,HandleInputStart,AnimationStart" +
-                            ",PerformTraversalsStart,DrawStart,SyncStart" +
+                            ",PerformTraversalsStart,DrawStart,SyncQueued,SyncStart" +
                             ",IssueDrawCommandsStart,SwapBuffers,FrameCompleted"));
 
-            long[] numparts = new long[13];
+            long[] numparts = new long[TIMESTAMP_COUNT];
             while ((line = reader.readLine()) != null && !line.isEmpty()) {
 
                 String[] parts = line.split(",");
-                assertTrue(parts.length >= 13);
-                for (int i = 0; i < 13; i++) {
+                assertTrue(parts.length >= TIMESTAMP_COUNT);
+                for (int i = 0; i < TIMESTAMP_COUNT; i++) {
                     numparts[i] = assertInteger(parts[i]);
                 }
                 if (numparts[0] != 0) {
@@ -850,12 +851,12 @@
                 // assert time is flowing forwards, skipping index 3 & 4
                 // as those are input timestamps that may or may not be present
                 assertTrue(numparts[5] >= numparts[2]);
-                for (int i = 6; i < 13; i++) {
+                for (int i = 6; i < TIMESTAMP_COUNT; i++) {
                     assertTrue("Index " + i + " did not flow forward, " +
                             numparts[i] + " not larger than " + numparts[i - 1],
                             numparts[i] >= numparts[i-1]);
                 }
-                long totalDuration = numparts[12] - numparts[1];
+                long totalDuration = numparts[13] - numparts[1];
                 assertTrue("Frame did not take a positive amount of time to process",
                         totalDuration > 0);
                 assertTrue("Bogus frame duration, exceeds 100 seconds",
diff --git a/tests/tests/accessibility/Android.mk b/tests/tests/accessibility/Android.mk
index bb943ee..263c47b 100644
--- a/tests/tests/accessibility/Android.mk
+++ b/tests/tests/accessibility/Android.mk
@@ -26,4 +26,6 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner
 
+LOCAL_SDK_VERSION := current
+
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/app.usage/AndroidManifest.xml b/tests/tests/app.usage/AndroidManifest.xml
index 3bd795a..54fde71 100644
--- a/tests/tests/app.usage/AndroidManifest.xml
+++ b/tests/tests/app.usage/AndroidManifest.xml
@@ -32,6 +32,7 @@
         <activity android:name=".Activities$ActivityTwo" />
         <activity android:name=".Activities$ActivityThree" />
         <activity android:name=".Activities$ActivityFour" />
+        <activity android:name=".ActivityTransitionActivity" />
     </application>
 
     <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/app.usage/res/layout/end.xml b/tests/tests/app.usage/res/layout/end.xml
new file mode 100644
index 0000000..2847249
--- /dev/null
+++ b/tests/tests/app.usage/res/layout/end.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
+              android:orientation="vertical">
+    <View android:layout_width="10dp"
+          android:layout_height="10dp"
+          android:background="#F00"
+          android:id="@+id/redSquare"/>
+    <TextView android:layout_width="wrap_content"
+              android:layout_height="wrap_content"
+              android:transitionName="target"
+              android:text="@string/hello"/>
+    <View android:layout_width="10dp"
+          android:layout_height="10dp"
+          android:background="#0F0"
+          android:id="@+id/greenSquare"/>
+</LinearLayout>
diff --git a/tests/tests/app.usage/res/layout/start.xml b/tests/tests/app.usage/res/layout/start.xml
new file mode 100644
index 0000000..793e9b5
--- /dev/null
+++ b/tests/tests/app.usage/res/layout/start.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
+              android:orientation="vertical">
+    <View android:layout_width="10dp"
+          android:layout_height="10dp"
+          android:background="#0F0"
+          android:id="@+id/greenSquare"/>
+    <View android:layout_width="10dp"
+          android:layout_height="10dp"
+          android:background="#F00"
+          android:id="@+id/redSquare"/>
+    <TextView android:layout_width="wrap_content"
+              android:layout_height="wrap_content"
+              android:transitionName="source"
+              android:id="@+id/hello"
+              android:text="@string/hello"/>
+</LinearLayout>
diff --git a/tests/tests/app.usage/res/values/strings.xml b/tests/tests/app.usage/res/values/strings.xml
new file mode 100644
index 0000000..8ca6f73
--- /dev/null
+++ b/tests/tests/app.usage/res/values/strings.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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.
+-->
+<resources>
+    <string name="hello">Hello</string>
+</resources>
diff --git a/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionActivity.java b/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionActivity.java
new file mode 100644
index 0000000..10ac4ea
--- /dev/null
+++ b/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionActivity.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2014 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.app.usage.cts;
+
+import android.app.Activity;
+import android.app.SharedElementCallback;
+import android.app.usage.cts.R;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.ResultReceiver;
+import android.os.SystemClock;
+import android.transition.ChangeBounds;
+import android.transition.Explode;
+import android.transition.Fade;
+import android.transition.Transition;
+import android.transition.Transition.TransitionListener;
+import android.view.View;
+
+import java.util.List;
+
+/**
+ * A simple activity containing the start state for an Activity Transition
+ */
+public class ActivityTransitionActivity extends Activity {
+    private static final long DURATION = 50;
+    private static final long SHARED_ELEMENT_READY_DELAY = 50;
+    public static final String LAYOUT_ID = "layoutId";
+    public static final String TEST = "test";
+    public static final String RESULT_RECEIVER = "resultReceiver";
+
+    public static final int NO_TEST = 0;
+    public static final int TEST_ARRIVE = 1;
+
+    public static final String ARRIVE_COUNT = "numArrived";
+    public static final String ARRIVE_ENTER_START_VISIBILITY = "arriveEnterStartVisibility";
+    public static final String ARRIVE_ENTER_DELAY_VISIBILITY = "arriveEnterDelayVisibility";
+    public static final String ARRIVE_ENTER_TIME_READY = "arriveEnterTimeReady";
+    public static final String ARRIVE_ENTER_TIME = "arriveEnterTime";
+    public static final String ARRIVE_RETURN_TIME_READY = "arriveReturnTimeReady";
+    public static final String ARRIVE_RETURN_TIME = "arriveReturnTime";
+
+    private int mLayoutId;
+    private int mTest;
+    private ResultReceiver mResultReceiver;
+    private int mNumSharedElementsArrivedCalled = 0;
+    private boolean mEntering = true;
+
+    public int resultCode = 0;
+    public Bundle result = new Bundle();
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+        getWindow().setSharedElementEnterTransition(new ChangeBounds().setDuration(DURATION));
+        getWindow().setSharedElementReturnTransition(new ChangeBounds().setDuration(DURATION));
+        getWindow().setEnterTransition(new Explode().setDuration(DURATION));
+        getWindow().setReturnTransition(new Explode().setDuration(DURATION));
+        getWindow().setExitTransition(new Fade().setDuration(DURATION));
+        mLayoutId = 0;
+        if (icicle != null) {
+            mLayoutId =  icicle.getInt(LAYOUT_ID);
+            mTest = icicle.getInt(TEST);
+            mResultReceiver = icicle.getParcelable(RESULT_RECEIVER);
+        }
+
+        if (mLayoutId == 0) {
+            Intent intent = getIntent();
+            mLayoutId = intent.getIntExtra(LAYOUT_ID, R.layout.start);
+            mTest = intent.getIntExtra(TEST, 0);
+            mResultReceiver = intent.getParcelableExtra(RESULT_RECEIVER);
+        }
+
+        setContentView(mLayoutId);
+
+        startTest();
+    }
+
+    @Override
+    protected void onSaveInstanceState(Bundle outState) {
+        outState.putInt(LAYOUT_ID, mLayoutId);
+        outState.putInt(TEST, mTest);
+        outState.putParcelable(RESULT_RECEIVER, mResultReceiver);
+    }
+
+    private void startTest() {
+        if (mTest == TEST_ARRIVE) {
+            setEnterSharedElementCallback(new SharedElementCallback() {
+                @Override
+                public void onSharedElementsArrived(List<String> sharedElementNames,
+                        final List<View> sharedElements,
+                        final OnSharedElementsReadyListener listener) {
+                    mNumSharedElementsArrivedCalled++;
+                    result.putInt(ARRIVE_COUNT, mNumSharedElementsArrivedCalled);
+                    if (mEntering) {
+                        result.putInt(ARRIVE_ENTER_START_VISIBILITY, sharedElements.get(0).getVisibility());
+                        result.putLong(ARRIVE_ENTER_TIME, SystemClock.uptimeMillis());
+                    } else {
+                        result.putLong(ARRIVE_RETURN_TIME, SystemClock.uptimeMillis());
+                    }
+
+                    getWindow().getDecorView().postDelayed(new Runnable() {
+                        @Override
+                        public void run() {
+                            if (mEntering) {
+                                result.putInt(ARRIVE_ENTER_DELAY_VISIBILITY,
+                                        sharedElements.get(0).getVisibility());
+                                result.putLong(ARRIVE_ENTER_TIME_READY, SystemClock.uptimeMillis());
+                            } else {
+                                result.putLong(ARRIVE_RETURN_TIME_READY,
+                                        SystemClock.uptimeMillis());
+                                mResultReceiver.send(RESULT_OK, result);
+                            }
+                            listener.onSharedElementsReady();
+                        }
+                    }, SHARED_ELEMENT_READY_DELAY);
+                }
+            });
+            getWindow().getEnterTransition().addListener(new TransitionListener() {
+                @Override
+                public void onTransitionStart(Transition transition) {
+                }
+
+                @Override
+                public void onTransitionEnd(Transition transition) {
+                    mEntering = false;
+                    setResult(RESULT_OK);
+                    getWindow().getDecorView().post(new Runnable() {
+                        @Override
+                        public void run() {
+                            finishAfterTransition();
+                        }
+                    });
+                }
+
+                @Override
+                public void onTransitionCancel(Transition transition) {
+                }
+
+                @Override
+                public void onTransitionPause(Transition transition) {
+                }
+
+                @Override
+                public void onTransitionResume(Transition transition) {
+                }
+            });
+        }
+    }
+
+    @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+        synchronized (this) {
+            super.onActivityResult(requestCode, resultCode, data);
+            this.resultCode = resultCode;
+            this.notifyAll();
+        }
+    }
+}
diff --git a/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionTest.java b/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionTest.java
new file mode 100644
index 0000000..ef126fe
--- /dev/null
+++ b/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionTest.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2015 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.app.usage.cts;
+
+import android.app.ActivityOptions;
+import android.app.SharedElementCallback;
+import android.app.usage.cts.R;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.ResultReceiver;
+import android.os.SystemClock;
+import android.test.ActivityInstrumentationTestCase2;
+import android.view.View;
+
+import java.util.List;
+
+public class ActivityTransitionTest extends
+        ActivityInstrumentationTestCase2<ActivityTransitionActivity> {
+    protected ActivityTransitionActivity mActivity;
+
+    private int mNumArrivedCalls;
+    private PassInfo mReceiver;
+    private long mExitTime;
+    private long mExitTimeReady;
+    private long mReenterTime;
+    private long mReenterTimeReady;
+
+    public ActivityTransitionTest() {
+        super(ActivityTransitionActivity.class);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        setActivityInitialTouchMode(false);
+        mActivity = getActivity();
+        mNumArrivedCalls = 0;
+    }
+
+    public void testOnSharedElementsArrived() throws Throwable {
+        getInstrumentation().waitForIdleSync();
+        runTestOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                mReceiver = new PassInfo(new Handler());
+                mActivity.setExitSharedElementCallback(new SharedElementCallback() {
+                    @Override
+                    public void onSharedElementsArrived(List<String> sharedElementNames,
+                            List<View> sharedElements,
+                            final OnSharedElementsReadyListener listener) {
+                        mNumArrivedCalls++;
+                        final boolean isExiting = mExitTimeReady == 0;
+                        if (isExiting) {
+                            mExitTime = SystemClock.uptimeMillis();
+                        } else {
+                            mReenterTime = SystemClock.uptimeMillis();
+                        }
+                        mActivity.getWindow().getDecorView().postDelayed(new Runnable() {
+                            @Override
+                            public void run() {
+                                if (isExiting) {
+                                    mExitTimeReady = SystemClock.uptimeMillis();
+                                } else {
+                                    mReenterTimeReady = SystemClock.uptimeMillis();
+                                }
+                                listener.onSharedElementsReady();
+                            }
+                        }, 60);
+                    }
+                });
+
+                Bundle options = ActivityOptions.makeSceneTransitionAnimation(mActivity,
+                        mActivity.findViewById(R.id.hello), "target").toBundle();
+                Intent intent = new Intent(mActivity, ActivityTransitionActivity.class);
+                intent.putExtra(ActivityTransitionActivity.TEST,
+                        ActivityTransitionActivity.TEST_ARRIVE);
+                intent.putExtra(ActivityTransitionActivity.LAYOUT_ID, R.layout.end);
+                intent.putExtra(ActivityTransitionActivity.RESULT_RECEIVER, mReceiver);
+                mActivity.startActivityForResult(intent, 0, options);
+            }
+        });
+
+        long endTime = SystemClock.uptimeMillis() + 1500;
+        synchronized (mActivity) {
+            while (mActivity.resultCode == 0) {
+                long waitTime = endTime - SystemClock.uptimeMillis();
+                if (waitTime <= 0) {
+                    fail("Activity didn't finish!");
+                }
+                mActivity.wait(waitTime);
+            }
+        }
+        assertNotNull(mReceiver.resultData);
+        assertEquals(2, mReceiver.resultData.getInt(
+                ActivityTransitionActivity.ARRIVE_COUNT, -1));
+        assertEquals(2, mNumArrivedCalls);
+        assertNotSame(View.VISIBLE, mReceiver.resultData.getInt(
+                ActivityTransitionActivity.ARRIVE_ENTER_START_VISIBILITY));
+        assertNotSame(View.VISIBLE, mReceiver.resultData.getInt(
+                ActivityTransitionActivity.ARRIVE_ENTER_DELAY_VISIBILITY));
+        long enterTimeReady = mReceiver.resultData.getLong(
+                ActivityTransitionActivity.ARRIVE_ENTER_TIME_READY);
+        long returnTimeReady = mReceiver.resultData.getLong(
+                ActivityTransitionActivity.ARRIVE_RETURN_TIME_READY);
+        long enterTime = mReceiver.resultData.getLong(
+                ActivityTransitionActivity.ARRIVE_ENTER_TIME);
+        long returnTime = mReceiver.resultData.getLong(
+                ActivityTransitionActivity.ARRIVE_RETURN_TIME);
+
+        assertTrue(mExitTime < mExitTimeReady);
+        assertTrue(mExitTimeReady <= enterTime);
+        assertTrue(enterTime < enterTimeReady);
+        assertTrue(enterTimeReady <= returnTime);
+        assertTrue(returnTime < returnTimeReady);
+        assertTrue(returnTimeReady <= mReenterTime);
+        assertTrue(mReenterTime < mReenterTimeReady);
+    }
+
+    public static class PassInfo extends ResultReceiver {
+        public int resultCode;
+        public Bundle resultData;
+
+        public PassInfo(Handler handler) {
+            super(handler);
+        }
+
+        @Override
+        protected void onReceiveResult(int resultCode, Bundle resultData) {
+            this.resultCode = resultCode;
+            this.resultData = resultData;
+        }
+    }
+}
diff --git a/tests/tests/app/Android.mk b/tests/tests/app/Android.mk
index 4a3d31f..301f931 100644
--- a/tests/tests/app/Android.mk
+++ b/tests/tests/app/Android.mk
@@ -31,4 +31,6 @@
 
 LOCAL_INSTRUMENTATION_FOR := CtsAppTestStubs
 
+LOCAL_SDK_VERSION := current
+
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java b/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java
index 9554438..58e69b8 100644
--- a/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java
+++ b/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java
@@ -577,26 +577,6 @@
         assertEquals(view, mView);
     }
 
-    public void testSetViewCustom() throws Throwable {
-        final int viewSpacingLeft = 10;
-        final int viewSpacingTop = 20;
-        final int viewSpacingRight = 30;
-        final int viewSpacingBottom = 40;
-        final View view = new View(mContext);
-        view.setId(100);
-        runTestOnUiThread(new Runnable() {
-            public void run() {
-                mBuilder = new AlertDialog.Builder(mContext);
-                mBuilder.setView(view, viewSpacingLeft, viewSpacingTop, viewSpacingRight,
-                        viewSpacingBottom);
-                mDialog = mBuilder.show();
-                mView = mDialog.getWindow().findViewById(100);
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-        assertEquals(view, mView);
-    }
-
     public void testSetInverseBackgroundForced() throws Throwable {
         runTestOnUiThread(new Runnable() {
             public void run() {
diff --git a/tests/tests/app/src/android/app/cts/InstrumentationTest.java b/tests/tests/app/src/android/app/cts/InstrumentationTest.java
index b21148e..25403f3 100644
--- a/tests/tests/app/src/android/app/cts/InstrumentationTest.java
+++ b/tests/tests/app/src/android/app/cts/InstrumentationTest.java
@@ -540,7 +540,6 @@
             public void openPanel(int featureId, KeyEvent event) {
             }
 
-            @Override
             public void alwaysReadCloseOnTouchAttr() {
             }
 
diff --git a/tests/tests/app/src/android/app/cts/NotificationTest.java b/tests/tests/app/src/android/app/cts/NotificationTest.java
index 17f433e..6179922 100644
--- a/tests/tests/app/src/android/app/cts/NotificationTest.java
+++ b/tests/tests/app/src/android/app/cts/NotificationTest.java
@@ -166,16 +166,6 @@
         assertNotNull(mNotification.contentView);
     }
 
-    public void testSetLatestEventInfo() {
-        mNotification = new Notification();
-        mNotification.icon = 1;
-        final Intent intent = new Intent();
-        final PendingIntent contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
-        mNotification.setLatestEventInfo(mContext, CONTENT_TITLE, CONTENT_TEXT, contentIntent);
-        assertTrue(mNotification.contentView instanceof RemoteViews);
-        assertNotNull(mNotification.contentView);
-    }
-
     public void testToString() {
         mNotification = new Notification();
         assertNotNull(mNotification.toString());
diff --git a/tests/tests/app/src/android/app/cts/SearchDialogTest.java b/tests/tests/app/src/android/app/cts/SearchDialogTest.java
deleted file mode 100644
index 1cf1ebd..0000000
--- a/tests/tests/app/src/android/app/cts/SearchDialogTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2015 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.app.cts;
-
-import android.app.SearchDialog;
-import android.content.Context;
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.InstrumentationTestCase;
-import android.view.ActionMode;
-import android.view.View;
-import android.view.ViewGroup;
-
-/**
- * Test {@link SearchDialog}.
- */
-public class SearchDialogTest extends InstrumentationTestCase {
-
-    private Context mContext;
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mContext = getInstrumentation().getTargetContext();
-    }
-
-    public void testPrimaryActionModesAreStopped() {
-        SearchDialog.SearchBar searchBar = new SearchDialog.SearchBar(mContext);
-        MockViewGroup viewGroup = new MockViewGroup(mContext);
-        viewGroup.addView(searchBar);
-
-        ActionMode mode = searchBar.startActionModeForChild(null, null, ActionMode.TYPE_PRIMARY);
-
-        assertNull(mode);
-        // Should not bubble up.
-        assertFalse(viewGroup.isStartActionModeForChildTypedCalled);
-        assertFalse(viewGroup.isStartActionModeForChildTypelessCalled);
-
-        mode = searchBar.startActionModeForChild(null, null);
-
-        assertNull(mode);
-        // Should not bubble up.
-        assertFalse(viewGroup.isStartActionModeForChildTypedCalled);
-        assertFalse(viewGroup.isStartActionModeForChildTypelessCalled);
-    }
-
-    public void testFloatingActionModesAreBubbledUp() {
-        SearchDialog.SearchBar searchBar = new SearchDialog.SearchBar(mContext);
-        MockViewGroup viewGroup = new MockViewGroup(mContext);
-        viewGroup.addView(searchBar);
-
-        searchBar.startActionModeForChild(null, null, ActionMode.TYPE_FLOATING);
-
-        // Should bubble up.
-        assertTrue(viewGroup.isStartActionModeForChildTypedCalled);
-    }
-
-    private static class MockViewGroup extends ViewGroup {
-        boolean isStartActionModeForChildTypedCalled = false;
-        boolean isStartActionModeForChildTypelessCalled = false;
-
-        public MockViewGroup(Context context) {
-            super(context);
-        }
-
-        @Override
-        public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
-            isStartActionModeForChildTypelessCalled = true;
-            return super.startActionModeForChild(originalView, callback);
-        }
-
-        @Override
-        public ActionMode startActionModeForChild(
-                View originalView, ActionMode.Callback callback, int type) {
-            isStartActionModeForChildTypedCalled = true;
-            return super.startActionModeForChild(originalView, callback, type);
-        }
-
-        @Override
-        protected void onLayout(boolean changed, int l, int t, int r, int b) {}
-    }
-}
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanReservedTest.java b/tests/tests/graphics/src/android/graphics/cts/VulkanReservedTest.java
new file mode 100644
index 0000000..bfd520e
--- /dev/null
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanReservedTest.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2015 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.graphics.cts;
+
+import android.cts.util.FileUtils;
+
+import junit.framework.TestCase;
+
+import java.io.File;
+
+public class VulkanReservedTest extends TestCase {
+
+    /**
+     * Assert that file with given path does not exist.
+     */
+    private static void assertNoFile(String filename) {
+        assertFalse(filename + " must not exist", new File(filename).exists());
+    }
+
+    /**
+     * Test that no vendor ships libvulkan.so before ratification and
+     * appropriate CTS coverage.
+     */
+    public void testNoVulkan() {
+        assertNoFile("/system/lib/libvulkan.so");
+        assertNoFile("/system/lib64/libvulkan.so");
+        assertNoFile("/vendor/lib/libvulkan.so");
+        assertNoFile("/vendor/lib64/libvulkan.so");
+    }
+}
diff --git a/tests/tests/graphics/src/android/opengl/cts/EglConfigGLSurfaceView.java b/tests/tests/graphics/src/android/opengl/cts/EglConfigGLSurfaceView.java
index 03e8d94..eb36166 100644
--- a/tests/tests/graphics/src/android/opengl/cts/EglConfigGLSurfaceView.java
+++ b/tests/tests/graphics/src/android/opengl/cts/EglConfigGLSurfaceView.java
@@ -101,7 +101,7 @@
             gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
             gl.glColor4f(1.0f, 0, 0, 0);
             gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFloatBuffer);
-            gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 9);
+            gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
 
             if (++mNumFrames == 10) {
                 post(mCallback);
diff --git a/tests/tests/hardware/AndroidTest.xml b/tests/tests/hardware/AndroidTest.xml
index 783eafe..4ddf28c 100644
--- a/tests/tests/hardware/AndroidTest.xml
+++ b/tests/tests/hardware/AndroidTest.xml
@@ -17,6 +17,6 @@
     <include name="common-config" />
     <!-- Put SensorService in restricted mode so that only CTS tests will be able to get access to
     sensors -->
-    <option name="run-command:run-command" value="dumpsys sensorservice restrict" />
+    <option name="run-command:run-command" value="dumpsys sensorservice restrict .cts." />
     <option name="run-command:teardown-command" value="dumpsys sensorservice enable" />
 </configuration>
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/RecordingTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/RecordingTest.java
index ad1951c..cd4b731 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/RecordingTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/RecordingTest.java
@@ -60,7 +60,7 @@
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
     private static final boolean DEBUG_DUMP = Log.isLoggable(TAG, Log.DEBUG);
     private static final int RECORDING_DURATION_MS = 3000;
-    private static final int DURATION_MARGIN_MS = 600;
+    private static final float DURATION_MARGIN = 0.2f;
     private static final double FRAME_DURATION_ERROR_TOLERANCE_MS = 3.0;
     private static final int BIT_RATE_1080P = 16000000;
     private static final int BIT_RATE_MIN = 64000;
@@ -1080,7 +1080,7 @@
         }
     }
 
-    private void validateRecording(Size sz, int durationMs) throws Exception {
+    private void validateRecording(Size sz, int expectedDurationMs) throws Exception {
         File outFile = new File(mOutMediaFileName);
         assertTrue("No video is recorded", outFile.exists());
 
@@ -1108,15 +1108,16 @@
             int duration = (int) (durationUs / 1000);
             if (VERBOSE) {
                 Log.v(TAG, String.format("Video duration: recorded %dms, expected %dms",
-                                         duration, durationMs));
+                                         duration, expectedDurationMs));
             }
 
             // TODO: Don't skip this for video snapshot
             if (!mStaticInfo.isHardwareLevelLegacy()) {
                 assertTrue(String.format(
                         "Camera %s: Video duration doesn't match: recorded %dms, expected %dms.",
-                        mCamera.getId(), duration, durationMs),
-                        Math.abs(duration - durationMs) < DURATION_MARGIN_MS);
+                        mCamera.getId(), duration, expectedDurationMs),
+                        Math.abs(duration - expectedDurationMs) <
+                        DURATION_MARGIN * expectedDurationMs);
             }
         } finally {
             extractor.release();
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java
index ee4ddd9..d8dda8f 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java
@@ -341,6 +341,12 @@
                 Log.i(TAG, "Testing AE precapture cancel for jpeg capture for Camera " + id);
                 openDevice(id);
 
+                // Legacy device doesn't support AE precapture trigger
+                if (mStaticInfo.isHardwareLevelLegacy()) {
+                    Log.i(TAG, "Skipping AE precapture trigger cancel test on legacy devices");
+                    continue;
+                }
+
                 takePictureTestByCamera(/*aeRegions*/null, /*awbRegions*/null, /*afRegions*/null,
                         /*addAeTriggerCancel*/true);
             } finally {
diff --git a/tests/tests/hardware/src/android/hardware/cts/SensorTest.java b/tests/tests/hardware/src/android/hardware/cts/SensorTest.java
index 4450339..6beeec8 100644
--- a/tests/tests/hardware/src/android/hardware/cts/SensorTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/SensorTest.java
@@ -348,9 +348,9 @@
         TestSensorEventListener listener = new TestSensorEventListener(environment, handler);
 
         CountDownLatch eventLatch = mTestSensorManager.registerListener(listener, 1);
-        listener.waitForEvents(eventLatch, 1);
+        listener.waitForEvents(eventLatch, 1, true);
         CountDownLatch flushLatch = mTestSensorManager.requestFlush();
-        listener.waitForFlushComplete(flushLatch);
+        listener.waitForFlushComplete(flushLatch, true);
         listener.assertEventsReceivedInHandler();
     }
 
@@ -382,9 +382,9 @@
 
         // specifyHandler <= false, use the SensorManager API without Handler parameter
         CountDownLatch eventLatch = mTestSensorManager.registerListener(listener, 1, false);
-        listener.waitForEvents(eventLatch, 1);
+        listener.waitForEvents(eventLatch, 1, true);
         CountDownLatch flushLatch = mTestSensorManager.requestFlush();
-        listener.waitForFlushComplete(flushLatch);
+        listener.waitForFlushComplete(flushLatch, true);
         listener.assertEventsReceivedInHandler();
     }
 
@@ -581,10 +581,10 @@
             try {
                 CountDownLatch eventLatch = sensorManager.registerListener(listener, mEventCount);
                 if (sensorReportingMode == Sensor.REPORTING_MODE_CONTINUOUS) {
-                    listener.waitForEvents(eventLatch, mEventCount);
+                    listener.waitForEvents(eventLatch, mEventCount, true);
                 }
                 CountDownLatch flushLatch = sensorManager.requestFlush();
-                listener.waitForFlushComplete(flushLatch);
+                listener.waitForFlushComplete(flushLatch, true);
             } finally {
                 sensorManager.unregisterListener();
             }
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorNotSupportedException.java b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorNotSupportedException.java
index e727092..0d90957 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorNotSupportedException.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorNotSupportedException.java
@@ -26,6 +26,11 @@
         super("Sensor '%s' of type %d is not supported.", getSensorName(sensorType), sensorType);
     }
 
+    public SensorNotSupportedException(int sensorType, boolean wakeup) {
+        super("Sensor '%s' of type %d and %s is not supported.", getSensorName(sensorType),
+               sensorType, wakeup ? "wake-up" : "non wake-up");
+    }
+
     private static String getSensorName(int sensorType) {
         return String.format("%s (%d)", getSimpleSensorName(sensorType), sensorType);
     }
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorStats.java b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorStats.java
index 8067aed..f0f0186 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorStats.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorStats.java
@@ -54,6 +54,7 @@
     public static final String MEAN_KEY = "mean";
     public static final String STANDARD_DEVIATION_KEY = "standard_deviation";
     public static final String MAGNITUDE_KEY = "magnitude";
+    public static final String DELAYED_BATCH_DELIVERY = "delayed_batch_delivery";
 
     private final Map<String, Object> mValues = new HashMap<>();
     private final Map<String, SensorStats> mSensorStats = new HashMap<>();
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/SuspendStateMonitor.java b/tests/tests/hardware/src/android/hardware/cts/helpers/SuspendStateMonitor.java
new file mode 100644
index 0000000..4426967
--- /dev/null
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/SuspendStateMonitor.java
@@ -0,0 +1,57 @@
+package android.hardware.cts.helpers;
+
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import android.hardware.Sensor;
+import android.hardware.TriggerEvent;
+import android.hardware.TriggerEventListener;
+import android.os.Handler;
+import android.os.SystemClock;
+import android.util.Log;
+
+import junit.framework.Assert;
+
+public class SuspendStateMonitor {
+    private final double firstRealTimeMillis;
+    private final double firstUpTimeMillis;
+    private double lastSleepTimeSeconds = 0;
+    private volatile long lastWakeUpTime = 0;
+    Timer sleepMonitoringTimer = new Timer();
+
+    /**
+     * Returns the time the device slept since the start of the application,
+     * in seconds.
+     */
+    public double getSleepTimeSeconds() {
+        double totalSinceStart = android.os.SystemClock.elapsedRealtime() - firstRealTimeMillis;
+        double upTimeSinceStart = android.os.SystemClock.uptimeMillis() - firstUpTimeMillis;
+        return (totalSinceStart - upTimeSinceStart) / 1000;
+    }
+
+    public long getLastWakeUpTime() {
+        return lastWakeUpTime;
+    }
+
+    public void cancel() {
+        sleepMonitoringTimer.cancel();
+    }
+
+     public SuspendStateMonitor() {
+        firstRealTimeMillis = android.os.SystemClock.elapsedRealtime();
+        firstUpTimeMillis = android.os.SystemClock.uptimeMillis();
+        // Every 100 miliseconds, check whether the device has slept.
+        TimerTask sleepMonitoringTask = new TimerTask() {
+                @Override
+                public void run() {
+                    if (getSleepTimeSeconds() - lastSleepTimeSeconds > 0.1) {
+                        lastSleepTimeSeconds = getSleepTimeSeconds();
+                        lastWakeUpTime = SystemClock.elapsedRealtime();
+                    }
+                }
+        };
+        sleepMonitoringTimer.schedule(sleepMonitoringTask, 0, 100);
+    }
+}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEnvironment.java b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEnvironment.java
index 143f0a1..6156d3d 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEnvironment.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEnvironment.java
@@ -40,6 +40,7 @@
     private final boolean mSensorMightHaveMoreListeners;
     private final int mSamplingPeriodUs;
     private final int mMaxReportLatencyUs;
+    private final boolean mIsDeviceSuspendTest;
 
     /**
      * Constructs an environment for sensor testing.
@@ -163,11 +164,27 @@
             boolean sensorMightHaveMoreListeners,
             int samplingPeriodUs,
             int maxReportLatencyUs) {
+        this(context,
+                sensor,
+                sensorMightHaveMoreListeners,
+                samplingPeriodUs,
+                maxReportLatencyUs,
+                false /* isDeviceSuspendTest */);
+    }
+
+    public TestSensorEnvironment(
+            Context context,
+            Sensor sensor,
+            boolean sensorMightHaveMoreListeners,
+            int samplingPeriodUs,
+            int maxReportLatencyUs,
+            boolean isDeviceSuspendTest) {
         mContext = context;
         mSensor = sensor;
         mSensorMightHaveMoreListeners = sensorMightHaveMoreListeners;
         mSamplingPeriodUs = samplingPeriodUs;
         mMaxReportLatencyUs = maxReportLatencyUs;
+        mIsDeviceSuspendTest = isDeviceSuspendTest;
     }
 
     /**
@@ -357,4 +374,9 @@
                 && mSamplingPeriodUs != SensorManager.SENSOR_DELAY_UI
                 && mSamplingPeriodUs != SensorManager.SENSOR_DELAY_NORMAL);
     }
+
+    public boolean isDeviceSuspendTest() {
+        return mIsDeviceSuspendTest;
+    }
 }
+
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEventListener.java b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEventListener.java
index 662c3ce..23effb9 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEventListener.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEventListener.java
@@ -18,12 +18,16 @@
 
 import junit.framework.Assert;
 
+import android.content.Context;
 import android.hardware.Sensor;
 import android.hardware.SensorEvent;
 import android.hardware.SensorEventListener2;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.SystemClock;
+import android.os.PowerManager;
+import android.os.PowerManager.WakeLock;
+import android.util.Log;
 
 import java.io.BufferedWriter;
 import java.io.File;
@@ -50,12 +54,14 @@
     private static final long FLUSH_TIMEOUT_US = TimeUnit.SECONDS.toMicros(10);
 
     private final ArrayList<TestSensorEvent> mCollectedEvents = new ArrayList<>();
+    private final ArrayList<Long> mTimeStampFlushCompleteEvents = new ArrayList<>();
     private final List<CountDownLatch> mEventLatches = new ArrayList<>();
     private final List<CountDownLatch> mFlushLatches = new ArrayList<>();
     private final AtomicInteger mEventsReceivedOutsideHandler = new AtomicInteger();
 
     private final Handler mHandler;
     private final TestSensorEnvironment mEnvironment;
+    private final PowerManager.WakeLock mTestSensorEventListenerWakeLock;
 
     /**
      * @deprecated Use {@link TestSensorEventListener(TestSensorEnvironment)}.
@@ -78,6 +84,10 @@
     public TestSensorEventListener(TestSensorEnvironment environment, Handler handler) {
         mEnvironment = environment;
         mHandler = handler;
+        PowerManager pm = (PowerManager) environment.getContext().getSystemService(
+                Context.POWER_SERVICE);
+        mTestSensorEventListenerWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
+                                                "TestSensorEventListenerWakeLock");
     }
 
     /**
@@ -93,6 +103,9 @@
         synchronized (mEventLatches) {
             for (CountDownLatch latch : mEventLatches) {
                 latch.countDown();
+                if (latch.getCount() == 0 && !mTestSensorEventListenerWakeLock.isHeld()) {
+                    mTestSensorEventListenerWakeLock.acquire();
+                }
             }
         }
     }
@@ -136,6 +149,10 @@
     @Override
     public void onFlushCompleted(Sensor sensor) {
         checkHandler();
+        long timestampNs = SystemClock.elapsedRealtimeNanos();
+        synchronized (mTimeStampFlushCompleteEvents) {
+           mTimeStampFlushCompleteEvents.add(timestampNs);
+        }
         synchronized (mFlushLatches) {
             for (CountDownLatch latch : mFlushLatches) {
                 latch.countDown();
@@ -175,7 +192,8 @@
      * It will overwrite the file if it already exists, the file is created in a relative directory
      * named 'events' under the sensor test directory (part of external storage).
      */
-    public void logCollectedEventsToFile(String fileName) throws IOException {
+    public void logCollectedEventsToFile(String fileName, long deviceWakeUpTimeMs)
+        throws IOException {
         StringBuilder builder = new StringBuilder();
         builder.append("Sensor='").append(mEnvironment.getSensor()).append("', ");
         builder.append("SamplingRateOverloaded=")
@@ -184,15 +202,54 @@
                 .append(mEnvironment.getRequestedSamplingPeriodUs()).append("us, ");
         builder.append("MaxReportLatency=")
                 .append(mEnvironment.getMaxReportLatencyUs()).append("us");
-
         synchronized (mCollectedEvents) {
-            for (TestSensorEvent event : mCollectedEvents) {
+            int i = 0, j = 0;
+            while (i < mCollectedEvents.size() && j < mTimeStampFlushCompleteEvents.size()) {
+                if (mCollectedEvents.get(i).receivedTimestamp <
+                        mTimeStampFlushCompleteEvents.get(j)) {
+                    TestSensorEvent event = mCollectedEvents.get(i);
+                    if (deviceWakeUpTimeMs != -1 && deviceWakeUpTimeMs <
+                            event.receivedTimestamp/1000000) {
+                        builder.append("\n");
+                        builder.append("AP wake-up time=").append(deviceWakeUpTimeMs).append("ms");
+                        deviceWakeUpTimeMs = -1;
+                    }
+                    builder.append("\n");
+                    builder.append("Timestamp=").append(event.timestamp/1000000).append("ms, ");
+                    builder.append("ReceivedTimestamp=").append(event.receivedTimestamp/1000000).
+                        append("ms, ");
+                    builder.append("Accuracy=").append(event.accuracy).append(", ");
+                    builder.append("Values=").append(Arrays.toString(event.values));
+                    ++i;
+                } else {
+                    builder.append("\n");
+                    builder.append("ReceivedTimestamp=")
+                    .append(mTimeStampFlushCompleteEvents.get(j)/1000000)
+                    .append(" Flush complete Event");
+                    ++j;
+                }
+            }
+            for (;i < mCollectedEvents.size(); ++i) {
+                TestSensorEvent event = mCollectedEvents.get(i);
+                if (deviceWakeUpTimeMs != -1 && deviceWakeUpTimeMs <
+                        event.receivedTimestamp/1000000) {
+                    builder.append("\n");
+                    builder.append("AP wake-up time=").append(deviceWakeUpTimeMs).append("ms");
+                    deviceWakeUpTimeMs = -1;
+                }
                 builder.append("\n");
-                builder.append("Timestamp=").append(event.timestamp).append("ns, ");
-                builder.append("ReceivedTimestamp=").append(event.receivedTimestamp).append("ns, ");
+                builder.append("Timestamp=").append(event.timestamp/1000000).append("ms, ");
+                builder.append("ReceivedTimestamp=").append(event.receivedTimestamp/1000000).
+                    append("ms, ");
                 builder.append("Accuracy=").append(event.accuracy).append(", ");
                 builder.append("Values=").append(Arrays.toString(event.values));
             }
+            for (;j < mTimeStampFlushCompleteEvents.size(); ++j) {
+                builder.append("\n");
+                builder.append("ReceivedTimestamp=")
+                    .append(mTimeStampFlushCompleteEvents.get(j)/1000000)
+                    .append("ms Flush complete Event");
+            }
         }
 
         File eventsDirectory = SensorCtsHelper.getSensorTestDataDirectory("events/");
@@ -208,8 +265,11 @@
      *
      * @throws AssertionError if there was a timeout after {@link #FLUSH_TIMEOUT_US} &micro;s
      */
-    public void waitForFlushComplete(CountDownLatch latch) throws InterruptedException {
-        clearEvents();
+    public void waitForFlushComplete(CountDownLatch latch,
+                                      boolean clearCollectedEvents) throws InterruptedException {
+        if (clearCollectedEvents) {
+            clearEvents();
+        }
         try {
             String message = SensorCtsHelper.formatAssertionMessage(
                     "WaitForFlush",
@@ -229,8 +289,11 @@
      *
      * @throws AssertionError if there was a timeout after {@link #FLUSH_TIMEOUT_US} &micro;s
      */
-    public void waitForEvents(CountDownLatch latch, int eventCount) throws InterruptedException {
-        clearEvents();
+    public void waitForEvents(CountDownLatch latch, int eventCount,
+                               boolean clearCollectedEvents) throws InterruptedException {
+        if (clearCollectedEvents) {
+            clearEvents();
+        }
         try {
             long samplingPeriodUs = mEnvironment.getMaximumExpectedSamplingPeriodUs();
             // timeout is 2 * event count * expected period + batch timeout + default wait
@@ -279,6 +342,12 @@
         Assert.assertEquals(message, 0 /* expected */, eventsOutsideHandler);
     }
 
+    public void releaseWakeLock() {
+        if (mTestSensorEventListenerWakeLock.isHeld()) {
+            mTestSensorEventListenerWakeLock.release();
+        }
+    }
+
     /**
      * Keeps track of the number of events that arrived in a different {@link Looper} than the one
      * associated with the {@link TestSensorEventListener}.
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
index 3b90b15..d6cc54e 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
@@ -16,7 +16,11 @@
 
 package android.hardware.cts.helpers.sensoroperations;
 
-import junit.framework.Assert;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 import android.hardware.cts.helpers.SensorCtsHelper;
 import android.hardware.cts.helpers.SensorStats;
@@ -25,6 +29,7 @@
 import android.hardware.cts.helpers.TestSensorEvent;
 import android.hardware.cts.helpers.TestSensorEventListener;
 import android.hardware.cts.helpers.TestSensorManager;
+import android.hardware.cts.helpers.SuspendStateMonitor;
 import android.hardware.cts.helpers.reporting.ISensorTestNode;
 import android.hardware.cts.helpers.sensorverification.EventGapVerification;
 import android.hardware.cts.helpers.sensorverification.EventOrderingVerification;
@@ -36,13 +41,11 @@
 import android.hardware.cts.helpers.sensorverification.MeanVerification;
 import android.hardware.cts.helpers.sensorverification.StandardDeviationVerification;
 import android.os.Handler;
+import android.os.SystemClock;
+import android.os.PowerManager.WakeLock;
 import android.util.Log;
 
-import java.io.IOException;
-import java.util.HashSet;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
+import junit.framework.Assert;
 
 /**
  * A {@link SensorOperation} used to verify that sensor events and sensor values are correct.
@@ -61,6 +64,7 @@
     private final TestSensorEnvironment mEnvironment;
     private final Executor mExecutor;
     private final Handler mHandler;
+    private long mDeviceWakeUpTimeMs = -1;
 
     /**
      * An interface that defines an abstraction for operations to be performed by the
@@ -118,7 +122,22 @@
     public void execute(ISensorTestNode parent) throws InterruptedException {
         getStats().addValue("sensor_name", mEnvironment.getSensor().getName());
         TestSensorEventListener listener = new TestSensorEventListener(mEnvironment, mHandler);
-        mExecutor.execute(mSensorManager, listener);
+
+        if (mEnvironment.isDeviceSuspendTest()) {
+            SuspendStateMonitor suspendStateMonitor = new SuspendStateMonitor();
+            long startTimeMs = SystemClock.elapsedRealtime();
+            // Device should go into suspend here.
+            mExecutor.execute(mSensorManager, listener);
+            long endTimeMs = SystemClock.elapsedRealtime();
+            // Check if the device has gone into suspend during test execution.
+            mDeviceWakeUpTimeMs = suspendStateMonitor.getLastWakeUpTime();
+            suspendStateMonitor.cancel();
+            Assert.assertTrue("Device did not go into suspend during test execution",
+                                       startTimeMs < mDeviceWakeUpTimeMs &&
+                                       mDeviceWakeUpTimeMs < endTimeMs);
+        } else {
+            mExecutor.execute(mSensorManager, listener);
+        }
 
         boolean failed = false;
         StringBuilder sb = new StringBuilder();
@@ -193,7 +212,7 @@
         }
 
         try {
-            listener.logCollectedEventsToFile(sanitizedFileName);
+            listener.logCollectedEventsToFile(sanitizedFileName, mDeviceWakeUpTimeMs);
         } catch (IOException e) {
             Log.w(TAG, "Unable to save collected events to file: " + sanitizedFileName, e);
         }
@@ -214,7 +233,7 @@
                     throws InterruptedException {
                 try {
                     CountDownLatch latch = sensorManager.registerListener(listener, eventCount);
-                    listener.waitForEvents(latch, eventCount);
+                    listener.waitForEvents(latch, eventCount, true);
                 } finally {
                     sensorManager.unregisterListener();
                 }
@@ -224,6 +243,62 @@
     }
 
     /**
+     * Creates an operation that will wait for a given amount of events to arrive.
+     *
+     * @param environment The test environment.
+     * @param eventCount The number of events to wait for.
+     */
+    public static TestSensorOperation createOperation(
+            final TestSensorEnvironment environment,
+            final int eventCount,
+            final WakeLock wakeLock,
+            final boolean flushRequested) {
+        Executor executor = new Executor() {
+            @Override
+            public void execute(TestSensorManager sensorManager, TestSensorEventListener listener)
+                    throws InterruptedException {
+                try {
+                    int eventCountForLatch = eventCount;
+                    if (flushRequested) {
+                        eventCountForLatch = eventCount + (int)environment.getFrequencyHz();
+                    }
+                    CountDownLatch latch = sensorManager.registerListener(listener,
+                                                                           eventCountForLatch);
+                    if (flushRequested) {
+                        SensorCtsHelper.sleep(1, TimeUnit.SECONDS);
+                        CountDownLatch flushLatch = sensorManager.requestFlush();
+                        listener.waitForFlushComplete(flushLatch, false);
+                    }
+                    if (wakeLock.isHeld()) {
+                        wakeLock.release();
+                    }
+                    listener.releaseWakeLock();
+                    Log.v("TestSensorOperation", "waitForEvents " +
+                            environment.getSensor().getName()
+                          + " " + latch.getCount());
+                    listener.waitForEvents(latch, eventCount, false);
+                    Log.v("TestSensorOperation", "waitForEvents DONE " + environment.getSensor().getName());
+                    if (!wakeLock.isHeld()) {
+                        wakeLock.acquire();
+                    }
+                    if (flushRequested) {
+                        SensorCtsHelper.sleep(1, TimeUnit.SECONDS);
+                        CountDownLatch flushLatch = sensorManager.requestFlush();
+                        listener.waitForFlushComplete(flushLatch, false);
+                    }
+                } finally {
+                    if(!wakeLock.isHeld()) {
+                        wakeLock.acquire();
+                    }
+                    listener.releaseWakeLock();
+                    sensorManager.unregisterListener();
+                }
+            }
+        };
+        return new TestSensorOperation(environment, executor);
+    }
+
+    /**
      * Creates an operation that will wait for a given amount of time to collect events.
      *
      * @param environment The test environment.
@@ -269,7 +344,7 @@
                     sensorManager.registerListener(listener);
                     SensorCtsHelper.sleep(duration, timeUnit);
                     CountDownLatch latch = sensorManager.requestFlush();
-                    listener.waitForFlushComplete(latch);
+                    listener.waitForFlushComplete(latch, true);
                 } finally {
                     sensorManager.unregisterListener();
                 }
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/BatchArrivalVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/BatchArrivalVerification.java
new file mode 100644
index 0000000..5e50c3a
--- /dev/null
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/BatchArrivalVerification.java
@@ -0,0 +1,139 @@
+
+package android.hardware.cts.helpers.sensorverification;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import android.hardware.Sensor;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.TestSensorEvent;
+import android.hardware.cts.helpers.sensorverification.AbstractSensorVerification.IndexedEventPair;
+import android.os.SystemClock;
+import android.provider.Settings.System;
+
+import junit.framework.Assert;
+
+/**
+ * A {@link ISensorVerification} which verifies that there are no missing events. This is done by
+ * checking the last received sensor timestamp and checking that it is within 1.8 * the expected
+ * period.
+ */
+public class BatchArrivalVerification extends AbstractSensorVerification {
+    public static final String PASSED_KEY = "missing_event_passed";
+
+    // Batch arrival tolerance is 5 seconds.
+    private static final int BATCH_ARRIVAL_TOLERANCE_US = 5000000;
+
+    // Number of indices to print in assert message before truncating
+    private static final int TRUNCATE_MESSAGE_LENGTH = 3;
+
+    // Number of events to truncate (discard) from the initial events received
+    private static final int TRUNCATE_EVENTS_COUNT = 100;
+
+    private final long mExpectedBatchArrivalTimeUs;
+
+    private final List<IndexedEventPair> mFailures = new LinkedList<IndexedEventPair>();
+    private TestSensorEvent mFirstEvent = null;
+    private int mIndex = 0;
+
+    /**
+     * Construct a {@link EventGapVerification}
+     *
+     * @param expectedDelayUs the expected period in us.
+     */
+    public BatchArrivalVerification(long expectedBatchArrivalTimeUs) {
+         mExpectedBatchArrivalTimeUs = expectedBatchArrivalTimeUs;
+    }
+
+    /**
+     * Get the default {@link EventGapVerification}.
+     *
+     * @param environment the test environment
+     * @return the verification or null if the verification is not a continuous mode sensor.
+     */
+    public static BatchArrivalVerification getDefault(TestSensorEnvironment environment) {
+        if (environment.getSensor().getReportingMode() != Sensor.REPORTING_MODE_CONTINUOUS) {
+            return null;
+        }
+        long fifoMaxEventCount = environment.getSensor().getFifoMaxEventCount();
+        int maximumExpectedSamplingPeriodUs = environment.getMaximumExpectedSamplingPeriodUs();
+        long reportLatencyUs = environment.getMaxReportLatencyUs();
+        if (fifoMaxEventCount > 0 && maximumExpectedSamplingPeriodUs != Integer.MAX_VALUE) {
+            long fifoBasedReportLatencyUs =
+                    fifoMaxEventCount * maximumExpectedSamplingPeriodUs;
+            // If the device goes into suspend mode during the test and the sensor under test is
+            // a non wake-up sensor, the FIFO will keep overwriting itself and the reportLatency
+            // of each event will be equal to the time it takes to fill up the FIFO.
+            if (environment.isDeviceSuspendTest() && !environment.getSensor().isWakeUpSensor()) {
+                reportLatencyUs = fifoBasedReportLatencyUs;
+            } else {
+                // In this case the sensor under test is either a wake-up sensor OR it
+                // is a non wake-up sensor but the device does not go into suspend.
+                // So the expected delay of a sensor_event is the minimum of the
+                // fifoBasedReportLatencyUs and the requested latency by the application.
+                reportLatencyUs = Math.min(reportLatencyUs, fifoBasedReportLatencyUs);
+            }
+        }
+        long expectedBatchArrivalTimeUs = reportLatencyUs + SystemClock.elapsedRealtime() * 1000;
+        return new BatchArrivalVerification(expectedBatchArrivalTimeUs);
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void verify(TestSensorEnvironment environment, SensorStats stats) {
+        final int count = mFailures.size();
+        stats.addValue(PASSED_KEY, count == 0);
+        stats.addValue(SensorStats.DELAYED_BATCH_DELIVERY, count);
+
+        if (count > 0) {
+            StringBuilder sb = new StringBuilder();
+            sb.append(count).append(" batch delayed: ");
+            for (int i = 0; i < Math.min(count, TRUNCATE_MESSAGE_LENGTH); i++) {
+                IndexedEventPair info = mFailures.get(i);
+                sb.append(String.format("expectedBatchArrival=%dms actualBatchArrivalTime=%dms "+
+                                        "diff=%dms tolerance=%dms",
+                                         (mExpectedBatchArrivalTimeUs)/1000,
+                                         info.event.receivedTimestamp/(1000 * 1000),
+                                         (mExpectedBatchArrivalTimeUs -
+                                          info.event.receivedTimestamp/1000)/1000,
+                                         BATCH_ARRIVAL_TOLERANCE_US/1000)
+
+                          );
+
+            }
+            if (count > TRUNCATE_MESSAGE_LENGTH) {
+                sb.append(count - TRUNCATE_MESSAGE_LENGTH).append(" more; ");
+            }
+            Assert.fail(sb.toString());
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public BatchArrivalVerification clone() {
+        return new BatchArrivalVerification(mExpectedBatchArrivalTimeUs);
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected void addSensorEventInternal(TestSensorEvent event) {
+        if (mFirstEvent == null) {
+            mFirstEvent = event;
+        }
+        if (mIndex == 1) {
+            if (Math.abs(mFirstEvent.receivedTimestamp/1000 - mExpectedBatchArrivalTimeUs) >
+                BATCH_ARRIVAL_TOLERANCE_US) {
+                mFailures.add(new IndexedEventPair(1, mFirstEvent, null));
+            }
+        }
+        ++mIndex;
+    }
+}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventTimestampSynchronizationVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventTimestampSynchronizationVerification.java
index a90725f..3af3f03 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventTimestampSynchronizationVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventTimestampSynchronizationVerification.java
@@ -75,6 +75,16 @@
                     fifoMaxEventCount * maximumExpectedSamplingPeriodUs;
             reportLatencyUs = Math.min(reportLatencyUs, fifoBasedReportLatencyUs) +
                 (long)(2.5 * maximumExpectedSamplingPeriodUs);
+            // of each event will be equal to the time it takes to fill up the FIFO.
+            if (environment.isDeviceSuspendTest() && !environment.getSensor().isWakeUpSensor()) {
+                reportLatencyUs = fifoBasedReportLatencyUs;
+            } else {
+                // In this case the sensor under test is either a wake-up sensor OR it
+                // is a non wake-up sensor but the device does not go into suspend.
+                // So the expected delay of a sensor_event is the minimum of the
+                // fifoBasedReportLatencyUs and the requested latency by the application.
+                reportLatencyUs = Math.min(reportLatencyUs, fifoBasedReportLatencyUs);
+            }
         }
         long expectedSyncLatencyNs = TimeUnit.MICROSECONDS.toNanos(reportLatencyUs);
         return new EventTimestampSynchronizationVerification(DEFAULT_THRESHOLD_NS,
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyChainTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyChainTest.java
index d8080a0..caa6336 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyChainTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyChainTest.java
@@ -17,9 +17,13 @@
 package android.keystore.cts;
 
 import android.content.pm.PackageManager;
+import android.os.Handler;
 import android.security.KeyChain;
+import android.security.KeyChainException;
 import android.test.AndroidTestCase;
 
+import java.util.concurrent.CountDownLatch;
+
 public class KeyChainTest extends AndroidTestCase {
     public void testIsKeyAlgorithmSupported_RequiredAlgorithmsSupported() throws Exception {
         assertFalse("DSA must not be supported", KeyChain.isKeyAlgorithmSupported("DSA"));
@@ -27,6 +31,56 @@
         assertTrue("RSA must be supported", KeyChain.isKeyAlgorithmSupported("RSA"));
     }
 
+    public void testNullPrivateKeyArgumentsFail()
+            throws KeyChainException, InterruptedException {
+        try {
+            KeyChain.getPrivateKey(null, null);
+            fail("NullPointerException was expected for null arguments to "
+                    + "KeyChain.getPrivateKey(Context, String)");
+        } catch (NullPointerException expected) {
+        }
+    }
+
+    public void testNullPrivateKeyAliasArgumentFails()
+            throws KeyChainException, InterruptedException {
+        try {
+            KeyChain.getPrivateKey(getContext(), null);
+            fail("NullPointerException was expected with null String argument to "
+                        + "KeyChain.getPrivateKey(Context, String).");
+        } catch (NullPointerException expected) {
+        }
+    }
+
+    public void testNullPrivateKeyContextArgumentFails()
+            throws KeyChainException, InterruptedException {
+        try {
+            KeyChain.getPrivateKey(null, "");
+            fail("NullPointerException was expected with null Context argument to "
+                    + "KeyChain.getPrivateKey(Context, String).");
+        } catch (NullPointerException expected) {
+        }
+    }
+
+    public void testGetPrivateKeyOnMainThreadFails() throws InterruptedException {
+        final CountDownLatch waiter = new CountDownLatch(1);
+        new Handler(getContext().getMainLooper()).post(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    KeyChain.getPrivateKey(getContext(), "");
+                    fail("IllegalStateException was expected for calling "
+                            + "KeyChain.getPrivateKey(Context, String) on main thread");
+                } catch (IllegalStateException expected) {
+                } catch (Exception invalid) {
+                    fail("Expected IllegalStateException, received " + invalid);
+                } finally {
+                    waiter.countDown();
+                }
+            }
+        });
+        waiter.await();
+    }
+
     /**
      * Tests whether the required algorithms are backed by a Keymaster HAL that
      * binds the key material to the specific device it was created or imported
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
index daf55a7..15438e8 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
@@ -587,6 +587,7 @@
     }
 
     public void testGetMaxSupportedInstances() {
+        StringBuilder xmlOverrides = new StringBuilder();
         MediaCodecList allCodecs = new MediaCodecList(MediaCodecList.ALL_CODECS);
         for (MediaCodecInfo info : allCodecs.getCodecInfos()) {
             Log.d(TAG, "codec: " + info.getName());
@@ -604,9 +605,25 @@
                     int actualMax = getActualMax(
                             info.isEncoder(), info.getName(), types[j], caps, max + 1);
                     Log.d(TAG, "actualMax " + actualMax + " vs reported max " + max);
-                    assertTrue(actualMax >= (int)(max * 0.9));
+                    if (actualMax < (int)(max * 0.9) || actualMax > (int) Math.ceil(max * 1.1)) {
+                        String codec = "<MediaCodec name=\"" + info.getName() +
+                                "\" type=\"" + types[j] + "\" >";
+                        String limit = "    <Limit name=\"concurrent-instances\" max=\"" +
+                                actualMax + "\" />";
+                        xmlOverrides.append(codec);
+                        xmlOverrides.append("\n");
+                        xmlOverrides.append(limit);
+                        xmlOverrides.append("\n");
+                        xmlOverrides.append("</MediaCodec>\n");
+                    }
                 }
             }
         }
+
+        if (xmlOverrides.length() > 0) {
+            String failMessage = "In order to pass the test, please publish following " +
+                    "codecs' concurrent instances limit in /etc/media_codecs.xml: \n";
+           fail(failMessage + xmlOverrides.toString());
+        }
     }
 }
diff --git a/tests/tests/media/src/android/media/cts/ResourceManagerStubActivity.java b/tests/tests/media/src/android/media/cts/ResourceManagerStubActivity.java
index 214ced4..d453e3f 100644
--- a/tests/tests/media/src/android/media/cts/ResourceManagerStubActivity.java
+++ b/tests/tests/media/src/android/media/cts/ResourceManagerStubActivity.java
@@ -53,7 +53,7 @@
                     Context context = getApplicationContext();
                     Intent intent1 = new Intent(context, ResourceManagerTestActivity1.class);
                     startActivityForResult(intent1, mRequestCodes[0]);
-                    Thread.sleep(2000);  // wait for process to launch.
+                    Thread.sleep(5000);  // wait for process to launch and allocate all codecs.
 
                     Intent intent2 = new Intent(context, ResourceManagerTestActivity2.class);
                     startActivityForResult(intent2, mRequestCodes[1]);
diff --git a/tests/tests/net/src/android/net/wifi/cts/WifiEnterpriseConfigTest.java b/tests/tests/net/src/android/net/wifi/cts/WifiEnterpriseConfigTest.java
index 6e395aa..6c416ca 100644
--- a/tests/tests/net/src/android/net/wifi/cts/WifiEnterpriseConfigTest.java
+++ b/tests/tests/net/src/android/net/wifi/cts/WifiEnterpriseConfigTest.java
@@ -32,6 +32,10 @@
     private static final String IDENTITY = "identity";
     private static final String PASSWORD = "password";
     private static final String SUBJECT_MATCH = "subjectmatch";
+    private static final String ALT_SUBJECT_MATCH = "altsubjectmatch";
+    private static final String DOM_SUBJECT_MATCH = "domsubjectmatch";
+    private static final String PLMN = "plmn";
+    private static final String REALM = "realm";
     private static final String ANON_IDENTITY = "anonidentity";
     private static final int ENABLE_DELAY = 10000;
 
@@ -87,6 +91,15 @@
         config.setClientKeyEntry(null, null);
         config.setSubjectMatch(SUBJECT_MATCH);
         assertTrue(config.getSubjectMatch().equals(SUBJECT_MATCH));
+        // Hotspot 2.0 related attributes
+        config.setPlmn(PLMN);
+        assertTrue(config.getPlmn().equals(PLMN));
+        config.setPlmn(REALM);
+        assertTrue(config.getRealm().equals(REALM));
+        config.setAltSubjectMatch(ALT_SUBJECT_MATCH);
+        assertTrue(config.getAltSubjectMatch().equals(ALT_SUBJECT_MATCH));
+        config.setDomainSuffixMatch(DOM_SUBJECT_MATCH);
+        assertTrue(config.getDomainSuffixMatch().equals(DOM_SUBJECT_MATCH));
     }
 
     public void testAddEapNetwork() {
diff --git a/tests/tests/os/jni/Android.mk b/tests/tests/os/jni/Android.mk
index 24a0651..c125f5c 100644
--- a/tests/tests/os/jni/Android.mk
+++ b/tests/tests/os/jni/Android.mk
@@ -38,6 +38,12 @@
 	ARCH_SUPPORTS_SECCOMP = 1
 endif
 
+ifeq ($(strip $(TARGET_ARCH)),arm64)
+	ARCH_SUPPORTS_SECCOMP = 1
+	# Required for __NR_poll definition.
+	LOCAL_CFLAGS += -D__ARCH_WANT_SYSCALL_DEPRECATED
+endif
+
 ifeq ($(strip $(TARGET_ARCH)),x86)
 	ARCH_SUPPORTS_SECCOMP = 1
 endif
diff --git a/tests/tests/os/jni/seccomp_sample_program.cpp b/tests/tests/os/jni/seccomp_sample_program.cpp
index e291e8a..3c90196 100644
--- a/tests/tests/os/jni/seccomp_sample_program.cpp
+++ b/tests/tests/os/jni/seccomp_sample_program.cpp
@@ -355,8 +355,6 @@
   {0x6, 0, 0, 0x30001},
 };
 #elif defined(__aarch64__)
-// Note: aarch64 is not required to support seccomp-bpf yet, but some Nexus
-// devices do support it. For completeness, this test BPF program is provided.
 struct sock_filter kTestSeccompFilter[] = {
   {0x20, 0, 0, 0x4},
   {0x15, 1, 0, 0xc00000b7},
diff --git a/tests/tests/os/src/android/os/cts/SeccompTest.java b/tests/tests/os/src/android/os/cts/SeccompTest.java
index 4c2f78f..0340580 100644
--- a/tests/tests/os/src/android/os/cts/SeccompTest.java
+++ b/tests/tests/os/src/android/os/cts/SeccompTest.java
@@ -51,9 +51,6 @@
     }
 
     public void testSeccomp() {
-        if (CpuFeatures.isArm64Cpu() || CpuFeatures.isArm64CpuIn32BitMode()) {
-            return; // seccomp not yet supported on arm64
-        }
         if (OSFeatures.needsSeccompSupport()) {
             assertTrue("Please enable seccomp support "
                        + "in your kernel (CONFIG_SECCOMP_FILTER=y)",
diff --git a/tests/tests/permission2/src/android/permission2/cts/NoWriteSecureSettingsPermissionTest.java b/tests/tests/permission2/src/android/permission2/cts/NoWriteSecureSettingsPermissionTest.java
index eb476c7..b46c45d 100644
--- a/tests/tests/permission2/src/android/permission2/cts/NoWriteSecureSettingsPermissionTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/NoWriteSecureSettingsPermissionTest.java
@@ -16,6 +16,9 @@
 
 package android.permission2.cts;
 
+import android.Manifest;
+import android.content.ContentValues;
+import android.provider.Settings;
 import android.test.AndroidTestCase;
 
 /**
@@ -30,7 +33,15 @@
      *   {@link android.Manifest.permission#WRITE_SECURE_SETTINGS}
      */
     public void testWriteSecureSettings() {
-        assertWritingContentUriRequiresPermission(android.provider.Settings.Secure.CONTENT_URI,
-                android.Manifest.permission.WRITE_SECURE_SETTINGS);
+        try {
+            ContentValues values = new ContentValues();
+            values.put(Settings.Secure.NAME, Settings.Secure.ACCESSIBILITY_ENABLED);
+            values.put(Settings.Secure.VALUE, Boolean.TRUE);
+            getContext().getContentResolver().insert(Settings.Secure.CONTENT_URI, values);
+            fail("expected SecurityException requiring "
+                    + Manifest.permission.WRITE_SECURE_SETTINGS);
+        } catch (SecurityException expected) {
+           /* do nothing */
+        }
     }
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/BNNMTest.java b/tests/tests/renderscript/src/android/renderscript/cts/BNNMTest.java
index b36175c..1822f6a 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/BNNMTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/BNNMTest.java
@@ -338,4 +338,163 @@
         assertTrue(testWithTolerance(c_byte, c_byte_output));
 
     }
+
+    // This test multiplies matrices where the results are expected to fall
+    // slightly outside the 0 to 255 valid output range. This test ensures the
+    // values get clamped to that range, rather than wrapping around.
+    public void testClamping() {
+        // The A matrix is:
+        // |   1 |   4 |
+        // |   2 |   5 |
+        // |   3 |   6 |
+        byte[] a_data = unsignedToSignedByte(new int[] {
+                1, 2, 3,
+                4, 5, 6,
+            });
+        final int a_rows = 3;
+        final int a_cols = 2;
+        final int a_offset = 0;
+        // The B matrix is:
+        // |  -1 |  -2 |  -3 |  -4 |
+        // |  -5 |  -6 |  -7 |  -8 |
+        // |  99 | -40 | -11 | -15 |
+        byte[] b_data = unsignedToSignedByte(new int[] {
+                126, 122, 226,
+                125, 121, 87,
+                124, 120, 116,
+                123, 119, 112,
+            });
+        final int b_cols = 4;
+        final int b_offset = 127;
+        // EightBitGemm implements C = B.transposed() * A,
+        // so we expect to get these results:
+        // 1*-1 + 2*-5 + 3* 99 + 128 = 414 (clamped to 255)
+        // 1*-2 + 2*-6 + 3*-40 + 128 = -6 (clamped to 0)
+        // 1*-3 + 2*-7 + 3*-11 + 128 = 78
+        // 1*-4 + 2*-8 + 3*-15 + 128 = 63
+        // 4*-1 + 5*-5 + 6* 99 + 128 = 693 (clamped to 255)
+        // 4*-2 + 5*-6 + 6*-40 + 128 = -150 (clamped to 0)
+        // 4*-3 + 5*-7 + 6*-11 + 128 = 15
+        // 4*-4 + 5*-8 + 6*-15 + 128 = -18 (clamped to 0)
+        // | 255 | 255 |
+        // |   0 |   0 |
+        // |  78 |  15 |
+        // |  63 |   0 |
+        final int c_offset = 128;
+        final int c_shift = 21;
+        final int c_mult_int = (1 << c_shift);
+        byte[] expected_data = unsignedToSignedByte(new int[] {
+              255, 0, 78, 63,
+              255, 0, 15, 0,
+            });
+
+        final int m = a_cols;
+        final int n = b_cols;
+        final int k = a_rows;
+
+        byte[] c_byte_output = runBNNM(m, n, k, a_data, a_offset, b_data, b_offset,
+                                       c_offset, c_mult_int);
+        assertTrue(testWithTolerance(expected_data, c_byte_output));
+    }
+
+    // This tests the exception handling for a_offset and b_offset.
+    public void testExceptionHandling() {
+        // The A matrix is:
+        // |   1 |   4 |
+        // |   2 |   5 |
+        // |   3 |   6 |
+        byte[] a_data = unsignedToSignedByte(new int[] {
+                1, 2, 3,
+                4, 5, 6,
+            });
+        final int a_rows = 3;
+        final int a_cols = 2;
+        // The B matrix is:
+        // |  -1 |  -2 |  -3 |  -4 |
+        // |  -5 |  -6 |  -7 |  -8 |
+        // |  -9 | -10 | -11 | -12 |
+        byte[] b_data = unsignedToSignedByte(new int[] {
+                11, 7, 3,
+                10, 6, 2,
+                9, 5, 1,
+                8, 4, 0,
+            });
+        final int b_cols = 4;
+        // EightBitGemm implements C = B.transposed() * A,
+        // so we expect to get these results:
+        // 1*-1 + 2*-5 + 3*-9 + 128 = 90
+        // 1*-2 + 2*-6 + 3*-10 + 128 = 84
+        // 1*-3 + 2*-7 + 3*-11 + 128 = 78
+        // 1*-4 + 2*-8 + 3*-12 + 128 = 72
+        // 4*-1 + 5*-5 + 6*-9 + 128 = 45
+        // 4*-2 + 5*-6 + 6*-10 + 128 = 30
+        // 4*-3 + 5*-7 + 6*-11 + 128 = 15
+        // 4*-4 + 5*-8 + 6*-12 + 128 = 0
+        // | 90 |  45 |
+        // | 84 |  30 |
+        // | 78 | 15 |
+        // | 72 | 0 |
+        final int c_offset = 128;
+        final int c_shift = 21;
+        final int c_mult_int = (1 << c_shift);
+        byte[] expected_data = unsignedToSignedByte(new int[] {
+                90, 84, 78, 72,
+                45, 30, 15, 0,
+            });
+
+        final int m = a_cols;
+        final int n = b_cols;
+        final int k = a_rows;
+
+        Allocation A, B, C;
+        Type.Builder builder = new Type.Builder(mRS, Element.U8(mRS));
+        Type a_type = builder.setX(k).setY(m).create();
+        Type b_type = builder.setX(k).setY(n).create();
+        Type c_type = builder.setX(n).setY(m).create();
+
+        A = Allocation.createTyped(mRS, a_type);
+        B = Allocation.createTyped(mRS, b_type);
+        C = Allocation.createTyped(mRS, c_type);
+
+        A.copyFrom(a_data);
+        B.copyFrom(b_data);
+        // C doesn't matter, is output only
+
+        ScriptIntrinsicBLAS blas = ScriptIntrinsicBLAS.create(mRS);
+        try {
+            int a_offset = 0;
+            int b_offset = 12;
+            blas.BNNM(A, a_offset, B, b_offset, C, c_offset, c_mult_int);
+        } catch (RSRuntimeException e) {
+            fail("should NOT throw RSRuntimeException for valid offsets");
+        }
+        try {
+            int a_offset = -23;
+            int b_offset = 12;
+            blas.BNNM(A, a_offset, B, b_offset, C, c_offset, c_mult_int);
+            fail("should throw RSRuntimeException for invalid offsets: a_offset < 0");
+        } catch (RSRuntimeException e) {
+        }
+        try {
+            int a_offset = 888;
+            int b_offset = 12;
+            blas.BNNM(A, a_offset, B, b_offset, C, c_offset, c_mult_int);
+            fail("should throw RSRuntimeException for invalid offsets: a_offset > 255");
+        } catch (RSRuntimeException e) {
+        }
+        try {
+            int a_offset = 0;
+            int b_offset = -1;
+            blas.BNNM(A, a_offset, B, b_offset, C, c_offset, c_mult_int);
+            fail("should throw RSRuntimeException for invalid offsets: b_offset < 0");
+        } catch (RSRuntimeException e) {
+        }
+        try {
+            int a_offset = 0;
+            int b_offset = 256;
+            blas.BNNM(A, a_offset, B, b_offset, C, c_offset, c_mult_int);
+            fail("should throw RSRuntimeException for invalid offsets: b_offset > 255");
+        } catch (RSRuntimeException e) {
+        }
+    }
 }
diff --git a/tests/tests/text/src/android/text/format/cts/FormatterTest.java b/tests/tests/text/src/android/text/format/cts/FormatterTest.java
index bf4a684..9c3c45d 100644
--- a/tests/tests/text/src/android/text/format/cts/FormatterTest.java
+++ b/tests/tests/text/src/android/text/format/cts/FormatterTest.java
@@ -32,24 +32,24 @@
         BigDecimal bd = new BigDecimal((long) 1024, mc);
 
         // test different long values with various length
-        assertEquals("0.00B", Formatter.formatFileSize(mContext, 0));
+        assertEquals("0.00 B", Formatter.formatFileSize(mContext, 0));
 
-        assertEquals("899B", Formatter.formatFileSize(mContext, 899));
+        assertEquals("899 B", Formatter.formatFileSize(mContext, 899));
 
-        assertEquals("1.00KB", Formatter.formatFileSize(mContext, bd.pow(1).longValue()));
+        assertEquals("1.00 KB", Formatter.formatFileSize(mContext, bd.pow(1).longValue()));
 
-        assertEquals("1.00MB", Formatter.formatFileSize(mContext, bd.pow(2).longValue()));
+        assertEquals("1.00 MB", Formatter.formatFileSize(mContext, bd.pow(2).longValue()));
 
-        assertEquals("1.00GB", Formatter.formatFileSize(mContext, bd.pow(3).longValue()));
+        assertEquals("1.00 GB", Formatter.formatFileSize(mContext, bd.pow(3).longValue()));
 
-        assertEquals("1.00TB", Formatter.formatFileSize(mContext, bd.pow(4).longValue()));
+        assertEquals("1.00 TB", Formatter.formatFileSize(mContext, bd.pow(4).longValue()));
 
-        assertEquals("1.00PB", Formatter.formatFileSize(mContext, bd.pow(5).longValue()));
+        assertEquals("1.00 PB", Formatter.formatFileSize(mContext, bd.pow(5).longValue()));
 
-        assertEquals("1024PB", Formatter.formatFileSize(mContext, bd.pow(6).longValue()));
+        assertEquals("1024 PB", Formatter.formatFileSize(mContext, bd.pow(6).longValue()));
 
         // test Negative value
-        assertEquals("-1.00B", Formatter.formatFileSize(mContext, -1));
+        assertEquals("-1.00 B", Formatter.formatFileSize(mContext, -1));
     }
 
     public void testFormatIpAddress() {
diff --git a/tests/tests/view/src/android/view/cts/ActionModeTest.java b/tests/tests/view/src/android/view/cts/ActionModeTest.java
index 6898d3c..534db311 100644
--- a/tests/tests/view/src/android/view/cts/ActionModeTest.java
+++ b/tests/tests/view/src/android/view/cts/ActionModeTest.java
@@ -67,6 +67,57 @@
         assertTrue(callback.mIsOnGetContentRectCalled);
     }
 
+    public void testSetAndGetTitleOptionalHint() {
+        MockActionMode actionMode = new MockActionMode();
+
+        // Check default value.
+        assertFalse(actionMode.getTitleOptionalHint());
+        // Test set and get.
+        actionMode.setTitleOptionalHint(true);
+        assertTrue(actionMode.getTitleOptionalHint());
+        actionMode.setTitleOptionalHint(false);
+        assertFalse(actionMode.getTitleOptionalHint());
+    }
+
+    public void testSetAndGetTag() {
+        MockActionMode actionMode = new MockActionMode();
+        Object tag = new Object();
+
+        // Check default value.
+        assertNull(actionMode.getTag());
+
+        actionMode.setTag(tag);
+        assertSame(tag, actionMode.getTag());
+    }
+
+    public void testIsTitleOptional() {
+        MockActionMode actionMode = new MockActionMode();
+
+        // Check default value.
+        assertFalse(actionMode.isTitleOptional());
+    }
+
+    public void testIsUiFocusable() {
+        MockActionMode actionMode = new MockActionMode();
+
+        // Check default value.
+        assertTrue(actionMode.isUiFocusable());
+    }
+
+    public void testHide() {
+        MockActionMode actionMode = new MockActionMode();
+
+        actionMode.hide(0);
+        actionMode.hide(ActionMode.DEFAULT_HIDE_DURATION);
+    }
+
+    public void testOnWindowFocusChanged() {
+        MockActionMode actionMode = new MockActionMode();
+
+        actionMode.onWindowFocusChanged(true);
+        actionMode.onWindowFocusChanged(false);
+    }
+
     private static class MockActionModeCallback2 extends ActionMode.Callback2 {
         boolean mIsOnGetContentRectCalled = false;
 
diff --git a/tests/tests/view/src/android/view/cts/MockTextView.java b/tests/tests/view/src/android/view/cts/MockTextView.java
index dc9420d..0c73614 100644
--- a/tests/tests/view/src/android/view/cts/MockTextView.java
+++ b/tests/tests/view/src/android/view/cts/MockTextView.java
@@ -179,19 +179,19 @@
     }
 
     public int getFrameLeft() {
-        return mLeft;
+        return getLeft();
     }
 
     public int getFrameTop() {
-        return mTop;
+        return getTop();
     }
 
     public int getFrameRight() {
-        return mRight;
+        return getRight();
     }
 
     public int getFrameBottom() {
-        return mBottom;
+        return getBottom();
     }
 
     public int getBottomPaddingOffset() {
diff --git a/tests/tests/view/src/android/view/cts/MockView.java b/tests/tests/view/src/android/view/cts/MockView.java
index 9093089..579d4fb 100644
--- a/tests/tests/view/src/android/view/cts/MockView.java
+++ b/tests/tests/view/src/android/view/cts/MockView.java
@@ -29,6 +29,7 @@
 import android.view.KeyEvent;
 import android.view.MotionEvent;
 import android.view.View;
+import android.view.ViewGroup;
 import android.view.ViewParent;
 import android.view.ContextMenu.ContextMenuInfo;
 
@@ -104,8 +105,8 @@
         return mCalledInvalidate;
     }
 
-    public void setParent(ViewParent parent) {
-        mParent = parent;
+    public void setParent(ViewGroup parent) {
+        parent.addView(this);
     }
 
     public static int[] getEnabledStateSet() {
@@ -162,16 +163,6 @@
     }
 
     @Override
-    protected void initializeFadingEdge(TypedArray a) {
-        super.initializeFadingEdge(a);
-    }
-
-    @Override
-    protected void initializeScrollbars(TypedArray a) {
-        super.initializeScrollbars(a);
-    }
-
-    @Override
     protected int getHorizontalScrollbarHeight() {
         return super.getHorizontalScrollbarHeight();
     }
diff --git a/tests/tests/view/src/android/view/cts/ViewGroupTest.java b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
index b98ac4e..7fc5579 100644
--- a/tests/tests/view/src/android/view/cts/ViewGroupTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
@@ -458,7 +458,7 @@
         MockTextView textView = new MockTextView(mContext);
         vg.addView(textView);
         vg.requestChildFocus(textView, null);
-        textView.setFrame(1, 1, 100, 100);
+        textView.layout(1, 1, 100, 100);
 
         assertTrue(vg.dispatchKeyEvent(event));
     }
@@ -529,7 +529,7 @@
         d.getMetrics(metrics);
         int screenWidth = metrics.widthPixels;
         int screenHeight = metrics.heightPixels;
-        vg.setFrame(0, 0, screenWidth, screenHeight);
+        vg.layout(0, 0, screenWidth, screenHeight);
         vg.setLayoutParams(new ViewGroup.LayoutParams(screenWidth, screenHeight));
 
         MockTextView textView = new MockTextView(mContext);
@@ -554,7 +554,7 @@
         assertFalse(vg.dispatchTouchEvent(me));
         assertNull(mMotionEvent);
 
-        textView.setFrame(0, 0, screenWidth, screenHeight);
+        textView.layout(0, 0, screenWidth, screenHeight);
         assertTrue(vg.dispatchTouchEvent(me));
         assertSame(me, mMotionEvent);
     }
@@ -568,7 +568,7 @@
 
         MockTextView textView = new MockTextView(mContext);
         vg.addView(textView);
-        textView.setFrame(1, 1, 100, 100);
+        textView.layout(1, 1, 100, 100);
         vg.requestChildFocus(textView, null);
         assertTrue(vg.dispatchTrackballEvent(me));
     }
@@ -579,7 +579,7 @@
         assertFalse(vg.dispatchUnhandledMove(textView, View.FOCUS_DOWN));
 
         vg.addView(textView);
-        textView.setFrame(1, 1, 100, 100);
+        textView.layout(1, 1, 100, 100);
         vg.requestChildFocus(textView, null);
         assertTrue(vg.dispatchUnhandledMove(textView, View.FOCUS_DOWN));
     }
@@ -769,13 +769,13 @@
         MockViewGroup vg = new MockViewGroup(mContext);
         MockTextView textView = new MockTextView(mContext);
 
-        textView.setFrame(1, 1, 100, 100);
+        textView.layout(1, 1, 100, 100);
         Rect rect = new Rect(1, 1, 50, 50);
         Point p = new Point();
         assertFalse(vg.getChildVisibleRect(textView, rect, p));
 
-        textView.setFrame(0, 0, 0, 0);
-        vg.setFrame(20, 20, 60, 60);
+        textView.layout(0, 0, 0, 0);
+        vg.layout(20, 20, 60, 60);
         rect = new Rect(10, 10, 40, 40);
         p = new Point();
         assertTrue(vg.getChildVisibleRect(textView, rect, p));
@@ -998,7 +998,7 @@
             // expected
         }
         vg.addView(textView);
-        textView.setFrame(1, 2, 3, 4);
+        textView.layout(1, 2, 3, 4);
         Rect rect = new Rect();
         vg.offsetDescendantRectToMyCoords(textView, rect);
         assertEquals(2, rect.bottom);
@@ -1009,7 +1009,7 @@
 
     public void testOffsetRectIntoDescendantCoords() {
         MockViewGroup vg = new MockViewGroup(mContext);
-        vg.setFrame(10, 20, 30, 40);
+        vg.layout(10, 20, 30, 40);
         MockTextView textView = new MockTextView(mContext);
 
         try {
@@ -1019,7 +1019,7 @@
         } catch (RuntimeException e) {
             // expected
         }
-        textView.setFrame(1, 2, 3, 4);
+        textView.layout(1, 2, 3, 4);
         vg.addView(textView);
 
         Rect rect = new Rect(5, 6, 7, 8);
@@ -1376,8 +1376,8 @@
 
         MockViewGroup vg = new MockViewGroup(mContext);
         MockTextView textView = new MockTextView(mContext);
-        textView.setFrame(1, 2, 30, 40);
-        vg.setFrame(1, 1, 100, 200);
+        textView.layout(1, 2, 30, 40);
+        vg.layout(1, 1, 100, 200);
         vg.setClipChildren(true);
 
         MockCanvas canvas = new MockCanvas(bitmap);
@@ -1434,7 +1434,7 @@
         final int frameRight = 100;
         final int frameBottom = 200;
         MockViewGroup vg = new MockViewGroup(mContext);
-        vg.setFrame(frameLeft, frameTop, frameRight, frameBottom);
+        vg.layout(frameLeft, frameTop, frameRight, frameBottom);
 
         vg.setClipToPadding(true);
         MockCanvas canvas = new MockCanvas();
@@ -1911,11 +1911,6 @@
         }
 
         @Override
-        public boolean setFrame(int l, int t, int r, int b) {
-            return super.setFrame(l, t, r, b);
-        }
-
-        @Override
         public void dispatchRestoreInstanceState(
                 SparseArray<Parcelable> container) {
             isDispatchRestoreInstanceStateCalled = true;
@@ -1945,11 +1940,6 @@
         }
 
         @Override
-        public boolean gatherTransparentRegion(Region region) {
-            return false;
-        }
-
-        @Override
         public boolean dispatchTouchEvent(MotionEvent event) {
             super.dispatchTouchEvent(event);
             return true;
@@ -2162,21 +2152,6 @@
         }
 
         @Override
-        public boolean setFrame(int left, int top, int right, int bottom) {
-            return super.setFrame(left, top, right, bottom);
-        }
-
-        @Override
-        public boolean isChildrenDrawnWithCacheEnabled() {
-            return super.isChildrenDrawnWithCacheEnabled();
-        }
-
-        @Override
-        public void setChildrenDrawnWithCacheEnabled(boolean enabled) {
-            super.setChildrenDrawnWithCacheEnabled(enabled);
-        }
-
-        @Override
         public void measureChild(View child, int parentWidthMeasureSpec,
                 int parentHeightMeasureSpec) {
             measureChildCalledTime++;
@@ -2327,6 +2302,21 @@
             super.resetResolvedDrawables();
             resetResolvedDrawablesCount++;
         }
+
+        @Override
+        public boolean setFrame(int left, int top, int right, int bottom) {
+            return super.setFrame(left, top, right, bottom);
+        }
+
+        @Override
+        public void setChildrenDrawnWithCacheEnabled(boolean enabled) {
+            super.setChildrenDrawnWithCacheEnabled(enabled);
+        }
+
+        @Override
+        public boolean isChildrenDrawnWithCacheEnabled() {
+            return super.isChildrenDrawnWithCacheEnabled();
+        }
     }
 
     static class MockView2 extends View {
diff --git a/tests/tests/view/src/android/view/cts/ViewGroup_MarginLayoutParamsTest.java b/tests/tests/view/src/android/view/cts/ViewGroup_MarginLayoutParamsTest.java
index e837b23..e53cba2 100644
--- a/tests/tests/view/src/android/view/cts/ViewGroup_MarginLayoutParamsTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewGroup_MarginLayoutParamsTest.java
@@ -89,7 +89,9 @@
     public void testSetMarginsRelative() {
         // create a new MarginLayoutParams instance
         mMarginLayoutParams = new ViewGroup.MarginLayoutParams(320, 480);
-        mMarginLayoutParams.setMarginsRelative(20, 30, 120, 140);
+        mMarginLayoutParams.setMargins(0, 30, 0, 140);
+        mMarginLayoutParams.setMarginStart(20);
+        mMarginLayoutParams.setMarginEnd(120);
         assertEquals(20, mMarginLayoutParams.getMarginStart());
         assertEquals(30, mMarginLayoutParams.topMargin);
         assertEquals(120, mMarginLayoutParams.getMarginEnd());
@@ -120,7 +122,9 @@
         assertEquals(false, mMarginLayoutParams.isMarginRelative());
 
         // LTR / relative margin case
-        mMarginLayoutParams.setMarginsRelative(20, 30, 120, 140);
+        mMarginLayoutParams.setMargins(0, 30, 0, 140);
+        mMarginLayoutParams.setMarginStart(20);
+        mMarginLayoutParams.setMarginEnd(120);
         vg.setLayoutParams(mMarginLayoutParams);
 
         assertEquals(20, mMarginLayoutParams.getMarginStart());
@@ -151,7 +155,9 @@
         assertEquals(false, mMarginLayoutParams.isMarginRelative());
 
         // RTL / relative margin case
-        mMarginLayoutParams.setMarginsRelative(20, 30, 120, 140);
+        mMarginLayoutParams.setMargins(0, 30, 0, 140);
+        mMarginLayoutParams.setMarginStart(20);
+        mMarginLayoutParams.setMarginEnd(120);
         vg.setLayoutParams(mMarginLayoutParams);
 
         assertEquals(20, mMarginLayoutParams.getMarginStart());
diff --git a/tests/tests/view/src/android/view/cts/ViewTest.java b/tests/tests/view/src/android/view/cts/ViewTest.java
index ea289ce..e95236d 100644
--- a/tests/tests/view/src/android/view/cts/ViewTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewTest.java
@@ -16,28 +16,26 @@
 
 package android.view.cts;
 
-import android.content.res.ColorStateList;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.ColorFilter;
-import android.graphics.PorterDuff;
-
-import android.os.Bundle;
 import com.android.cts.view.R;
 import com.android.internal.view.menu.ContextMenuBuilder;
-import com.google.android.collect.Lists;
 
 import android.content.Context;
+import android.content.res.ColorStateList;
 import android.content.res.Resources;
 import android.content.res.XmlResourceParser;
 import android.cts.util.PollingCheck;
 import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.ColorFilter;
 import android.graphics.Point;
+import android.graphics.PorterDuff;
 import android.graphics.Rect;
 import android.graphics.drawable.BitmapDrawable;
 import android.graphics.drawable.ColorDrawable;
 import android.graphics.drawable.Drawable;
 import android.graphics.drawable.StateListDrawable;
+import android.os.Bundle;
 import android.os.Parcelable;
 import android.os.SystemClock;
 import android.os.Vibrator;
@@ -64,6 +62,7 @@
 import android.view.View;
 import android.view.View.BaseSavedState;
 import android.view.View.OnClickListener;
+import android.view.View.OnContextClickListener;
 import android.view.View.OnCreateContextMenuListener;
 import android.view.View.OnFocusChangeListener;
 import android.view.View.OnKeyListener;
@@ -425,7 +424,9 @@
         assertTrue(view.isLayoutRequested());
 
         view.setParent(mMockParent);
-        assertFalse(mMockParent.hasRequestLayout());
+        assertTrue(mMockParent.hasRequestLayout());
+
+        mMockParent.reset();
         view.requestLayout();
         assertTrue(view.isLayoutRequested());
         assertTrue(mMockParent.hasRequestLayout());
@@ -883,6 +884,18 @@
         assertFalse(view.isClickable());
     }
 
+    public void testAccessContextClickable() {
+        View view = new View(mActivity);
+
+        assertFalse(view.isContextClickable());
+
+        view.setContextClickable(true);
+        assertTrue(view.isContextClickable());
+
+        view.setContextClickable(false);
+        assertFalse(view.isContextClickable());
+    }
+
     public void testGetContextMenuInfo() {
         MockView view = new MockView(mActivity);
 
@@ -1131,8 +1144,8 @@
         mockView2.setParent(mMockParent);
 
         mMockParent.dispatchSetSelected(true);
-        assertFalse(mockView1.isSelected());
-        assertFalse(mockView2.isSelected());
+        assertTrue(mockView1.isSelected());
+        assertTrue(mockView2.isSelected());
 
         mMockParent.dispatchSetSelected(false);
         assertFalse(mockView1.isSelected());
@@ -1155,8 +1168,8 @@
         mockView2.setParent(mMockParent);
 
         mMockParent.dispatchSetPressed(true);
-        assertFalse(mockView1.isPressed());
-        assertFalse(mockView2.isPressed());
+        assertTrue(mockView1.isPressed());
+        assertTrue(mockView2.isPressed());
 
         mMockParent.dispatchSetPressed(false);
         assertFalse(mockView1.isPressed());
@@ -1317,6 +1330,30 @@
         assertTrue(view.isLongClickable());
     }
 
+    public void testPerformContextClick() {
+        MockView view = new MockView(mActivity);
+        view.setParent(mMockParent);
+        OnContextClickListenerImpl listener = new OnContextClickListenerImpl();
+
+        view.setOnContextClickListener(listener);
+        assertFalse(listener.hasOnContextClick());
+
+        assertTrue(view.performContextClick());
+        assertTrue(listener.hasOnContextClick());
+    }
+
+    public void testSetOnContextClickListener() {
+        MockView view = new MockView(mActivity);
+        view.setParent(mMockParent);
+
+        assertFalse(view.performContextClick());
+        assertFalse(view.isContextClickable());
+
+        view.setOnContextClickListener(new OnContextClickListenerImpl());
+        assertTrue(view.performContextClick());
+        assertTrue(view.isContextClickable());
+    }
+
     public void testAccessOnFocusChangeListener() {
         View view = new View(mActivity);
         OnFocusChangeListener listener = new OnFocusChangeListenerImpl();
@@ -3017,16 +3054,13 @@
 
     @UiThreadTest
     public void testScrollbarStyle() {
-        MockView view = (MockView) mActivity.findViewById(R.id.mock_view);
+        MockView view = (MockView) mActivity.findViewById(R.id.scroll_view);
         Bitmap bitmap = Bitmap.createBitmap(200, 300, Bitmap.Config.RGB_565);
         BitmapDrawable d = new BitmapDrawable(bitmap);
         view.setBackgroundDrawable(d);
         view.setHorizontalFadingEdgeEnabled(true);
         view.setVerticalFadingEdgeEnabled(true);
 
-        view.setHorizontalScrollBarEnabled(true);
-        view.setVerticalScrollBarEnabled(true);
-        view.initializeScrollbars(mActivity.obtainStyledAttributes(android.R.styleable.View));
         assertTrue(view.isHorizontalScrollBarEnabled());
         assertTrue(view.isVerticalScrollBarEnabled());
         int verticalScrollBarWidth = view.getVerticalScrollbarWidth();
@@ -3156,7 +3190,10 @@
 
     public void testOnStartAndFinishTemporaryDetach() throws Throwable {
         final MockListView listView = new MockListView(mActivity);
-        List<String> items = Lists.newArrayList("1", "2", "3");
+        List<String> items = new ArrayList<>();
+        items.add("1");
+        items.add("2");
+        items.add("3");
         final Adapter<String> adapter = new Adapter<String>(mActivity, 0, items);
 
         runTestOnUiThread(new Runnable() {
@@ -3638,7 +3675,7 @@
         }
     }
 
-    private final static class MockViewParent extends View implements ViewParent {
+    private final static class MockViewParent extends ViewGroup {
         private boolean mHasClearChildFocus = false;
         private boolean mHasRequestLayout = false;
         private boolean mHasCreateContextMenu = false;
@@ -3678,12 +3715,12 @@
         }
 
         @Override
-        protected void dispatchSetPressed(boolean pressed) {
+        public void dispatchSetPressed(boolean pressed) {
             super.dispatchSetPressed(pressed);
         }
 
         @Override
-        protected void dispatchSetSelected(boolean selected) {
+        public void dispatchSetSelected(boolean selected) {
             super.dispatchSetSelected(selected);
         }
 
@@ -3716,23 +3753,15 @@
             return false;
         }
 
+        @Override
+        protected void onLayout(boolean changed, int l, int t, int r, int b) {
+
+        }
+
         public boolean hasGetChildVisibleRect() {
             return mHasGetChildVisibleRect;
         }
 
-        public void invalidateChild(View child, Rect r) {
-            mTempRect = new Rect(r);
-            mHasInvalidateChild = true;
-        }
-
-        public Rect getTempRect() {
-            return mTempRect;
-        }
-
-        public boolean hasInvalidateChild() {
-            return mHasInvalidateChild;
-        }
-
         public ViewParent invalidateChildInParent(int[] location, Rect r) {
             return null;
         }
@@ -3753,6 +3782,7 @@
 
         }
 
+        @Override
         public void requestLayout() {
             mHasRequestLayout = true;
         }
@@ -3955,6 +3985,23 @@
         }
     }
 
+    private static final class OnContextClickListenerImpl implements OnContextClickListener {
+        private boolean mHasContextClick = false;
+
+        public boolean hasOnContextClick() {
+            return mHasContextClick;
+        }
+
+        public void reset() {
+            mHasContextClick = false;
+        }
+
+        public boolean onContextClick(View v) {
+            mHasContextClick = true;
+            return true;
+        }
+    }
+
     private static final class OnFocusChangeListenerImpl implements OnFocusChangeListener {
         private boolean mHasOnFocusChange = false;
 
diff --git a/tests/tests/view/src/android/view/cts/ViewTreeObserverTest.java b/tests/tests/view/src/android/view/cts/ViewTreeObserverTest.java
index 1b21dac..7071808 100644
--- a/tests/tests/view/src/android/view/cts/ViewTreeObserverTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewTreeObserverTest.java
@@ -25,8 +25,6 @@
 import android.test.TouchUtils;
 import android.view.View;
 import android.view.ViewTreeObserver;
-import android.view.ViewTreeObserver.InternalInsetsInfo;
-import android.view.ViewTreeObserver.OnComputeInternalInsetsListener;
 import android.view.ViewTreeObserver.OnGlobalFocusChangeListener;
 import android.view.ViewTreeObserver.OnGlobalLayoutListener;
 import android.view.ViewTreeObserver.OnPreDrawListener;
@@ -155,22 +153,6 @@
         }.run();
     }
 
-    public void testAddOnComputeInternalInsetsListener() {
-        final View view1 = mActivity.findViewById(R.id.view1);
-        mViewTreeObserver = view1.getViewTreeObserver();
-
-        MockOnComputeInternalInsetsListener listener = new MockOnComputeInternalInsetsListener();
-        mViewTreeObserver.addOnComputeInternalInsetsListener(listener);
-    }
-
-    public void testRemoveOnComputeInternalInsetsListener() {
-        final View view1 = mActivity.findViewById(R.id.view1);
-        mViewTreeObserver = view1.getViewTreeObserver();
-
-        MockOnComputeInternalInsetsListener listener = new MockOnComputeInternalInsetsListener();
-        mViewTreeObserver.removeOnComputeInternalInsetsListener(listener);
-    }
-
     public void testDispatchOnGlobalLayout() {
         final LinearLayout layout = (LinearLayout) mActivity.findViewById(R.id.linearlayout);
         mViewTreeObserver = layout.getViewTreeObserver();
@@ -434,12 +416,6 @@
         }
     }
 
-    private class MockOnComputeInternalInsetsListener implements OnComputeInternalInsetsListener {
-        @Override
-        public void onComputeInternalInsets(InternalInsetsInfo inoutInfo) {
-        }
-    }
-
     private static class MockOnScrollChangedListener implements OnScrollChangedListener {
         private boolean mCalledOnScrollChanged = false;
 
diff --git a/tests/tests/view/src/android/view/cts/util/XmlUtils.java b/tests/tests/view/src/android/view/cts/util/XmlUtils.java
index 4a13d54..f1df4ff 100644
--- a/tests/tests/view/src/android/view/cts/util/XmlUtils.java
+++ b/tests/tests/view/src/android/view/cts/util/XmlUtils.java
@@ -16,8 +16,6 @@
 
 package android.view.cts.util;
 
-import com.android.internal.util.FastXmlSerializer;
-
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 import org.xmlpull.v1.XmlSerializer;
@@ -44,7 +42,6 @@
 import java.util.Map;
 import java.util.Set;
 
-/** {@hide} */
 public class XmlUtils {
 
     public static void skipCurrentTag(XmlPullParser parser)
@@ -171,28 +168,6 @@
     }
 
     /**
-     * Flatten a Map into an output stream as XML.  The map can later be
-     * read back with readMapXml().
-     *
-     * @param val The map to be flattened.
-     * @param out Where to write the XML data.
-     *
-     * @see #writeMapXml(Map, String, XmlSerializer)
-     * @see #writeListXml
-     * @see #writeValueXml
-     * @see #readMapXml
-     */
-    public static final void writeMapXml(Map val, OutputStream out)
-            throws XmlPullParserException, IOException {
-        XmlSerializer serializer = new FastXmlSerializer();
-        serializer.setOutput(out, StandardCharsets.UTF_8.name());
-        serializer.startDocument(null, true);
-        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
-        writeMapXml(val, null, serializer);
-        serializer.endDocument();
-    }
-
-    /**
      * Flatten a List into an output stream as XML.  The list can later be
      * read back with readListXml().
      *
@@ -224,7 +199,6 @@
      *             none.
      * @param out XmlSerializer to write the map into.
      *
-     * @see #writeMapXml(Map, OutputStream)
      * @see #writeListXml
      * @see #writeValueXml
      * @see #readMapXml
@@ -244,7 +218,6 @@
      * @param out XmlSerializer to write the map into.
      * @param callback Method to call when an Object type is not recognized.
      *
-     * @see #writeMapXml(Map, OutputStream)
      * @see #writeListXml
      * @see #writeValueXml
      * @see #readMapXml
@@ -278,7 +251,6 @@
      * @param val The map to be flattened.
      * @param out XmlSerializer to write the map into.
      *
-     * @see #writeMapXml(Map, OutputStream)
      * @see #writeListXml
      * @see #writeValueXml
      * @see #readMapXml
diff --git a/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java b/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java
index 7fe016f..fc5eb08 100644
--- a/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java
@@ -21,7 +21,6 @@
 import android.content.Context;
 import android.content.res.Resources.Theme;
 import android.cts.util.PollingCheck;
-import android.cts.util.ReadElf;
 import android.cts.util.TestThread;
 import android.database.ContentObserver;
 import android.database.Cursor;
@@ -40,7 +39,6 @@
 
 import com.android.cts.widget.R;
 
-
 /**
  * Test {@link CursorAdapter}.
  */
@@ -347,14 +345,23 @@
     }
 
     private final class MockCursorAdapter extends CursorAdapter {
+        private final Context mContext;
+        private final boolean mAutoRequery;
+
         private boolean mContentChanged = false;
 
         public MockCursorAdapter(Context context, Cursor c) {
             super(context, c);
+
+            mContext = context;
+            mAutoRequery = false;
         }
 
         public MockCursorAdapter(Context context, Cursor c, boolean autoRequery) {
             super(context, c, autoRequery);
+
+            mContext = context;
+            mAutoRequery = autoRequery;
         }
 
         public Context getContext() {
diff --git a/tests/tests/widget/src/android/widget/cts/GalleryTest.java b/tests/tests/widget/src/android/widget/cts/GalleryTest.java
index 2813965..a3ac16c 100644
--- a/tests/tests/widget/src/android/widget/cts/GalleryTest.java
+++ b/tests/tests/widget/src/android/widget/cts/GalleryTest.java
@@ -17,16 +17,17 @@
 package android.widget.cts;
 
 import com.android.cts.widget.R;
-import com.android.internal.view.menu.ContextMenuBuilder;
-
 
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 
 import android.app.Activity;
 import android.app.Instrumentation;
+import android.content.ComponentName;
 import android.content.Context;
+import android.content.Intent;
 import android.cts.util.WidgetTestUtils;
+import android.graphics.drawable.Drawable;
 import android.os.SystemClock;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.UiThreadTest;
@@ -36,7 +37,8 @@
 import android.view.ContextMenu;
 import android.view.Gravity;
 import android.view.KeyEvent;
-import android.view.MotionEvent;
+import android.view.MenuItem;
+import android.view.SubMenu;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.ContextMenu.ContextMenuInfo;
@@ -311,11 +313,165 @@
         MyGallery gallery = new MyGallery(mContext);
         gallery.setOnCreateContextMenuListener(listener);
         assertFalse(listener.hasCreatedContextMenu());
-        gallery.createContextMenu(new ContextMenuBuilder(mContext));
+        gallery.createContextMenu(new MockContextMenu());
         assertTrue(listener.hasCreatedContextMenu());
         assertSame(gallery.getContextMenuInfo(), listener.getContextMenuInfo());
     }
 
+    private static class MockContextMenu implements ContextMenu {
+        @Override
+        public ContextMenu setHeaderTitle(int titleRes) {
+            return null;
+        }
+
+        @Override
+        public ContextMenu setHeaderTitle(CharSequence title) {
+            return null;
+        }
+
+        @Override
+        public ContextMenu setHeaderIcon(int iconRes) {
+            return null;
+        }
+
+        @Override
+        public ContextMenu setHeaderIcon(Drawable icon) {
+            return null;
+        }
+
+        @Override
+        public ContextMenu setHeaderView(View view) {
+            return null;
+        }
+
+        @Override
+        public void clearHeader() {
+
+        }
+
+        @Override
+        public MenuItem add(CharSequence title) {
+            return null;
+        }
+
+        @Override
+        public MenuItem add(int titleRes) {
+            return null;
+        }
+
+        @Override
+        public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
+            return null;
+        }
+
+        @Override
+        public MenuItem add(int groupId, int itemId, int order, int titleRes) {
+            return null;
+        }
+
+        @Override
+        public SubMenu addSubMenu(CharSequence title) {
+            return null;
+        }
+
+        @Override
+        public SubMenu addSubMenu(int titleRes) {
+            return null;
+        }
+
+        @Override
+        public SubMenu addSubMenu(int groupId, int itemId, int order,
+                CharSequence title) {
+            return null;
+        }
+
+        @Override
+        public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
+            return null;
+        }
+
+        @Override
+        public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller,
+                Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
+            return 0;
+        }
+
+        @Override
+        public void removeItem(int id) {
+
+        }
+
+        @Override
+        public void removeGroup(int groupId) {
+
+        }
+
+        @Override
+        public void clear() {
+
+        }
+
+        @Override
+        public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
+
+        }
+
+        @Override
+        public void setGroupVisible(int group, boolean visible) {
+
+        }
+
+        @Override
+        public void setGroupEnabled(int group, boolean enabled) {
+
+        }
+
+        @Override
+        public boolean hasVisibleItems() {
+            return false;
+        }
+
+        @Override
+        public MenuItem findItem(int id) {
+            return null;
+        }
+
+        @Override
+        public int size() {
+            return 0;
+        }
+
+        @Override
+        public MenuItem getItem(int index) {
+            return null;
+        }
+
+        @Override
+        public void close() {
+
+        }
+
+        @Override
+        public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
+            return false;
+        }
+
+        @Override
+        public boolean isShortcutKey(int keyCode, KeyEvent event) {
+            return false;
+        }
+
+        @Override
+        public boolean performIdentifierAction(int id, int flags) {
+            return false;
+        }
+
+        @Override
+        public void setQwertyMode(boolean isQwerty) {
+
+        }
+    }
+
     private static class MockOnCreateContextMenuListener implements OnCreateContextMenuListener {
         private boolean hasCreatedContextMenu;
         private ContextMenuInfo mContextMenuInfo;
diff --git a/tests/tests/widget/src/android/widget/cts/MyGallery.java b/tests/tests/widget/src/android/widget/cts/MyGallery.java
index 91665ee..27b5d45 100644
--- a/tests/tests/widget/src/android/widget/cts/MyGallery.java
+++ b/tests/tests/widget/src/android/widget/cts/MyGallery.java
@@ -49,10 +49,6 @@
         return super.getChildStaticTransformation(child, t);
     }
 
-    protected void setParent(ViewParent v) {
-        mParent = v;
-    }
-
     @Override
     protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
         return super.checkLayoutParams(p);
diff --git a/tests/tests/widget/src/android/widget/cts/QuickContactBadgeTest.java b/tests/tests/widget/src/android/widget/cts/QuickContactBadgeTest.java
index cfd61a2..25d8e5e 100644
--- a/tests/tests/widget/src/android/widget/cts/QuickContactBadgeTest.java
+++ b/tests/tests/widget/src/android/widget/cts/QuickContactBadgeTest.java
@@ -21,8 +21,6 @@
 import android.content.ContextWrapper;
 import android.content.Intent;
 import android.net.Uri;
-import android.os.Bundle;
-import android.os.UserHandle;
 import android.provider.ContactsContract;
 import android.provider.ContactsContract.Contacts;
 import android.test.InstrumentationTestCase;
@@ -39,22 +37,12 @@
         final String plainMimeType = "text/plain";
         final Uri nonExistentContactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, 0);
         final CountDownLatch latch = new CountDownLatch(1);
-        Context context = new ContextWrapper(getInstrumentation().getContext()) {
+        final Context context = new ContextWrapper(getInstrumentation().getContext()) {
             @Override
             public void startActivity(Intent intent) {
                 testCallback(intent);
             }
 
-            @Override
-            public void startActivityAsUser(Intent intent, UserHandle user) {
-                testCallback(intent);
-            }
-
-            @Override
-            public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
-                testCallback(intent);
-            }
-
             private void testCallback(Intent intent) {
                 assertEquals(plainMimeType, intent.getStringExtra(
                         ContactsContract.QuickContact.EXTRA_PRIORITIZED_MIMETYPE));
diff --git a/tests/tests/widget/src/android/widget/cts/ResourceCursorAdapterTest.java b/tests/tests/widget/src/android/widget/cts/ResourceCursorAdapterTest.java
index 28bfd06..52d699b 100644
--- a/tests/tests/widget/src/android/widget/cts/ResourceCursorAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ResourceCursorAdapterTest.java
@@ -170,13 +170,19 @@
     }
 
     private static class MockResourceCursorAdapter extends ResourceCursorAdapter {
+        private final boolean mAutoRequery;
+
         public MockResourceCursorAdapter(Context context, int layout, Cursor c) {
             super(context, layout, c);
+
+            mAutoRequery = false;
         }
 
         public MockResourceCursorAdapter(Context context, int layout,
                 Cursor c, boolean autoRequery) {
             super(context, layout, c, autoRequery);
+
+            mAutoRequery = autoRequery;
         }
 
         @Override
diff --git a/tests/tests/widget/src/android/widget/cts/TableLayoutTest.java b/tests/tests/widget/src/android/widget/cts/TableLayoutTest.java
index 5259736..b9f0d1f 100644
--- a/tests/tests/widget/src/android/widget/cts/TableLayoutTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TableLayoutTest.java
@@ -18,7 +18,6 @@
 
 import com.android.cts.widget.R;
 
-
 import android.content.Context;
 import android.content.res.XmlResourceParser;
 import android.test.ActivityInstrumentationTestCase2;
diff --git a/tests/tests/widget/src/android/widget/cts/TableLayout_LayoutParamsTest.java b/tests/tests/widget/src/android/widget/cts/TableLayout_LayoutParamsTest.java
index 8a38c81..cbc41ce 100644
--- a/tests/tests/widget/src/android/widget/cts/TableLayout_LayoutParamsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TableLayout_LayoutParamsTest.java
@@ -16,7 +16,7 @@
 
 package android.widget.cts;
 
-import com.android.internal.R;
+import com.android.cts.widget.R;
 
 import org.xmlpull.v1.XmlPullParser;
 
@@ -140,8 +140,7 @@
         XmlResourceParser parser = null;
         AttributeSet attrs = null;
         try {
-            parser = mTargetContext.getResources()
-                    .getXml(com.android.cts.widget.R.xml.base_attributes);
+            parser = mTargetContext.getResources().getXml(R.xml.base_attributes);
 
             int type;
             while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
diff --git a/tests/tests/widget/src/android/widget/cts/TableRow_LayoutParamsTest.java b/tests/tests/widget/src/android/widget/cts/TableRow_LayoutParamsTest.java
index 06f851d..8308414 100644
--- a/tests/tests/widget/src/android/widget/cts/TableRow_LayoutParamsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TableRow_LayoutParamsTest.java
@@ -16,7 +16,7 @@
 
 package android.widget.cts;
 
-import com.android.internal.R;
+import com.android.cts.widget.R;
 
 import org.xmlpull.v1.XmlPullParser;
 
@@ -91,8 +91,8 @@
         assertEquals(0, layoutParams.span);
 
         TableCtsActivity activity = getActivity();
-        activity.setContentView(com.android.cts.widget.R.layout.table_layout_2);
-        int idTable = com.android.cts.widget.R.id.table2;
+        activity.setContentView(R.layout.table_layout_2);
+        int idTable = R.id.table2;
         TableLayout tableLayout = (TableLayout) activity.findViewById(idTable);
         View vVitural1 = ((TableRow) tableLayout.getChildAt(0)).getVirtualChildAt(1);
         layoutParams = (TableRow.LayoutParams) vVitural1.getLayoutParams();
@@ -186,8 +186,7 @@
         XmlResourceParser parser = null;
         AttributeSet attrs = null;
         try {
-            parser = mTargetContext.getResources()
-                    .getXml(com.android.cts.widget.R.xml.base_attributes);
+            parser = mTargetContext.getResources().getXml(R.xml.base_attributes);
 
             int type;
             while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
diff --git a/tests/tests/widget/src/android/widget/cts/TextViewTest.java b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
index 31a4636..936f38f 100644
--- a/tests/tests/widget/src/android/widget/cts/TextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
@@ -17,7 +17,6 @@
 package android.widget.cts;
 
 import com.android.cts.widget.R;
-import com.android.internal.util.FastMath;
 
 import org.xmlpull.v1.XmlPullParserException;
 
@@ -786,37 +785,37 @@
         float add = 1.2f;
         float mult = 1.4f;
         setLineSpacing(add, mult);
-        assertEquals(FastMath.round(originalLineHeight * mult + add), mTextView.getLineHeight());
+        assertEquals(Math.round(originalLineHeight * mult + add), mTextView.getLineHeight());
         add = 0.0f;
         mult = 1.4f;
         setLineSpacing(add, mult);
-        assertEquals(FastMath.round(originalLineHeight * mult + add), mTextView.getLineHeight());
+        assertEquals(Math.round(originalLineHeight * mult + add), mTextView.getLineHeight());
 
         // abnormal
         add = -1.2f;
         mult = 1.4f;
         setLineSpacing(add, mult);
-        assertEquals(FastMath.round(originalLineHeight * mult + add), mTextView.getLineHeight());
+        assertEquals(Math.round(originalLineHeight * mult + add), mTextView.getLineHeight());
         add = -1.2f;
         mult = -1.4f;
         setLineSpacing(add, mult);
-        assertEquals(FastMath.round(originalLineHeight * mult + add), mTextView.getLineHeight());
+        assertEquals(Math.round(originalLineHeight * mult + add), mTextView.getLineHeight());
         add = 1.2f;
         mult = 0.0f;
         setLineSpacing(add, mult);
-        assertEquals(FastMath.round(originalLineHeight * mult + add), mTextView.getLineHeight());
+        assertEquals(Math.round(originalLineHeight * mult + add), mTextView.getLineHeight());
 
         // edge
         add = Float.MIN_VALUE;
         mult = Float.MIN_VALUE;
         setLineSpacing(add, mult);
         float expected = originalLineHeight * mult + add;
-        assertEquals(FastMath.round(expected), mTextView.getLineHeight());
+        assertEquals(Math.round(expected), mTextView.getLineHeight());
         add = Float.MAX_VALUE;
         mult = Float.MAX_VALUE;
         setLineSpacing(add, mult);
         expected = originalLineHeight * mult + add;
-        assertEquals(FastMath.round(expected), mTextView.getLineHeight());
+        assertEquals(Math.round(expected), mTextView.getLineHeight());
     }
 
     public void testInstanceState() {
diff --git a/tests/tests/widget/src/android/widget/cts/util/ListScenario.java b/tests/tests/widget/src/android/widget/cts/util/ListScenario.java
index 11d670d..b61673c 100644
--- a/tests/tests/widget/src/android/widget/cts/util/ListScenario.java
+++ b/tests/tests/widget/src/android/widget/cts/util/ListScenario.java
@@ -17,6 +17,7 @@
 package android.widget.cts.util;
 
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
@@ -35,8 +36,6 @@
 import android.widget.ListView;
 import android.widget.TextView;
 
-import com.google.android.collect.Maps;
-
 /**
  * Utility base class for creating various List scenarios.  Configurable by the number
  * of items, how tall each item should be (in relation to the screen height), and
@@ -52,7 +51,7 @@
 
     private int mStartingSelectionPosition;
     private double mItemScreenSizeFactor;
-    private Map<Integer, Double> mOverrideItemScreenSizeFactors = Maps.newHashMap();
+    private Map<Integer, Double> mOverrideItemScreenSizeFactors = new HashMap<>();
 
     private int mScreenHeight;
 
@@ -102,7 +101,7 @@
         private double mItemScreenSizeFactor = 1 / 5;
         private Double mFadingEdgeScreenSizeFactor = null;
 
-        private Map<Integer, Double> mOverrideItemScreenSizeFactors = Maps.newHashMap();
+        private Map<Integer, Double> mOverrideItemScreenSizeFactors = new HashMap<>();
 
         // separators
         private List<Integer> mUnselectableItems = new ArrayList<Integer>(8);
diff --git a/tests/tests/widget/src/android/widget/cts/util/XmlUtils.java b/tests/tests/widget/src/android/widget/cts/util/XmlUtils.java
index c357e5e..1ff922f 100644
--- a/tests/tests/widget/src/android/widget/cts/util/XmlUtils.java
+++ b/tests/tests/widget/src/android/widget/cts/util/XmlUtils.java
@@ -16,8 +16,6 @@
 
 package android.widget.cts.util;
 
-import com.android.internal.util.FastXmlSerializer;
-
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 import org.xmlpull.v1.XmlSerializer;
@@ -171,28 +169,6 @@
     }
 
     /**
-     * Flatten a Map into an output stream as XML.  The map can later be
-     * read back with readMapXml().
-     *
-     * @param val The map to be flattened.
-     * @param out Where to write the XML data.
-     *
-     * @see #writeMapXml(Map, String, XmlSerializer)
-     * @see #writeListXml
-     * @see #writeValueXml
-     * @see #readMapXml
-     */
-    public static final void writeMapXml(Map val, OutputStream out)
-            throws XmlPullParserException, IOException {
-        XmlSerializer serializer = new FastXmlSerializer();
-        serializer.setOutput(out, StandardCharsets.UTF_8.name());
-        serializer.startDocument(null, true);
-        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
-        writeMapXml(val, null, serializer);
-        serializer.endDocument();
-    }
-
-    /**
      * Flatten a List into an output stream as XML.  The list can later be
      * read back with readListXml().
      *
@@ -224,7 +200,6 @@
      *             none.
      * @param out XmlSerializer to write the map into.
      *
-     * @see #writeMapXml(Map, OutputStream)
      * @see #writeListXml
      * @see #writeValueXml
      * @see #readMapXml
@@ -244,7 +219,6 @@
      * @param out XmlSerializer to write the map into.
      * @param callback Method to call when an Object type is not recognized.
      *
-     * @see #writeMapXml(Map, OutputStream)
      * @see #writeListXml
      * @see #writeValueXml
      * @see #readMapXml
@@ -278,7 +252,6 @@
      * @param val The map to be flattened.
      * @param out XmlSerializer to write the map into.
      *
-     * @see #writeMapXml(Map, OutputStream)
      * @see #writeListXml
      * @see #writeValueXml
      * @see #readMapXml